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_base::Interner;
16use rucc_codegen::pipeline::{self, Machine};
17use rucc_diag::{Diagnostic, Severity, Span};
18use rucc_lex::{Convert, Keywords, PpToken, convert};
19use rucc_sema::{Checker, Context as CheckContext};
20use rucc_session::{EmitKind, FileSystem, Options, Session};
21use rucc_target::TargetInfo;
22
23use crate::preprocess::render;
24
25/// What a compilation produced, which is text for most of the kinds and bytes for one of them.
26///
27/// Two variants rather than a string, because an object file is not text and a `Vec<u8>` holding
28/// UTF-8 for six kinds and a file format for the seventh would leave every reader guessing which
29/// it had. [`Artifact::Nothing`] is what a compilation that stopped early gives back, and it is
30/// not the same as an empty file: nothing is written for it at all.
31#[derive(Debug, Clone, PartialEq, Eq, Default)]
32pub enum Artifact {
33    /// The compilation stopped before it produced anything, or the kind asked for produces
34    /// nothing yet.
35    #[default]
36    Nothing,
37    /// Text, which is every kind up to and including assembly.
38    Text(String),
39    /// An object file, which is `-c`.
40    Object(Vec<u8>),
41}
42
43impl Artifact {
44    /// The bytes to write, which is nothing at all for [`Artifact::Nothing`].
45    #[must_use]
46    pub fn bytes(&self) -> &[u8] {
47        match self {
48            Artifact::Nothing => &[],
49            Artifact::Text(text) => text.as_bytes(),
50            Artifact::Object(bytes) => bytes,
51        }
52    }
53}
54
55/// What compiling one file produced.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Compiled {
58    /// What to write, which is nothing when the compilation failed or produced nothing.
59    pub artifact: Artifact,
60    /// The diagnostics, already rendered, one per element, in the order they were reported.
61    pub messages: Vec<String>,
62    /// How many of them were errors.
63    pub errors: u32,
64}
65
66impl Compiled {
67    /// Whether anything went wrong badly enough that the output should not be used.
68    #[must_use]
69    pub fn failed(&self) -> bool {
70        self.errors > 0
71    }
72
73    /// The text that was produced, and the empty string for anything that is not text.
74    ///
75    /// A caller that asked for one of the text kinds knows which it asked for, so this saves it
76    /// matching on a variant it has already ruled out.
77    #[must_use]
78    pub fn text(&self) -> &str {
79        match &self.artifact {
80            Artifact::Text(text) => text,
81            _ => "",
82        }
83    }
84}
85
86/// Compiles one file as far as `opts.emit` asks for and renders the result.
87///
88/// `name` is the path as the user wrote it, which is the name every diagnostic about the file
89/// uses. Every kind but the executable produces something today, and that one runs the same front
90/// end and gives back nothing, so that a file with a mistake in it is reported the same way
91/// whichever kind was asked for, rather than compiling silently until the part that is written
92/// notices.
93///
94/// The checking is skipped when the parse reported an error. The two poisoning rules mean a
95/// diagnosed expression produces no further complaints, but a declaration the parser had to skip
96/// past leaves no declaration behind at all, and every later use of that name would be reported
97/// as undeclared. One mistake is worth one message.
98#[must_use]
99pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
100    let mut sess = Session::new(opts.clone());
101    // Before anything else interns a name. The keyword symbols have to be one unbroken run for
102    // a lookup to be a subtraction, and the preprocessor interns every identifier it reads, so
103    // building this after the expansion would mean building it after `char` had been seen.
104    let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
105    let mut diagnostics: Vec<Diagnostic> = Vec::new();
106
107    let bytes = match fs.read(Path::new(name)) {
108        Ok(bytes) => bytes,
109        Err(e) => return failure(format!("{name}: {e}")),
110    };
111    let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
112        return failure(format!("{name}: the source map has no room left for this file"));
113    };
114
115    // Phases 1 to 4. The expanded stream is turned into pp-tokens straight away, because the
116    // include context borrows the source map that rendering a diagnostic reads and the borrow
117    // has to end before anything is rendered.
118    let mut pp = rucc_pp::Preprocessor::new();
119    let predef = rucc_pp::Predef::for_options(opts);
120    let expanded: Vec<PpToken> = {
121        let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
122        cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
123        if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
124            return failure(format!("{name}: the source map has no room for the built in macros"));
125        }
126        pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
127    };
128    diagnostics.extend(pp.take_diagnostics());
129
130    // Phase 7, which is where a spelling becomes a keyword and a preprocessing number becomes
131    // a constant of a type.
132    let cx = Convert {
133        keywords: &keywords,
134        interner: &sess.interner,
135        target: &sess.target,
136        std: opts.std,
137        gnu: opts.gnu_extensions,
138        pedantic: opts.pedantic,
139    };
140    let (tokens, complaints) = convert(&expanded, &cx);
141    diagnostics.extend(complaints);
142
143    let parsed = rucc_parse::parse(
144        &tokens,
145        rucc_parse::Context {
146            interner: &sess.interner,
147            std: opts.std,
148            gnu: opts.gnu_extensions,
149            pedantic: opts.pedantic,
150            error_limit: opts.error_limit as usize,
151        },
152    );
153    let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
154    diagnostics.extend(parsed.diagnostics);
155
156    let mut artifact = Artifact::Nothing;
157    if !parse_failed {
158        let mut checker = Checker::new(
159            &parsed.ast,
160            CheckContext {
161                names: &sess.interner,
162                target: &sess.target,
163                std: opts.std,
164                gnu: opts.gnu_extensions,
165                pedantic: opts.pedantic,
166                error_limit: opts.error_limit as usize,
167            },
168        );
169        checker.check_unit();
170        let checked = checker.finish();
171        if !checked.failed() {
172            match opts.emit {
173                EmitKind::Tast => {
174                    artifact = Artifact::Text(rucc_sema::print(
175                        &checked.tast,
176                        &checked.types,
177                        &sess.interner,
178                    ));
179                }
180                EmitKind::Ir
181                | EmitKind::MirFinal
182                | EmitKind::Asm
183                | EmitKind::Object
184                | EmitKind::Executable => {
185                    let mut lowered = rucc_lower::lower(
186                        name,
187                        rucc_lower::Context {
188                            tast: &checked.tast,
189                            types: &checked.types,
190                            target: &sess.target,
191                            names: &mut sess.interner,
192                        },
193                    );
194                    // The walk reports what it cannot build, and what it did build is printed
195                    // anyway: a file with one construct missing from it is more use to read
196                    // than nothing at all, and the errors are what stop it being compiled.
197                    let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
198                    if !failed {
199                        // The verifier runs on everything the walk builds, always. It is the
200                        // one check that a bug in the walk cannot talk its way past, and a
201                        // wrong instruction found here costs a message rather than an hour
202                        // in front of a debugger over the assembly it turned into.
203                        if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
204                            for error in errors {
205                                diagnostics.push(internal(&format!("invalid IR, {error}")));
206                            }
207                        } else if opts.emit == EmitKind::Ir {
208                            artifact =
209                                Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
210                        } else {
211                            // The back end, which is every pass after the IR and which is
212                            // where a construct nothing has a rule for is finally noticed.
213                            match generate(
214                                &mut lowered.module,
215                                &mut sess.interner,
216                                &sess.target,
217                                opts,
218                            ) {
219                                Ok(made) => artifact = made,
220                                Err(complaints) => diagnostics.extend(complaints),
221                            }
222                        }
223                    }
224                    diagnostics.extend(lowered.diagnostics);
225                }
226                _ => {}
227            }
228        }
229        diagnostics.extend(checked.diagnostics);
230    }
231
232    let mut messages = Vec::with_capacity(diagnostics.len());
233    let mut errors = 0;
234    for diag in &diagnostics {
235        if diag.severity.is_fatal()
236            || (diag.severity == Severity::Warning && opts.warnings_are_errors)
237        {
238            errors += 1;
239        }
240        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
241    }
242    if errors > 0 {
243        // A tree built from a file that did not compile is not a tree anything should read.
244        artifact = Artifact::Nothing;
245    }
246    Compiled { artifact, messages, errors }
247}
248
249/// Reads one file of IR, checks it, and prints it back.
250///
251/// This is the compiler's own textual IR arriving as an input rather than leaving as an output,
252/// which is what makes the round trip in the M2 exit criterion something to run rather than
253/// something to believe: what the printer wrote is read back, verified, and written again, and
254/// the two files are either the same bytes or they are not.
255///
256/// The verifier runs here for the reason it runs after the walk. A module that was printed by
257/// this compiler has been through it once already, and one that a person edited has not.
258#[must_use]
259pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
260    let mut sess = Session::new(opts.clone());
261    if opts.emit != EmitKind::Ir {
262        return failure(format!(
263            "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
264             the C in front of it became",
265            opts.emit.as_str()
266        ));
267    }
268    let bytes = match fs.read(Path::new(name)) {
269        Ok(bytes) => bytes,
270        Err(e) => return failure(format!("{name}: {e}")),
271    };
272    let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
273        return failure(format!("{name}: this is not text, so it is not IR"));
274    };
275
276    let module = match rucc_ir::parse(text, &mut sess.interner) {
277        Ok(module) => module,
278        Err(error) => {
279            return failure(format!("{name}:{}: {}", error.line, error.message));
280        }
281    };
282    let mut diagnostics: Vec<Diagnostic> = Vec::new();
283    if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
284        for error in errors {
285            diagnostics.push(invalid(&format!("invalid IR, {error}")));
286        }
287    }
288    let mut messages = Vec::with_capacity(diagnostics.len());
289    for diag in &diagnostics {
290        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
291    }
292    let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
293    let artifact = if errors > 0 {
294        Artifact::Nothing
295    } else {
296        Artifact::Text(rucc_ir::print(&module, &sess.interner))
297    };
298    Compiled { artifact, messages, errors }
299}
300
301/// Runs the back end over every function in `module` and writes what came out.
302///
303/// One machine function per definition in the module, in the order the module holds them, every
304/// register physical and every frame offset a constant. A declaration has no body and is skipped,
305/// because there is nothing in it to compile.
306///
307/// What the last step is, is the only thing `--emit=mir-final`, `-S` and `-c` disagree about. The
308/// three read the same functions and differ in whether they are printed as machine IR, printed as
309/// assembly, or encoded and put in a file, which is the point of section 11.1 of
310/// `spec/11-asm-objects-debug.md`: a listing that disagrees with the object file beside it is
311/// worse than no listing, and the way to make that impossible is to have one description of an
312/// instruction and two ways of writing it down.
313///
314/// # Errors
315///
316/// One diagnostic per function the back end could not compile, or one about the target when no
317/// back end covers it at all. Every function is attempted rather than stopping at the first, so a
318/// file with three constructs missing from the rule set reports three rather than one at a time.
319fn generate(
320    module: &mut rucc_ir::Module,
321    names: &mut Interner,
322    target: &TargetInfo,
323    opts: &Options,
324) -> Result<Artifact, Vec<Diagnostic>> {
325    let Some(machine) = Machine::for_target(target) else {
326        return Err(vec![unsupported(&format!(
327            "there is no back end for {} in this compiler yet, so there is nothing to generate",
328            target.triple
329        ))]);
330    };
331    let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
332
333    let mut funcs = Vec::new();
334    let mut complaints = Vec::new();
335    for id in module.funcs() {
336        if module[id].is_declaration() {
337            continue;
338        }
339        match pipeline::compile(&mut module[id], names, &machine, flags) {
340            Ok(func) => funcs.push(func),
341            Err(why) => {
342                let name = names.resolve(module[id].name).to_owned();
343                // The function knows where the instruction came from, so the message lands on
344                // the line somebody wrote rather than on the file as a whole.
345                let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
346                let said = format!("cannot generate code for '{name}': {why}");
347                complaints.push(unsupported_at(&said, span));
348            }
349        }
350    }
351    if !complaints.is_empty() {
352        return Err(complaints);
353    }
354    // The variables the file defines, which go through the back end the way the functions did not:
355    // there is nothing in a variable to select instructions for, so the module is what says what
356    // one is right up to the point where it is written down.
357    let globals = match opts.emit {
358        EmitKind::Asm | EmitKind::Object | EmitKind::Executable => {
359            rucc_asm::globals(module, names).map_err(refused)?
360        }
361        _ => rucc_asm::Globals::default(),
362    };
363    // A failure in either of the last two is a bug here rather than a program this compiler is
364    // behind on, because every instruction in a function that got this far came out of the same
365    // description both of them read and every register in it has been allocated.
366    match opts.emit {
367        EmitKind::Asm => {
368            rucc_asm::print(&funcs, &globals, names, target).map(Artifact::Text).map_err(refused)
369        }
370        // An executable is an object as far as this gets: one is what each file of a link
371        // contributes, and the linker is what turns them into the other.
372        EmitKind::Object | EmitKind::Executable => {
373            let text = rucc_asm::assemble(&funcs, names, target).map_err(refused)?;
374            let data = globals.image();
375            // A format with no writer is a target this compiler is behind on and anything else
376            // the writer refused is a bug here, and the two are not the same news to get.
377            rucc_object::write(&text, &data, target).map(Artifact::Object).map_err(
378                |why| match why {
379                    rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
380                    rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
381                },
382            )
383        }
384        _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
385    }
386}
387
388/// What the assembler said, as the kind of news it is.
389///
390/// One of these is about a program and the rest are about this compiler. A thread-local variable
391/// is valid C that the back end does not build yet, and everything else the assembler refuses is
392/// something that should never have reached it.
393fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
394    match why {
395        rucc_asm::Error::Thread { .. } => vec![unsupported(&why.to_string())],
396        _ => vec![internal(&why.to_string())],
397    }
398}
399
400/// A diagnostic about a program this compiler is not finished enough to compile.
401///
402/// Not an internal error, because nothing here is wrong: the program is valid C and the part of
403/// the back end that would handle it has not been written. The note says so, so that a report
404/// about one of these is filed against the milestone rather than as a miscompilation.
405fn unsupported(message: &str) -> Diagnostic {
406    unsupported_at(message, Span::DUMMY)
407}
408
409/// The same, about somewhere in the file rather than about the file.
410///
411/// The note names the issue tracker rather than `spec/17-milestones.md`, which is a document
412/// about the plan: a reader who follows it wants to know whether the construct in front of them
413/// is already written down as work, and the milestone list does not answer that.
414fn unsupported_at(message: &str, span: Span) -> Diagnostic {
415    Diagnostic::error(message.to_owned(), span)
416        .with_code("E0653")
417        .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
418}
419
420/// A diagnostic about IR that was handed to us rather than built by us.
421fn invalid(message: &str) -> Diagnostic {
422    Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
423}
424
425/// A diagnostic about this compiler rather than about the program it was given.
426fn internal(message: &str) -> Diagnostic {
427    Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
428        .with_code("E0652")
429        .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
430}
431
432/// A result that is nothing but one message, for the failures that happen before there is
433/// anything to compile.
434fn failure(message: String) -> Compiled {
435    Compiled {
436        artifact: Artifact::Nothing,
437        messages: vec![format!("rucc: error: {message}")],
438        errors: 1,
439    }
440}
441
442#[cfg(test)]
443mod tests {
444    use rucc_session::{MemoryFileSystem, Std};
445    use rucc_target::Triple;
446
447    use super::*;
448
449    fn options() -> Options {
450        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
451        opts.emit = EmitKind::Tast;
452        opts
453    }
454
455    fn run(opts: &Options, source: &str) -> Compiled {
456        let mut fs = MemoryFileSystem::new();
457        fs.insert("/main.c", source.to_owned().into_bytes());
458        compile(opts, "/main.c", &fs)
459    }
460
461    /// Options with the compiler's own headers on the search path and nothing else, which is
462    /// what a freestanding compilation is. There is no file system underneath these tests,
463    /// so a header that reached for one would fail to resolve and say so.
464    fn freestanding() -> Options {
465        let mut opts = options();
466        opts.hosted = false;
467        opts.search.push_system(rucc_session::runtime::DIR);
468        opts
469    }
470
471    /// The typed tree of a freestanding `source`, insisting that it compiled cleanly.
472    fn shipped(source: &str) -> String {
473        let result = run(&freestanding(), source);
474        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
475        result.text().to_owned()
476    }
477
478    /// The typed tree of `source`, insisting that it compiled cleanly.
479    fn tast(source: &str) -> String {
480        let result = run(&options(), source);
481        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
482        result.text().to_owned()
483    }
484
485    #[test]
486    fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
487        let text = shipped(concat!(
488            "#include <stdarg.h>\n",
489            "int sum(int n, ...) {\n",
490            "  va_list ap, copy;\n",
491            "  va_start(ap, n);\n",
492            "  va_copy(copy, ap);\n",
493            "  int total = va_arg(ap, int) + va_arg(copy, int);\n",
494            "  va_end(ap);\n",
495            "  va_end(copy);\n",
496            "  return total;\n",
497            "}\n",
498        ));
499        assert!(text.contains("va-start"), "{text}");
500        assert!(text.contains("va-copy"), "{text}");
501        assert!(text.contains("va-arg"), "{text}");
502        assert!(text.contains("va-end"), "{text}");
503    }
504
505    /// glibc includes `<stdarg.h>` this way from every header that declares a `vprintf`, and
506    /// what it wants is the type without the four macro names. Answering the whole header
507    /// would put `va_start` in the way of a program that has its own.
508    #[test]
509    fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
510        let text = shipped(concat!(
511            "#define __need___va_list\n",
512            "#include <stdarg.h>\n",
513            "int vprint(const char *f, __gnuc_va_list ap);\n",
514            "#ifdef va_start\n",
515            "#error va_start should not be defined\n",
516            "#endif\n",
517            "#ifdef _VA_LIST_DEFINED\n",
518            "#error va_list should not have been made\n",
519            "#endif\n",
520        ));
521        assert!(text.contains("vprint"), "{text}");
522    }
523
524    /// The same protocol on `<stddef.h>`, which glibc uses far more heavily: `<stdio.h>` asks
525    /// for `size_t` and `NULL` and would be wrong to receive `offsetof` as well.
526    #[test]
527    fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
528        let text = shipped(concat!(
529            "#define __need_size_t\n",
530            "#include <stddef.h>\n",
531            "#ifdef offsetof\n",
532            "#error offsetof should not be defined yet\n",
533            "#endif\n",
534            "#define __need_ptrdiff_t\n",
535            "#include <stddef.h>\n",
536            "#include <stddef.h>\n",
537            "size_t a;\n",
538            "ptrdiff_t b;\n",
539            "wchar_t c;\n",
540            "max_align_t d;\n",
541            "void *e = NULL;\n",
542            "struct P { int x; long y; };\n",
543            "size_t f = offsetof(struct P, y);\n",
544        ));
545        assert!(text.contains("decl #0 a : unsigned long"), "{text}");
546        assert!(text.contains("decl #1 b : long"), "{text}");
547    }
548
549    #[test]
550    fn the_shipped_limits_and_float_are_the_targets_own_answers() {
551        let text = shipped(concat!(
552            "#include <limits.h>\n",
553            "#include <float.h>\n",
554            "int bits = CHAR_BIT;\n",
555            "long big = LONG_MAX;\n",
556            "int low = INT_MIN;\n",
557            "int radix = FLT_RADIX;\n",
558            "int digits = DBL_MANT_DIG;\n",
559        ));
560        assert!(text.contains("const 8 : int"), "{text}");
561        assert!(text.contains("const 9223372036854775807 : long"), "{text}");
562        assert!(text.contains("const 2 : int"), "{text}");
563        assert!(text.contains("const 53 : int"), "{text}");
564    }
565
566    /// Freestanding, so there is no library header to chain to and `<stdint.h>` writes the
567    /// whole set out itself. The widths are the ones the target picked, which is the only
568    /// reason this header is the compiler's.
569    #[test]
570    fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
571        let text = shipped(concat!(
572            "#include <stdint.h>\n",
573            "int64_t a = INT64_C(1);\n",
574            "uint_least16_t b;\n",
575            "intptr_t c;\n",
576            "uintmax_t d = UINTMAX_MAX;\n",
577            "int wide = sizeof(int_fast64_t);\n",
578        ));
579        assert!(text.contains("decl #0 a : long"), "{text}");
580        assert!(text.contains("decl #1 b : unsigned short"), "{text}");
581        assert!(text.contains("decl #2 c : long"), "{text}");
582    }
583
584    #[test]
585    fn the_three_formality_headers_still_have_to_work() {
586        let text = shipped(concat!(
587            "#include <stdbool.h>\n",
588            "#include <stdalign.h>\n",
589            "#include <iso646.h>\n",
590            "#include <stdnoreturn.h>\n",
591            "int t = true and not false;\n",
592            "_Alignas(16) char buf[16];\n",
593            "int a = alignof(long);\n",
594        ));
595        assert!(text.contains("decl #0 t : int"), "{text}");
596        assert!(text.contains("const 8 : unsigned long"), "{text}");
597    }
598
599    /// Including everything twice has to change nothing, because that is what happens in any
600    /// program large enough to matter and a guard that is wrong shows up nowhere else.
601    #[test]
602    fn every_shipped_header_can_be_included_twice() {
603        let mut source = String::new();
604        for _ in 0..2 {
605            for name in rucc_session::runtime::names() {
606                source.push_str(&format!("#include <{name}>\n"));
607            }
608        }
609        source.push_str("int x;\n");
610        let text = shipped(&source);
611        assert!(text.starts_with("decl #0 x : int"), "{text}");
612    }
613
614    #[test]
615    fn a_file_that_is_not_there_says_so_and_produces_nothing() {
616        let fs = MemoryFileSystem::new();
617        let result = compile(&options(), "/nope.c", &fs);
618        assert!(result.failed());
619        assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
620        assert!(result.text().is_empty());
621    }
622
623    #[test]
624    fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
625        let text = tast("int x = 1;\n");
626        let expected = "\
627decl #0 x : int object external static defined
628  init
629    +0
630      const 1 : int
631";
632        assert_eq!(text, expected);
633    }
634
635    #[test]
636    fn the_macros_are_expanded_before_anything_is_parsed() {
637        // The whole pipeline in one line. The bound came out of a macro, so it was expanded,
638        // converted from a preprocessing number to a constant of a type, parsed as an
639        // expression, and folded to the number the array type carries.
640        let text = tast("#define N 2\nint a[N];\n");
641        assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
642    }
643
644    /// A pragma survives the preprocessor on purpose, since what one means is not its
645    /// business, and nothing after it has a place for a `#` in the grammar. `pack` is the one
646    /// the parser reads and every other line is walked past. Both spellings are here because
647    /// they arrive by different routes and only one of them was ever on a line of its own in
648    /// the source.
649    #[test]
650    fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
651        let text = tast(concat!(
652            "#pragma pack(4)\n",
653            "struct s { int a; };\n",
654            "#pragma pack()\n",
655            "int b;\n",
656            "_Pragma(\"GCC visibility push(default)\") int c;\n",
657        ));
658        assert!(text.contains("decl #0 b : int"), "{text}");
659        assert!(text.contains("decl #1 c : int"), "{text}");
660    }
661
662    /// Every number in these two tests was read off gcc 16 on x86-64 under `-std=gnu23`
663    /// rather than reasoned about, which is why they are written as assertions the program
664    /// makes about itself: a compilation with no messages is every one of them holding.
665    ///
666    /// This half is the attributes. `packed` takes the padding out, on the record or on one
667    /// member, `aligned` raises and never lowers, and the two written together are the
668    /// combination that packs and then aligns the whole thing.
669    #[test]
670    fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
671        tast(concat!(
672            "struct A { char c; int i; } __attribute__((packed));\n",
673            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
674            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
675            // `aligned` with nothing in the parentheses is the largest alignment the target
676            // has, which gcc calls BIGGEST_ALIGNMENT and which is sixteen everywhere here.
677            "struct B { char c; int i; } __attribute__((aligned));\n",
678            "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
679            "struct C { char c; int i __attribute__((packed)); };\n",
680            "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
681            "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
682            "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
683            "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
684            "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
685            "struct E { char c; _Alignas(8) int i; };\n",
686            "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
687            "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
688            "struct F { char c; int i __attribute__((aligned(8))); };\n",
689            "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
690            // Two the record already had, so the attribute asks for nothing new, and two
691            // where four was already there, so the attribute is ignored rather than obeyed.
692            "struct G { char c; short s; } __attribute__((aligned(2)));\n",
693            "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
694            "struct H { char c; int i; } __attribute__((aligned(2)));\n",
695            "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
696            // `packed` on a member takes the padding out in front of that member alone, so on
697            // the first one it does nothing and on the second one it does all of it.
698            "struct I { [[gnu::packed]] char c; int i; };\n",
699            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
700            "struct J { char c; [[gnu::packed]] int i; };\n",
701            "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
702            "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
703            "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
704            "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
705            "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
706            "union L { char c; int i; } __attribute__((packed));\n",
707            "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
708            // The armoured spellings, which are the ones a system header writes, since a
709            // program is entitled to a macro called `packed` and is not entitled to one called
710            // `__packed__`. The two names are one attribute and the layout is the same one.
711            "struct O { char c; int i; } __attribute__((__packed__));\n",
712            "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
713            "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
714            "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
715        ));
716    }
717
718    /// Where a bit-field goes, which packing decides and which is the part of all this that
719    /// is not what the names suggest. A bit-field goes at the next free bit unless that would
720    /// make it span more storage than its own type occupies, and then it moves to the next
721    /// boundary of its alignment. Any packing at all takes that rule out, and `#pragma pack`
722    /// counts even where it lowers nothing, which is the fourth and seventh cases here.
723    ///
724    /// Nothing in the language can be asked where a bit-field is, since `offsetof` refuses one
725    /// and every size below comes out the same either way, so what is asked is the byte a read
726    /// of the field loads from.
727    #[test]
728    fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
729        // A `char` field after twelve bits, which will not straddle unpacked and does packed.
730        assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
731        assert_eq!(
732            bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
733            1
734        );
735        assert_eq!(
736            bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
737            1
738        );
739        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
740        // A thirty bit field after a byte, which is the case the rule was written for.
741        assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
742        assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
743        // Four is what an `int` asked for anyway, so this caps nothing and still counts.
744        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
745        assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
746    }
747
748    /// The byte a read of `s.y` loads from, which is where the bit-field was placed.
749    fn bit_field_byte(record: &str) -> u64 {
750        let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
751        let body = body(&source);
752        let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
753        let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
754        constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
755    }
756
757    /// An attribute in the middle of a specifier list, which is where a member usually carries
758    /// one and which was read and then thrown away. The `[[...]]` spelling and whatever was
759    /// written in front of the declaration are collected as the list is walked and the
760    /// `__attribute__` spelling is put straight on the specifiers, and the two were assigned
761    /// over each other rather than joined.
762    #[test]
763    fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
764        tast(concat!(
765            "struct a { char c; __attribute__((aligned(8))) int i; };\n",
766            "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
767            "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
768            "struct b { char c; __attribute__((packed)) int i; };\n",
769            "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
770            "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
771            "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
772            "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
773        ));
774    }
775
776    /// The other half, which is `#pragma pack`. It caps a member's alignment where `packed`
777    /// drops it, so `pack(2)` leaves a `short` where it was and moves an `int`, and it caps a
778    /// member the program asked to align as well, which is where the two differ. It is read
779    /// at the closing brace of the body, so a line written in the middle of one settles the
780    /// whole record rather than the members after it, and `push` and `pop` nest.
781    #[test]
782    fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
783        tast(concat!(
784            "#pragma pack(1)\n",
785            "struct A { char c; int i; };\n",
786            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
787            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
788            "#pragma pack()\n",
789            "struct B { char c; int i; };\n",
790            "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
791            "#pragma pack(2)\n",
792            "struct C { char c; int i; double d; };\n",
793            "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
794            "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
795            // A member the program aligned, which `pack` caps and `packed` would not.
796            "struct K { char c; int i __attribute__((aligned(8))); };\n",
797            "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
798            "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
799            // The record's own `aligned` is not a member's, so it is not capped.
800            "struct J { char c; int i; } __attribute__((aligned(8)));\n",
801            "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
802            "#pragma pack()\n",
803            "#pragma pack(push, 1)\n",
804            "struct D { char c; short s; };\n",
805            "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
806            "#pragma pack(pop)\n",
807            "struct E { char c; short s; };\n",
808            "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
809            // Written in the middle of a body, and it still settles the whole record.
810            "struct H { char c;\n",
811            "#pragma pack(1)\n",
812            "  int i; };\n",
813            "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
814            "#pragma pack(1)\n",
815            "struct I { char c;\n",
816            "#pragma pack()\n",
817            "  int i; };\n",
818            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
819            "#pragma pack()\n",
820            // Nested pushes, each one giving back what the one under it had.
821            "#pragma pack(push, 8)\n",
822            "#pragma pack(push, 1)\n",
823            "struct P { char c; int i; };\n",
824            "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
825            "#pragma pack(pop)\n",
826            "struct Q { char c; int i; };\n",
827            "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
828            "#pragma pack(pop)\n",
829            // A cap above what every member already asks for changes nothing at all.
830            "#pragma pack(16)\n",
831            "struct R { char c; int i; };\n",
832            "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
833            "#pragma pack()\n",
834            "#pragma pack(1)\n",
835            "struct S { char c; int i : 5; int j : 20; };\n",
836            "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
837            "union T { char c; int i; };\n",
838            "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
839            "#pragma pack()\n",
840        ));
841    }
842
843    /// A line the reader cannot make sense of is a warning and the line is dropped, which is
844    /// what GCC does with one, and these are its words for each of them. The last line is the
845    /// one nothing else would reach, since it stands after every record in the file.
846    #[test]
847    fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
848        let result = run(
849            &options(),
850            concat!(
851                "#pragma pack 4\n",
852                "#pragma pack(pop)\n",
853                "#pragma pack(3)\n",
854                "#pragma pack(1) junk\n",
855                "#pragma pack(push, 1\n",
856                "#pragma pack(x)\n",
857                // These two are well formed and say nothing. Zero is how a line asks for the
858                // target's own alignments back without writing empty parentheses.
859                "#pragma pack(0)\n",
860                "#pragma pack(push)\n",
861                "struct s { char c; int i; };\n",
862                "#pragma pack(pop)\n",
863                "#pragma pack(pop, foo)\n",
864            ),
865        );
866        let expected = [
867            "missing `(` after `#pragma pack` - ignored",
868            "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
869            "alignment must be a small power of two, not 3",
870            "junk at end of `#pragma pack`",
871            "malformed `#pragma pack(push[, id][, <n>])` - ignored",
872            "unknown action `x` for `#pragma pack` - ignored",
873            "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
874        ];
875        assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
876        for (message, want) in result.messages.iter().zip(expected) {
877            assert!(message.contains(want), "expected {want:?} in {message:?}");
878        }
879    }
880
881    /// The two typedef spellings of the 128 bit types. gcc offers them as keywords rather
882    /// than as typedefs in a header, which is the only way a program that includes nothing at
883    /// all can still use them, and Apple's `<mach/arm/_structs.h>` is one such program.
884    #[test]
885    fn the_wide_integer_answers_to_all_three_of_its_names() {
886        let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
887        assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
888        assert!(text.contains("decl #1 b : __int128"), "{text}");
889        assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
890    }
891
892    #[test]
893    fn every_conversion_the_language_performs_is_a_node_in_the_output() {
894        // The point of a typed tree. The source has one operator and the output has the
895        // widening that operator asked for, spelled out, so that nothing downstream has to
896        // work out the conversion rules a second time.
897        let text = tast("long f(int a, long b) { return a + b; }\n");
898        assert!(text.contains("convert arithmetic"), "{text}");
899    }
900
901    #[test]
902    fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
903        for source in [
904            "#error stop\n",
905            "int f(void) { return 1 + ; }\n",
906            "int f(void) { return undeclared; }\n",
907        ] {
908            let result = run(&options(), source);
909            assert!(result.failed(), "expected this to fail:\n{source}");
910            assert!(
911                result.text().is_empty(),
912                "a file that did not compile wrote a tree:\n{source}"
913            );
914        }
915    }
916
917    #[test]
918    fn one_undeclared_name_is_one_message_and_not_one_per_use() {
919        // The poisoning rule from `spec/06-lexer-and-parser.md` section 6.8, seen from the
920        // outside. Three uses of a name that was never declared, and the operators over them
921        // say nothing at all.
922        let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
923        assert_eq!(result.errors, 1, "{:?}", result.messages);
924    }
925
926    #[test]
927    fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
928        // The reason the checking is skipped after a failed parse. The parser gave up on the
929        // first line and there is no `x` in the tree, so a checker run over it would report
930        // every use of `x` below as undeclared, which is a second message about one mistake.
931        let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
932        assert_eq!(result.errors, 1, "{:?}", result.messages);
933    }
934
935    #[test]
936    fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
937        let source = "int f(void) { char c = 300; return c; }\n";
938        let plain = run(&options(), source);
939        assert_eq!(plain.errors, 0, "{:?}", plain.messages);
940        assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
941        assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
942
943        let mut opts = options();
944        opts.warnings_are_errors = true;
945        let strict = run(&opts, source);
946        assert!(strict.failed());
947        assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
948        for message in &strict.messages {
949            assert!(!message.contains("warning:"), "{message}");
950        }
951    }
952
953    #[test]
954    fn the_dialect_reaches_the_keywords_and_the_checking() {
955        // `typeof` is C23's and GNU's, so the same source is a declaration under one dialect
956        // and a mistake under the other, which is the keyword table being built per dialect.
957        let source = "typeof(1) x;\n";
958        let mut opts = options();
959        opts.std = Std::C23;
960        opts.gnu_extensions = false;
961        assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
962
963        opts.std = Std::C17;
964        assert!(run(&opts, source).failed());
965    }
966
967    #[test]
968    fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
969        let mut opts = options();
970        opts.emit = EmitKind::Object;
971        let result = run(&opts, "int x = 1;\n");
972        assert!(!result.failed(), "{:?}", result.messages);
973        assert!(result.text().is_empty());
974        // And it still finds what the checking finds, so a later kind on a broken file is not
975        // a silent success.
976        assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
977    }
978
979    /// The machine code of `source`, insisting that it compiled cleanly.
980    fn mir(source: &str) -> String {
981        let mut opts = options();
982        opts.emit = EmitKind::MirFinal;
983        let result = run(&opts, source);
984        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
985        result.text().to_owned()
986    }
987
988    /// The whole compiler in one assertion, which is what this emit kind is for.
989    ///
990    /// C in, machine instructions out, every register a real one and every frame offset a
991    /// number. Everything between the two is checked somewhere else, one pass at a time. What is
992    /// checked here is that the passes are joined up and that the driver runs them.
993    #[test]
994    fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
995        let text = mir("int add(int a, int b) { return a + b; }\n");
996        assert!(text.starts_with("mfunc @add {"), "{text}");
997        assert!(text.contains("x64.add_rr_32"), "{text}");
998        assert!(text.contains("x64.ret"), "{text}");
999        // A virtual register is what the allocator was there to remove, so one left in the
1000        // output is the difference between code and something that looks like code.
1001        assert!(!text.contains('%'), "{text}");
1002    }
1003
1004    /// A declaration has no body, so there is nothing to generate for one and nothing is.
1005    #[test]
1006    fn a_function_with_no_body_produces_no_machine_function() {
1007        let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1008        assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1009        assert!(text.contains("mfunc @f {"), "{text}");
1010        assert!(text.contains("x64.call"), "{text}");
1011    }
1012
1013    /// Two functions come out in the order the module holds them, which is source order.
1014    #[test]
1015    fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1016        let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1017        let first = text.find("mfunc @a").expect("the first function");
1018        let second = text.find("mfunc @b").expect("the second function");
1019        assert!(first < second, "{text}");
1020    }
1021
1022    /// The target reaches the back end, so the same C is different instructions on Windows.
1023    #[test]
1024    fn the_target_decides_which_convention_the_generated_code_follows() {
1025        let mut opts = options();
1026        opts.emit = EmitKind::MirFinal;
1027        let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1028        assert!(linux.contains("$rdi"), "{linux}");
1029
1030        opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1031        let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1032        assert!(windows.contains("$rcx"), "{windows}");
1033        assert!(!windows.contains("$rdi"), "{windows}");
1034    }
1035
1036    /// A target with no back end says so rather than generating something for another machine.
1037    #[test]
1038    fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1039        let mut opts = options();
1040        opts.emit = EmitKind::MirFinal;
1041        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1042        let result = run(&opts, "int f(int a) { return a; }\n");
1043        assert!(result.failed());
1044        assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1045        assert!(result.text().is_empty());
1046    }
1047
1048    /// A construct the rule set does not reach yet is named, along with the function it is in.
1049    ///
1050    /// The message is about this compiler being unfinished rather than about the program, which
1051    /// is valid C either way, so it carries the note that says where the work is tracked. Both
1052    /// functions are attempted, so a file that is ahead of the back end in three places says so
1053    /// three times rather than one recompilation at a time.
1054    #[test]
1055    fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1056        let mut opts = options();
1057        opts.emit = EmitKind::MirFinal;
1058        let source = "long double a(long double x) { return x; }\n\
1059                      long double b(long double x) { return x; }\n";
1060        let result = run(&opts, source);
1061        assert!(result.failed());
1062        assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1063        assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1064        assert!(result.messages[0].contains("x87 stack"), "{:?}", result);
1065        assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1066        assert!(result.text().is_empty());
1067    }
1068
1069    /// An opcode the rule language has no word for is named anyway, and pointed at.
1070    ///
1071    /// The rule language's spelling is the better name when there is one, but an opcode it has
1072    /// no word for is exactly the opcode no rule lowers, so falling back to the opcode and the
1073    /// type is what makes the message say anything at all in the cases that happen. The span is
1074    /// the instruction's own, so the message lands on the line rather than on the file.
1075    #[test]
1076    fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1077        let mut opts = options();
1078        opts.emit = EmitKind::MirFinal;
1079        let result = run(&opts, "int f(int a) {\n  __int128 wide = a;\n  return (int) wide;\n}\n");
1080        assert!(result.failed());
1081        assert!(
1082            result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1083            "{result:?}"
1084        );
1085        assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1086        assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1087    }
1088
1089    /// The note names the issue tracker, which is where a reader finds out whether it is known.
1090    #[test]
1091    fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1092        let mut opts = options();
1093        opts.emit = EmitKind::MirFinal;
1094        let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1095        assert!(result.failed());
1096        let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1097        assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1098        assert!(!note.contains("spec/17-milestones.md"), "{note}");
1099    }
1100
1101    /// The two frame flags reach the frame, which is the only thing either of them does.
1102    #[test]
1103    fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1104        let source = "int f(int a) { return a; }\n";
1105        assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1106
1107        let mut opts = options();
1108        opts.emit = EmitKind::MirFinal;
1109        opts.frame_pointer = true;
1110        let kept = run(&opts, source).text().to_owned();
1111        assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1112    }
1113
1114    /// The assembly of `source`, insisting that it compiled cleanly.
1115    fn asm(source: &str) -> String {
1116        let mut opts = options();
1117        opts.emit = EmitKind::Asm;
1118        let result = run(&opts, source);
1119        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1120        result.text().to_owned()
1121    }
1122
1123    /// `-S`, which is the same compiler as the kind above it with a different last step.
1124    ///
1125    /// What the assembly says is checked in `rucc-asm`, one instruction at a time and against the
1126    /// target's own description of what an instruction is. What is checked here is that a C file
1127    /// goes all the way to a listing an assembler would take, which means the directives around
1128    /// the function as well as the instructions in it.
1129    #[test]
1130    fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1131        let text = asm("int add(int a, int b) { return a + b; }\n");
1132        assert!(text.contains("\t.globl\tadd\n"), "{text}");
1133        assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1134        assert!(text.contains("\nadd:\n"), "{text}");
1135        assert!(text.contains("\taddl\t"), "{text}");
1136        assert!(text.contains("\tret\n"), "{text}");
1137        assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1138        // Without this the stack the program runs on is executable, which is not a default
1139        // anybody chose and is not a thing a reader would notice missing.
1140        assert!(text.contains(".note.GNU-stack"), "{text}");
1141    }
1142
1143    /// A call through a function pointer, which is a different instruction from a call to a name.
1144    ///
1145    /// Both are in the one function on purpose. What is being read is that the two calls are told
1146    /// apart all the way down: one carries a name the linker resolves and one carries a register,
1147    /// and neither turns into the other on the way.
1148    #[test]
1149    fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1150        let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1151        assert!(text.contains("\tcall\t*%"), "{text}");
1152        assert!(text.contains("\tcall\tg\n"), "{text}");
1153        // The address arrived in the first argument register and the argument the call passes has
1154        // to end up there, so the two cannot be the same register and the compiler has to have
1155        // moved one of them.
1156        assert!(text.contains("%rdi"), "{text}");
1157    }
1158
1159    /// A name at file scope, which is the one address a function cannot compute for itself.
1160    #[test]
1161    fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1162        let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1163        assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1164    }
1165
1166    /// A cast between a pointer and an integer as wide as one, which is every one C writes here.
1167    #[test]
1168    fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1169        let text = asm("long f(void *p) { return (long)p; }\n");
1170        // Every instruction in the body is a full width move or the return. The copies are the
1171        // allocator taking no hints, and what matters here is what is not among them: nothing
1172        // narrows the value and nothing widens it again, which is what a cast that did something
1173        // would look like.
1174        for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1175            let mnemonic = line.split_whitespace().next().unwrap_or("");
1176            assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1177        }
1178    }
1179
1180    /// The object format decides the directives, and the target decides the object format.
1181    #[test]
1182    fn the_target_decides_how_the_assembly_is_spelled() {
1183        let mut opts = options();
1184        opts.emit = EmitKind::Asm;
1185        opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1186        let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1187        assert!(text.contains("__TEXT,__text"), "{text}");
1188        assert!(text.contains("\n_f:\n"), "{text}");
1189        assert!(!text.contains(".note.GNU-stack"), "{text}");
1190    }
1191
1192    /// The object file of `source`, insisting that it compiled cleanly.
1193    fn obj(source: &str) -> Vec<u8> {
1194        let mut opts = options();
1195        opts.emit = EmitKind::Object;
1196        let result = run(&opts, source);
1197        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1198        match result.artifact {
1199            Artifact::Object(bytes) => bytes,
1200            other => panic!("expected an object, got {other:?}"),
1201        }
1202    }
1203
1204    /// `-c`, which is the last step of the three the back end can end with.
1205    ///
1206    /// What is in the file is checked in `rucc-object`, a field at a time. What is checked here is
1207    /// that a C file goes all the way to one, which is the whole compiler in one line and the
1208    /// thing that stops working when a layer between them changes its mind about something.
1209    #[test]
1210    fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1211        let bytes = obj("int add(int a, int b) { return a + b; }\n");
1212        assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1213        let text = asm("int add(int a, int b) { return a + b; }\n");
1214        assert!(
1215            text.contains("\taddl\t"),
1216            "and the listing of it is the same instructions:\n{text}"
1217        );
1218    }
1219
1220    /// A variable this file defines, which is what a reference to one has to resolve against.
1221    #[test]
1222    fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1223        let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1224        assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1225        assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1226        assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1227        // A zeroed variable carries its size and none of its bytes, and a `static` one is not
1228        // announced to the linker at all, which is the whole of what `static` means here.
1229        assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1230        assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1231        assert!(!text.contains(".globl\thidden"), "{text}");
1232        // Nothing writes through it, so it goes in a page the loader can map read only and every
1233        // process running the program can share.
1234        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1235    }
1236
1237    /// A string literal, which is a variable the program never named.
1238    #[test]
1239    fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1240        let text = asm("const char *f(void) { return \"hi\"; }\n");
1241        assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1242        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1243        let label = text
1244            .lines()
1245            .find(|line| line.starts_with(".Lstr"))
1246            .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1247        assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1248    }
1249
1250    /// A variable holding the address of another one, which is the only hole an image has in it.
1251    #[test]
1252    fn an_address_in_an_initializer_is_left_to_the_linker() {
1253        let source = "int counter;\nint *p = &counter;\n";
1254        let text = asm(source);
1255        assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1256        // And in the object it is eight zero bytes and a relocation, which is what the two paths
1257        // being one description is for.
1258        let bytes = obj(source);
1259        assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1260    }
1261
1262    /// A thread-local variable, which is valid C that the back end does not build yet.
1263    #[test]
1264    fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
1265        let mut opts = options();
1266        opts.emit = EmitKind::Asm;
1267        let result = run(&opts, "_Thread_local int x = 1;\n");
1268        assert!(result.failed(), "every thread sharing one variable is worse than a message");
1269        assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
1270        // Not an internal error: nothing here is wrong and the note says where the work is.
1271        assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
1272    }
1273
1274    /// Not a rewording of the check above: what the two paths agree about is the point.
1275    #[test]
1276    fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1277        // A call, because it is the one thing whose spelling in the two differs completely: the
1278        // listing writes a name and the object writes four zero bytes and a relocation asking the
1279        // linker for the same name. If either path had lost the callee, one of these would fail.
1280        let source = "int callee(void); int g(void) { return callee(); }\n";
1281        let bytes = obj(source);
1282        assert!(
1283            bytes.windows(7).any(|w| w == b"callee\0"),
1284            "the object has to name the callee for the linker to find it"
1285        );
1286        let text = asm(source);
1287        assert!(text.contains("\tcall\tcallee\n"), "{text}");
1288    }
1289
1290    /// What a file of a link contributes is an object, and the default emit is a link.
1291    ///
1292    /// This is here because getting it wrong is silent in the worst way: an empty file is a valid
1293    /// empty linker script, so a link fed one gets as far as reporting every symbol of the file as
1294    /// undefined and says nothing about the compilation that produced nothing.
1295    #[test]
1296    fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
1297        let mut opts = options();
1298        // What a command line with no `-c` and no `-S` on it asks for.
1299        opts.emit = EmitKind::Executable;
1300        let result = run(&opts, "int main(void) { return 0; }\n");
1301        assert_eq!(result.messages, Vec::<String>::new());
1302        match result.artifact {
1303            Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
1304            other => panic!("expected an object, got {other:?}"),
1305        }
1306    }
1307
1308    /// A target with a back end but no object writer says so rather than writing the wrong file.
1309    #[test]
1310    fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
1311        let mut opts = options();
1312        opts.emit = EmitKind::Object;
1313        opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1314        let result = run(&opts, "int f(void) { return 0; }\n");
1315        assert!(result.failed(), "an object nobody can read is worse than a message");
1316        assert!(
1317            result.messages.iter().any(|m| m.contains("no object writer")),
1318            "{:?}",
1319            result.messages
1320        );
1321    }
1322
1323    /// The IR of `source`, insisting that it compiled cleanly.
1324    fn ir(source: &str) -> String {
1325        let mut opts = options();
1326        opts.emit = EmitKind::Ir;
1327        let result = run(&opts, source);
1328        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1329        result.text().to_owned()
1330    }
1331
1332    /// The body of the one function in `source`, which is what most of these are about.
1333    fn body(source: &str) -> String {
1334        let text = ir(source);
1335        let (_, rest) = text.split_once("{\n").expect("a function definition");
1336        let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1337        body.to_owned()
1338    }
1339
1340    /// `__builtin_constant_p` is answered in the front end and never reaches the IR.
1341    ///
1342    /// gcc folds it after optimization, so its answer for an argument that is not written as a
1343    /// constant can differ between `-O0` and `-O2`. What is checked here is the front end's
1344    /// answer, which is the same at every level, and the four cases where gcc gives the same
1345    /// answer at both levels are the ones measured on gcc 16: a literal is one, a variable is
1346    /// zero, a string literal is one and the address of an object is zero.
1347    #[test]
1348    fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1349        let text = ir(concat!(
1350            "int g;\n",
1351            "int a = __builtin_constant_p(1);\n",
1352            "int b = __builtin_constant_p(g);\n",
1353            "int c = __builtin_constant_p(\"abc\");\n",
1354            "int d = __builtin_constant_p(&g);\n",
1355            "int e = __builtin_constant_p(1.5);\n",
1356            "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1357        ));
1358        assert!(text.contains("global @a : i32 = 1,"), "{text}");
1359        assert!(text.contains("global @b : i32 = 0,"), "{text}");
1360        assert!(text.contains("global @c : i32 = 1,"), "{text}");
1361        assert!(text.contains("global @d : i32 = 0,"), "{text}");
1362        assert!(text.contains("global @e : i32 = 1,"), "{text}");
1363        assert!(text.contains("global @h : i32 = 11,"), "{text}");
1364        assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1365
1366        // The argument is not evaluated, which is what gcc does with it as well, so `i` is
1367        // still zero. The second constant is the answer, which nothing reads and which the
1368        // first pass that looks for dead code will take out.
1369        let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1370        assert_eq!(text, "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 0\n    return %0\n");
1371    }
1372
1373    /// A library builtin is the library function of the same name, and the call says so.
1374    ///
1375    /// A program writes `__builtin_strlen` rather than `strlen` to reach the function the C
1376    /// library promises where its own name has been taken by a macro, and to say that the usual
1377    /// meaning is the one intended. So the name in the program and the name in the object file
1378    /// are two different names and the call carries the second one. gcc folds several of these
1379    /// when the arguments allow it, which is an optimization on top of a call that is already
1380    /// right rather than instead of it, so nothing here depends on any folding happening.
1381    #[test]
1382    fn a_call_to_a_library_builtin_reaches_the_library_function() {
1383        let text = body("void f(void) { __builtin_abort(); }\n");
1384        assert_eq!(text, "block0:\n    call @abort() : ()\n    return\n");
1385
1386        // Nothing declared either of these and nothing had to: the prefix is what says the name
1387        // belongs to the implementation, and the type comes out of `features.toml`.
1388        let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1389        assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1390        assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1391        assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1392    }
1393
1394    /// The hint builtins are their first argument, and nothing is left of the hint.
1395    ///
1396    /// Which way a branch is expected to go is the whole of what they say, and there is nothing
1397    /// here that reads a branch weight yet, so what reaches the IR is the value and the hint is
1398    /// gone. The one thing the prototype has to keep doing is converting: gcc gives both of them
1399    /// a `long` result, so `sizeof(__builtin_expect((char)1, 1))` is eight and a narrower argument
1400    /// widens before it is answered with.
1401    ///
1402    /// The arguments after the first are checked and then dropped, so a side effect in one does
1403    /// not happen. That is what gcc does with them too, measured on gcc 16.2.0: the `i` below
1404    /// comes back zero there as well.
1405    #[test]
1406    fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
1407        let text = ir(concat!(
1408            "long a = __builtin_expect(7, 1);\n",
1409            "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
1410            "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
1411        ));
1412        assert!(text.contains("global @a : i64 = 7,"), "{text}");
1413        assert!(text.contains("global @b : i64 = 9,"), "{text}");
1414        assert!(text.contains("global @c : i64 = 8,"), "{text}");
1415        assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
1416
1417        // A narrower argument is widened by the prototype before it is handed back, and it is
1418        // widened with its sign, since the parameter is a signed `long`.
1419        let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
1420        assert!(text.contains("sext"), "{text}");
1421
1422        // The second argument is not evaluated, so `i` is still zero, and neither is the third.
1423        // What is left of each statement is the first argument widened, which nothing reads and
1424        // which the first pass that looks for dead code will take out.
1425        let one = "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 1\n    %2 = sext.i64 %1\n    return %0\n";
1426        assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
1427        let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
1428        assert_eq!(body(source), one);
1429    }
1430
1431    /// The two names stay apart, which is what having both of them is for.
1432    ///
1433    /// The one the program wrote is what the call is checked against and what a diagnostic about
1434    /// it says, and the one the library defines is what the call ends up carrying. A compiler
1435    /// that kept only the second would report this against `abort`, which is a function the
1436    /// program never mentions.
1437    #[test]
1438    fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1439        let mut opts = options();
1440        opts.emit = EmitKind::Ir;
1441        let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1442        assert!(
1443            messages.iter().any(|m| m.contains("__builtin_abort")),
1444            "expected the written name in {messages:?}"
1445        );
1446    }
1447
1448    /// A builtin nothing lowers is refused where it is written, rather than at the link.
1449    ///
1450    /// The names are one from each shape the table holds: a `__builtin_` with a prototype, one
1451    /// whose type comes from the call it was written in, and one from each of the two older
1452    /// families whose prefix is not `__builtin_`. What the message has to carry is the name,
1453    /// because the whole complaint about the link error this replaces is that the name in it was
1454    /// one the compiler chose.
1455    #[test]
1456    fn a_builtin_nothing_lowers_is_refused_by_name() {
1457        let mut opts = options();
1458        opts.emit = EmitKind::Ir;
1459        for (builtin, call) in [
1460            ("__builtin_clz", "__builtin_clz(1u)"),
1461            ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
1462            ("__atomic_load_n", "__atomic_load_n(&counter, 0)"),
1463            ("__sync_fetch_and_add", "(int)__sync_fetch_and_add(&counter, 1)"),
1464        ] {
1465            let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
1466            let messages = run(&opts, &source).messages;
1467            let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
1468            assert!(named, "expected {builtin} to be refused by name in {messages:?}");
1469        }
1470    }
1471
1472    /// The refusal is about a call and not about the name, so the rest of what C does with one
1473    /// still works.
1474    ///
1475    /// `sizeof` does not evaluate its operand, so nothing is called and there is nothing to
1476    /// refuse; the type of the call is what it asks for and that comes from the front end. A
1477    /// program that defines the name itself gets the function it wrote, which is not what this
1478    /// is for but is what a definition in front of us means.
1479    #[test]
1480    fn what_is_refused_is_the_call_and_not_the_name() {
1481        let text = ir("unsigned long n = sizeof(__builtin_clz(1u));\n");
1482        assert!(text.contains("global @n : i64 = 4,"), "{text}");
1483
1484        let text = ir(
1485            "int __builtin_clz(unsigned x) { return 1; }\nint f(void) { return __builtin_clz(2u); }\n",
1486        );
1487        assert!(text.contains("call @__builtin_clz"), "{text}");
1488    }
1489
1490    /// A `static` function nothing refers to is not emitted, and one that is refered to is.
1491    ///
1492    /// The pair is written as one program so that the two answers come out of one walk. What
1493    /// makes the difference is the call in `main` and nothing else about either definition.
1494    #[test]
1495    fn a_static_function_nothing_refers_to_is_not_emitted() {
1496        let text = ir("static int dropped(void) { return 1; }\n\
1497                       static int kept(void) { return 2; }\n\
1498                       int main(void) { return kept(); }\n");
1499        assert!(text.contains("func @kept"), "{text}");
1500        assert!(!text.contains("dropped"), "{text}");
1501    }
1502
1503    /// The set is transitive, so two of them that only call each other are both dropped.
1504    ///
1505    /// Counting the references to a name would keep this pair, since each is named once, and
1506    /// that is the mistake this is here to catch: what decides it is whether a root reaches the
1507    /// definition, and a root is something the file has a reason to emit on its own.
1508    #[test]
1509    fn two_static_functions_that_only_call_each_other_are_both_dropped() {
1510        let text = ir("static int ping(void);\n\
1511                       static int pong(void) { return ping(); }\n\
1512                       static int ping(void) { return pong(); }\n\
1513                       int main(void) { return 0; }\n");
1514        assert!(!text.contains("ping"), "{text}");
1515        assert!(!text.contains("pong"), "{text}");
1516    }
1517
1518    /// Everything that names a function keeps it, whether or not the name is being called.
1519    ///
1520    /// An address taken in a body, an image that holds one, and a body that is only reached
1521    /// through another `static` function are three different ways for a definition to be needed
1522    /// and none of them is a call at the top level of a reachable function.
1523    #[test]
1524    fn naming_a_static_function_anywhere_keeps_it() {
1525        let text = ir("static int by_address(void) { return 1; }\n\
1526                       static int in_an_image(void) { return 2; }\n\
1527                       static int deeper(void) { return 3; }\n\
1528                       static int reaches_deeper(void) { return deeper(); }\n\
1529                       static int (*table[1])(void) = {in_an_image};\n\
1530                       int main(void) {\n\
1531                         int (*p)(void) = by_address;\n\
1532                         return p() + table[0]() + reaches_deeper();\n\
1533                       }\n");
1534        for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
1535            assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
1536        }
1537    }
1538
1539    /// An attribute that says something outside the file reaches it keeps the definition.
1540    ///
1541    /// None of the five is implemented as anything else yet, and this is the part of each of
1542    /// them that a program notices first: a symbol a linker script names or a function the
1543    /// run-up to `main` calls is not written about anywhere a C file can see.
1544    #[test]
1545    fn an_attribute_keeps_a_static_function_nothing_refers_to() {
1546        for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
1547            let source = format!(
1548                "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
1549                 int main(void) {{ return 0; }}\n"
1550            );
1551            let text = ir(&source);
1552            assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
1553        }
1554    }
1555
1556    /// A function with external linkage is emitted whatever this file does with it, because
1557    /// another one may call it, and that is what external linkage is.
1558    #[test]
1559    fn a_function_anything_could_call_is_emitted_without_being_called() {
1560        let text =
1561            ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
1562        assert!(text.contains("func @nobody_here_calls_it"), "{text}");
1563    }
1564
1565    /// Four of the classification builtins are operators C already has, and become those.
1566    ///
1567    /// What the standard's macro promises over the operator is that it does not raise the
1568    /// invalid operation exception on a quiet NaN. This compiler does not model floating point
1569    /// exceptions, so there is nothing left for a node of its own to carry and a second way of
1570    /// spelling a comparison would be a second thing every pass has to know about.
1571    #[test]
1572    fn a_classification_c_has_an_operator_for_is_that_operator() {
1573        for (builtin, operator) in [
1574            ("__builtin_isgreater", "binary >"),
1575            ("__builtin_isgreaterequal", "binary >="),
1576            ("__builtin_isless", "binary <"),
1577            ("__builtin_islessequal", "binary <="),
1578        ] {
1579            let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1580            let text = tast(&source);
1581            assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1582        }
1583    }
1584
1585    /// The rest of the family are comparisons in the IR and never a call to anything.
1586    ///
1587    /// `math.h` defines the macro of each of these names as the builtin of the same name, so
1588    /// there is no function under any of them for a call to reach. `isunordered` and
1589    /// `islessgreater` are predicates the IR's comparison already has, `isnan` is the value that
1590    /// is unordered with itself, and the two that ask about a magnitude are written against the
1591    /// infinities. `signbit` is the one that is not a question about the value, since a negative
1592    /// zero compares equal to a positive one, so its answer comes from the bits.
1593    #[test]
1594    fn the_classification_builtins_are_comparisons_and_not_calls() {
1595        let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1596        assert_eq!(
1597            text,
1598            "block0(%0: f64, %1: f64):\n    %2 = fcmp uno %0, %1\n    %3 = zext.i32 \
1599                          %2\n    return %3\n"
1600        );
1601
1602        // Not `x != y`, which is true when the two are unordered and so is true of a NaN.
1603        let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1604        assert!(text.contains("fcmp one %0, %1"), "{text}");
1605
1606        let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1607        assert!(text.contains("fcmp uno %0, %0"), "{text}");
1608
1609        let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1610        assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1611        assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1612        assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1613        assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1614        assert!(text.contains("%5 = or %3, %4"), "{text}");
1615
1616        // Strictly between the two infinities, which a NaN is not, because an ordered comparison
1617        // against either of them is false. That is what makes this one test rather than two.
1618        let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1619        assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1620        assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1621        assert!(text.contains("%5 = and %3, %4"), "{text}");
1622
1623        let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1624        assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1625        assert!(text.contains("icmp slt %1, %2"), "{text}");
1626
1627        // The same question of a value in the target's widest format, where the bits are eighty
1628        // and the object they sit in is sixteen bytes.
1629        let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1630        assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1631
1632        // The operand is evaluated once however many times it is compared, which is the whole
1633        // reason these are nodes rather than a rewriting into the operators.
1634        let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1635        assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1636    }
1637
1638    /// A spelling that names a width converts its argument before it asks.
1639    ///
1640    /// gcc gives `__builtin_isinff` a `float` parameter and `__builtin_isinf` no parameter type
1641    /// at all, and the difference is visible rather than academic: `1e300` does not fit in a
1642    /// `float`, so converting it first is an infinity and not converting it is not. Both numbers
1643    /// here are what gcc 16 gives.
1644    #[test]
1645    fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1646        let text = ir(concat!(
1647            "int a = __builtin_isinff(1e300);\n",
1648            "int b = __builtin_isinf(1e300);\n",
1649            // Folded here rather than compared at run time, because a question about a value has
1650            // an answer as soon as the value is a constant, and an initializer for an object
1651            // with static storage duration has to have one.
1652            "int c = __builtin_isnan(0.0);\n",
1653            "int d = __builtin_signbit(-0.0);\n",
1654            "int e = __builtin_islessgreater(1.0, 2.0);\n",
1655        ));
1656        assert!(text.contains("global @a : i32 = 1,"), "{text}");
1657        assert!(text.contains("global @b : i32 = 0,"), "{text}");
1658        assert!(text.contains("global @c : i32 = 0,"), "{text}");
1659        assert!(text.contains("global @d : i32 = 1,"), "{text}");
1660        assert!(text.contains("global @e : i32 = 1,"), "{text}");
1661    }
1662
1663    /// An argument that is not floating point is refused, in gcc's words.
1664    #[test]
1665    fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1666        let mut opts = options();
1667        opts.emit = EmitKind::Ir;
1668        let source = concat!(
1669            "int a(int x) { return __builtin_isnan(x); }\n",
1670            "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1671            "int c(double x) { return __builtin_isnan(x, x); }\n",
1672        );
1673        let messages = run(&opts, source).messages;
1674        assert_eq!(
1675            messages,
1676            [
1677                "/main.c:1:23: error: non-floating-point argument in call to function \
1678                 '__builtin_isnan' [E0685]",
1679                "/main.c:2:30: error: non-floating-point arguments in call to function \
1680                 '__builtin_isunordered' [E0685]",
1681                "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1682            ]
1683        );
1684    }
1685
1686    /// A builtin whose answer is a constant is one, and is not a call to the library.
1687    ///
1688    /// This is the reason the family is answered in the front end at all. `double x =
1689    /// __builtin_inf();` at file scope initializes an object with static storage duration, so
1690    /// there is no point in the program at which a call could be made, and a compiler that
1691    /// lowered it to one would reject a program gcc accepts. Every number here is the encoding
1692    /// gcc 16 gives on x86-64.
1693    #[test]
1694    fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
1695        let text = ir(concat!(
1696            "double a = __builtin_inf();\n",
1697            "float b = __builtin_huge_valf();\n",
1698            "long double c = __builtin_infl();\n",
1699            "double d = __builtin_huge_val();\n",
1700        ));
1701        assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
1702        assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
1703        assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1704        assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
1705        assert!(!text.contains("call"), "{text}");
1706    }
1707
1708    /// A nan is written with the payload the program asked for.
1709    ///
1710    /// The string is read the way `strtoull` reads a number, which is what the library function
1711    /// of the same name does with it, and a string that is not one at all leaves the call for the
1712    /// library to answer at run time. A quiet nan has the high fraction bit set and a signalling
1713    /// one does not, except that a signalling nan with nothing in it would be an infinity, so it
1714    /// gets the next bit down instead. Every encoding here was measured against gcc 16, the two
1715    /// `long double` ones on a machine with the x87 format.
1716    #[test]
1717    fn a_nan_is_written_with_the_payload_the_program_asked_for() {
1718        let text = ir(concat!(
1719            "double a = __builtin_nan(\"\");\n",
1720            "double b = __builtin_nan(\"0x1\");\n",
1721            // Octal, since there is a leading zero, so this is eight and not ten.
1722            "double c = __builtin_nan(\"010\");\n",
1723            "double d = __builtin_nans(\"\");\n",
1724            "double e = __builtin_nans(\"0x1\");\n",
1725            "float f = __builtin_nanf(\"0x1\");\n",
1726            "float g = __builtin_nansf(\"\");\n",
1727            "long double h = __builtin_nansl(\"\");\n",
1728        ));
1729        assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
1730        assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
1731        assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
1732        assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
1733        assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
1734        assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
1735        assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
1736        assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
1737
1738        // A payload that is not a number, and one that is not known until run time, are both
1739        // left to the library, which is the same thing gcc emits for either of them.
1740        let text = ir(concat!(
1741            "double f(const char *p) { return __builtin_nan(p); }\n",
1742            "double g(void) { return __builtin_nans(\"1x\"); }\n",
1743        ));
1744        assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
1745        assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
1746    }
1747
1748    /// The length and the order of a string literal are known here.
1749    ///
1750    /// A program that asks for either of them is asking about something the translation already
1751    /// has in front of it, and folding is not only an optimization: `execute/921007-1.c` in the
1752    /// torture suite calls `__builtin_strcmp` in a file that defines its own `strcmp` with a
1753    /// different signature, so leaving the call behind is a name collision that gcc does not
1754    /// have. The comparison is over `unsigned char`, which is why the second one is negative.
1755    #[test]
1756    fn the_length_and_the_order_of_a_string_literal_are_known_here() {
1757        let text = ir(concat!(
1758            "unsigned long a = __builtin_strlen(\"hello\");\n",
1759            "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
1760            "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
1761            "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
1762            "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
1763        ));
1764        assert!(text.contains("global @a : i64 = 5,"), "{text}");
1765        assert!(text.contains("global @b : i64 = 1,"), "{text}");
1766        assert!(text.contains("global @c : i32 = 1,"), "{text}");
1767        assert!(text.contains("global @d : i32 = 0,"), "{text}");
1768        assert!(text.contains("global @e : i32 = 1,"), "{text}");
1769        assert!(!text.contains("call"), "{text}");
1770
1771        // An argument that is not a literal is the library's to answer, as it has to be.
1772        let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
1773        assert!(text.contains("call @strlen("), "{text}");
1774    }
1775
1776    /// A sign builtin is a mask over the bits, and is not a call.
1777    ///
1778    /// `fabs` and `copysign` are in the math library rather than the C one, so a program that
1779    /// only ever wrote the prefixed spelling never asked for `-lm` and a call left behind here
1780    /// would not link. Neither needs anything the library has: one clears the sign bit and the
1781    /// other takes it from the second operand, and every other bit goes through untouched.
1782    #[test]
1783    fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
1784        let text = body("double f(double x) { return __builtin_fabs(x); }\n");
1785        assert!(text.contains("bitcast.i64 %0"), "{text}");
1786        assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
1787        assert!(text.contains("and %1, %2"), "{text}");
1788        assert!(text.contains("bitcast.f64 %3"), "{text}");
1789        assert!(!text.contains("call"), "{text}");
1790
1791        let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
1792        assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
1793        assert!(text.contains("%8 = or %4, %7"), "{text}");
1794        assert!(!text.contains("call"), "{text}");
1795
1796        // The x87 format, whose value is eighty bits sitting in an object of sixteen. The mask is
1797        // as wide as the value and not as wide as the object, so the padding is not part of it.
1798        let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
1799        assert!(text.contains("bitcast.i80 %0"), "{text}");
1800        assert!(text.contains("bitcast.f80"), "{text}");
1801
1802        // The width a name does not spell out is `double`, so a `float` argument widens first and
1803        // the answer is a `double`, which is what gcc's declaration of it says.
1804        let text = body("double f(float x) { return __builtin_fabs(x); }\n");
1805        assert!(text.contains("fpext.f64 %0"), "{text}");
1806        assert!(text.contains("bitcast.i64 %1"), "{text}");
1807    }
1808
1809    /// The sign builtins answer a zero and a nan the way the bits say.
1810    ///
1811    /// This is why they are described over the bits rather than written with comparisons and
1812    /// negation. A negative zero compares equal to a positive one and has a sign bit to clear,
1813    /// and a nan compares equal to nothing at all and keeps its payload through both operations.
1814    /// `execute/ieee/copysign1.c` in the torture suite is the test that notices, because it
1815    /// compares its answers with `memcmp`. Every number here is what gcc 16 gives, the two in the
1816    /// x87 format measured on a machine that has it.
1817    #[test]
1818    fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
1819        let text = ir(concat!(
1820            "double a = __builtin_fabs(-3.5);\n",
1821            "double b = __builtin_copysign(1.0, -0.0);\n",
1822            "double c = __builtin_copysign(0.0, -2.0);\n",
1823            // The payload survives both, and only the sign bit moves.
1824            "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
1825            "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
1826            "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
1827            "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
1828            "long double i = __builtin_fabsl(-__builtin_infl());\n",
1829        ));
1830        assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
1831        assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
1832        assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
1833        assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
1834        assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
1835        assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
1836        assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
1837        assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1838    }
1839
1840    /// A `constexpr` object is a named constant, which is the whole reason the keyword exists.
1841    ///
1842    /// C23 6.6p8 puts two of them on the list an integer constant expression is built from: one
1843    /// of an arithmetic type, and a member of one of a structure or union type. A subscript of
1844    /// one is not on the list and is a variably modified type in gcc 16 as well, and every
1845    /// number here is what gcc 16 gives on x86-64.
1846    #[test]
1847    fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
1848        let text = ir(concat!(
1849            "constexpr int side = 4;\n",
1850            "constexpr int wider = side + 1;\n",
1851            "constexpr double half = 1.5;\n",
1852            "struct point { int x; int y; };\n",
1853            "constexpr struct point origin = { 5, 6 };\n",
1854            "int square[side * side];\n",
1855            "int rectangle[wider];\n",
1856            "int rounded[(int)half * 2];\n",
1857            "int across[origin.y];\n",
1858            "enum named { four = side };\n",
1859            "int e = four;\n",
1860        ));
1861        assert!(text.contains("global @square : bytes 64 ="), "{text}");
1862        assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
1863        assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
1864        assert!(text.contains("global @across : bytes 24 ="), "{text}");
1865        assert!(text.contains("global @e : i32 = 4,"), "{text}");
1866
1867        // A `const` object is not one of them, which is what makes `int a[n];` a variable
1868        // length array in C and is the distinction the keyword was added to draw.
1869        let mut opts = options();
1870        opts.emit = EmitKind::Ir;
1871        let konst = "const int n = 1;\nint a[n];\n";
1872        let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
1873        assert_eq!(run(&opts, konst).messages, [message]);
1874
1875        // Nor is a subscript of one, which gcc 16 refuses in the same words.
1876        let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
1877        assert_eq!(run(&opts, subscript).messages, [message]);
1878
1879        // And `constexpr` implies `const`, so the address of one is an address of a `const`.
1880        let address = "constexpr int c = 3;\nint *p = &c;\n";
1881        let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
1882             pointer target type [E0514]";
1883        assert_eq!(run(&opts, address).messages, [warning]);
1884    }
1885
1886    /// A definition that names its parameters and then declares them under the list.
1887    ///
1888    /// The declarations say what the types are, 6.9.1p6, and what the function takes is those
1889    /// types with the default argument promotions over them, which is what a caller of an
1890    /// unprototyped function hands over. A prototype already in scope overrules the promoted
1891    /// types, since a header saying `int narrow(char);` over a definition written this way is
1892    /// the pairing all the code written this way relies on and 6.7.6.3p15 is read that way by
1893    /// every compiler.
1894    #[test]
1895    fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
1896        // C17, since the default dialect is the one that warns about the form and this is
1897        // about what it means rather than about the warning.
1898        let mut opts = options();
1899        opts.std = Std::C17;
1900        let source = concat!(
1901            "int add(a, b)\n",
1902            "int a;\n",
1903            "int b;\n",
1904            "{ return a + b; }\n",
1905            "int promoted(c)\n",
1906            "char c;\n",
1907            "{ return c; }\n",
1908            "int narrow(char);\n",
1909            "int narrow(c)\n",
1910            "char c;\n",
1911            "{ return c; }\n",
1912            "int first(a)\n",
1913            "int a[4];\n",
1914            "{ return a[0]; }\n",
1915        );
1916        let result = run(&opts, source);
1917        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1918        let text = result.text();
1919        assert!(text.contains("add : int(int, int) function external defined"), "{text}");
1920        assert!(text.contains("promoted : int(int) function external defined"), "{text}");
1921        // The body still sees the `char` it was declared as, whatever the caller hands over.
1922        assert!(text.contains("c : char object automatic defined"), "{text}");
1923        assert!(text.contains("narrow : int(char) function external defined"), "{text}");
1924        // An array parameter is a pointer here as much as it is in a prototype.
1925        assert!(text.contains("first : int(int *) function external defined"), "{text}");
1926    }
1927
1928    /// What the two halves of an old-style parameter list can disagree about.
1929    ///
1930    /// Each of these is a sentence gcc 16 has, and every message below is the one it prints,
1931    /// read off it on x86-64 rather than reasoned about. The last two are the dialect: a name
1932    /// with no declaration is an `int` in C89 and a diagnostic from C99 on, and the whole form
1933    /// left the language in C23, where gcc still takes it and warns.
1934    #[test]
1935    fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
1936        let mut opts = options();
1937        opts.std = Std::C17;
1938        for (source, message) in [
1939            ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
1940            (
1941                "int f(a)\nint a;\nint b;\n{ return a; }\n",
1942                "3:5: error: declaration for parameter 'b' but no such parameter",
1943            ),
1944            ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
1945            ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
1946            (
1947                "int f(a)\nstatic int a;\n{ return a; }\n",
1948                "2:12: error: storage class specified for parameter 'a'",
1949            ),
1950            (
1951                "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
1952                "2:7: error: argument 'a' doesn't match prototype",
1953            ),
1954        ] {
1955            let result = run(&opts, source);
1956            assert!(result.failed(), "expected this to fail:\n{source}");
1957            assert!(result.messages[0].contains(message), "{:?}", result.messages);
1958        }
1959
1960        // A name the declarations never mention. C89 gave it an `int` and gcc still takes it
1961        // in that dialect, and every dialect after it made the same line a diagnostic.
1962        let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
1963        let mut older = options();
1964        older.std = Std::C89;
1965        assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
1966        let result = run(&opts, implicit);
1967        assert!(
1968            result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
1969            "{:?}",
1970            result.messages
1971        );
1972
1973        // C23 took the form out of the language and gcc kept accepting it with a warning, and
1974        // a warning is what this is, because the code written this way is not going to be
1975        // rewritten and refusing it would put the compiler out of reach of it.
1976        let mut newer = options();
1977        newer.std = Std::C23;
1978        let plain = "int f(a)\nint a;\n{ return a; }\n";
1979        let result = run(&newer, plain);
1980        assert!(!result.failed(), "{:?}", result.messages);
1981        assert_eq!(
1982            result.messages,
1983            ["/main.c:1:5: warning: old-style function definition [E0412]"]
1984        );
1985        assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
1986    }
1987
1988    /// A type nothing is ever an object of is a type `sizeof` still has to answer about, which
1989    /// is what `991014-1.c` in the gcc.c-torture execution suite asks.
1990    ///
1991    /// The limit is `PTRDIFF_MAX` and it is the same one for an array and for a record, so a
1992    /// record of every byte an object may have is laid out and one byte more is refused. All
1993    /// four numbers are what gcc 16 gives on x86-64.
1994    #[test]
1995    fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
1996        let text = ir(concat!(
1997            "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
1998            "struct brim { char buf[9223372036854775807L]; };\n",
1999            "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
2000            "unsigned long h = sizeof(struct huge_struct);\n",
2001            "unsigned long b = sizeof(struct brim);\n",
2002            "unsigned long y = sizeof(struct bitty);\n",
2003        ));
2004        assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
2005        assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
2006        assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
2007
2008        let mut opts = options();
2009        opts.emit = EmitKind::Ir;
2010        let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
2011        let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
2012        assert_eq!(run(&opts, over).messages, [message]);
2013        let array = "struct wide { short buf[1L << 62]; };\n";
2014        let message = "/main.c:1:25: error: size of array 'buf' exceeds \
2015             maximum object size '9223372036854775807' [E0537]";
2016        assert_eq!(run(&opts, array).messages[0], message);
2017    }
2018
2019    /// A byte in the source that is not part of a character, which only a literal may hold.
2020    ///
2021    /// The source cannot be a `&str` here, which is the whole point: a file is bytes and only
2022    /// mostly text.
2023    fn compile_bytes(source: &[u8]) -> Compiled {
2024        let mut opts = options();
2025        opts.emit = EmitKind::Ir;
2026        let mut fs = MemoryFileSystem::new();
2027        fs.insert("/main.c", source.to_vec());
2028        compile(&opts, "/main.c", &fs)
2029    }
2030
2031    /// A raw byte inside a string literal is that byte, which gcc has always taken and which is
2032    /// the only place in a source file where a byte does not have to be part of a character.
2033    /// Replacing it would give the object three bytes rather than one, since the replacement
2034    /// character is three bytes of UTF-8, so the object would not be the one that was written
2035    /// even where the diagnostic is ignored. Anywhere else the byte is still a mistake, which
2036    /// is where gcc draws the same line.
2037    #[test]
2038    fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
2039        let mut source = b"char s[] = \"a".to_vec();
2040        source.push(0xff);
2041        source.extend_from_slice(b"b\";\nchar c = '");
2042        source.push(0xff);
2043        source.extend_from_slice(b"';\n");
2044        let result = compile_bytes(&source);
2045        assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
2046        assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
2047        // Plain `char` is signed on this target, so the constant is minus one rather than 255.
2048        assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
2049
2050        let mut stray = b"int a".to_vec();
2051        stray.push(0xff);
2052        stray.extend_from_slice(b" = 1;\n");
2053        let result = compile_bytes(&stray);
2054        assert!(
2055            result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
2056            "{:?}",
2057            result.messages
2058        );
2059    }
2060
2061    #[test]
2062    fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
2063        let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
2064        assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
2065        let expected = "\
2066func @add(i32, i32) -> i32, linkage(external) {
2067block0(%0: i32, %1: i32):
2068    %2 = add.nsw %0, %1
2069    return %2
2070}
2071";
2072        assert!(text.contains(expected), "{text}");
2073    }
2074
2075    #[test]
2076    fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
2077        let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
2078        assert!(!text.contains("alloca"), "{text}");
2079        assert!(!text.contains("load"), "{text}");
2080        assert!(!text.contains("store"), "{text}");
2081    }
2082
2083    #[test]
2084    fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
2085        let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
2086        let expected = "\
2087block0:
2088    %0 = alloca, size 4, align 4
2089    %1 = iconst.i32 1
2090    store %1 -> %0, align 4
2091    %2 = call @g(%0) : (ptr) -> i32
2092    return %2
2093";
2094        assert_eq!(text, expected);
2095    }
2096
2097    #[test]
2098    fn a_loop_carries_what_it_changes_as_block_parameters() {
2099        // The whole point of building SSA during the walk rather than after it: `i` and
2100        // `total` are values that arrive on an edge, and neither has ever been in memory.
2101        let text = body(
2102            "int f(int n) {\n  int total = 0;\n  for (int i = 0; i < n; i++) total += i;\n  \
2103             return total;\n}\n",
2104        );
2105        assert!(!text.contains("alloca"), "{text}");
2106        assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
2107        assert!(text.contains("jump block1("), "{text}");
2108    }
2109
2110    #[test]
2111    fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
2112        let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
2113        assert!(text.contains("icmp slt %0, %1"), "{text}");
2114        assert!(!text.contains("zext"), "{text}");
2115    }
2116
2117    #[test]
2118    fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
2119        let text = body("int f(int a, int b) { return a && b; }\n");
2120        let expected = "\
2121block0(%0: i32, %1: i32):
2122    %2 = iconst.i32 0
2123    %3 = icmp ne %0, %2
2124    %4 = iconst.i1 0
2125    br_if %3, block1, block2(%4)
2126
2127block1:
2128    %5 = iconst.i32 0
2129    %6 = icmp ne %1, %5
2130    jump block2(%6)
2131
2132block2(%7: i1):
2133    %8 = zext.i32 %7
2134    return %8
2135";
2136        assert_eq!(text, expected);
2137    }
2138
2139    #[test]
2140    fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
2141        let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
2142        // Three blocks, the test and the two arms. The join the `return 3` would need is
2143        // never created, because a block nothing branches to is not a block.
2144        assert!(!text.contains("block3"), "{text}");
2145        assert!(!text.contains("iconst.i32 3"), "{text}");
2146    }
2147
2148    #[test]
2149    fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
2150        assert!(body("int main(void) { }\n").contains("iconst.i32 0\n    return"));
2151        assert_eq!(body("void f(void) { }\n"), "block0:\n    return\n");
2152        assert!(body("int f(void) { }\n").contains("unreachable"));
2153    }
2154
2155    #[test]
2156    fn a_structure_is_copied_rather_than_held_in_a_value() {
2157        let text = body(
2158            "struct point { int x, y; };\n\
2159             int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
2160        );
2161        assert!(text.contains("memcpy"), "{text}");
2162    }
2163
2164    #[test]
2165    fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
2166        let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
2167        assert!(text.contains("memset"), "{text}");
2168    }
2169
2170    #[test]
2171    fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
2172        let text = body(
2173            "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
2174             default: r = 4; } return r; }\n",
2175        );
2176        let expected = "\
2177block0(%0: i32):
2178    %1 = iconst.i32 0
2179    switch %0, block1, [1 => block2, 2 => block3(%1)]
2180
2181block1:
2182    %2 = iconst.i32 4
2183    jump block4(%2)
2184
2185block2:
2186    %3 = iconst.i32 1
2187    jump block3(%3)
2188
2189block3(%4: i32):
2190    %5 = iconst.i32 2
2191    %6 = add.nsw %4, %5
2192    jump block4(%6)
2193
2194block4(%7: i32):
2195    return %7
2196";
2197        assert_eq!(text, expected);
2198    }
2199
2200    #[test]
2201    fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
2202        // GNU's `case 1 ... 9`. Nine table entries would be nine here and four billion for the
2203        // range a program is allowed to write, so it is a subtraction and one unsigned compare.
2204        let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
2205        assert!(text.contains("%2 = sub %0, %1"), "{text}");
2206        assert!(text.contains("icmp ule"), "{text}");
2207        assert!(!text.contains("switch"), "{text}");
2208    }
2209
2210    #[test]
2211    fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
2212        let text = body(
2213            "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
2214             case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
2215        );
2216        // The `continue` goes to the step and the `break` goes to the `t++` after the switch,
2217        // which is also where the default falls out to.
2218        assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
2219        assert!(text.contains("block5:\n    jump block7("), "{text}");
2220        assert!(text.contains("block6:\n    jump block8("), "{text}");
2221    }
2222
2223    #[test]
2224    fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
2225        assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n    return\n");
2226    }
2227
2228    #[test]
2229    fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
2230        // A branch into the middle of a loop that nothing else reaches, the Duff's device shape.
2231        // The `while` is not reached in order, so the walk starts a block nothing branches to and
2232        // builds it from there. What comes out is the loop with an edge straight into its body,
2233        // and the header that nothing arrives at is pruned.
2234        let text = body(
2235            "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
2236             return n; }\n",
2237        );
2238        // `case 2` lands on the body, `case 1` and the default land on the return, and the test
2239        // at the bottom of the loop comes back round to the body.
2240        assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
2241        assert!(text.contains("block3(%3: i32):\n    %4 = iconst.i32 1"), "{text}");
2242        assert!(text.contains("block5:\n    jump block3("), "{text}");
2243    }
2244
2245    #[test]
2246    fn a_goto_into_a_loop_body_enters_it_without_the_test() {
2247        // The same thing through a `goto`. The first pass through the body runs whatever the
2248        // label is on, and only then does the loop reach its own test.
2249        let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
2250        assert!(text.starts_with("block0(%0: i32, %1: i32):\n    jump block1(%1)"), "{text}");
2251        assert!(text.contains("block1(%2: i32):\n    %3 = iconst.i32 1"), "{text}");
2252        assert!(text.contains("br_if %7, block3, block4"), "{text}");
2253    }
2254
2255    #[test]
2256    fn a_goto_is_a_jump_to_the_block_the_label_starts() {
2257        let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
2258        // Both edges into `out` carry what `r` holds on the way, and neither is a stack slot.
2259        assert!(!text.contains("alloca"), "{text}");
2260        assert!(text.contains("block3(%4: i32):\n    return %4"), "{text}");
2261        assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
2262    }
2263
2264    #[test]
2265    fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
2266        let text =
2267            body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
2268        assert!(!text.contains("alloca"), "{text}");
2269        assert!(text.contains("block1(%2: i32):"), "{text}");
2270        assert!(text.contains("jump block1(%5)"), "{text}");
2271    }
2272
2273    #[test]
2274    fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
2275        // A block nothing branches to is not a legal function, and which labels are dead is not
2276        // known until the last statement has been walked, since the `goto` is allowed to be it.
2277        assert_eq!(
2278            body("int f(int x) { return x; spare: return 0; }\n"),
2279            "block0(%0: i32):\n    return %0\n"
2280        );
2281    }
2282
2283    #[test]
2284    fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
2285        let text = body(
2286            "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
2287        );
2288        // One byte holds both fields, and the signed one needs no mask: shifting it down
2289        // arithmetically is what says its top bit is a sign.
2290        assert_eq!(
2291            text,
2292            "\
2293block0(%0: ptr):
2294    %1 = load.i8 %0, align 1
2295    %2 = iconst.i8 3
2296    %3 = ashr %1, %2
2297    %4 = sext.i32 %3
2298    return %4
2299"
2300        );
2301    }
2302
2303    #[test]
2304    fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
2305        // C11 says an ordinary member beside a bit-field is a memory location of its own, so
2306        // the four byte store this would take is a data race in a program that has none. The
2307        // three bytes of `a` go in as two and one, and `c` is not touched.
2308        let text =
2309            body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
2310        assert_eq!(
2311            text,
2312            "\
2313block0(%0: ptr, %1: i32):
2314    %2 = iconst.i32 16777215
2315    %3 = and %1, %2
2316    %4 = trunc.i16 %3
2317    store %4 -> %0, align 2
2318    %5 = iconst.i32 16
2319    %6 = lshr %3, %5
2320    %7 = trunc.i8 %6
2321    %8 = iconst.i64 2
2322    %9 = ptr_add %0, %8
2323    store %7 -> %9, align 1
2324    return
2325"
2326        );
2327    }
2328
2329    #[test]
2330    fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
2331        let text =
2332            body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
2333        // 33 does not fit in five bits, and 1 is both what goes in the field and what the
2334        // assignment is worth.
2335        assert!(text.contains("%3 = iconst.i8 31\n    %4 = and %2, %3"), "{text}");
2336        assert!(text.ends_with("%9 = zext.i32 %4\n    return %9\n"), "{text}");
2337    }
2338
2339    #[test]
2340    fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
2341        // The value of an assignment to a bit-field takes a shift to build, and a statement
2342        // has no use for it. Nothing here reads back what was stored.
2343        let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
2344        assert_eq!(text.matches("ashr").count(), 0, "{text}");
2345        assert!(text.ends_with("store %8 -> %0, align 1\n    return\n"), "{text}");
2346    }
2347
2348    #[test]
2349    fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
2350        // A bit-field writes part of a byte and leaves the rest of it alone, so the object has
2351        // to be zero before it goes in or what the initializer did not name is whatever the
2352        // stack held.
2353        let text = body(
2354            "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
2355        );
2356        assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
2357    }
2358
2359    #[test]
2360    fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
2361        // Two fields in one byte are not two entries in the image, because an image is written
2362        // in bytes: they are the byte they are both in.
2363        let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
2364        assert!(
2365            text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
2366            "{text}"
2367        );
2368    }
2369
2370    #[test]
2371    fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
2372        // `sizeof` answers without the array and the definition has to hold what was written, so
2373        // the object is the size of its image. gcc 16 gives these four, three and two bytes and
2374        // so does this. The image used to be written at the size the type had, which left the
2375        // verifier looking at twenty bytes going into four.
2376        let text = ir(concat!(
2377            "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
2378            "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
2379            "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
2380            "char s[2] = \"hi\";\n",
2381        ));
2382        assert!(
2383            text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
2384            "{text}"
2385        );
2386        assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
2387        assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
2388        // The array with a length of its own still cuts the literal down to it, which is the
2389        // one case in C where a string initializer drops its terminator.
2390        assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
2391    }
2392
2393    #[test]
2394    fn a_definition_takes_a_parameter_it_left_unnamed() {
2395        // The entry block's parameters are the definition's, and one the front end dropped for
2396        // having no name left the two lists different lengths, which the walk read as an
2397        // old-style definition and refused. gcc has taken these for far longer than C23 has.
2398        let text = ir("int f(int a, int) { return a; }\n");
2399        assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
2400        assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
2401
2402        // The unnamed one first, so that the named one is the second parameter of the entry
2403        // block and not the first: the list says the order and not only how many there are.
2404        let text = ir("int g(int, int n) { return n; }\n");
2405        assert!(text.contains("block0(%0: i32, %1: i32):\n    return %1\n"), "{text}");
2406    }
2407
2408    #[test]
2409    fn an_assignment_of_a_structure_is_the_object_it_wrote() {
2410        // `d = e = c` used to be refused, because the middle assignment is a value of structure
2411        // type and the walk had nowhere to read one from. What an assignment is worth is the
2412        // value it stored, so the object it stored into is the answer and the chain is three
2413        // copies out of the one source with no temporary in it.
2414        let text = body(concat!(
2415            "struct s { int f; int g; };\n",
2416            "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
2417            "{ *d = *e = a[0] = *c; }\n",
2418        ));
2419        assert_eq!(text.matches("memcpy").count(), 3, "{text}");
2420        assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
2421        assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
2422        assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
2423    }
2424
2425    #[test]
2426    fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
2427        // The excess used to be laid into the object anyway, so the row after was written over
2428        // and the image refused the entry that came to it. C 6.7.10p14 says the terminator goes
2429        // in only if there is room for it, and gcc discards the rest of a literal that is longer
2430        // still, which is what the first of these is and why it warns.
2431        let mut opts = options();
2432        opts.emit = EmitKind::Ir;
2433        let result = run(
2434            &opts,
2435            concat!(
2436                "const char a[2][3] = { \"1234\", \"xyz\" };\n",
2437                "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
2438                "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
2439                "const union u c = { { \"1234\", \"567\" } };\n",
2440            ),
2441        );
2442        let text = result.text();
2443        assert_eq!(
2444            result.messages,
2445            ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
2446              (5 chars into 3 available) [E0637]"]
2447        );
2448        assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
2449        assert!(
2450            text.contains(
2451                "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
2452                 bytes \"9\\00\", zero 3 }"
2453            ),
2454            "{text}"
2455        );
2456        // The eight bytes are four, three and a terminator, and then the byte the shorter
2457        // literal left for the string in the other member of the union to end at.
2458        assert!(
2459            text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
2460            "{text}"
2461        );
2462    }
2463
2464    #[test]
2465    fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
2466        // gcc accepts one and does nothing with it, which sema already had. Lowering asked for
2467        // the object under it and had no arm for a cast, so `(struct s)x` in an initializer was
2468        // refused with E0519. It is one copy out of the object named, not two.
2469        let text = body(concat!(
2470            "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
2471            "void g(struct v *);\n",
2472            "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
2473        ));
2474        assert_eq!(text.matches("memcpy").count(), 1, "{text}");
2475    }
2476
2477    #[test]
2478    fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
2479        // C 6.7.11p4 says a compound literal at file scope has static storage duration, which
2480        // makes it a constant element, and tcc and c-testsuite both write one. Sema used to call
2481        // it a non constant because reading it is a node of its own and the read was what it
2482        // looked at, and lowering had no way to put an object where it wanted a number.
2483        let text = ir(concat!(
2484            "struct s { int x; };\n",
2485            "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2486            "int n = (int){ 7 };\n",
2487            "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2488        ));
2489        assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2490        assert!(text.contains("global @n : i32 = 7,"), "{text}");
2491        // The second literal names nothing, so what it puts in is the zeros of its own size and
2492        // not the tail of the object it went in, which would have been the same bytes by luck.
2493        assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2494    }
2495
2496    #[test]
2497    fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2498        // Nothing declares a compound literal, so the reference is the only thing that can ask
2499        // for it to be emitted. The image named `.Lanon.0` and the module defined no such
2500        // symbol, which the link would have been the first to find out.
2501        let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2502        assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2503        assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2504    }
2505
2506    #[test]
2507    fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2508        // A zero length array, which gcc allows and real code uses as the tail of a structure.
2509        // The image is there and holds nothing, which is not the global that has no image at
2510        // all, and the IR reader used to stop on the empty one.
2511        let text = ir("unsigned char foo[1][0];\n");
2512        assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2513    }
2514
2515    #[test]
2516    fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2517        // `NULL` in a static initializer, which every program has. The IR type is `ptr` and a
2518        // `ptr` has no width of its own, so the width the bits are cut to is the target's.
2519        let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2520        assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2521        assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2522    }
2523
2524    #[test]
2525    fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2526        // Which the verifier used to refuse, having read a declaration as a definition with
2527        // nothing in it. `extern const` is how a program names something in the library's read
2528        // only data, and glibc and Darwin both have one in a header a real program includes.
2529        let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2530        assert!(
2531            text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2532            "{text}"
2533        );
2534    }
2535
2536    #[test]
2537    fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2538        // A structure is not a value in the IR, so the two arms cannot be joined as one. The
2539        // addresses can, and the answer is the address of whichever arm was taken rather than
2540        // a copy of it into a third place: both arms outlive the expression, so a copy would
2541        // be one nothing could observe. SQLite's parser writes one of these.
2542        let text = body(
2543            "\
2544struct s { int a, b; };
2545struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2546",
2547        );
2548        // The join takes an address, each arm hands it the one it has, and nothing is copied.
2549        assert!(text.contains("block3(%7: ptr)"), "{text}");
2550        assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2551        assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2552    }
2553
2554    #[test]
2555    fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2556        // `struct pair` is two eightbytes on SysV, one of them integer, so the signature says
2557        // one `i64` in each direction and the body takes the object apart and puts it back
2558        // together around the call.
2559        let text = ir("\
2560struct pair { int a, b; };
2561struct pair make(int a, int b);
2562struct pair twice(struct pair p) { return make(p.a, p.b); }
2563");
2564        assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2565        assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2566    }
2567
2568    #[test]
2569    fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2570        // Over two eightbytes the caller passes the bytes in the argument area, which is
2571        // `byval`, and passes somewhere to write the return value, which is `sret`. Neither is
2572        // a parameter the program wrote and both are parameters the function has.
2573        let text = ir("\
2574struct big { double v[8]; };
2575struct big grow(struct big b);
2576struct big twice(struct big b) { return grow(grow(b)); }
2577");
2578        assert!(
2579            text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2580            "{text}"
2581        );
2582        assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2583        // The inner call writes into a slot and the outer one reads the same slot, so the
2584        // object between the two calls is never copied anywhere.
2585        assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2586    }
2587
2588    #[test]
2589    fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
2590        // The bytes travel in the argument area the same way they would for a parameter, and
2591        // `printf` has no parameter there to say it on, so the call says it instead. The one
2592        // that fits in registers says nothing, because travelling as the registers it fits in
2593        // is what an argument does when nothing says otherwise.
2594        let text = ir("\
2595struct big { double v[8]; };
2596struct pair { int a, b; };
2597int p(const char *, ...);
2598int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
2599");
2600        assert!(
2601            text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
2602            "{text}"
2603        );
2604    }
2605
2606    #[test]
2607    fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
2608        // `make(1, 2).b` has no object to read a member of until one is made, and what makes it
2609        // is a slot the returned registers are written to.
2610        let body = body(
2611            "\
2612struct pair { int a, b; };
2613struct pair make(int a, int b);
2614int second(void) { return make(1, 2).b; }
2615",
2616        );
2617        assert!(body.starts_with("block0:\n    %0 = alloca, size 8, align 4\n"), "{body}");
2618        assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
2619    }
2620
2621    #[test]
2622    fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
2623        // The same declaration, classified by a different ABI: three `float` members are an
2624        // eightbyte of two of them and a half eightbyte of the third on SysV, and three vector
2625        // registers on AAPCS64.
2626        let source = "\
2627struct hfa { float x, y, z; };
2628int take(struct hfa h);
2629int give(struct hfa h) { return take(h); }
2630";
2631        assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
2632        let mut opts = options();
2633        opts.emit = EmitKind::Ir;
2634        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
2635        let result = run(&opts, source);
2636        assert_eq!(result.messages, Vec::<String>::new());
2637        assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
2638    }
2639
2640    #[test]
2641    fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
2642        // The size is a multiplication rather than a number, the slot is taken from the stack
2643        // where the declaration is, and the scope it was declared in gives it back.
2644        let source = "\
2645int use(int *);
2646void f(int n) {
2647  {
2648    int a[n];
2649    use(a);
2650  }
2651  use(0);
2652}
2653";
2654        let body = body(source);
2655        assert!(body.contains("mul.nsw"), "{body}");
2656        assert!(body.contains("stacksave"), "{body}");
2657        assert!(body.contains("alloca %"), "{body}");
2658        assert!(body.contains("stackrestore"), "{body}");
2659    }
2660
2661    #[test]
2662    fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
2663        // The label is outside the block the array is in, so arriving there means the array is
2664        // gone, and the restore that says so goes in front of the branch. The `goto` is written
2665        // before the walk knows where the label is, which is why the restore is put there at
2666        // the end rather than built where the branch was.
2667        let source = "\
2668int use(int *);
2669int f(int n) {
2670  {
2671    int a[n];
2672    if (use(a)) goto out;
2673    use(0);
2674  }
2675out:
2676  return 0;
2677}
2678";
2679        let body = body(source);
2680        // Two ways out of the block and a restore on each: the jump and the end of the block.
2681        assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
2682        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2683        assert!(after.starts_with(" %4\n    jump block"), "{body}");
2684    }
2685
2686    #[test]
2687    fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
2688        // The label is after the declaration and in the same block, so control that arrives
2689        // there arrives somewhere the array exists. Giving it back would be giving back an
2690        // object the next statement reads.
2691        let source = "\
2692int use(int *);
2693int f(int n) {
2694  int a[n];
2695again:
2696  if (use(a)) goto again;
2697  return 0;
2698}
2699";
2700        let body = body(source);
2701        assert!(body.contains("stacksave"), "{body}");
2702        assert!(!body.contains("stackrestore"), "{body}");
2703    }
2704
2705    #[test]
2706    fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
2707        // A loop written out of a `goto`, with the array made inside it. The label is in the
2708        // same block as the declaration and before it, which is a place where the array does
2709        // not exist yet, so the jump there leaves its scope and has to give the stack back. A
2710        // compiler that skips this restore grows the stack once per iteration.
2711        let source = "\
2712int use(int *);
2713int f(int n) {
2714again:
2715  {
2716    int a[n];
2717    if (use(a)) goto again;
2718  }
2719  return 0;
2720}
2721";
2722        let body = body(source);
2723        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2724        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2725        assert!(after.starts_with(" %4\n    jump block1\n"), "{body}");
2726    }
2727
2728    #[test]
2729    fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
2730        // The scope opened for `for (int a[n];;)` used to stay open, and a scope left open is
2731        // not one mark nobody reads. The marks are a stack, so the next close took this one
2732        // instead of its own, and the body of the loop gave back nothing while the block after
2733        // the loop restored a pointer saved inside it. The verifier refused that, which is how
2734        // it was found.
2735        let source = "\
2736int f(void);
2737void t(void) {
2738  int count = 10;
2739  for (; count--;) {
2740    int b[f()];
2741    int i;
2742    for (i = 0; i < f(); i++) {
2743      b[i] = count;
2744    }
2745  }
2746}
2747";
2748        let body = body(source);
2749        // One save, in the body, and one restore for it, also in the body: the block the
2750        // restore is in is the one the inner loop leaves through, and it goes back round the
2751        // outer loop rather than out of it.
2752        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2753        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2754        let (next, _) = after.split_once("\n\n").expect("a block after the restore");
2755        assert!(next.contains("jump block1("), "{body}");
2756    }
2757
2758    #[test]
2759    fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
2760        // What C says about the length being evaluated once: `sizeof a` after `n` changed is
2761        // still as long as the array is, which is what `n` was when the array came into being.
2762        let source = "\
2763unsigned long f(int n) {
2764  int a[n];
2765  n = 0;
2766  return sizeof a;
2767}
2768";
2769        let body = body(source);
2770        // One read of the parameter, at the declaration, and the answer is built out of it.
2771        assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
2772    }
2773
2774    #[test]
2775    fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
2776        // GNU's statement expression: the statements happen where they are written and the last
2777        // one is the value, so the temporary in it never becomes a slot and never is copied.
2778        let source = "\
2779int use(int);
2780int f(int x) {
2781  return ({
2782    int t = use(x);
2783    t * t;
2784  });
2785}
2786";
2787        let expected = "\
2788block0(%0: i32):
2789    %1 = call @use(%0) : (i32) -> i32
2790    %2 = mul.nsw %1, %1
2791    return %2
2792";
2793        assert_eq!(body(source), expected);
2794    }
2795
2796    #[test]
2797    fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
2798        // A macro that always jumps, which is what this shape is in real code. The value is
2799        // never taken, and the block the rest of the expression would have been built in is
2800        // one nothing branches to, so it goes with the other unreachable blocks.
2801        let source = "int f(int x) { return ({ return x; 0; }); }\n";
2802        assert_eq!(body(source), "block0(%0: i32):\n    return %0\n");
2803    }
2804
2805    #[test]
2806    fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
2807        // What it becomes is the target's answer, and this is not where the target's answers
2808        // are, so the walk writes down which list and which type and leaves it at that. Two of
2809        // them are two instructions, since each moves the list on.
2810        let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
2811        let expected = "\
2812block0(%0: ptr):
2813    %1 = va_arg.f64 %0
2814    %2 = va_arg.f64 %0
2815    %3 = fadd %1, %2
2816    return %3
2817";
2818        assert_eq!(body(source), expected);
2819    }
2820
2821    #[test]
2822    fn one_that_reads_a_structure_answers_where_the_object_is() {
2823        // An aggregate is not a value, so there is nothing for the result of `va_arg` to be and
2824        // the object form is a second instruction. What it answers is an address, so it is a
2825        // place already and the walk copies nothing out of it: the copy here is the one the
2826        // initializer asks for, into the variable being declared. The size and the alignment
2827        // travel with it because they are what steps the list on and what a target that has to
2828        // put registers somewhere needs to know.
2829        let source = "\
2830struct s { int a; long b; };
2831long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
2832";
2833        let expected = "\
2834block0(%0: ptr):
2835    %1 = alloca, size 16, align 8
2836    %2 = va_object %0, size 16, align 8
2837    memcpy %1, %2, size 16, align 8
2838    %3 = iconst.i64 8
2839    %4 = ptr_add %1, %3
2840    %5 = load.i64 %4, align 8
2841    return %5
2842";
2843        assert_eq!(body(source), expected);
2844    }
2845
2846    #[test]
2847    fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
2848        // GNU's computed goto. Which label the address holds is not known here, so all of them
2849        // are listed, and the values arriving at one are passed on every edge the same way they
2850        // are on an ordinary branch.
2851        let source = "\
2852int f(int c) {
2853  void *p = c ? &&one : &&two;
2854  goto *p;
2855one:
2856  return 1;
2857two:
2858  return 2;
2859}
2860";
2861        let expected = "\
2862block0(%0: i32):
2863    %1 = iconst.i32 0
2864    %2 = icmp ne %0, %1
2865    br_if %2, block1, block2
2866
2867block1:
2868    %3 = block_addr block3
2869    jump block4(%3)
2870
2871block2:
2872    %4 = block_addr block5
2873    jump block4(%4)
2874
2875block3:
2876    %5 = iconst.i32 1
2877    return %5
2878
2879block4(%6: ptr):
2880    indirect_br %6, block3, block5
2881
2882block5:
2883    %7 = iconst.i32 2
2884    return %7
2885";
2886        assert_eq!(body(source), expected);
2887    }
2888
2889    #[test]
2890    fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
2891        // The address came from outside the function, and a jump to a label in another function
2892        // is undefined. The expression is still evaluated, since a call in it has to happen.
2893        let source = "void **next(void);
2894void f(void) { goto *next(); }
2895";
2896        let expected = "\
2897block0:
2898    %0 = call @next() : () -> ptr
2899    unreachable
2900";
2901        assert_eq!(body(source), expected);
2902    }
2903
2904    #[test]
2905    fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
2906        // Nothing reads a result, so the only thing that keeps it is that it is volatile, which
2907        // a basic asm implies.
2908        let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
2909        let expected = "\
2910block0:
2911    inline_asm.volatile \"mfence\", \"\", \"memory\"()
2912    return
2913";
2914        assert_eq!(body(source), expected);
2915    }
2916
2917    #[test]
2918    fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
2919        // The outputs first and then the inputs, which is the numbering `%0` and `%1` use. An
2920        // output in a register is a result, and one that is read as well is an argument too.
2921        let source = "\
2922int f(int x, int y) {
2923  int r;
2924  __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
2925  return r + y;
2926}
2927";
2928        let expected = "\
2929block0(%0: i32, %1: i32):
2930    %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
2931    %4 = add.nsw %2, %3
2932    return %4
2933";
2934        assert_eq!(body(source), expected);
2935    }
2936
2937    #[test]
2938    fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
2939        // The assembly is handed a pointer, so the object cannot live in a value, and the scan
2940        // that runs before the walk has to have known that or there would be nothing to point
2941        // at. A structure travels this way whatever else its constraint allows, since there is
2942        // no register that holds one.
2943        let source = "\
2944struct pair { int a, b; };
2945int f(int x) {
2946  int slot = x;
2947  struct pair p = { x, x };
2948  __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
2949  return slot + p.a;
2950}
2951";
2952        let text = body(source);
2953        assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
2954        assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
2955        assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
2956    }
2957
2958    #[test]
2959    fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
2960        // The output is only in scope where the instruction dominates, which is the fall through
2961        // block, so the edge to the label carries the value the object had before the assembly
2962        // ran. That is what document 11 asks for and it is what putting the fall through first
2963        // buys.
2964        let source = "\
2965int f(int x) {
2966  int r = 7;
2967  __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
2968  return r;
2969away:
2970  return r;
2971}
2972";
2973        let expected = "\
2974block0(%0: i32):
2975    %1 = iconst.i32 7
2976    %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
2977
2978block1:
2979    return %2
2980
2981block2:
2982    return %1
2983";
2984        assert_eq!(body(source), expected);
2985    }
2986
2987    #[test]
2988    fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
2989        // The operands are checked here rather than by the assembler, because by the time the
2990        // assembler sees the template the operands have become registers and it has nothing left
2991        // to say about the C that named them.
2992        let mut opts = options();
2993        opts.emit = EmitKind::Ir;
2994        for (source, expected) in [
2995            (
2996                "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
2997                "output operand constraint lacks '='",
2998            ),
2999            (
3000                "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
3001                "lvalue required in 'asm' statement",
3002            ),
3003            (
3004                "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
3005                "read-only variable 'g' used as 'asm' output",
3006            ),
3007            (
3008                "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
3009                "input operand constraint contains '='",
3010            ),
3011            (
3012                "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
3013                "memory input 0 is not directly addressable",
3014            ),
3015            ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
3016            (
3017                "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
3018                "duplicate asm operand name 'a'",
3019            ),
3020            ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
3021        ] {
3022            let result = run(&opts, source);
3023            assert!(result.failed(), "expected this to be reported:\n{source}");
3024            assert!(
3025                result.messages.iter().any(|m| m.contains(expected)),
3026                "{expected}\n{:?}",
3027                result.messages
3028            );
3029        }
3030    }
3031
3032    #[test]
3033    fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
3034        let mut opts = options();
3035        opts.emit = EmitKind::Ir;
3036        for source in [
3037            "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
3038            "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
3039        ] {
3040            let result = run(&opts, source);
3041            assert!(result.failed(), "expected this to be reported:\n{source}");
3042            assert!(
3043                result.messages.iter().any(|m| m.contains("not supported yet")),
3044                "{:?}",
3045                result.messages
3046            );
3047        }
3048    }
3049
3050    /// Compiles `source` to IR, reads that back as an input, and gives back both texts.
3051    fn round_trip(source: &str) -> (String, String) {
3052        let printed = ir(source);
3053        let mut opts = options();
3054        opts.emit = EmitKind::Ir;
3055        let mut fs = MemoryFileSystem::new();
3056        fs.insert("/main.ir", printed.clone().into_bytes());
3057        let result = compile_ir(&opts, "/main.ir", &fs);
3058        assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
3059        (printed, result.text().to_owned())
3060    }
3061
3062    #[test]
3063    fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
3064        // The other half of the round trip test below, through the driver rather than through
3065        // the library, which is what makes the property something to run over a real program
3066        // rather than over the modules a test builds.
3067        let (printed, again) = round_trip(
3068            "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",
3069        );
3070        assert_eq!(printed, again);
3071    }
3072
3073    #[test]
3074    fn ir_that_is_not_ir_says_which_line_stopped_it() {
3075        let mut opts = options();
3076        opts.emit = EmitKind::Ir;
3077        let mut fs = MemoryFileSystem::new();
3078        let text = "\
3079; ModuleID = 'a.c'
3080; format 0
3081target triple = \"x86_64-unknown-linux-gnu\"
3082target datalayout = \"e-p:64:64-i64:64-S128\"
3083
3084func @f(), linkage(external) {
3085block0:
3086    frobnicate
3087}
3088";
3089        fs.insert("/main.ir", text.as_bytes().to_vec());
3090        let result = compile_ir(&opts, "/main.ir", &fs);
3091        assert!(result.failed());
3092        assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
3093    }
3094
3095    #[test]
3096    fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
3097        // A module that a person edited has not been through the verifier, and the return of
3098        // an `i32` from a function that returns nothing is the kind of thing editing produces.
3099        let mut opts = options();
3100        opts.emit = EmitKind::Ir;
3101        let mut fs = MemoryFileSystem::new();
3102        let text = "\
3103; ModuleID = 'a.c'
3104; format 0
3105target triple = \"x86_64-unknown-linux-gnu\"
3106target datalayout = \"e-p:64:64-i64:64-S128\"
3107
3108func @f(), linkage(external) {
3109block0:
3110    %0 = iconst.i32 1
3111    return %0
3112}
3113";
3114        fs.insert("/main.ir", text.as_bytes().to_vec());
3115        let result = compile_ir(&opts, "/main.ir", &fs);
3116        assert!(result.failed());
3117        assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
3118    }
3119
3120    #[test]
3121    fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
3122        // The C that became this is not here any more, so there is nothing to print a tree of.
3123        let mut fs = MemoryFileSystem::new();
3124        fs.insert("/main.ir", Vec::new());
3125        let result = compile_ir(&options(), "/main.ir", &fs);
3126        assert!(result.failed());
3127        assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
3128    }
3129
3130    #[test]
3131    fn the_printed_ir_reads_back_as_the_same_module() {
3132        // The M2 exit criterion: the text is the module and nothing about it is lost by
3133        // writing it down. Anything the printer invents or the parser drops shows up here.
3134        let text = ir("\
3135struct point { int x, y; };
3136static const char greeting[] = \"hi\";
3137int table[4] = { 1, 2, 3 };
3138int puts(const char *);
3139double half(double x) { return x / 2.0; }
3140int f(int n) {
3141  int total = 0;
3142  for (int i = 0; i < n; i++) {
3143    if (i == 3) continue;
3144    total += table[i];
3145  }
3146  switch (n) {
3147    case 0: total = 1;
3148    case 1: total++; break;
3149    default: total = -total;
3150  }
3151  struct point p = { total, 1 };
3152  int *q = &p.y;
3153  puts(greeting);
3154  return p.x + *q;
3155}
3156int dispatch(int c) {
3157  void *p = c ? &&one : &&two;
3158  goto *p;
3159one:
3160  return 1;
3161two:
3162  return 2;
3163}
3164int assembly(int x, int *p) {
3165  int r;
3166  __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
3167  __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
3168  return r;
3169away:
3170  return 0;
3171}
3172");
3173        let mut names = Interner::new();
3174        let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
3175        assert_eq!(rucc_ir::print(&module, &names), text);
3176    }
3177}