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::coverage::Fired;
17use rucc_codegen::elsewhere::Elsewhere;
18use rucc_codegen::pipeline::{self, Machine};
19use rucc_diag::{Diagnostic, Severity, Span};
20use rucc_lex::{Convert, Keywords, PpToken, convert};
21use rucc_sema::{Checker, Context as CheckContext};
22use rucc_session::{EmitKind, FileSystem, Options, Session};
23use rucc_target::TargetInfo;
24
25use crate::preprocess::render;
26
27/// What a compilation produced, which is text for most of the kinds and bytes for one of them.
28///
29/// Two variants rather than a string, because an object file is not text and a `Vec<u8>` holding
30/// UTF-8 for six kinds and a file format for the seventh would leave every reader guessing which
31/// it had. [`Artifact::Nothing`] is what a compilation that stopped early gives back, and it is
32/// not the same as an empty file: nothing is written for it at all.
33#[derive(Debug, Clone, PartialEq, Eq, Default)]
34pub enum Artifact {
35    /// The compilation stopped before it produced anything, or the kind asked for produces
36    /// nothing yet.
37    #[default]
38    Nothing,
39    /// Text, which is every kind up to and including assembly.
40    Text(String),
41    /// An object file, which is `-c`.
42    Object(Vec<u8>),
43}
44
45impl Artifact {
46    /// The bytes to write, which is nothing at all for [`Artifact::Nothing`].
47    #[must_use]
48    pub fn bytes(&self) -> &[u8] {
49        match self {
50            Artifact::Nothing => &[],
51            Artifact::Text(text) => text.as_bytes(),
52            Artifact::Object(bytes) => bytes,
53        }
54    }
55}
56
57/// What compiling one file produced.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Compiled {
60    /// What to write, which is nothing when the compilation failed or produced nothing.
61    pub artifact: Artifact,
62    /// The diagnostics, already rendered, one per element, in the order they were reported.
63    pub messages: Vec<String>,
64    /// How many of them were errors.
65    pub errors: u32,
66    /// Which lowering rules this file fired, for `-Zrule-coverage`.
67    ///
68    /// Empty for a compilation that stopped before the back end, which every kind up to and
69    /// including `--emit=ir` does. That is not the same as a rule set nothing reaches and the
70    /// caller unions these rather than reading one, so a file that fired nothing adds nothing.
71    pub fired: Fired,
72    /// What `-fdump-ir=` asked to see, in the order the passes ran.
73    ///
74    /// The optimizer does not write files, because nothing below the driver in
75    /// `spec/18-package-layout.md` knows what a file is, so the text comes back here and the
76    /// caller decides where it goes.
77    pub dumps: Vec<rucc_opt::Dump>,
78    /// What `-fopt-info` asked to hear, already rendered, one remark per line.
79    ///
80    /// Empty when the flag was not given, and also empty when it was given and no pass had
81    /// anything of the kinds asked for to say. Those two are the same text and different facts,
82    /// which is why a misspelled keyword is an error rather than a quiet nothing.
83    pub remarks: String,
84}
85
86impl Compiled {
87    /// Whether anything went wrong badly enough that the output should not be used.
88    #[must_use]
89    pub fn failed(&self) -> bool {
90        self.errors > 0
91    }
92
93    /// The text that was produced, and the empty string for anything that is not text.
94    ///
95    /// A caller that asked for one of the text kinds knows which it asked for, so this saves it
96    /// matching on a variant it has already ruled out.
97    #[must_use]
98    pub fn text(&self) -> &str {
99        match &self.artifact {
100            Artifact::Text(text) => text,
101            _ => "",
102        }
103    }
104}
105
106/// Compiles one file as far as `opts.emit` asks for and renders the result.
107///
108/// `name` is the path as the user wrote it, which is the name every diagnostic about the file
109/// uses. Every kind but the executable produces something today, and that one runs the same front
110/// end and gives back nothing, so that a file with a mistake in it is reported the same way
111/// whichever kind was asked for, rather than compiling silently until the part that is written
112/// notices.
113///
114/// The checking is skipped when the parse reported an error. The two poisoning rules mean a
115/// diagnosed expression produces no further complaints, but a declaration the parser had to skip
116/// past leaves no declaration behind at all, and every later use of that name would be reported
117/// as undeclared. One mistake is worth one message.
118#[must_use]
119pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
120    let mut sess = Session::new(opts.clone());
121    // Before anything else interns a name. The keyword symbols have to be one unbroken run for
122    // a lookup to be a subtraction, and the preprocessor interns every identifier it reads, so
123    // building this after the expansion would mean building it after `char` had been seen.
124    let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
125    let mut diagnostics: Vec<Diagnostic> = Vec::new();
126    // Filled in by the back end when there is one, and empty for every kind that stops before it.
127    let mut fired = Fired::new();
128    // Filled in by the optimizer, and only when `-fdump-ir=` asked for something.
129    let mut dumps = Vec::new();
130    let mut remarks = String::new();
131
132    let bytes = match fs.read(Path::new(name)) {
133        Ok(bytes) => bytes,
134        Err(e) => return failure(format!("{name}: {e}")),
135    };
136    let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
137        return failure(format!("{name}: the source map has no room left for this file"));
138    };
139
140    // Phases 1 to 4. The expanded stream is turned into pp-tokens straight away, because the
141    // include context borrows the source map that rendering a diagnostic reads and the borrow
142    // has to end before anything is rendered.
143    let mut pp = rucc_pp::Preprocessor::new();
144    let predef = rucc_pp::Predef::for_options(opts);
145    let expanded: Vec<PpToken> = {
146        let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
147        cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
148        if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
149            return failure(format!("{name}: the source map has no room for the built in macros"));
150        }
151        pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
152    };
153    diagnostics.extend(pp.take_diagnostics());
154
155    // Phase 7, which is where a spelling becomes a keyword and a preprocessing number becomes
156    // a constant of a type.
157    let cx = Convert {
158        keywords: &keywords,
159        interner: &sess.interner,
160        target: &sess.target,
161        std: opts.std,
162        gnu: opts.gnu_extensions,
163        pedantic: opts.pedantic,
164    };
165    let (tokens, complaints) = convert(&expanded, &cx);
166    diagnostics.extend(complaints);
167
168    let parsed = rucc_parse::parse(
169        &tokens,
170        rucc_parse::Context {
171            interner: &sess.interner,
172            std: opts.std,
173            gnu: opts.gnu_extensions,
174            pedantic: opts.pedantic,
175            error_limit: opts.error_limit as usize,
176        },
177    );
178    let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
179    diagnostics.extend(parsed.diagnostics);
180
181    let mut artifact = Artifact::Nothing;
182    // Zero when nothing instruments, which is the truthful summary of a file built without
183    // `-fsafety`: no checks went in, so none is standing, and every call it makes is unmodelled.
184    let mut instrumented = Instrumented::default();
185    if !parse_failed {
186        let mut checker = Checker::new(
187            &parsed.ast,
188            CheckContext {
189                names: &sess.interner,
190                target: &sess.target,
191                std: opts.std,
192                gnu: opts.gnu_extensions,
193                pedantic: opts.pedantic,
194                gnu89_inline: opts.gnu89_inline,
195                error_limit: opts.error_limit as usize,
196                // A freestanding program has no C library, so a name that is the library's
197                // everywhere else is the program's own here and means whatever it defined.
198                builtins: opts.builtins && opts.hosted,
199                no_builtin: &opts.no_builtin,
200            },
201        );
202        checker.check_unit();
203        let checked = checker.finish();
204        if !checked.failed() {
205            match opts.emit {
206                EmitKind::Tast => {
207                    artifact = Artifact::Text(rucc_sema::print(
208                        &checked.tast,
209                        &checked.types,
210                        &sess.interner,
211                    ));
212                }
213                // Nothing past the checker, because a granule is a fact about a layout and a
214                // layout is settled the moment the closing brace is seen. Lowering the
215                // function bodies would take minutes on an amalgamation and answer nothing.
216                EmitKind::TypeGranules => {
217                    artifact = Artifact::Text(rucc_types::granule_report(
218                        &checked.types,
219                        &sess.interner,
220                        &sess.target,
221                    ));
222                }
223                EmitKind::Ir
224                | EmitKind::MirFinal
225                | EmitKind::Asm
226                | EmitKind::Object
227                | EmitKind::Executable
228                | EmitKind::SafetySummary => {
229                    let mut lowered = rucc_lower::lower(
230                        name,
231                        rucc_lower::Context {
232                            tast: &checked.tast,
233                            types: &checked.types,
234                            target: &sess.target,
235                            names: &mut sess.interner,
236                        },
237                    );
238                    // The walk reports what it cannot build, and what it did build is printed
239                    // anyway: a file with one construct missing from it is more use to read
240                    // than nothing at all, and the errors are what stop it being compiled.
241                    let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
242                    if !failed {
243                        // The verifier runs on everything the walk builds, always. It is the
244                        // one check that a bug in the walk cannot talk its way past, and a
245                        // wrong instruction found here costs a message rather than an hour
246                        // in front of a debugger over the assembly it turned into.
247                        if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
248                            for error in errors {
249                                diagnostics.push(internal(&format!("invalid IR, {error}")));
250                            }
251                        } else if let Err(complaints) =
252                            instrument(&mut lowered.module, &mut sess.interner, opts)
253                                .map(|done| instrumented = done)
254                        {
255                            diagnostics.extend(complaints);
256                        } else if let Err(complaints) = optimize(
257                            &mut lowered.module,
258                            &sess.interner,
259                            opts,
260                            name,
261                            &mut dumps,
262                            &mut remarks,
263                        ) {
264                            diagnostics.extend(complaints);
265                        } else if opts.emit == EmitKind::SafetySummary {
266                            // After the optimizer, because the number that matters is how many
267                            // checks are still standing and there is no way to know that before it
268                            // has run. Before the back end, because the back end turns a check into
269                            // a call and a summary of calls is not a summary of checks.
270                            artifact = Artifact::Text(
271                                rucc_safety::summarize(
272                                    &lowered.module,
273                                    &sess.interner,
274                                    name,
275                                    opts.safety.as_str(),
276                                    instrumented.checks,
277                                    instrumented.interposed,
278                                    instrumented.crossings,
279                                )
280                                .render(),
281                            );
282                        } else if opts.emit == EmitKind::Ir {
283                            // After the optimizer rather than before it, so that `--emit=ir -O2`
284                            // is the IR the back end will be given rather than the IR it would
285                            // have been given at `-O0`. There is no other way to see what a pass
286                            // did without reading the assembly it turned into.
287                            artifact =
288                                Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
289                        } else {
290                            // The back end, which is every pass after the IR and which is
291                            // where a construct nothing has a rule for is finally noticed.
292                            match generate(
293                                &mut lowered.module,
294                                &mut sess.interner,
295                                &sess.target,
296                                opts,
297                                &mut fired,
298                            ) {
299                                Ok(made) => artifact = made,
300                                Err(complaints) => diagnostics.extend(complaints),
301                            }
302                        }
303                    }
304                    diagnostics.extend(lowered.diagnostics);
305                }
306                _ => {}
307            }
308        }
309        diagnostics.extend(checked.diagnostics);
310    }
311
312    let mut messages = Vec::with_capacity(diagnostics.len());
313    let mut errors = 0;
314    for diag in &diagnostics {
315        // `-w` drops the warning here rather than at the several hundred places one is raised,
316        // and it drops it before the count, so `-w -Werror` compiles. A warning that was never
317        // raised is not a warning there is anything to promote.
318        if !opts.warnings && diag.severity == Severity::Warning {
319            continue;
320        }
321        if diag.severity.is_fatal()
322            || (diag.severity == Severity::Warning && opts.warnings_are_errors)
323        {
324            errors += 1;
325        }
326        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
327    }
328    if errors > 0 {
329        // A tree built from a file that did not compile is not a tree anything should read.
330        artifact = Artifact::Nothing;
331    }
332    // Kept even when the compilation failed, because a rule that fired did fire and a report about
333    // which rules a corpus reaches should not lose the ones a file with a mistake in it reached.
334    Compiled { artifact, messages, errors, fired, dumps, remarks }
335}
336
337/// Reads one file of IR, checks it, and prints it back.
338///
339/// This is the compiler's own textual IR arriving as an input rather than leaving as an output,
340/// which is what makes the round trip in the M2 exit criterion something to run rather than
341/// something to believe: what the printer wrote is read back, verified, and written again, and
342/// the two files are either the same bytes or they are not.
343///
344/// The verifier runs here for the reason it runs after the walk. A module that was printed by
345/// this compiler has been through it once already, and one that a person edited has not.
346#[must_use]
347pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
348    let mut sess = Session::new(opts.clone());
349    if opts.emit != EmitKind::Ir {
350        return failure(format!(
351            "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
352             the C in front of it became",
353            opts.emit.as_str()
354        ));
355    }
356    let bytes = match fs.read(Path::new(name)) {
357        Ok(bytes) => bytes,
358        Err(e) => return failure(format!("{name}: {e}")),
359    };
360    let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
361        return failure(format!("{name}: this is not text, so it is not IR"));
362    };
363
364    let module = match rucc_ir::parse(text, &mut sess.interner) {
365        Ok(module) => module,
366        Err(error) => {
367            return failure(format!("{name}:{}: {}", error.line, error.message));
368        }
369    };
370    let mut diagnostics: Vec<Diagnostic> = Vec::new();
371    if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
372        for error in errors {
373            diagnostics.push(invalid(&format!("invalid IR, {error}")));
374        }
375    }
376    let mut messages = Vec::with_capacity(diagnostics.len());
377    for diag in &diagnostics {
378        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
379    }
380    let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
381    let artifact = if errors > 0 {
382        Artifact::Nothing
383    } else {
384        Artifact::Text(rucc_ir::print(&module, &sess.interner))
385    };
386    // Nothing here reaches the back end, so no rule fired and there is nothing to record.
387    Compiled {
388        artifact,
389        messages,
390        errors,
391        fired: Fired::new(),
392        dumps: Vec::new(),
393        remarks: String::new(),
394    }
395}
396
397/// Puts the memory safety checks in and redirects the calls that cross the boundary, when
398/// `-fsafety=` asked for them.
399///
400/// Between the walk and the optimizer, which is where section 15.3 of
401/// `spec/safe-memory/15-integration.md` puts it and which is the whole design in one line: the
402/// checks go in while the addresses the program computes still exist, and the optimizer then
403/// discharges the ones it can prove. Every sanitizer that came before instruments after the
404/// optimizer so that its checks cannot be deleted, and pays for all of them forever.
405///
406/// The calls to the C library are redirected here too, and in the same window and for a related
407/// reason. `spec/safe-memory/10-boundaries.md` section 10.3 wants a `memcpy` modelled by a wrapper
408/// that performs the judgements, and `rucc_safety::wrap` is why that has to happen before the
409/// optimizer sees the call rather than after.
410///
411/// The verifier runs again afterwards, for the reason it runs after the walk. This pass rewrites
412/// every function in the module, and a pass that produced IR nothing else accepts should say so
413/// here rather than in the assembly it turned into.
414///
415/// # Errors
416///
417/// When the inserted checks left the module in a state the verifier refuses, which is a bug in
418/// this compiler and not in the program being compiled.
419fn instrument(
420    module: &mut rucc_ir::Module,
421    names: &mut Interner,
422    opts: &Options,
423) -> Result<Instrumented, Vec<Diagnostic>> {
424    if !opts.safety.instruments() {
425        return Ok(Instrumented::default());
426    }
427    let checks = rucc_safety::run(module);
428    // Before the optimizer rather than beside the check lowering, which is what
429    // `rucc_safety::wrap` argues out: `memcpy` is a name an optimizer knows things about, and a
430    // pass that turns a short copy into a pair of loads and stores would leave behind accesses the
431    // check insertion has already finished walking past.
432    let interposed = rucc_safety::redirect(module, names);
433    // After the redirection, so that a call this build models with a wrapper is not also counted
434    // as a crossing it did not model.
435    let crossings = rucc_safety::witness(module, names);
436    match rucc_ir::verify(module, names) {
437        Ok(()) => Ok(Instrumented { checks, interposed, crossings }),
438        Err(errors) => Err(errors
439            .iter()
440            .map(|e| internal(&format!("invalid IR after check insertion, {e}")))
441            .collect()),
442    }
443}
444
445/// What the instrumentation did, which nothing but the summary reads.
446///
447/// Carried out of [`instrument`] rather than recovered from the module afterwards because neither
448/// number survives the optimizer: a check that was discharged leaves nothing behind saying it was
449/// ever there, and a call that was pointed at a wrapper looks like a call that always named one.
450#[derive(Clone, Copy, Debug, Default)]
451struct Instrumented {
452    /// How many checks of each class went in.
453    checks: rucc_safety::Counts,
454    /// How many calls were pointed at an interposition wrapper.
455    interposed: usize,
456    /// How many places a pointer crosses to or from code this build did not instrument.
457    crossings: rucc_safety::Sites,
458}
459
460/// Runs the optimizer over the module, and collects whatever the dumps asked for.
461///
462/// The level chooses a pipeline, the `-f` flags edit it, and at `-O0` there is nothing in it, so
463/// this is a walk over an empty list rather than a branch on the level. See section 9.1 of
464/// `spec/09-optimizer.md` for why the pipelines are written out rather than assembled.
465///
466/// # Errors
467///
468/// When a pass left the module in a state the verifier refuses, which is a bug in the pass and
469/// not in the program being compiled, so it is reported as an internal error the way a bad
470/// lowering is.
471fn optimize(
472    module: &mut rucc_ir::Module,
473    names: &Interner,
474    opts: &Options,
475    file: &str,
476    dumps: &mut Vec<rucc_opt::Dump>,
477    remarks: &mut String,
478) -> Result<(), Vec<Diagnostic>> {
479    let mut settings = rucc_opt::Options::for_level(opts.opt_level);
480    settings.toggles.clone_from(&opts.passes);
481    settings.fuel = opts.pass_fuel.iter().cloned().collect();
482    settings.global_fuel = opts.pass_fuel_global;
483    settings.verify |= opts.verify_each;
484    for (on, spec) in &opts.pass_gates {
485        // Same argument as the dumps below: every spelling in here was checked while the
486        // arguments were parsed, so a rejection now is this compiler disagreeing with itself.
487        if let Err(why) = settings.gates.add(*on, spec) {
488            return Err(vec![internal(&why)]);
489        }
490    }
491    for spec in &opts.dump_ir {
492        // Every spelling in here was checked while the arguments were parsed, so a rejection
493        // now is this compiler disagreeing with itself rather than the command line being wrong.
494        if let Err(why) = settings.dumps.add(spec) {
495            return Err(vec![internal(&why)]);
496        }
497    }
498    let mut wants = rucc_opt::Wants::none();
499    for spec in &opts.opt_info {
500        // Same argument as the dumps above: every spelling was checked while the arguments were
501        // parsed, so a rejection now is the compiler disagreeing with itself.
502        if let Err(why) = wants.add(spec) {
503            return Err(vec![internal(&why)]);
504        }
505    }
506    let report = rucc_opt::run(module, names, &settings);
507    remarks.push_str(&rucc_opt::optinfo::render(file, &report, names, wants));
508    dumps.extend(report.dumps);
509    match report.broke.is_empty() {
510        true => Ok(()),
511        false => Err(report.broke.iter().map(|why| internal(why)).collect()),
512    }
513}
514
515/// Runs the back end over every function in `module` and writes what came out.
516///
517/// One machine function per definition in the module, in the order the module holds them, every
518/// register physical and every frame offset a constant. A declaration has no body and is skipped,
519/// because there is nothing in it to compile.
520///
521/// What the last step is, is the only thing `--emit=mir-final`, `-S` and `-c` disagree about. The
522/// three read the same functions and differ in whether they are printed as machine IR, printed as
523/// assembly, or encoded and put in a file, which is the point of section 11.1 of
524/// `spec/11-asm-objects-debug.md`: a listing that disagrees with the object file beside it is
525/// worse than no listing, and the way to make that impossible is to have one description of an
526/// instruction and two ways of writing it down.
527///
528/// # Errors
529///
530/// One diagnostic per function the back end could not compile, or one about the target when no
531/// back end covers it at all. Every function is attempted rather than stopping at the first, so a
532/// file with three constructs missing from the rule set reports three rather than one at a time.
533fn generate(
534    module: &mut rucc_ir::Module,
535    names: &mut Interner,
536    target: &TargetInfo,
537    opts: &Options,
538    fired: &mut Fired,
539) -> Result<Artifact, Vec<Diagnostic>> {
540    let Some(machine) = Machine::for_target(target) else {
541        return Err(vec![unsupported(&format!(
542            "there is no back end for {} in this compiler yet, so there is nothing to generate",
543            target.triple
544        ))]);
545    };
546    let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
547
548    // The checks become calls here rather than beside the insertion, because the id each one
549    // carries is an index into a table and a row for a check the optimizer deleted is a row nothing
550    // will ever name. Section 6.3.1 of `spec/safe-memory/06-instrumentation.md` is what this
551    // eventually becomes and `rucc_safety::lower` says why it is not that yet.
552    //
553    // It is inside the back end rather than beside the optimizer so that `--emit=ir` still shows
554    // the checks. The IR a person reads should say what the compiler decided, not how it spelled it
555    // for the machine.
556    if opts.safety.instruments() {
557        rucc_safety::lower(module, names);
558        if let Err(errors) = rucc_ir::verify(module, names) {
559            return Err(errors
560                .iter()
561                .map(|e| internal(&format!("invalid IR after check lowering, {e}")))
562                .collect());
563        }
564    }
565
566    // Worked out before the loop and not inside it, because it reads the whole module and the loop
567    // is holding one function of it. It has to be after the check lowering above, since that adds
568    // calls to the runtime and so can add a name this file does not define.
569    let elsewhere = Elsewhere::of(module);
570
571    let mut funcs = Vec::new();
572    let mut complaints = Vec::new();
573    for id in module.funcs() {
574        if module[id].is_declaration() {
575            continue;
576        }
577        match pipeline::compile_recording(
578            &mut module[id],
579            names,
580            &machine,
581            &elsewhere,
582            flags,
583            fired,
584        ) {
585            Ok(func) => funcs.push(func),
586            Err(why) => {
587                let name = names.resolve(module[id].name).to_owned();
588                // The function knows where the instruction came from, so the message lands on
589                // the line somebody wrote rather than on the file as a whole.
590                let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
591                let said = format!("cannot generate code for '{name}': {why}");
592                complaints.push(unsupported_at(&said, span));
593            }
594        }
595    }
596    if !complaints.is_empty() {
597        return Err(complaints);
598    }
599    // The variables the file defines, which go through the back end the way the functions did not:
600    // there is nothing in a variable to select instructions for, so the module is what says what
601    // one is right up to the point where it is written down.
602    // The second names go the same way and for the same reason, and they are neither a function
603    // nor a variable: an alias is an entry in the symbol table and no bytes of anything.
604    let (globals, aliases) = match opts.emit {
605        EmitKind::Asm | EmitKind::Object | EmitKind::Executable => (
606            rucc_asm::globals(module, names).map_err(refused)?,
607            rucc_asm::aliases(module, names).map_err(refused)?,
608        ),
609        _ => (rucc_asm::Globals::default(), Vec::new()),
610    };
611    // A failure in either of the last two is a bug here rather than a program this compiler is
612    // behind on, because every instruction in a function that got this far came out of the same
613    // description both of them read and every register in it has been allocated.
614    match opts.emit {
615        EmitKind::Asm => rucc_asm::print(&funcs, &globals, &aliases, names, target)
616            .map(Artifact::Text)
617            .map_err(refused),
618        // An executable is an object as far as this gets: one is what each file of a link
619        // contributes, and the linker is what turns them into the other.
620        EmitKind::Object | EmitKind::Executable => {
621            let text = rucc_asm::assemble(&funcs, names, target).map_err(refused)?;
622            let data = globals.image();
623            // A format with no writer is a target this compiler is behind on and anything else
624            // the writer refused is a bug here, and the two are not the same news to get.
625            rucc_object::write(&text, &data, &aliases, target).map(Artifact::Object).map_err(
626                |why| match why {
627                    rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
628                    rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
629                },
630            )
631        }
632        _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
633    }
634}
635
636/// What the assembler said, as the kind of news it is.
637///
638/// Two of these are about a program and the rest are about this compiler. A thread-local variable
639/// and an ifunc are both valid C that the back end does not build yet, and everything else the
640/// assembler refuses is something that should never have reached it.
641fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
642    match why {
643        rucc_asm::Error::Thread { .. } | rucc_asm::Error::IFunc { .. } => {
644            vec![unsupported(&why.to_string())]
645        }
646        _ => vec![internal(&why.to_string())],
647    }
648}
649
650/// A diagnostic about a program this compiler is not finished enough to compile.
651///
652/// Not an internal error, because nothing here is wrong: the program is valid C and the part of
653/// the back end that would handle it has not been written. The note says so, so that a report
654/// about one of these is filed against the milestone rather than as a miscompilation.
655fn unsupported(message: &str) -> Diagnostic {
656    unsupported_at(message, Span::DUMMY)
657}
658
659/// The same, about somewhere in the file rather than about the file.
660///
661/// The note names the issue tracker rather than `spec/17-milestones.md`, which is a document
662/// about the plan: a reader who follows it wants to know whether the construct in front of them
663/// is already written down as work, and the milestone list does not answer that.
664fn unsupported_at(message: &str, span: Span) -> Diagnostic {
665    Diagnostic::error(message.to_owned(), span)
666        .with_code("E0653")
667        .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
668}
669
670/// A diagnostic about IR that was handed to us rather than built by us.
671fn invalid(message: &str) -> Diagnostic {
672    Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
673}
674
675/// A diagnostic about this compiler rather than about the program it was given.
676fn internal(message: &str) -> Diagnostic {
677    Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
678        .with_code("E0652")
679        .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
680}
681
682/// A result that is nothing but one message, for the failures that happen before there is
683/// anything to compile.
684fn failure(message: String) -> Compiled {
685    Compiled {
686        artifact: Artifact::Nothing,
687        messages: vec![format!("rucc: error: {message}")],
688        errors: 1,
689        fired: Fired::new(),
690        dumps: Vec::new(),
691        remarks: String::new(),
692    }
693}
694
695#[cfg(test)]
696mod tests {
697    use rucc_session::{MemoryFileSystem, Std};
698    use rucc_target::Triple;
699
700    use super::*;
701
702    fn options() -> Options {
703        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
704        opts.emit = EmitKind::Tast;
705        opts
706    }
707
708    fn run(opts: &Options, source: &str) -> Compiled {
709        let mut fs = MemoryFileSystem::new();
710        fs.insert("/main.c", source.to_owned().into_bytes());
711        compile(opts, "/main.c", &fs)
712    }
713
714    /// Options with the compiler's own headers on the search path and nothing else, which is
715    /// what a freestanding compilation is. There is no file system underneath these tests,
716    /// so a header that reached for one would fail to resolve and say so.
717    fn freestanding() -> Options {
718        let mut opts = options();
719        opts.hosted = false;
720        opts.search.push_system(rucc_session::runtime::DIR);
721        opts
722    }
723
724    /// The typed tree of a freestanding `source`, insisting that it compiled cleanly.
725    fn shipped(source: &str) -> String {
726        let result = run(&freestanding(), source);
727        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
728        result.text().to_owned()
729    }
730
731    /// The typed tree of `source`, insisting that it compiled cleanly.
732    fn tast(source: &str) -> String {
733        let result = run(&options(), source);
734        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
735        result.text().to_owned()
736    }
737
738    #[test]
739    fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
740        let text = shipped(concat!(
741            "#include <stdarg.h>\n",
742            "int sum(int n, ...) {\n",
743            "  va_list ap, copy;\n",
744            "  va_start(ap, n);\n",
745            "  va_copy(copy, ap);\n",
746            "  int total = va_arg(ap, int) + va_arg(copy, int);\n",
747            "  va_end(ap);\n",
748            "  va_end(copy);\n",
749            "  return total;\n",
750            "}\n",
751        ));
752        assert!(text.contains("va-start"), "{text}");
753        assert!(text.contains("va-copy"), "{text}");
754        assert!(text.contains("va-arg"), "{text}");
755        assert!(text.contains("va-end"), "{text}");
756    }
757
758    /// glibc includes `<stdarg.h>` this way from every header that declares a `vprintf`, and
759    /// what it wants is the type without the four macro names. Answering the whole header
760    /// would put `va_start` in the way of a program that has its own.
761    #[test]
762    fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
763        let text = shipped(concat!(
764            "#define __need___va_list\n",
765            "#include <stdarg.h>\n",
766            "int vprint(const char *f, __gnuc_va_list ap);\n",
767            "#ifdef va_start\n",
768            "#error va_start should not be defined\n",
769            "#endif\n",
770            "#ifdef _VA_LIST_DEFINED\n",
771            "#error va_list should not have been made\n",
772            "#endif\n",
773        ));
774        assert!(text.contains("vprint"), "{text}");
775    }
776
777    /// The same protocol on `<stddef.h>`, which glibc uses far more heavily: `<stdio.h>` asks
778    /// for `size_t` and `NULL` and would be wrong to receive `offsetof` as well.
779    #[test]
780    fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
781        let text = shipped(concat!(
782            "#define __need_size_t\n",
783            "#include <stddef.h>\n",
784            "#ifdef offsetof\n",
785            "#error offsetof should not be defined yet\n",
786            "#endif\n",
787            "#define __need_ptrdiff_t\n",
788            "#include <stddef.h>\n",
789            "#include <stddef.h>\n",
790            "size_t a;\n",
791            "ptrdiff_t b;\n",
792            "wchar_t c;\n",
793            "max_align_t d;\n",
794            "void *e = NULL;\n",
795            "struct P { int x; long y; };\n",
796            "size_t f = offsetof(struct P, y);\n",
797        ));
798        assert!(text.contains("decl #0 a : unsigned long"), "{text}");
799        assert!(text.contains("decl #1 b : long"), "{text}");
800    }
801
802    #[test]
803    fn the_shipped_limits_and_float_are_the_targets_own_answers() {
804        let text = shipped(concat!(
805            "#include <limits.h>\n",
806            "#include <float.h>\n",
807            "int bits = CHAR_BIT;\n",
808            "long big = LONG_MAX;\n",
809            "int low = INT_MIN;\n",
810            "int radix = FLT_RADIX;\n",
811            "int digits = DBL_MANT_DIG;\n",
812        ));
813        assert!(text.contains("const 8 : int"), "{text}");
814        assert!(text.contains("const 9223372036854775807 : long"), "{text}");
815        assert!(text.contains("const 2 : int"), "{text}");
816        assert!(text.contains("const 53 : int"), "{text}");
817    }
818
819    /// Freestanding, so there is no library header to chain to and `<stdint.h>` writes the
820    /// whole set out itself. The widths are the ones the target picked, which is the only
821    /// reason this header is the compiler's.
822    #[test]
823    fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
824        let text = shipped(concat!(
825            "#include <stdint.h>\n",
826            "int64_t a = INT64_C(1);\n",
827            "uint_least16_t b;\n",
828            "intptr_t c;\n",
829            "uintmax_t d = UINTMAX_MAX;\n",
830            "int wide = sizeof(int_fast64_t);\n",
831        ));
832        assert!(text.contains("decl #0 a : long"), "{text}");
833        assert!(text.contains("decl #1 b : unsigned short"), "{text}");
834        assert!(text.contains("decl #2 c : long"), "{text}");
835    }
836
837    #[test]
838    fn the_three_formality_headers_still_have_to_work() {
839        let text = shipped(concat!(
840            "#include <stdbool.h>\n",
841            "#include <stdalign.h>\n",
842            "#include <iso646.h>\n",
843            "#include <stdnoreturn.h>\n",
844            "int t = true and not false;\n",
845            "_Alignas(16) char buf[16];\n",
846            "int a = alignof(long);\n",
847        ));
848        assert!(text.contains("decl #0 t : int"), "{text}");
849        assert!(text.contains("const 8 : unsigned long"), "{text}");
850    }
851
852    /// Including everything twice has to change nothing, because that is what happens in any
853    /// program large enough to matter and a guard that is wrong shows up nowhere else.
854    #[test]
855    fn every_shipped_header_can_be_included_twice() {
856        let mut source = String::new();
857        for _ in 0..2 {
858            for name in rucc_session::runtime::names() {
859                source.push_str(&format!("#include <{name}>\n"));
860            }
861        }
862        source.push_str("int x;\n");
863        let text = shipped(&source);
864        assert!(text.starts_with("decl #0 x : int"), "{text}");
865    }
866
867    #[test]
868    fn a_file_that_is_not_there_says_so_and_produces_nothing() {
869        let fs = MemoryFileSystem::new();
870        let result = compile(&options(), "/nope.c", &fs);
871        assert!(result.failed());
872        assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
873        assert!(result.text().is_empty());
874    }
875
876    #[test]
877    fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
878        let text = tast("int x = 1;\n");
879        let expected = "\
880decl #0 x : int object external static defined
881  init
882    +0
883      const 1 : int
884";
885        assert_eq!(text, expected);
886    }
887
888    #[test]
889    fn the_macros_are_expanded_before_anything_is_parsed() {
890        // The whole pipeline in one line. The bound came out of a macro, so it was expanded,
891        // converted from a preprocessing number to a constant of a type, parsed as an
892        // expression, and folded to the number the array type carries.
893        let text = tast("#define N 2\nint a[N];\n");
894        assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
895    }
896
897    /// A pragma survives the preprocessor on purpose, since what one means is not its
898    /// business, and nothing after it has a place for a `#` in the grammar. `pack` is the one
899    /// the parser reads and every other line is walked past. Both spellings are here because
900    /// they arrive by different routes and only one of them was ever on a line of its own in
901    /// the source.
902    #[test]
903    fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
904        let text = tast(concat!(
905            "#pragma pack(4)\n",
906            "struct s { int a; };\n",
907            "#pragma pack()\n",
908            "int b;\n",
909            "_Pragma(\"GCC visibility push(default)\") int c;\n",
910        ));
911        assert!(text.contains("decl #0 b : int"), "{text}");
912        assert!(text.contains("decl #1 c : int"), "{text}");
913    }
914
915    /// Every number in these two tests was read off gcc 16 on x86-64 under `-std=gnu23`
916    /// rather than reasoned about, which is why they are written as assertions the program
917    /// makes about itself: a compilation with no messages is every one of them holding.
918    ///
919    /// This half is the attributes. `packed` takes the padding out, on the record or on one
920    /// member, `aligned` raises and never lowers, and the two written together are the
921    /// combination that packs and then aligns the whole thing.
922    #[test]
923    fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
924        tast(concat!(
925            "struct A { char c; int i; } __attribute__((packed));\n",
926            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
927            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
928            // `aligned` with nothing in the parentheses is the largest alignment the target
929            // has, which gcc calls BIGGEST_ALIGNMENT and which is sixteen everywhere here.
930            "struct B { char c; int i; } __attribute__((aligned));\n",
931            "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
932            "struct C { char c; int i __attribute__((packed)); };\n",
933            "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
934            "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
935            "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
936            "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
937            "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
938            "struct E { char c; _Alignas(8) int i; };\n",
939            "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
940            "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
941            "struct F { char c; int i __attribute__((aligned(8))); };\n",
942            "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
943            // Two the record already had, so the attribute asks for nothing new, and two
944            // where four was already there, so the attribute is ignored rather than obeyed.
945            "struct G { char c; short s; } __attribute__((aligned(2)));\n",
946            "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
947            "struct H { char c; int i; } __attribute__((aligned(2)));\n",
948            "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
949            // `packed` on a member takes the padding out in front of that member alone, so on
950            // the first one it does nothing and on the second one it does all of it.
951            "struct I { [[gnu::packed]] char c; int i; };\n",
952            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
953            "struct J { char c; [[gnu::packed]] int i; };\n",
954            "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
955            "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
956            "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
957            "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
958            "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
959            "union L { char c; int i; } __attribute__((packed));\n",
960            "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
961            // The armoured spellings, which are the ones a system header writes, since a
962            // program is entitled to a macro called `packed` and is not entitled to one called
963            // `__packed__`. The two names are one attribute and the layout is the same one.
964            "struct O { char c; int i; } __attribute__((__packed__));\n",
965            "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
966            "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
967            "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
968        ));
969    }
970
971    /// The same attribute on a declaration rather than on a type, which asks that this object or
972    /// this function be at a multiple of that, and which is where a program that has to hand a
973    /// buffer to hardware or keep two counters off one cache line writes it.
974    ///
975    /// A raise and never a lower, which is the one place it does not agree with `_Alignas`: below
976    /// what the type already has, `_Alignas` is a constraint violation and this is ignored without
977    /// a word. `__alignof__` of the object answers what the object got and not what its type has,
978    /// because that is the question a program asking it is asking.
979    #[test]
980    fn the_aligned_attribute_on_a_declaration_raises_what_that_one_object_is_aligned_to() {
981        tast(concat!(
982            "int v __attribute__((aligned(64)));\n",
983            "_Static_assert(__alignof__(v) == 64, \"v\");\n",
984            // Written on the specifiers rather than after the declarator, which asks the same
985            // thing and is the spelling a header is more likely to use.
986            "__attribute__((aligned(32))) int w;\n",
987            "_Static_assert(__alignof__(w) == 32, \"w\");\n",
988            "[[gnu::aligned(16)]] int x;\n",
989            "_Static_assert(__alignof__(x) == 16, \"x\");\n",
990            // Two below the four an `int` already has, so nothing is asked for and nothing is
991            // said, and the type still answers for the object.
992            "int y __attribute__((aligned(2)));\n",
993            "_Static_assert(__alignof__(y) == 4, \"y\");\n",
994            // A local, which is the same question one scope down.
995            "void f(void) { int a __attribute__((aligned(128)));\n",
996            "_Static_assert(__alignof__(a) == 128, \"a\"); (void)a; }\n",
997            // The type is untouched by any of it: `aligned` on a declaration says where that
998            // declaration goes and says nothing about every other `int` in the program.
999            "_Static_assert(__alignof__(int) == 4, \"int\");\n",
1000            // A function, which has no alignment of its own for this to be measured against and
1001            // takes whatever was asked for.
1002            "void g(void) __attribute__((aligned(256)));\n",
1003            "void g(void) {}\n",
1004            "_Static_assert(__alignof__(g) == 256, \"g\");\n",
1005        ));
1006    }
1007
1008    /// And what the object file says, which is the half that makes the answer above true. A
1009    /// function is at a fixed offset inside the text section, so it is at a multiple of two
1010    /// hundred and fifty six only if the section is at one too.
1011    #[test]
1012    fn what_a_declaration_asked_to_be_aligned_to_is_what_the_assembler_is_told() {
1013        let text = asm(concat!(
1014            "int v __attribute__((aligned(64)));\n",
1015            "void g(void) __attribute__((aligned(256)));\n",
1016            "void g(void) {}\n",
1017            "void plain(void) {}\n",
1018        ));
1019        assert!(text.contains("\t.p2align\t6\n\t.type\tv, @object\n"), "{text}");
1020        assert!(text.contains("\t.p2align\t8, 0x90\n\t.globl\tg\n"), "{text}");
1021        assert!(text.contains("\t.p2align\t4, 0x90\n\t.globl\tplain\n"), "{text}");
1022    }
1023
1024    /// And the one position where the attribute means something else. On a declaration it raises
1025    /// what that one object is aligned to, and on a typedef it says what the type is aligned to,
1026    /// which gcc lets it lower as well: `typedef int L __attribute__((aligned(2)))` really is an
1027    /// `int` at a multiple of two and a record with one in it really is smaller for it.
1028    ///
1029    /// The size is left alone, which is gcc's answer rather than an omission here. An aligned
1030    /// typedef whose alignment is larger than what it stands for keeps the size it stands for,
1031    /// and gcc refuses an array of one rather than padding the elements out to fit.
1032    #[test]
1033    fn an_aligned_typedef_says_what_an_object_of_it_is_aligned_to_and_may_lower_it() {
1034        tast(concat!(
1035            "typedef int L __attribute__((aligned(2)));\n",
1036            "_Static_assert(__alignof__(L) == 2, \"L\");\n",
1037            "_Static_assert(_Alignof(L) == 2, \"L alignof\");\n",
1038            // Below what an `int` has, which is the half a declaration cannot ask for.
1039            "_Static_assert(sizeof(L) == 4, \"L size\");\n",
1040            "struct T { char c; L x; };\n",
1041            "_Static_assert(sizeof(struct T) == 6, \"T\");\n",
1042            "_Static_assert(__builtin_offsetof(struct T, x) == 2, \"T.x\");\n",
1043            // And upwards, which is the ordinary direction and the one a header writes.
1044            "typedef int H __attribute__((aligned(16)));\n",
1045            "_Static_assert(__alignof__(H) == 16, \"H\");\n",
1046            "_Static_assert(sizeof(H) == 4, \"H size\");\n",
1047            "struct U { char c; H x; };\n",
1048            "_Static_assert(sizeof(struct U) == 32, \"U\");\n",
1049            "_Static_assert(__builtin_offsetof(struct U, x) == 16, \"U.x\");\n",
1050            // A typedef of a typedef, where the nearer one is the one the declaration was
1051            // written with and is the one that answers.
1052            "typedef L M __attribute__((aligned(8)));\n",
1053            "_Static_assert(__alignof__(M) == 8, \"M\");\n",
1054            // And one that asked for nothing, which still has whatever the one behind it asked
1055            // for because it is the same type spelled again.
1056            "typedef L N;\n",
1057            "_Static_assert(__alignof__(N) == 2, \"N\");\n",
1058            // The type it stands for is untouched by any of it.
1059            "_Static_assert(__alignof__(int) == 4, \"int\");\n",
1060        ));
1061        let text = asm(concat!(
1062            "typedef int L __attribute__((aligned(2)));\n",
1063            "typedef int H __attribute__((aligned(16)));\n",
1064            "L low;\n",
1065            "H high;\n",
1066        ));
1067        assert!(text.contains("\t.p2align\t1\n\t.type\tlow, @object\n"), "{text}");
1068        assert!(text.contains("\t.p2align\t4\n\t.type\thigh, @object\n"), "{text}");
1069    }
1070
1071    /// The attribute that builds a type rather than changing a layout. `vector_size(n)` says the
1072    /// declared type is `n` bytes of what was written, taken as lanes, and every operator over
1073    /// one is that operator over each lane.
1074    ///
1075    /// The size is in bytes and not in lanes, which is the part a reader gets backwards: sixteen
1076    /// of `int` is four lanes and sixteen of `char` is sixteen. A vector is aligned to its own
1077    /// size, which is what a machine that has the registers wants and what gcc gives one here.
1078    #[test]
1079    fn the_vector_size_attribute_builds_a_type_of_lanes_and_measures_it_in_bytes() {
1080        tast(concat!(
1081            "typedef int __attribute__((vector_size(16))) v4si;\n",
1082            "_Static_assert(sizeof(v4si) == 16 && _Alignof(v4si) == 16, \"v4si\");\n",
1083            "typedef char __attribute__((vector_size(16))) v16qi;\n",
1084            "_Static_assert(sizeof(v16qi) == 16, \"v16qi\");\n",
1085            // One lane, which is a power of two and is a vector rather than the type it was
1086            // written on: the operators it takes are the vector's and not the scalar's.
1087            "typedef int __attribute__((vector_size(4))) v1si;\n",
1088            "_Static_assert(sizeof(v1si) == 4, \"v1si\");\n",
1089            // The armoured spelling and the bracket one, which are the same attribute.
1090            "typedef float __attribute__((__vector_size__(8))) v2sf;\n",
1091            "_Static_assert(sizeof(v2sf) == 8, \"v2sf\");\n",
1092            "typedef short [[gnu::vector_size(8)]] v4hi;\n",
1093            "_Static_assert(sizeof(v4hi) == 8, \"v4hi\");\n",
1094            // A lane is what a subscript answers with, and a vector is not a pointer: there is
1095            // nothing to decay and the lane type is the one the arithmetic happens in.
1096            "v4si g;\n",
1097            "_Static_assert(sizeof(g[0]) == 4, \"lane\");\n",
1098            "_Static_assert(sizeof(g + g) == 16, \"whole\");\n",
1099            // A scalar beside a vector stands for itself in every lane, so the answer is still
1100            // the vector and not the wider of the two types.
1101            "_Static_assert(sizeof(g + 1) == 16, \"broadcast\");\n",
1102            // An array of them, which is the ordinary way a program holds several.
1103            "_Static_assert(sizeof(v4si[3]) == 48, \"array\");\n",
1104        ));
1105    }
1106
1107    /// A whole vector written into an array of them, and a vector named by a type name rather
1108    /// than by a typedef.
1109    ///
1110    /// Both are the same question asked twice. A vector is filled like an array of its lanes when
1111    /// a list is written into it, so a braced element that is itself a vector has to be taken
1112    /// whole rather than started as the first lane, and the type of what was written is the only
1113    /// thing that says which was meant. And a type name is where a compound literal and a cast
1114    /// spell the type out, which a macro taking a lane type and a lane count does, so the
1115    /// attribute has to be read there and not only on a declaration.
1116    #[test]
1117    fn a_vector_is_written_whole_into_an_array_of_them_and_named_by_a_type_name() {
1118        tast(concat!(
1119            "typedef int __attribute__((vector_size(8))) v2si;\n",
1120            "v2si table[] = { (v2si){ 1, 2 }, (v2si){ 3, 4 } };\n",
1121            "_Static_assert(sizeof(table) == 16, \"two of them and not eight lanes\");\n",
1122            // The size written out rather than named, which is the spelling a macro expands to.
1123            "v2si written = (int __attribute__((vector_size(8)))){ 5, 6 };\n",
1124            "_Static_assert(sizeof((int __attribute__((vector_size(16)))){ 0 }) == 16, \"named\");\n",
1125            // A lane is still a lane, so a list of them fills the vector the way it always did
1126            // and the rule above did not turn brace elision off.
1127            "v2si lanes[2] = { 1, 2, 3, 4 };\n",
1128            "_Static_assert(sizeof(lanes) == 16, \"still elided\");\n",
1129        ));
1130    }
1131
1132    /// A lane written rather than read, and a shift whose two vectors are not the same type.
1133    ///
1134    /// Both are places where a vector is not the aggregate it looks like. A subscript of one is
1135    /// an lvalue because the vector it came from is an object, so a lane can be assigned to and
1136    /// has an address, and a qualifier written on the vector reaches every lane the way it does
1137    /// on an array. And a shift is the one lanewise operator whose sides are not brought to a
1138    /// single type, since the right side counts rather than computes.
1139    #[test]
1140    fn a_lane_is_assignable_and_a_shift_takes_a_count_of_its_own_lane() {
1141        let result = run(
1142            &options(),
1143            concat!(
1144                "typedef int __attribute__((vector_size(16))) v4si;\n",
1145                "typedef unsigned __attribute__((vector_size(16))) v4ui;\n",
1146                "void write(v4si *out, v4ui a, v4si b, int n) {\n",
1147                "  v4si v = { 1, 2, 3, 4 };\n",
1148                "  v[0] = n;\n",
1149                "  v[1] += n;\n",
1150                "  v[2]++;\n",
1151                "  *&v[3] = n;\n",
1152                // The count is signed and the value is not, which no other operator allows.
1153                "  v4ui shifted = a >> b;\n",
1154                "  shifted <<= b;\n",
1155                // A scalar stands in every lane on either side of a shift, which is the half
1156                // that looks wrong: the shape of the answer comes off the count here.
1157                "  *out = v + (v4si)shifted + (1 << b);\n",
1158                "}\n",
1159                // A qualifier on the vector is a qualifier on the lane, so there is nothing here
1160                // to write to.
1161                "void refused(const v4si c) {\n",
1162                "  c[0] = 1;\n",
1163                "}\n",
1164            ),
1165        );
1166        assert_eq!(result.messages.len(), 1, "{:?}", result.messages);
1167        assert!(result.messages[0].contains("assignment of read-only"), "{:?}", result.messages);
1168    }
1169
1170    /// The third layout attribute, and the one that is refused rather than read. Reversing the
1171    /// byte order of every scalar in a record is not something a compiler can do half of, and a
1172    /// compilation that ignored it would lay the record out in the host's order and hand back
1173    /// every field with its bytes the wrong way round. Both spellings are here because a header
1174    /// writes the armoured one, and the member is here because the refusal has to arrive before
1175    /// the layout is used rather than after.
1176    #[test]
1177    fn a_record_that_asks_for_the_other_byte_order_is_refused_rather_than_laid_out_in_this_one() {
1178        let opts = options();
1179        let big = "struct s { int i; } __attribute__((scalar_storage_order(\"big-endian\")));\n";
1180        assert_eq!(
1181            run(&opts, big).messages,
1182            ["/main.c:1:36: error: 'scalar_storage_order' is not implemented yet [E0688]\n\
1183              /main.c:1:36: note: every scalar in this record would be read in the wrong byte \
1184              order"]
1185        );
1186
1187        let armoured =
1188            "struct s { int i; } __attribute__((__scalar_storage_order__(\"little-endian\")));\n";
1189        let messages = run(&opts, armoured).messages;
1190        assert!(messages[0].contains("[E0688]"), "{messages:?}");
1191
1192        // The attribute in front of the body reaches the same list as the one behind it, and
1193        // the C23 spelling in gcc's namespace is the same attribute written a third way.
1194        let front = "struct __attribute__((scalar_storage_order(\"big-endian\"))) s { int i; };\n";
1195        assert!(run(&opts, front).messages[0].contains("[E0688]"), "{front}");
1196        let standard = "struct s { int i; } [[gnu::scalar_storage_order(\"big-endian\")]];\n";
1197        assert!(run(&opts, standard).messages[0].contains("[E0688]"), "{standard}");
1198    }
1199
1200    /// Where a bit-field goes, which packing decides and which is the part of all this that
1201    /// is not what the names suggest. A bit-field goes at the next free bit unless that would
1202    /// make it span more storage than its own type occupies, and then it moves to the next
1203    /// boundary of its alignment. Any packing at all takes that rule out, and `#pragma pack`
1204    /// counts even where it lowers nothing, which is the fourth and seventh cases here.
1205    ///
1206    /// Nothing in the language can be asked where a bit-field is, since `offsetof` refuses one
1207    /// and every size below comes out the same either way, so what is asked is the byte a read
1208    /// of the field loads from.
1209    #[test]
1210    fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
1211        // A `char` field after twelve bits, which will not straddle unpacked and does packed.
1212        assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
1213        assert_eq!(
1214            bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
1215            1
1216        );
1217        assert_eq!(
1218            bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
1219            1
1220        );
1221        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
1222        // A thirty bit field after a byte, which is the case the rule was written for.
1223        assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
1224        assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
1225        // Four is what an `int` asked for anyway, so this caps nothing and still counts.
1226        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
1227        assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
1228    }
1229
1230    /// The byte a read of `s.y` loads from, which is where the bit-field was placed.
1231    fn bit_field_byte(record: &str) -> u64 {
1232        let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
1233        let body = body(&source);
1234        let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
1235        let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
1236        constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
1237    }
1238
1239    /// An attribute in the middle of a specifier list, which is where a member usually carries
1240    /// one and which was read and then thrown away. The `[[...]]` spelling and whatever was
1241    /// written in front of the declaration are collected as the list is walked and the
1242    /// `__attribute__` spelling is put straight on the specifiers, and the two were assigned
1243    /// over each other rather than joined.
1244    #[test]
1245    fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
1246        tast(concat!(
1247            "struct a { char c; __attribute__((aligned(8))) int i; };\n",
1248            "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
1249            "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
1250            "struct b { char c; __attribute__((packed)) int i; };\n",
1251            "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
1252            "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
1253            "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
1254            "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
1255        ));
1256    }
1257
1258    /// The other half, which is `#pragma pack`. It caps a member's alignment where `packed`
1259    /// drops it, so `pack(2)` leaves a `short` where it was and moves an `int`, and it caps a
1260    /// member the program asked to align as well, which is where the two differ. It is read
1261    /// at the closing brace of the body, so a line written in the middle of one settles the
1262    /// whole record rather than the members after it, and `push` and `pop` nest.
1263    #[test]
1264    fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
1265        tast(concat!(
1266            "#pragma pack(1)\n",
1267            "struct A { char c; int i; };\n",
1268            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
1269            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
1270            "#pragma pack()\n",
1271            "struct B { char c; int i; };\n",
1272            "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
1273            "#pragma pack(2)\n",
1274            "struct C { char c; int i; double d; };\n",
1275            "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
1276            "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
1277            // A member the program aligned, which `pack` caps and `packed` would not.
1278            "struct K { char c; int i __attribute__((aligned(8))); };\n",
1279            "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
1280            "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
1281            // The record's own `aligned` is not a member's, so it is not capped.
1282            "struct J { char c; int i; } __attribute__((aligned(8)));\n",
1283            "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
1284            "#pragma pack()\n",
1285            "#pragma pack(push, 1)\n",
1286            "struct D { char c; short s; };\n",
1287            "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
1288            "#pragma pack(pop)\n",
1289            "struct E { char c; short s; };\n",
1290            "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
1291            // Written in the middle of a body, and it still settles the whole record.
1292            "struct H { char c;\n",
1293            "#pragma pack(1)\n",
1294            "  int i; };\n",
1295            "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
1296            "#pragma pack(1)\n",
1297            "struct I { char c;\n",
1298            "#pragma pack()\n",
1299            "  int i; };\n",
1300            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
1301            "#pragma pack()\n",
1302            // Nested pushes, each one giving back what the one under it had.
1303            "#pragma pack(push, 8)\n",
1304            "#pragma pack(push, 1)\n",
1305            "struct P { char c; int i; };\n",
1306            "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
1307            "#pragma pack(pop)\n",
1308            "struct Q { char c; int i; };\n",
1309            "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
1310            "#pragma pack(pop)\n",
1311            // A cap above what every member already asks for changes nothing at all.
1312            "#pragma pack(16)\n",
1313            "struct R { char c; int i; };\n",
1314            "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
1315            "#pragma pack()\n",
1316            "#pragma pack(1)\n",
1317            "struct S { char c; int i : 5; int j : 20; };\n",
1318            "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
1319            "union T { char c; int i; };\n",
1320            "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
1321            "#pragma pack()\n",
1322        ));
1323    }
1324
1325    /// A line the reader cannot make sense of is a warning and the line is dropped, which is
1326    /// what GCC does with one, and these are its words for each of them. The last line is the
1327    /// one nothing else would reach, since it stands after every record in the file.
1328    #[test]
1329    fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
1330        let result = run(
1331            &options(),
1332            concat!(
1333                "#pragma pack 4\n",
1334                "#pragma pack(pop)\n",
1335                "#pragma pack(3)\n",
1336                "#pragma pack(1) junk\n",
1337                "#pragma pack(push, 1\n",
1338                "#pragma pack(x)\n",
1339                // These two are well formed and say nothing. Zero is how a line asks for the
1340                // target's own alignments back without writing empty parentheses.
1341                "#pragma pack(0)\n",
1342                "#pragma pack(push)\n",
1343                "struct s { char c; int i; };\n",
1344                "#pragma pack(pop)\n",
1345                "#pragma pack(pop, foo)\n",
1346            ),
1347        );
1348        let expected = [
1349            "missing `(` after `#pragma pack` - ignored",
1350            "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
1351            "alignment must be a small power of two, not 3",
1352            "junk at end of `#pragma pack`",
1353            "malformed `#pragma pack(push[, id][, <n>])` - ignored",
1354            "unknown action `x` for `#pragma pack` - ignored",
1355            "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
1356        ];
1357        assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
1358        for (message, want) in result.messages.iter().zip(expected) {
1359            assert!(message.contains(want), "expected {want:?} in {message:?}");
1360        }
1361    }
1362
1363    /// The two typedef spellings of the 128 bit types. gcc offers them as keywords rather
1364    /// than as typedefs in a header, which is the only way a program that includes nothing at
1365    /// all can still use them, and Apple's `<mach/arm/_structs.h>` is one such program.
1366    #[test]
1367    fn the_wide_integer_answers_to_all_three_of_its_names() {
1368        let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
1369        assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
1370        assert!(text.contains("decl #1 b : __int128"), "{text}");
1371        assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
1372    }
1373
1374    #[test]
1375    fn every_conversion_the_language_performs_is_a_node_in_the_output() {
1376        // The point of a typed tree. The source has one operator and the output has the
1377        // widening that operator asked for, spelled out, so that nothing downstream has to
1378        // work out the conversion rules a second time.
1379        let text = tast("long f(int a, long b) { return a + b; }\n");
1380        assert!(text.contains("convert arithmetic"), "{text}");
1381    }
1382
1383    #[test]
1384    fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
1385        for source in [
1386            "#error stop\n",
1387            "int f(void) { return 1 + ; }\n",
1388            "int f(void) { return undeclared; }\n",
1389        ] {
1390            let result = run(&options(), source);
1391            assert!(result.failed(), "expected this to fail:\n{source}");
1392            assert!(
1393                result.text().is_empty(),
1394                "a file that did not compile wrote a tree:\n{source}"
1395            );
1396        }
1397    }
1398
1399    #[test]
1400    fn one_undeclared_name_is_one_message_and_not_one_per_use() {
1401        // The poisoning rule from `spec/06-lexer-and-parser.md` section 6.8, seen from the
1402        // outside. Three uses of a name that was never declared, and the operators over them
1403        // say nothing at all.
1404        let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
1405        assert_eq!(result.errors, 1, "{:?}", result.messages);
1406    }
1407
1408    #[test]
1409    fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
1410        // The reason the checking is skipped after a failed parse. The parser gave up on the
1411        // first line and there is no `x` in the tree, so a checker run over it would report
1412        // every use of `x` below as undeclared, which is a second message about one mistake.
1413        let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
1414        assert_eq!(result.errors, 1, "{:?}", result.messages);
1415    }
1416
1417    #[test]
1418    fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
1419        let source = "int f(void) { char c = 300; return c; }\n";
1420        let plain = run(&options(), source);
1421        assert_eq!(plain.errors, 0, "{:?}", plain.messages);
1422        assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
1423        assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
1424
1425        let mut opts = options();
1426        opts.warnings_are_errors = true;
1427        let strict = run(&opts, source);
1428        assert!(strict.failed());
1429        assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
1430        for message in &strict.messages {
1431            assert!(!message.contains("warning:"), "{message}");
1432        }
1433    }
1434
1435    #[test]
1436    fn w_drops_the_warning_before_werror_can_promote_it() {
1437        let source = "int f(void) { char c = 300; return c; }\n";
1438        let mut opts = options();
1439        opts.warnings = false;
1440        let quiet = run(&opts, source);
1441        assert_eq!(quiet.messages, Vec::<String>::new());
1442        assert_eq!(quiet.errors, 0);
1443        assert!(!quiet.text().is_empty(), "and the file still compiles");
1444
1445        // A build that passes both means it wants neither, and the order it wrote them in is not
1446        // something to make it think about.
1447        opts.warnings_are_errors = true;
1448        let both = run(&opts, source);
1449        assert_eq!(both.messages, Vec::<String>::new());
1450        assert!(!both.failed(), "-w -Werror is not an error about a warning nobody saw");
1451    }
1452
1453    #[test]
1454    fn the_dialect_reaches_the_keywords_and_the_checking() {
1455        // `typeof` is C23's and GNU's, so the same source is a declaration under one dialect
1456        // and a mistake under the other, which is the keyword table being built per dialect.
1457        let source = "typeof(1) x;\n";
1458        let mut opts = options();
1459        opts.std = Std::C23;
1460        opts.gnu_extensions = false;
1461        assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
1462
1463        opts.std = Std::C17;
1464        assert!(run(&opts, source).failed());
1465    }
1466
1467    #[test]
1468    fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
1469        let mut opts = options();
1470        opts.emit = EmitKind::Object;
1471        let result = run(&opts, "int x = 1;\n");
1472        assert!(!result.failed(), "{:?}", result.messages);
1473        assert!(result.text().is_empty());
1474        // And it still finds what the checking finds, so a later kind on a broken file is not
1475        // a silent success.
1476        assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
1477    }
1478
1479    /// The machine code of `source`, insisting that it compiled cleanly.
1480    fn mir(source: &str) -> String {
1481        let mut opts = options();
1482        opts.emit = EmitKind::MirFinal;
1483        let result = run(&opts, source);
1484        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1485        result.text().to_owned()
1486    }
1487
1488    /// The whole compiler in one assertion, which is what this emit kind is for.
1489    ///
1490    /// C in, machine instructions out, every register a real one and every frame offset a
1491    /// number. Everything between the two is checked somewhere else, one pass at a time. What is
1492    /// checked here is that the passes are joined up and that the driver runs them.
1493    #[test]
1494    fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
1495        let text = mir("int add(int a, int b) { return a + b; }\n");
1496        assert!(text.starts_with("mfunc @add {"), "{text}");
1497        assert!(text.contains("x64.add_rr_32"), "{text}");
1498        assert!(text.contains("x64.ret"), "{text}");
1499        // A virtual register is what the allocator was there to remove, so one left in the
1500        // output is the difference between code and something that looks like code.
1501        assert!(!text.contains('%'), "{text}");
1502    }
1503
1504    /// A declaration has no body, so there is nothing to generate for one and nothing is.
1505    #[test]
1506    fn a_function_with_no_body_produces_no_machine_function() {
1507        let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1508        assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1509        assert!(text.contains("mfunc @f {"), "{text}");
1510        assert!(text.contains("x64.call"), "{text}");
1511    }
1512
1513    /// Two functions come out in the order the module holds them, which is source order.
1514    #[test]
1515    fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1516        let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1517        let first = text.find("mfunc @a").expect("the first function");
1518        let second = text.find("mfunc @b").expect("the second function");
1519        assert!(first < second, "{text}");
1520    }
1521
1522    /// The target reaches the back end, so the same C is different instructions on Windows.
1523    #[test]
1524    fn the_target_decides_which_convention_the_generated_code_follows() {
1525        let mut opts = options();
1526        opts.emit = EmitKind::MirFinal;
1527        let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1528        assert!(linux.contains("$rdi"), "{linux}");
1529
1530        opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1531        let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1532        assert!(windows.contains("$rcx"), "{windows}");
1533        assert!(!windows.contains("$rdi"), "{windows}");
1534    }
1535
1536    /// A target with no back end says so rather than generating something for another machine.
1537    #[test]
1538    fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1539        let mut opts = options();
1540        opts.emit = EmitKind::MirFinal;
1541        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1542        let result = run(&opts, "int f(int a) { return a; }\n");
1543        assert!(result.failed());
1544        assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1545        assert!(result.text().is_empty());
1546    }
1547
1548    /// A construct the rule set does not reach yet is named, along with the function it is in.
1549    ///
1550    /// The message is about this compiler being unfinished rather than about the program, which
1551    /// is valid C either way, so it carries the note that says where the work is tracked. Both
1552    /// functions are attempted, so a file that is ahead of the back end in three places says so
1553    /// three times rather than one recompilation at a time.
1554    #[test]
1555    fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1556        let mut opts = options();
1557        opts.emit = EmitKind::MirFinal;
1558        let source = "void a(int n) { int v[n]; v[0] = 1; }\n\
1559                      void b(int n) { int v[n]; v[0] = 1; }\n";
1560        let result = run(&opts, source);
1561        assert!(result.failed());
1562        assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1563        assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1564        assert!(result.messages[0].contains("no rule lowers a `stacksave`"), "{:?}", result);
1565        assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1566        assert!(result.text().is_empty());
1567    }
1568
1569    /// An opcode the rule language has no word for is named anyway, and pointed at.
1570    ///
1571    /// The rule language's spelling is the better name when there is one, but an opcode it has
1572    /// no word for is exactly the opcode no rule lowers, so falling back to the opcode and the
1573    /// type is what makes the message say anything at all in the cases that happen. The span is
1574    /// the instruction's own, so the message lands on the line rather than on the file.
1575    #[test]
1576    fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1577        let mut opts = options();
1578        opts.emit = EmitKind::MirFinal;
1579        let result = run(&opts, "int f(int a) {\n  __int128 wide = a;\n  return (int) wide;\n}\n");
1580        assert!(result.failed());
1581        assert!(
1582            result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1583            "{result:?}"
1584        );
1585        assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1586        assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1587    }
1588
1589    /// The note names the issue tracker, which is where a reader finds out whether it is known.
1590    #[test]
1591    fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1592        let mut opts = options();
1593        opts.emit = EmitKind::MirFinal;
1594        let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1595        assert!(result.failed());
1596        let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1597        assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1598        assert!(!note.contains("spec/17-milestones.md"), "{note}");
1599    }
1600
1601    /// The two frame flags reach the frame, which is the only thing either of them does.
1602    #[test]
1603    fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1604        let source = "int f(int a) { return a; }\n";
1605        assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1606
1607        let mut opts = options();
1608        opts.emit = EmitKind::MirFinal;
1609        opts.frame_pointer = true;
1610        let kept = run(&opts, source).text().to_owned();
1611        assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1612    }
1613
1614    /// The assembly of `source`, insisting that it compiled cleanly.
1615    fn asm(source: &str) -> String {
1616        let mut opts = options();
1617        opts.emit = EmitKind::Asm;
1618        let result = run(&opts, source);
1619        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1620        result.text().to_owned()
1621    }
1622
1623    /// `-S`, which is the same compiler as the kind above it with a different last step.
1624    ///
1625    /// What the assembly says is checked in `rucc-asm`, one instruction at a time and against the
1626    /// target's own description of what an instruction is. What is checked here is that a C file
1627    /// goes all the way to a listing an assembler would take, which means the directives around
1628    /// the function as well as the instructions in it.
1629    #[test]
1630    fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1631        let text = asm("int add(int a, int b) { return a + b; }\n");
1632        assert!(text.contains("\t.globl\tadd\n"), "{text}");
1633        assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1634        assert!(text.contains("\nadd:\n"), "{text}");
1635        assert!(text.contains("\taddl\t"), "{text}");
1636        assert!(text.contains("\tret\n"), "{text}");
1637        assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1638        // Without this the stack the program runs on is executable, which is not a default
1639        // anybody chose and is not a thing a reader would notice missing.
1640        assert!(text.contains(".note.GNU-stack"), "{text}");
1641    }
1642
1643    /// A call through a function pointer, which is a different instruction from a call to a name.
1644    ///
1645    /// Both are in the one function on purpose. What is being read is that the two calls are told
1646    /// apart all the way down: one carries a name the linker resolves and one carries a register,
1647    /// and neither turns into the other on the way.
1648    #[test]
1649    fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1650        let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1651        assert!(text.contains("\tcall\t*%"), "{text}");
1652        assert!(text.contains("\tcall\tg\n"), "{text}");
1653        // The address arrived in the first argument register and the argument the call passes has
1654        // to end up there, so the two cannot be the same register and the compiler has to have
1655        // moved one of them.
1656        assert!(text.contains("%rdi"), "{text}");
1657    }
1658
1659    /// A name at file scope, which is the one address a function cannot compute for itself.
1660    #[test]
1661    fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1662        let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1663        assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1664    }
1665
1666    /// A cast between a pointer and an integer as wide as one, which is every one C writes here.
1667    #[test]
1668    fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1669        let text = asm("long f(void *p) { return (long)p; }\n");
1670        // Every instruction in the body is a full width move or the return. The copies are the
1671        // allocator taking no hints, and what matters here is what is not among them: nothing
1672        // narrows the value and nothing widens it again, which is what a cast that did something
1673        // would look like.
1674        for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1675            let mnemonic = line.split_whitespace().next().unwrap_or("");
1676            assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1677        }
1678    }
1679
1680    /// The arguments past the sixth arrive in the caller's memory rather than in a register, and
1681    /// where that memory is depends on what the prologue did, so this is checked at the end of the
1682    /// pipeline rather than in the middle of it.
1683    #[test]
1684    fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
1685        let six = "long a, long b, long c, long d, long e, long f";
1686        let text = asm(&format!("long f({six}, long g, long h) {{ return g + h; }}\n"));
1687
1688        // Nothing is pushed and no frame is taken, so the only thing between the stack pointer and
1689        // the caller's arguments is the return address the call pushed. Which is where gcc 16.2.0
1690        // reads them from too, at `-O0`, in the same two instructions.
1691        assert!(text.contains("\tmovq\t8(%rsp), "), "{text}");
1692        assert!(text.contains("\tmovq\t16(%rsp), "), "{text}");
1693
1694        // A narrower one is read at its own width, because the bits above it are bits the
1695        // convention says nothing about, and one in the other register file with the other file's
1696        // instruction.
1697        let narrow = asm(&format!("int f({six}, int g) {{ return g; }}\n"));
1698        assert!(narrow.contains("\tmovl\t8(%rsp), "), "{narrow}");
1699        let eight =
1700            "double a, double b, double c, double d, double e, double f, double g, double h";
1701        let float = asm(&format!("double f({eight}, double i) {{ return i; }}\n"));
1702        assert!(float.contains("\tmovsd\t8(%rsp), "), "{float}");
1703    }
1704
1705    /// The other end of the same thing. What the caller writes is at the stack pointer, because
1706    /// that is the bottom of its frame and the bottom of its frame is where the callee looks.
1707    #[test]
1708    fn a_call_writes_the_arguments_with_no_register_left_at_the_stack_pointer() {
1709        let six = "1, 2, 3, 4, 5, 6";
1710        let decl = "long g(long, long, long, long, long, long, long, long);\n";
1711        let text = asm(&format!("{decl}long f(void) {{ return g({six}, 7, 8); }}\n"));
1712
1713        assert!(text.contains("\tmovq\t%"), "{text}");
1714        assert!(text.contains(", (%rsp)\n"), "{text}");
1715        assert!(text.contains(", 8(%rsp)\n"), "{text}");
1716        // And it reserved the bytes it wrote into, so nothing else in the frame is on top of them.
1717        assert!(text.contains("\tsubq\t$"), "{text}");
1718
1719        // A narrower one is written at its own width, matching what the callee reads it back with.
1720        let narrow = "int g(int, int, int, int, int, int, int);\n";
1721        let text = asm(&format!("{narrow}int f(void) {{ return g({six}, 7); }}\n"));
1722        assert!(text.contains("\tmovl\t%"), "{text}");
1723        assert!(text.contains(", (%rsp)\n"), "{text}");
1724    }
1725
1726    /// The count a variadic callee on this convention reads is a count of vector registers, so a
1727    /// float that ran out of them and went to memory is not in it.
1728    #[test]
1729    fn a_variadic_call_counts_registers_and_not_arguments() {
1730        let nine = "1., 2., 3., 4., 5., 6., 7., 8., 9.";
1731        let decl = "int g(int, ...);\n";
1732        let text = asm(&format!("{decl}int f(void) {{ return g(0, {nine}); }}\n"));
1733
1734        assert!(text.contains("\tmovl\t$8, "), "eight registers, not nine: {text}");
1735        assert!(text.contains("\tmovsd\t%"), "{text}");
1736        assert!(text.contains(", (%rsp)\n"), "{text}");
1737    }
1738
1739    /// The callee's half of the same convention. Every argument register it was handed is written
1740    /// into its frame on the way in, because which of them hold anything is a thing only the caller
1741    /// knew, and the ones the signature does name are left out because `va_start` sets the offsets
1742    /// past them and nothing ever reads their slots.
1743    #[test]
1744    fn a_variadic_function_writes_the_argument_registers_it_was_handed_into_its_frame() {
1745        let body =
1746            "__builtin_va_list ap; __builtin_va_start(ap, n); __builtin_va_end(ap); return n;";
1747        let text = asm(&format!("int f(int n, ...) {{ {body} }}\n"));
1748
1749        // Five general purpose registers and eight vector ones, since the one parameter the
1750        // signature names took the first of the six.
1751        let stores = |mnemonic: &str| text.matches(&format!("\t{mnemonic}\t%")).count();
1752        assert!(text.contains(", 8(%r"), "the second slot, not the first: {text}");
1753        assert!(!text.contains(", 0(%r"), "{text}");
1754        assert_eq!(stores("movsd"), 8, "every vector register: {text}");
1755
1756        // And the area is one of the function's own stack objects, so the frame holds it.
1757        assert!(text.contains("\tsubq\t$"), "{text}");
1758    }
1759
1760    /// What `va_start` writes is the four fields of the list, and the two numbers among them are
1761    /// where the arguments the signature names left the walk over each file's registers.
1762    #[test]
1763    fn va_start_writes_the_four_fields_the_psabi_describes() {
1764        let start = "__builtin_va_list ap; __builtin_va_start(ap, d);";
1765        let params = "int a, int b, int c, double d";
1766        let text = asm(&format!("int f({params}, ...) {{ {start} return a; }}\n"));
1767
1768        // Three integers took three of the six general purpose registers, and one double took one
1769        // of the eight vector ones, so the walk starts at twenty four bytes into the first half and
1770        // sixteen bytes into the second, which begins at forty eight.
1771        assert!(text.contains("	movl	$24, "), "{text}");
1772        assert!(text.contains("	movl	$64, "), "{text}");
1773        // The other two fields are addresses rather than numbers, so each is stored as a word and
1774        // each is a `lea` away. One of them reaches above the frame, which is where the caller's
1775        // arguments are and is the only thing in this function that is not below the stack pointer.
1776        assert!(text.contains(", 8(%r"), "{text}");
1777        assert!(text.contains(", 16(%r"), "{text}");
1778        let frame: u32 = text
1779            .lines()
1780            .find_map(|line| line.trim().strip_prefix("subq	$")?.split(',').next()?.parse().ok())
1781            .expect("a variadic function takes a frame for the save area");
1782        let above = |line: &str| {
1783            let at: u32 = line.trim().strip_prefix("leaq	")?.split('(').next()?.parse().ok()?;
1784            Some(at > frame)
1785        };
1786        assert!(text.lines().filter_map(above).any(|it| it), "{frame}: {text}");
1787    }
1788
1789    /// A `va_arg` is a branch on whether the argument it wants is still in the save area, and which
1790    /// of the two halves it walks is the type's answer.
1791    #[test]
1792    fn va_arg_branches_on_whether_the_argument_is_still_in_the_save_area() {
1793        let read = "__builtin_va_list ap; __builtin_va_start(ap, n);";
1794        let ints = format!("int f(int n, ...) {{ {read} return __builtin_va_arg(ap, int); }}\n");
1795        let text = asm(&ints);
1796
1797        // The last general purpose slot begins at forty, so an offset above it is an argument the
1798        // caller left in its own memory instead.
1799        assert!(text.contains("$40, "), "{text}");
1800        assert!(text.contains("	cmpl	"), "{text}");
1801        assert!(text.contains("	setbe	"), "unsigned, since an offset is a count of bytes: {text}");
1802
1803        let arg = "__builtin_va_arg(ap, double)";
1804        let text = asm(&format!("double f(int n, ...) {{ {read} return {arg}; }}\n"));
1805        assert!(text.contains("$160, "), "the last vector slot: {text}");
1806    }
1807
1808    /// A structure assigned is a copy of a known size, and a copy of a known size is a run of
1809    /// moves rather than a call to a library this compiler has no way to reach yet.
1810    #[test]
1811    fn a_structure_assignment_is_a_move_for_each_word_of_it() {
1812        let decl = "struct pair { long a, b; };\n";
1813        let body = "struct pair p = *q; return p.a + p.b;";
1814        let text = asm(&format!("{decl}long f(struct pair *q) {{ {body} }}\n"));
1815
1816        assert!(!text.contains("memcpy"), "nothing calls the library: {text}");
1817        assert!(!text.contains("\tcall"), "{text}");
1818        // Sixteen bytes aligned to eight is two words, and each is a load and a store.
1819        assert!(text.matches("\tmovq\t").count() >= 4, "two words each way: {text}");
1820    }
1821
1822    /// A word is as wide as the object is aligned to and no wider, so a character array is copied
1823    /// a byte at a time and a structure of longs eight bytes at a time.
1824    #[test]
1825    fn how_wide_a_word_of_a_copy_is_follows_the_alignment() {
1826        let decl = "struct bytes { char a[8]; };\n";
1827        let body = "struct bytes p = *q; return p.a[0];";
1828        let text = asm(&format!("{decl}int f(struct bytes *q) {{ {body} }}\n"));
1829
1830        // Eight bytes aligned to one is eight words, and each is a load and a store.
1831        assert!(text.matches("\tmovb\t").count() >= 16, "a byte at a time: {text}");
1832    }
1833
1834    /// What an initialiser does not name is zero, which the front end writes as a fill and this
1835    /// writes as the byte spread across each word.
1836    #[test]
1837    fn the_part_of_an_initialiser_that_names_nothing_is_stored_as_zero() {
1838        let decl = "struct wide { long a, b, c; };\n";
1839        let text = asm(&format!("{decl}long f(void) {{ struct wide w = {{ 7 }}; return w.c; }}\n"));
1840
1841        assert!(!text.contains("memset"), "nothing calls the library: {text}");
1842        assert!(text.contains("\tmovq\t$0, ") || text.contains("$0, %"), "the zero: {text}");
1843    }
1844
1845    /// A copy too large to be worth unrolling is a call to the runtime, which is the C library on
1846    /// a hosted target and `rucc-builtins` on a freestanding one.
1847    #[test]
1848    fn a_copy_too_large_to_unroll_calls_the_runtime() {
1849        let decl = "struct huge { char a[4096]; };\n";
1850        let mut opts = options();
1851        opts.emit = EmitKind::Asm;
1852        let source = format!("{decl}void f(struct huge *p, struct huge *q) {{ *p = *q; }}\n");
1853        let result = run(&opts, &source);
1854        assert!(!result.failed(), "{:?}", result.messages);
1855        let text = result.text();
1856        assert!(text.contains("call") && text.contains("memcpy"), "{text}");
1857        // The size in the register the convention passes the third argument in, which is what
1858        // says the call was built from the convention and not from the shape of the IR.
1859        assert!(text.contains("4096"), "the size travels: {text}");
1860    }
1861
1862    /// A frame that had to force its own alignment cannot say how far away the caller's stack
1863    /// pointer was, so it reaches back through the frame pointer instead.
1864    #[test]
1865    fn a_realigned_frame_reads_them_through_the_frame_pointer() {
1866        let six = "long a, long b, long c, long d, long e, long f";
1867        let body = "_Alignas(32) long wide[4]; wide[0] = g; return wide[0];";
1868        let text = asm(&format!("long f({six}, long g) {{ {body} }}\n"));
1869
1870        // The frame pointer is saved and pointed at where it was saved before the alignment is
1871        // forced, so the caller's arguments stay a constant distance from it: one word for the
1872        // saved frame pointer and one for the return address.
1873        assert!(text.contains("\tandq\t$-32, %rsp"), "{text}");
1874        assert!(text.contains("\tmovq\t16(%rbp), "), "{text}");
1875        assert!(!text.contains("\tmovq\t16(%rsp), "), "{text}");
1876    }
1877
1878    /// The object format decides the directives, and the target decides the object format.
1879    #[test]
1880    fn the_target_decides_how_the_assembly_is_spelled() {
1881        let mut opts = options();
1882        opts.emit = EmitKind::Asm;
1883        opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1884        let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1885        assert!(text.contains("__TEXT,__text"), "{text}");
1886        assert!(text.contains("\n_f:\n"), "{text}");
1887        assert!(!text.contains(".note.GNU-stack"), "{text}");
1888    }
1889
1890    /// The object file of `source`, insisting that it compiled cleanly.
1891    fn obj(source: &str) -> Vec<u8> {
1892        let mut opts = options();
1893        opts.emit = EmitKind::Object;
1894        let result = run(&opts, source);
1895        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1896        match result.artifact {
1897            Artifact::Object(bytes) => bytes,
1898            other => panic!("expected an object, got {other:?}"),
1899        }
1900    }
1901
1902    /// `-c`, which is the last step of the three the back end can end with.
1903    ///
1904    /// What is in the file is checked in `rucc-object`, a field at a time. What is checked here is
1905    /// that a C file goes all the way to one, which is the whole compiler in one line and the
1906    /// thing that stops working when a layer between them changes its mind about something.
1907    #[test]
1908    fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1909        let bytes = obj("int add(int a, int b) { return a + b; }\n");
1910        assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1911        let text = asm("int add(int a, int b) { return a + b; }\n");
1912        assert!(
1913            text.contains("\taddl\t"),
1914            "and the listing of it is the same instructions:\n{text}"
1915        );
1916    }
1917
1918    /// A variable this file defines, which is what a reference to one has to resolve against.
1919    #[test]
1920    fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1921        let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1922        assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1923        assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1924        assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1925        // A zeroed variable carries its size and none of its bytes, and a `static` one is not
1926        // announced to the linker at all, which is the whole of what `static` means here.
1927        assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1928        assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1929        assert!(!text.contains(".globl\thidden"), "{text}");
1930        // Nothing writes through it, so it goes in a page the loader can map read only and every
1931        // process running the program can share.
1932        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1933    }
1934
1935    /// A bit-field with a value in it, which is written as the bytes the value lands in.
1936    ///
1937    /// The interesting one is the field whose lowest byte is zero. The bytes a bit-field
1938    /// initializer makes are put together first and then taken back out as the run they make,
1939    /// and taking them out starts at the byte the field starts at, so a zero byte at the front
1940    /// used to end the object up in `.bss` with the rest of its value thrown away.
1941    #[test]
1942    fn a_bit_field_initializer_writes_every_byte_of_the_value_and_not_only_the_ones_that_are_set() {
1943        let text = asm("struct s { unsigned f : 20; } x = { 0x12300 };\n");
1944        assert!(text.contains("\t.data\n"), "there is something to write: {text}");
1945        assert!(text.contains("\nx:\n\t.ascii\t\"\\000#\\001\"\n"), "and it is the value: {text}");
1946
1947        // Two fields, the first of them zero, which is the same thing said with the zero byte
1948        // inside the run rather than at the front of it.
1949        let text = asm("struct s { unsigned a : 8; unsigned b : 8; } x = { 0, 3 };\n");
1950        assert!(text.contains("\nx:\n\t.ascii\t\"\\000\\003\"\n"), "{text}");
1951
1952        // Wider than an `int`, which is the same code and is worth saying because the value no
1953        // longer fits in the thirty two bits a bit-field used to be read at.
1954        let text = asm("struct s { unsigned long long f : 40; } x = { 0x100000 };\n");
1955        assert!(text.contains("\nx:\n\t.ascii\t\"\\000\\000\\020\"\n\t.space\t5\n"), "{text}");
1956
1957        // Nothing in it, which still costs no bytes in the file.
1958        let text = asm("struct s { unsigned f : 20; } x = { 0 };\n");
1959        assert!(text.contains("\t.bss\n"), "an object of zeroes is zeroes: {text}");
1960        assert!(text.contains("\nx:\n\t.space\t4\n"), "{text}");
1961    }
1962
1963    /// A string literal, which is a variable the program never named.
1964    #[test]
1965    fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1966        let text = asm("const char *f(void) { return \"hi\"; }\n");
1967        assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1968        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1969        let label = text
1970            .lines()
1971            .find(|line| line.starts_with(".Lstr"))
1972            .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1973        assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1974    }
1975
1976    /// A variable holding the address of another one, which is the only hole an image has in it.
1977    #[test]
1978    fn an_address_in_an_initializer_is_left_to_the_linker() {
1979        let source = "int counter;\nint *p = &counter;\n";
1980        let text = asm(source);
1981        assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1982        // And in the object it is eight zero bytes and a relocation, which is what the two paths
1983        // being one description is for.
1984        let bytes = obj(source);
1985        assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1986    }
1987
1988    /// A const table of function pointers, which is the shape that made SQLite link with a warning.
1989    ///
1990    /// The table is const so nothing in the program writes it, but the addresses in it are not
1991    /// numbers a link knows, so the loader writes it once at startup. Putting it in `.rodata`
1992    /// leaves a relocation in a section that is never writable, and what the linker does about
1993    /// that is set `DT_TEXTREL` on the whole image and say so. `.data.rel.ro` is writable for
1994    /// exactly as long as the loader is writing it and read only afterwards, which is what the
1995    /// program asked for in the first place.
1996    #[test]
1997    fn a_constant_holding_an_address_goes_in_the_section_the_loader_may_write_once() {
1998        // Both names are `static` and both are defined here, so nothing else can be the one that
1999        // defines them and the linker may lay the table out in the first pages of the segment.
2000        let text = asm("static void a(void) {}\nstatic void b(void) {}\n\
2001             struct m { void (*x)(void); void (*y)(void); };\n\
2002             const struct m t = { a, b };\n");
2003        assert!(text.contains("\t.section\t.data.rel.ro.local,\"aw\",@progbits\n"), "{text}");
2004        assert!(text.contains("\nt:\n\t.quad\ta\n\t.quad\tb\n"), "{text}");
2005
2006        // One name this file only declares is enough to lose the `.local` half, because a name the
2007        // link resolves from somewhere else is one another object may turn out to define.
2008        let text =
2009            asm("void a(void);\nstruct m { void (*x)(void); };\nconst struct m t = { a };\n");
2010        assert!(text.contains("\t.section\t.data.rel.ro,\"aw\",@progbits\n"), "{text}");
2011
2012        // And a constant with no address in it stays exactly where it was.
2013        let text = asm("const int fixed = 7;\n");
2014        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
2015    }
2016
2017    /// A thread-local variable, which is valid C that the back end does not build yet.
2018    #[test]
2019    fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
2020        let mut opts = options();
2021        opts.emit = EmitKind::Asm;
2022        let result = run(&opts, "_Thread_local int x = 1;\n");
2023        assert!(result.failed(), "every thread sharing one variable is worse than a message");
2024        assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
2025        // Not an internal error: nothing here is wrong and the note says where the work is.
2026        assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
2027    }
2028
2029    /// Not a rewording of the check above: what the two paths agree about is the point.
2030    #[test]
2031    fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
2032        // A call, because it is the one thing whose spelling in the two differs completely: the
2033        // listing writes a name and the object writes four zero bytes and a relocation asking the
2034        // linker for the same name. If either path had lost the callee, one of these would fail.
2035        let source = "int callee(void); int g(void) { return callee(); }\n";
2036        let bytes = obj(source);
2037        assert!(
2038            bytes.windows(7).any(|w| w == b"callee\0"),
2039            "the object has to name the callee for the linker to find it"
2040        );
2041        let text = asm(source);
2042        assert!(text.contains("\tcall\tcallee\n"), "{text}");
2043    }
2044
2045    /// What a file of a link contributes is an object, and the default emit is a link.
2046    ///
2047    /// This is here because getting it wrong is silent in the worst way: an empty file is a valid
2048    /// empty linker script, so a link fed one gets as far as reporting every symbol of the file as
2049    /// undefined and says nothing about the compilation that produced nothing.
2050    #[test]
2051    fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
2052        let mut opts = options();
2053        // What a command line with no `-c` and no `-S` on it asks for.
2054        opts.emit = EmitKind::Executable;
2055        let result = run(&opts, "int main(void) { return 0; }\n");
2056        assert_eq!(result.messages, Vec::<String>::new());
2057        match result.artifact {
2058            Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
2059            other => panic!("expected an object, got {other:?}"),
2060        }
2061    }
2062
2063    /// A target with a back end but no object writer says so rather than writing the wrong file.
2064    #[test]
2065    fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
2066        let mut opts = options();
2067        opts.emit = EmitKind::Object;
2068        opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
2069        let result = run(&opts, "int f(void) { return 0; }\n");
2070        assert!(result.failed(), "an object nobody can read is worse than a message");
2071        assert!(
2072            result.messages.iter().any(|m| m.contains("no object writer")),
2073            "{:?}",
2074            result.messages
2075        );
2076    }
2077
2078    /// The IR of `source`, insisting that it compiled cleanly.
2079    fn ir(source: &str) -> String {
2080        let mut opts = options();
2081        opts.emit = EmitKind::Ir;
2082        let result = run(&opts, source);
2083        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2084        result.text().to_owned()
2085    }
2086
2087    /// What was said about `source`, insisting that something was.
2088    fn errors(source: &str) -> Vec<String> {
2089        let mut opts = options();
2090        opts.emit = EmitKind::Ir;
2091        let result = run(&opts, source);
2092        assert!(result.failed(), "expected this to be refused:\n{source}");
2093        result.messages
2094    }
2095
2096    /// The body of the one function in `source`, which is what most of these are about.
2097    fn body(source: &str) -> String {
2098        let text = ir(source);
2099        let (_, rest) = text.split_once("{\n").expect("a function definition");
2100        let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
2101        body.to_owned()
2102    }
2103
2104    /// What `-fgnu89-inline` is for, seen at the only place it shows: whether a body reached the
2105    /// module or only a declaration did.
2106    ///
2107    /// The C99 reading is the one an inline definition is written for and is not being changed
2108    /// here. What the flag is for is a program written before C99 swapped the two, which relies on
2109    /// `inline` alone leaving something behind for another unit to call, and there are twelve of
2110    /// those in the GCC torture suite alone.
2111    #[test]
2112    fn gnu89_inline_is_what_decides_whether_a_bare_inline_definition_reaches_the_module() {
2113        let source = "inline int f(int x) { return x + 1; }\n";
2114        let with = |flag: bool| {
2115            let mut opts = options();
2116            opts.emit = EmitKind::Ir;
2117            opts.gnu89_inline = flag;
2118            let result = run(&opts, source);
2119            assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile");
2120            result.text().to_owned()
2121        };
2122
2123        // Under C's reading the module holds the declaration and the calls in this unit go to
2124        // whatever definition another unit has, which is C 6.7.4p7 and is what gcc does too.
2125        assert!(!with(false).contains("block0"), "no body: {}", with(false));
2126
2127        // Under GNU's it is an ordinary external definition, so the body is there and the symbol
2128        // is one the linker can resolve against.
2129        assert!(with(true).contains("block0"), "a body: {}", with(true));
2130    }
2131
2132    /// The IR of `source` at one safety tier, insisting that it compiled cleanly.
2133    fn safe_ir(tier: rucc_session::Safety, source: &str) -> String {
2134        let mut opts = options();
2135        opts.emit = EmitKind::Ir;
2136        opts.safety = tier;
2137        let result = run(&opts, source);
2138        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2139        result.text().to_owned()
2140    }
2141
2142    const READS_THROUGH_A_POINTER: &str = "int read(int *p) { return p[1]; }\n";
2143
2144    #[test]
2145    fn a_build_that_did_not_ask_for_the_monitor_is_compiled_the_way_it_always_was() {
2146        // This is the load bearing test of the whole flag. The monitor is being built in the open
2147        // and every build in the world is compiled by this compiler with the flag absent, so a
2148        // check that leaked into that path would be a regression for everybody.
2149        let text = ir(READS_THROUGH_A_POINTER);
2150        assert!(!text.contains("check_"), "{text}");
2151        assert!(!text.contains("cap_of"), "{text}");
2152    }
2153
2154    #[test]
2155    fn asking_for_a_tier_puts_the_checks_in_before_the_optimizer_sees_them() {
2156        let text = safe_ir(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2157        assert!(text.contains("cap_of"), "{text}");
2158        assert!(text.contains("check_bounds"), "{text}");
2159        assert!(text.contains("check_live"), "{text}");
2160        // The subscript is address arithmetic, so J2 applies to it as well as J1.
2161        assert!(text.contains("check_deriv"), "{text}");
2162    }
2163
2164    #[test]
2165    fn the_three_tiers_that_are_not_off_all_check_the_same_accesses_so_far() {
2166        // What separates them is the reporter and the boundary, which are milestones S2 and S3.
2167        // Pinning it here means the day they stop agreeing, this test says so rather than the
2168        // difference going unnoticed.
2169        let detect = safe_ir(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2170        for tier in [rucc_session::Safety::Enforce, rucc_session::Safety::Kernel] {
2171            assert_eq!(safe_ir(tier, READS_THROUGH_A_POINTER), detect, "{tier}");
2172        }
2173    }
2174
2175    /// The safety summary of `source` at one tier, insisting that it compiled cleanly.
2176    fn summary(tier: rucc_session::Safety, source: &str) -> String {
2177        let mut opts = options();
2178        opts.emit = EmitKind::SafetySummary;
2179        opts.safety = tier;
2180        let result = run(&opts, source);
2181        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2182        result.text().to_owned()
2183    }
2184
2185    #[test]
2186    fn the_summary_counts_the_checks_that_went_in_and_the_ones_still_standing() {
2187        let text = summary(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2188        assert!(text.contains("\"tier\": \"detect\""), "{text}");
2189        // One load, so one of each of the two access checks, and the subscript is a derivation.
2190        assert!(
2191            text.contains("\"bounds\": { \"emitted\": 1, \"remaining\": 1, \"discharged\": 0 }"),
2192            "{text}"
2193        );
2194        assert!(
2195            text.contains(
2196                "\"derivation\": { \"emitted\": 1, \"remaining\": 1, \"discharged\": 0 }"
2197            ),
2198            "{text}"
2199        );
2200    }
2201
2202    #[test]
2203    fn a_build_without_the_monitor_summarises_as_a_build_with_no_checks_in_it() {
2204        // Which is the honest summary rather than an error. A build system that emits a summary
2205        // for every unit should get one for the units nobody asked to instrument too, and the
2206        // zeroes are what say that the guarantee over that file is nothing at all.
2207        let text = summary(rucc_session::Safety::Off, READS_THROUGH_A_POINTER);
2208        assert!(text.contains("\"tier\": \"off\""), "{text}");
2209        assert!(
2210            text.contains("\"bounds\": { \"emitted\": 0, \"remaining\": 0, \"discharged\": 0 }"),
2211            "{text}"
2212        );
2213    }
2214
2215    #[test]
2216    fn a_call_the_boundary_models_is_counted_apart_from_one_it_does_not() {
2217        let text = summary(
2218            rucc_session::Safety::Detect,
2219            "void *memcpy(void *, const void *, unsigned long);\n\
2220             int puts(const char *);\n\
2221             void f(char *d, char *s) { memcpy(d, s, 4); puts(d); }\n",
2222        );
2223        assert!(text.contains("\"interposed\": 1"), "{text}");
2224        assert!(text.contains("\"puts\""), "{text}");
2225        // The wrapper it was pointed at is ours, so it is not on the list of things this build
2226        // failed to model. Counting it there would make instrumenting a file look worse than
2227        // leaving it alone.
2228        assert!(!text.contains("__rucc_wrap_memcpy\""), "{text}");
2229    }
2230
2231    #[test]
2232    fn the_two_directions_a_pointer_crosses_the_boundary_are_counted_apart() {
2233        // `f` is a name the linker can bind to and takes a pointer, so a pointer arrives there.
2234        // `notes_open` is a library this build did not instrument, so a pointer comes back from
2235        // it. Both are crossings and neither is the other, which is why there are two numbers.
2236        let text = summary(
2237            rucc_session::Safety::Detect,
2238            "void *notes_open(void);\n\
2239             char *f(char *p) { char *q = notes_open(); return q ? q : p; }\n",
2240        );
2241        assert!(text.contains("\"crossings\": { \"entered\": 1, \"returned\": 1 }"), "{text}");
2242        assert!(text.contains("\"notes_open\""), "{text}");
2243    }
2244
2245    #[test]
2246    fn a_static_function_nobody_takes_the_address_of_is_not_a_crossing() {
2247        // Nothing outside the file can reach it, so a witness on its parameters would be counting
2248        // a crossing that does not happen.
2249        let text = summary(
2250            rucc_session::Safety::Detect,
2251            "static int len(const char *p) { return p ? 1 : 0; }\n\
2252             int f(void) { return len(\"x\"); }\n",
2253        );
2254        assert!(text.contains("\"crossings\": { \"entered\": 0, \"returned\": 0 }"), "{text}");
2255    }
2256
2257    /// The granule report for `source`, insisting that it compiled cleanly.
2258    fn granules(source: &str) -> String {
2259        let mut opts = options();
2260        opts.emit = EmitKind::TypeGranules;
2261        let result = run(&opts, source);
2262        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2263        result.text().to_owned()
2264    }
2265
2266    #[test]
2267    fn the_granule_report_names_every_record_and_both_keyings() {
2268        let text = granules(
2269            "struct hot { char *p; int a; int b; };\n\
2270             int f(struct hot *h) { return h->a; }\n",
2271        );
2272        assert!(text.contains("struct hot"), "{text}");
2273        // Both keyings are reported because which types count as one is a decision the design
2274        // has not made yet, and a report that picked one would be hiding the cost of the other.
2275        assert!(text.contains("every type distinct"), "{text}");
2276        assert!(text.contains("every pointer one type"), "{text}");
2277        assert!(text.contains("budget"), "{text}");
2278    }
2279
2280    #[test]
2281    fn a_record_nothing_uses_is_still_measured() {
2282        // The measurement is about what a program declares, not about what it runs, so a type
2283        // that is only ever declared still costs the plane whatever its layout costs.
2284        let text = granules("struct unused { long a; double b; };\nint f(void) { return 0; }\n");
2285        assert!(text.contains("struct unused"), "{text}");
2286    }
2287
2288    #[test]
2289    fn the_granule_report_stops_before_anything_is_lowered() {
2290        // A layout is settled at the closing brace, so lowering the function bodies would take
2291        // minutes on an amalgamation and answer nothing. The evidence that it stops is that a
2292        // body the back end has no way to compile still produces a report.
2293        let text = granules(
2294            "struct wide { long double d; };\n\
2295             long double f(long double x) { return x * x; }\n",
2296        );
2297        assert!(text.contains("struct wide"), "{text}");
2298    }
2299
2300    #[test]
2301    fn a_witness_reaches_the_assembler_as_a_call_to_the_runtime() {
2302        // The count only means anything if the call is really there, and a summary saying one is
2303        // there is not evidence that the back end emitted it.
2304        let text = safe_asm(rucc_session::Safety::Detect, "char *f(char *p) { return p; }\n");
2305        assert!(text.contains("\tcall\t__rucc_cap_witness\n"), "{text}");
2306    }
2307
2308    #[test]
2309    fn a_pointer_turned_into_an_integer_is_on_the_trust_set() {
2310        let text = summary(
2311            rucc_session::Safety::Detect,
2312            "unsigned long f(int *p) { return (unsigned long) p; }\n",
2313        );
2314        assert!(text.contains("\"exposed\": 1"), "{text}");
2315    }
2316
2317    /// The assembly of `source` at one safety tier, insisting that it compiled cleanly.
2318    fn safe_asm(tier: rucc_session::Safety, source: &str) -> String {
2319        let mut opts = options();
2320        opts.emit = EmitKind::Asm;
2321        opts.safety = tier;
2322        let result = run(&opts, source);
2323        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2324        result.text().to_owned()
2325    }
2326
2327    #[test]
2328    fn a_check_reaches_the_assembler_as_a_call_to_the_runtime() {
2329        let text = safe_asm(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2330        assert!(text.contains("\tcall\t__rucc_check_bounds\n"), "{text}");
2331        assert!(text.contains("\tcall\t__rucc_check_live\n"), "{text}");
2332        assert!(text.contains("\tcall\t__rucc_check_deriv\n"), "{text}");
2333    }
2334
2335    #[test]
2336    fn every_check_that_reached_the_assembler_has_a_row_describing_it() {
2337        // Three checks and three descriptors, each in the section the runtime's reporter reads.
2338        // The width is `rucc_safety::lower::WIDTH` and the row is `rucc_safe_rt::fail::Descriptor`,
2339        // and the two agreeing is what makes the address a check is handed mean anything.
2340        let text = safe_asm(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2341        let section = format!("\t.section\t{},", rucc_safety::SECTION);
2342        assert_eq!(text.matches(&section).count(), 3, "{text}");
2343        for index in 0..3 {
2344            let name = format!("__rucc_safety_desc_{index}");
2345            // Defined once and referenced once, because a descriptor nothing points at describes
2346            // nothing and a reference with no definition does not link.
2347            assert!(text.contains(&format!("{name}:\n")), "{text}");
2348            assert!(text.contains(&format!("{name}(%rip)")), "{text}");
2349        }
2350        assert!(!text.contains("__rucc_safety_desc_3"), "{text}");
2351    }
2352
2353    /// `__builtin_constant_p` is answered in the front end and never reaches the IR.
2354    ///
2355    /// gcc folds it after optimization, so its answer for an argument that is not written as a
2356    /// constant can differ between `-O0` and `-O2`. What is checked here is the front end's
2357    /// answer, which is the same at every level, and the four cases where gcc gives the same
2358    /// answer at both levels are the ones measured on gcc 16: a literal is one, a variable is
2359    /// zero, a string literal is one and the address of an object is zero.
2360    #[test]
2361    fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
2362        let text = ir(concat!(
2363            "int g;\n",
2364            "int a = __builtin_constant_p(1);\n",
2365            "int b = __builtin_constant_p(g);\n",
2366            "int c = __builtin_constant_p(\"abc\");\n",
2367            "int d = __builtin_constant_p(&g);\n",
2368            "int e = __builtin_constant_p(1.5);\n",
2369            "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
2370        ));
2371        assert!(text.contains("global @a : i32 = 1,"), "{text}");
2372        assert!(text.contains("global @b : i32 = 0,"), "{text}");
2373        assert!(text.contains("global @c : i32 = 1,"), "{text}");
2374        assert!(text.contains("global @d : i32 = 0,"), "{text}");
2375        assert!(text.contains("global @e : i32 = 1,"), "{text}");
2376        assert!(text.contains("global @h : i32 = 11,"), "{text}");
2377        assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
2378
2379        // The argument is not evaluated, which is what gcc does with it as well, so `i` is
2380        // still zero. The second constant is the answer, which nothing reads and which the
2381        // first pass that looks for dead code will take out.
2382        let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
2383        assert_eq!(text, "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 0\n    return %0\n");
2384    }
2385
2386    /// A library builtin is the library function of the same name, and the call says so.
2387    ///
2388    /// A program writes `__builtin_strlen` rather than `strlen` to reach the function the C
2389    /// library promises where its own name has been taken by a macro, and to say that the usual
2390    /// meaning is the one intended. So the name in the program and the name in the object file
2391    /// are two different names and the call carries the second one. gcc folds several of these
2392    /// when the arguments allow it, which is an optimization on top of a call that is already
2393    /// right rather than instead of it, so nothing here depends on any folding happening.
2394    #[test]
2395    fn a_call_to_a_library_builtin_reaches_the_library_function() {
2396        let text = body("void f(void) { __builtin_abort(); }\n");
2397        assert_eq!(text, "block0:\n    call @abort() : ()\n    return\n");
2398
2399        // Nothing declared either of these and nothing had to: the prefix is what says the name
2400        // belongs to the implementation, and the type comes out of `features.toml`.
2401        let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
2402        assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
2403        assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
2404        assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
2405    }
2406
2407    /// The absolute value family is four instructions and not a call, whoever declared the name.
2408    ///
2409    /// `abs`, `labs` and `llabs` are reserved to the implementation, so a program that writes one
2410    /// means the one the C library promises and the compiler is allowed to know what it does. The
2411    /// program in `gcc.c-torture/execute/20021127-1.c` is the one that insists: it defines `llabs`
2412    /// to abort and expects the call not to reach it. Measured against gcc 16.2.0, which writes a
2413    /// `neg` and a `cmovns` and never calls the definition either.
2414    ///
2415    /// The most negative value comes back as itself, which is what the arithmetic gives and what
2416    /// gcc's pair of instructions gives, and C says the answer is undefined there.
2417    #[test]
2418    fn the_absolute_value_family_is_the_magnitude_and_not_a_call() {
2419        let text = body(concat!(
2420            "long long llabs(long long);\n",
2421            "long long f(long long x) { return llabs(x); }\n",
2422        ));
2423        assert!(text.contains("%1 = iconst.i64 63"), "{text}");
2424        assert!(text.contains("%2 = ashr %0, %1"), "{text}");
2425        assert!(text.contains("%3 = xor %0, %2"), "{text}");
2426        assert!(text.contains("%4 = sub %3, %2"), "{text}");
2427        assert!(!text.contains("call"), "the call does not happen:\n{text}");
2428
2429        // The narrower two, whose width comes from the type the library gives the name and not
2430        // from anything at the call.
2431        let text = body("int abs(int);\nint f(int x) { return abs(x); }\n");
2432        assert!(text.contains("iconst.i32 31"), "{text}");
2433        let text = body("long labs(long);\nlong f(long x) { return labs(x); }\n");
2434        assert!(text.contains("iconst.i64 63"), "{text}");
2435
2436        // The prefixed spelling is the same node, and it is what a program writes to reach the
2437        // library's meaning where the plain name has been taken.
2438        let text = body("long long f(long long x) { return __builtin_llabs(x); }\n");
2439        assert!(!text.contains("call"), "{text}");
2440
2441        // A definition of the name in the same file changes nothing, which is the whole point.
2442        let text = ir(concat!(
2443            "long long llabs(long long b);\n",
2444            "long long g(long long x) { return llabs(x); }\n",
2445            "long long llabs(long long b) { return 7; }\n",
2446        ));
2447        assert!(!text.contains("call @llabs"), "{text}");
2448    }
2449
2450    /// A byte swap is one instruction and not a call, and nothing had to declare it.
2451    ///
2452    /// SQLite writes these for its page headers and glibc's `<endian.h>` defines `htobe32` and its
2453    /// neighbours as exactly these, so a program that reads a file format reaches one without ever
2454    /// naming it. There is no object file anywhere that defines `__builtin_bswap32`, so a call left
2455    /// standing here would not link.
2456    #[test]
2457    fn a_byte_swap_is_arithmetic_and_not_a_call() {
2458        let text = body("unsigned f(unsigned x) { return __builtin_bswap32(x); }\n");
2459        assert_eq!(text, "block0(%0: i32):\n    %1 = bswap %0\n    return %1\n");
2460
2461        // The argument is converted by the prototype the way any other call's would be, so the
2462        // swap happens at the width the name says and not at the width the program wrote.
2463        let text = body("unsigned f(unsigned char c) { return __builtin_bswap32(c); }\n");
2464        assert!(text.contains("zext.i32 %0"), "widened first: {text}");
2465        assert!(text.contains("bswap %1"), "and swapped at four bytes: {text}");
2466    }
2467
2468    /// Each of the three reverses in the width its name says, which is the type of the node.
2469    ///
2470    /// The width matters more here than it looks. `__builtin_bswap16` is the two bytes of a
2471    /// `uint16_t` exchanged, and if the node came out at the machine's width instead then the bits
2472    /// above the value would be dragged into the answer and the result would be zero.
2473    #[test]
2474    fn the_byte_swaps_reverse_at_the_width_their_name_says() {
2475        for (name, ty, width) in [
2476            ("__builtin_bswap16", "unsigned short", "i16"),
2477            ("__builtin_bswap32", "unsigned", "i32"),
2478            ("__builtin_bswap64", "unsigned long long", "i64"),
2479        ] {
2480            let source = format!("{ty} f({ty} x) {{ return {name}(x); }}\n");
2481            let text = body(&source);
2482            assert_eq!(
2483                text,
2484                format!("block0(%0: {width}):\n    %1 = bswap %0\n    return %1\n"),
2485                "{name}"
2486            );
2487        }
2488    }
2489
2490    /// The three bit counts the IR has an instruction for are that instruction and not a call.
2491    ///
2492    /// Fifteen rows of `features.toml` come out of five questions, and three of the five are one
2493    /// instruction each. The kernel's bitmap search is built on them, ffmpeg counts leading zeroes
2494    /// in its bitstream reader and SQLite uses one to size a page, so a call left standing here
2495    /// would not link against anything and would be slow if it did.
2496    #[test]
2497    fn the_bit_counts_are_instructions_and_not_calls() {
2498        let text = body("int f(unsigned x) { return __builtin_clz(x); }\n");
2499        assert_eq!(text, "block0(%0: i32):\n    %1 = ctlz %0\n    return %1\n");
2500
2501        let text = body("int f(unsigned x) { return __builtin_ctz(x); }\n");
2502        assert_eq!(text, "block0(%0: i32):\n    %1 = cttz %0\n    return %1\n");
2503
2504        let text = body("int f(unsigned x) { return __builtin_popcount(x); }\n");
2505        assert_eq!(text, "block0(%0: i32):\n    %1 = ctpop %0\n    return %1\n");
2506    }
2507
2508    /// The width counted is the operand's and the width answered is `int`, which are two different
2509    /// things at every spelling but the narrowest.
2510    ///
2511    /// This is the mistake the family invites. `__builtin_clz` of a value counts the leading zeroes
2512    /// of it narrowed to `unsigned int` and `__builtin_clzll` counts them at sixty four bits, and
2513    /// those are different numbers for the same value. What decides it is the prototype the row
2514    /// carries, so the count happens after the conversion and the narrowing back to `int` happens
2515    /// after the count.
2516    #[test]
2517    fn the_bit_counts_ask_about_the_width_their_name_says() {
2518        let text = body("int f(unsigned long long x) { return __builtin_clzll(x); }\n");
2519        assert!(text.starts_with("block0(%0: i64):"), "counted at eight bytes: {text}");
2520        assert!(text.contains("%1 = ctlz %0"), "{text}");
2521        assert!(text.contains("trunc.i32 %1"), "and answered in an int: {text}");
2522
2523        // The same value asked about at the narrower width, which converts first and so counts
2524        // something else.
2525        let text = body("int f(unsigned long long x) { return __builtin_clz(x); }\n");
2526        assert!(text.contains("trunc.i32 %0"), "narrowed to what was asked about: {text}");
2527        assert!(text.contains("ctlz %1"), "and counted there: {text}");
2528
2529        let text = body("int f(unsigned long x) { return __builtin_popcountl(x); }\n");
2530        assert!(text.contains("%1 = ctpop %0"), "{text}");
2531        assert!(!text.contains("call"), "{text}");
2532    }
2533
2534    /// A parity is whether the count of set bits is odd, which is that count and its low bit.
2535    ///
2536    /// Not the machine's parity flag, which on x86-64 is over the low byte of a result and so is a
2537    /// different question, and not the count itself, since C says the answer is zero or one.
2538    #[test]
2539    fn a_parity_is_the_low_bit_of_the_set_bit_count() {
2540        let text = body("int f(unsigned x) { return __builtin_parity(x); }\n");
2541        assert!(text.contains("%1 = ctpop %0"), "{text}");
2542        assert!(text.contains("iconst.i32 1"), "{text}");
2543        assert!(text.contains("and %1, %2"), "the low bit of it: {text}");
2544    }
2545
2546    /// `__builtin_ffs` is the trailing zero count and one, kept only when there was a bit to find.
2547    ///
2548    /// The one in the family defined at zero, where it answers zero. Written as a mask rather than
2549    /// as a branch: the count and the comparison do not depend on each other and both are cheap, so
2550    /// a branch would buy nothing and cost two blocks and a join.
2551    #[test]
2552    fn the_first_set_bit_is_one_based_and_zero_for_a_zero() {
2553        let text = body("int f(int x) { return __builtin_ffs(x); }\n");
2554        assert!(text.contains("%1 = cttz %0"), "{text}");
2555        assert!(text.contains("%4 = add %1, %2"), "one more than the count: {text}");
2556        assert!(text.contains("%5 = icmp ne %0, %3"), "whether there was a bit at all: {text}");
2557        assert!(text.contains("%7 = sub %3, %6"), "spread to a mask: {text}");
2558        assert!(text.contains("%8 = and %4, %7"), "and kept only then: {text}");
2559        assert!(!text.contains("br_if"), "no branch: {text}");
2560    }
2561
2562    /// The three overflow checks are arithmetic and a flag, and not a call to anything.
2563    ///
2564    /// gcc has emitted these since 5.0 and there is no object file that defines one, so a call left
2565    /// standing here would not link. SQLite reaches all three within twenty lines of each other, in
2566    /// `sqlite3AddInt64` and its two neighbours, which is the reason they were done now.
2567    ///
2568    /// The IR instruction answers two things at once, the wrapped value and whether it wrapped,
2569    /// which is a shape nothing else in the IR has. The store is the builtin writing the answer
2570    /// through the pointer it was handed.
2571    #[test]
2572    fn an_overflow_check_is_arithmetic_and_not_a_call() {
2573        let text =
2574            body("int f(int a, int b, int *r) { return __builtin_add_overflow(a, b, r); }\n");
2575        assert!(text.contains("%3, %4 = sadd_overflow.(i32, i1) %0, %1"), "{text}");
2576        assert!(text.contains("store %3 -> %2"), "{text}");
2577        assert!(!text.contains("call"), "{text}");
2578
2579        let text =
2580            body("int f(int a, int b, int *r) { return __builtin_sub_overflow(a, b, r); }\n");
2581        assert!(text.contains("ssub_overflow.(i32, i1) %0, %1"), "{text}");
2582
2583        let text =
2584            body("int f(int a, int b, int *r) { return __builtin_mul_overflow(a, b, r); }\n");
2585        assert!(text.contains("smul_overflow.(i32, i1) %0, %1"), "{text}");
2586
2587        // Unsigned operands get the unsigned form, which is a different question about the same
2588        // arithmetic: an unsigned sum wraps where a signed one of the same bits does not.
2589        let text = body(
2590            "int f(unsigned a, unsigned b, unsigned *r) { return __builtin_add_overflow(a, b, r); }\n",
2591        );
2592        assert!(text.contains("uadd_overflow.(i32, i1) %0, %1"), "{text}");
2593    }
2594
2595    /// The arithmetic happens at a type that holds every value all three written types can hold.
2596    ///
2597    /// That is what makes the check exact. `unsigned int` and `int` in one call need thirty three
2598    /// bits between them, so the add is done at sixty four with each operand extended the way its
2599    /// own signedness says: the unsigned one zero extended, the signed one sign extended. Sign
2600    /// extending the unsigned one would turn three billion into a negative number before the
2601    /// addition ever saw it.
2602    #[test]
2603    fn an_overflow_check_is_done_at_a_type_that_holds_every_operand() {
2604        let text = body(
2605            "int f(unsigned a, int b, long long *r) { return __builtin_add_overflow(a, b, r); }\n",
2606        );
2607        assert!(text.contains("%3 = zext.i64 %0"), "the unsigned operand keeps its value: {text}");
2608        assert!(text.contains("%4 = sext.i64 %1"), "and so does the signed one: {text}");
2609        assert!(text.contains("sadd_overflow.(i64, i1) %3, %4"), "{text}");
2610
2611        // Three types that agree need no extension at all, which is what nearly every real call
2612        // is written as.
2613        let text = body(
2614            "int f(long long a, long long b, long long *r) { return __builtin_mul_overflow(a, b, r); }\n",
2615        );
2616        assert!(text.contains("smul_overflow.(i64, i1) %0, %1"), "{text}");
2617        assert!(!text.contains("sext."), "{text}");
2618        // The one widening left is the answer, which is a bit becoming the `int` C says it is.
2619        assert!(!text.contains("zext.i64"), "{text}");
2620    }
2621
2622    /// The wrapped answer is written through the pointer whether or not it fit.
2623    ///
2624    /// That is gcc's rule and it is what makes the builtin usable as a wrapping add with a flag on
2625    /// the side. A destination narrower than the arithmetic is narrowed and widened back, and the
2626    /// answer being different is the second half of the test: the instruction says whether the
2627    /// arithmetic itself needed more room, and the round trip says whether what came out survived
2628    /// the trip down to where it was going.
2629    #[test]
2630    fn an_overflow_check_writes_the_wrapped_answer_whether_or_not_it_fit() {
2631        let text =
2632            body("int f(int a, int b, char *r) { return __builtin_sub_overflow(a, b, r); }\n");
2633        assert!(text.contains("%3, %4 = ssub_overflow.(i32, i1) %0, %1"), "{text}");
2634        assert!(text.contains("%5 = trunc.i8 %3"), "narrowed to where it goes: {text}");
2635        assert!(text.contains("%6 = sext.i32 %5"), "and back: {text}");
2636        assert!(text.contains("%7 = icmp ne %6, %3"), "which is whether it fit: {text}");
2637        assert!(text.contains("store %5 -> %2"), "the narrowed value is stored either way: {text}");
2638        assert!(text.contains("%8 = or %4, %7"), "and either bit is an overflow: {text}");
2639    }
2640
2641    /// A call needing more than sixty four bits is refused by name rather than got wrong.
2642    ///
2643    /// Two ways to reach it: a `__int128` operand, and a sixty four bit unsigned type mixed with a
2644    /// signed one, which needs sixty five bits to represent both. gcc handles the second by being
2645    /// cleverer in the mixed case rather than by widening. Until that is written, the message says
2646    /// what the call needed.
2647    #[test]
2648    fn a_call_needing_more_than_sixty_four_bits_says_so() {
2649        let refused = concat!(
2650            "int f(unsigned long long a, long long b, long long *r) {\n",
2651            "    return __builtin_add_overflow(a, b, r);\n",
2652            "}\n",
2653        );
2654        let messages = errors(refused);
2655        assert_eq!(messages.len(), 1, "{messages:?}");
2656        assert!(messages[0].contains("E0694"), "{messages:?}");
2657        assert!(messages[0].contains("wider than 64 bits"), "{messages:?}");
2658    }
2659
2660    /// An operand that is not an integer at all is the older message, from the type checking every
2661    /// type generic builtin shares.
2662    #[test]
2663    fn an_overflow_check_over_something_that_is_not_an_integer_says_so() {
2664        let messages =
2665            errors("int f(double a, int b, int *r) { return __builtin_add_overflow(a, b, r); }\n");
2666        assert!(messages.iter().any(|line| line.contains("E0671")), "{messages:?}");
2667
2668        let messages =
2669            errors("int f(int a, int b, double *r) { return __builtin_add_overflow(a, b, r); }\n");
2670        assert!(messages.iter().any(|line| line.contains("E0671")), "{messages:?}");
2671    }
2672
2673    /// An ordered access is an ordered access in the IR, with the ordering the program wrote.
2674    ///
2675    /// Which is the point of the node existing at all. An ordering is not an argument anything is
2676    /// passed, it is a thing the IR says about an access, so the number in the source is read once
2677    /// in the front end and after that the ordering travels on the instruction where every pass
2678    /// that moves code can see it.
2679    ///
2680    /// SQLite is why these are done: `AtomicLoad` and `AtomicStore` in `sqlite3.c` are
2681    /// `__atomic_load_n` and `__atomic_store_n` at the relaxed ordering, and there are thirty five
2682    /// calls to the pair.
2683    #[test]
2684    fn an_ordered_access_is_ordered_in_the_ir() {
2685        let text = body("int f(int *p) { return __atomic_load_n(p, 0); }\n");
2686        assert!(text.contains("atomic_load.i32 %0, align 4, relaxed"), "{text}");
2687
2688        let text = body("long f(long *p) { return __atomic_load_n(p, 2); }\n");
2689        assert!(text.contains("atomic_load.i64 %0, align 8, acquire"), "{text}");
2690
2691        let text = body("void f(int *p, int v) { __atomic_store_n(p, v, 3); }\n");
2692        assert!(text.contains("atomic_store %1 -> %0, align 4, release"), "{text}");
2693
2694        let text = body("void f(int *p, int v) { __atomic_store_n(p, v, 5); }\n");
2695        assert!(text.contains("atomic_store %1 -> %0, align 4, seq_cst"), "{text}");
2696
2697        // The value is converted to what the pointer points at before it is stored, which is what
2698        // the call would have done if it had a prototype to convert against.
2699        let text = body("void f(char *p, int v) { __atomic_store_n(p, v, 0); }\n");
2700        assert!(text.contains("trunc.i8 %1"), "{text}");
2701        assert!(text.contains("atomic_store %2 -> %0, align 1, relaxed"), "{text}");
2702    }
2703
2704    /// On this machine the ordered access is the plain instruction, except at the strongest
2705    /// ordering of a store.
2706    ///
2707    /// x86-64 is total store order: every load is already an acquire and every store is already a
2708    /// release, and an aligned access no wider than a word is indivisible whether or not anybody
2709    /// asked. So the whole family is `mov` and the one thing the machine does not give away is a
2710    /// store staying in front of a later load, which is `mfence` behind the store. Every line below
2711    /// is what gcc 16.2.0 writes for the same function.
2712    #[test]
2713    fn an_ordered_access_is_the_plain_instruction_on_this_machine() {
2714        let text = asm("int f(int *p) { return __atomic_load_n(p, 5); }\n");
2715        assert!(text.contains("movl\t(%rdi), %eax"), "{text}");
2716        assert!(!text.contains("mfence"), "a load needs no barrier here: {text}");
2717
2718        let text = asm("void f(int *p, int v) { __atomic_store_n(p, v, 3); }\n");
2719        assert!(text.contains("movl\t%esi, (%rdi)"), "{text}");
2720        assert!(!text.contains("mfence"), "a release store needs no barrier here: {text}");
2721
2722        let text = asm("void f(int *p, int v) { __atomic_store_n(p, v, 5); }\n");
2723        let (before, after) = text.split_once("mfence").expect("a barrier: {text}");
2724        assert!(before.contains("movl\t%esi, (%rdi)"), "the store comes first: {text}");
2725        assert!(!after.contains("movl"), "and nothing else is between them: {text}");
2726    }
2727
2728    /// A barrier is one instruction at the strongest ordering and no instruction below it.
2729    ///
2730    /// The same reasoning the other way round. An acquire, a release and an acquire release fence
2731    /// are already true of every program running on this machine, and what a program wanted from
2732    /// one is that the compiler not move accesses across it, which is already so by the time any
2733    /// instruction is picked. Sequential consistency is the one that costs something.
2734    ///
2735    /// `__sync_synchronize` is the older family's spelling of the strongest one and compiles to
2736    /// exactly the same instruction, which is what SQLite calls twice in `sqlite3.c`.
2737    #[test]
2738    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
2739        assert!(asm("void f(void) { __atomic_thread_fence(5); }\n").contains("mfence"));
2740        assert!(asm("void f(void) { __sync_synchronize(); }\n").contains("mfence"));
2741
2742        for weaker in ["1", "2", "3", "4"] {
2743            let source = format!("void f(void) {{ __atomic_thread_fence({weaker}); }}\n");
2744            assert!(!asm(&source).contains("mfence"), "{weaker} costs nothing here");
2745        }
2746    }
2747
2748    /// The two lock free questions are numbers in the program rather than calls to anything.
2749    ///
2750    /// Both answer from the size, which has to be a power of two no wider than the widest access
2751    /// this compiler writes, and from what the pointer says about the alignment. Sixteen bytes is
2752    /// no here and is no in gcc without `-mcx16`, because `cmpxchg16b` is not in the baseline and
2753    /// nothing here writes it. Three bytes is no because there is no three byte access at all.
2754    ///
2755    /// The whole point of both names is that the answer is available before the program runs, so
2756    /// what is checked is that a `mov` of a constant is the whole function and that no call was
2757    /// left behind. A call would be to `__atomic_is_lock_free` in libatomic, which is not a library
2758    /// this links against.
2759    #[test]
2760    fn the_lock_free_questions_are_answered_as_constants() {
2761        for size in ["1", "2", "4", "8"] {
2762            let source =
2763                format!("int f(void) {{ return __atomic_always_lock_free({size}, 0); }}\n");
2764            let text = asm(&source);
2765            assert!(text.contains("movb\t$1, %al"), "{size} bytes is lock free: {text}");
2766            assert!(!text.contains("call"), "and is not a call: {text}");
2767        }
2768        for size in ["3", "16", "sizeof(long double)"] {
2769            let source = format!("int f(void) {{ return __atomic_is_lock_free({size}, 0); }}\n");
2770            let text = asm(&source);
2771            assert!(text.contains("movb\t$0, %al"), "{size} bytes is not: {text}");
2772            assert!(!text.contains("call"), "and is not a call either: {text}");
2773        }
2774
2775        // A size the compiler cannot work out, which is no rather than a refusal, and an object
2776        // whose type is aligned under the size asked about, which is the whole of what the second
2777        // argument is for.
2778        let text = asm("int f(int n) { return __atomic_is_lock_free(n, 0); }\n");
2779        assert!(text.contains("movb\t$0, %al"), "a size nobody knows is not lock free: {text}");
2780        let text = asm("int f(int *p) { return __atomic_always_lock_free(8, p); }\n");
2781        assert!(text.contains("movb\t$0, %al"), "eight bytes at four is not: {text}");
2782        let text = asm("int f(long *p) { return __atomic_always_lock_free(8, p); }\n");
2783        assert!(text.contains("movb\t$1, %al"), "and at eight it is: {text}");
2784    }
2785
2786    /// A memory order an operation cannot carry is read as the strongest one, and said so about.
2787    ///
2788    /// There are three ways the number is not one the operation can take: it is not a constant at
2789    /// all, it is not one of the six the headers define, or it is one of them and means nothing for
2790    /// this operation, which is a release load or an acquire store. All three become sequential
2791    /// consistency, which is stronger than anything the program could have meant, so a program that
2792    /// wrote nonsense gets a correct answer rather than a fast one. gcc does the same.
2793    ///
2794    /// The last two also warn, because the number was written down and is wrong. The first does
2795    /// not: gcc takes a computed order, and so does the C11 spelling, so a warning there would fire
2796    /// on correct programs.
2797    #[test]
2798    fn a_memory_order_an_operation_cannot_carry_is_read_as_the_strongest() {
2799        let mut opts = options();
2800        opts.emit = EmitKind::Ir;
2801
2802        let acquire_store = run(&opts, "void f(int *p, int v) { __atomic_store_n(p, v, 2); }\n");
2803        assert!(acquire_store.text().contains("seq_cst"), "{:?}", acquire_store.text());
2804        assert!(acquire_store.messages[0].contains("[W0333]"), "{:?}", acquire_store.messages);
2805
2806        let nonsense = run(&opts, "int f(int *p) { return __atomic_load_n(p, 99); }\n");
2807        assert!(nonsense.text().contains("seq_cst"), "{:?}", nonsense.text());
2808        assert!(nonsense.messages[0].contains("[W0333]"), "{:?}", nonsense.messages);
2809
2810        let computed = run(&opts, "int f(int *p, int n) { return __atomic_load_n(p, n); }\n");
2811        assert!(computed.text().contains("seq_cst"), "{:?}", computed.text());
2812        assert_eq!(computed.messages, Vec::<String>::new(), "a computed order is not a mistake");
2813    }
2814
2815    /// A conversion between a float and the widest unsigned integer, which the machine has not got.
2816    ///
2817    /// Every other conversion between a float and an integer is the signed one at some width with a
2818    /// widening in front or a narrowing behind. These two are not, because there is no signed width
2819    /// that holds every value of an unsigned sixty four bit integer, so each is the signed
2820    /// conversion with arithmetic around it that brings the value into range and puts it back.
2821    ///
2822    /// What is checked here is that the conversion happens at all and that it happens without a
2823    /// branch. gcc writes a branch for both; this writes the choice as a mask, because every rewrite
2824    /// in that pass stays inside the block it started in. The arithmetic itself is checked in
2825    /// `rucc-codegen`, where it can be run against the answer rather than read in the assembly.
2826    #[test]
2827    fn a_conversion_between_a_float_and_the_widest_unsigned_integer_is_written_without_a_branch() {
2828        let text = asm("double f(unsigned long long x) { return (double)x; }\n");
2829        assert!(text.contains("cvtsi2sdq"), "the signed conversion is what runs: {text}");
2830        assert!(text.contains("shrq"), "with the value halved first: {text}");
2831        assert!(text.contains("addsd"), "and doubled after: {text}");
2832        assert!(!text.contains("\tj"), "and no branch anywhere: {text}");
2833
2834        let text = asm("unsigned long long f(double d) { return (unsigned long long)d; }\n");
2835        assert!(text.contains("cvttsd2siq"), "the signed conversion is what runs: {text}");
2836        assert!(text.contains("subsd"), "with half the range taken off first: {text}");
2837        assert!(text.contains("shlq\t$63"), "and the top bit put back: {text}");
2838        assert!(!text.contains("\tj"), "and no branch anywhere: {text}");
2839    }
2840
2841    /// The plain names are the library's only where nothing else has taken them.
2842    ///
2843    /// Four ways a program says it means something else. A `static` definition is its own
2844    /// function and the name outside the file is somebody else's. A declaration of another type
2845    /// is another function. `-fno-builtin` and `-fno-builtin-<name>` say so outright, and
2846    /// `-ffreestanding` says there is no C library for the name to be the name of. Every one of
2847    /// these was measured against gcc 16.2.0, which calls the program's function in all of them.
2848    ///
2849    /// The `__builtin_` spelling goes on meaning the library's function through all of it, which
2850    /// is what the prefix is for and what lets a freestanding build reach one deliberately.
2851    #[test]
2852    fn a_plain_name_the_program_took_is_the_programs_own_function() {
2853        let taken = concat!(
2854            "static long long llabs(long long b) { return 7; }\n",
2855            "long long f(long long x) { return llabs(x); }\n",
2856        );
2857        assert!(ir(taken).contains("call @llabs"), "a static definition is the program's own");
2858
2859        let retyped = concat!("int llabs(int b);\n", "int f(int x) { return llabs(x); }\n",);
2860        assert!(ir(retyped).contains("call @llabs"), "another type is another function");
2861
2862        let plain = concat!(
2863            "long long llabs(long long b);\n",
2864            "long long f(long long x) { return llabs(x); }\n",
2865        );
2866        let mut opts = options();
2867        opts.emit = EmitKind::Ir;
2868        assert!(!run(&opts, plain).text().contains("call @llabs"), "the library's by default");
2869
2870        opts.builtins = false;
2871        assert!(run(&opts, plain).text().contains("call @llabs"), "-fno-builtin");
2872
2873        opts.builtins = true;
2874        opts.no_builtin = vec!["llabs".to_owned()];
2875        assert!(run(&opts, plain).text().contains("call @llabs"), "-fno-builtin-llabs");
2876        let one = "long labs(long b);\nlong f(long x) { return labs(x); }\n";
2877        assert!(!run(&opts, one).text().contains("call @labs"), "one name and not the family");
2878
2879        // `-ffreestanding` reaches the front end as the same answer, which is what the driver
2880        // does with it in `compile`, and the prefixed spelling is untouched by any of it.
2881        opts.no_builtin = Vec::new();
2882        opts.builtins = false;
2883        let prefixed = "long long f(long long x) { return __builtin_llabs(x); }\n";
2884        assert!(!run(&opts, prefixed).text().contains("call @llabs"), "the prefix is a promise");
2885    }
2886
2887    /// The hint builtins are their first argument, and nothing is left of the hint.
2888    ///
2889    /// Which way a branch is expected to go is the whole of what they say, and there is nothing
2890    /// here that reads a branch weight yet, so what reaches the IR is the value and the hint is
2891    /// gone. The one thing the prototype has to keep doing is converting: gcc gives both of them
2892    /// a `long` result, so `sizeof(__builtin_expect((char)1, 1))` is eight and a narrower argument
2893    /// widens before it is answered with.
2894    ///
2895    /// Whether a side effect in the hint happens depends on the first argument, which is gcc's
2896    /// answer rather than a rule anybody designed. A constant first argument folds the whole call
2897    /// where it is written and the hint goes with it, and a first argument that is not a constant
2898    /// leaves the hint standing. Both halves are below and both were measured on gcc 16.2.0.
2899    #[test]
2900    fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
2901        let text = ir(concat!(
2902            "long a = __builtin_expect(7, 1);\n",
2903            "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
2904            "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
2905        ));
2906        assert!(text.contains("global @a : i64 = 7,"), "{text}");
2907        assert!(text.contains("global @b : i64 = 9,"), "{text}");
2908        assert!(text.contains("global @c : i64 = 8,"), "{text}");
2909        assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
2910
2911        // A narrower argument is widened by the prototype before it is handed back, and it is
2912        // widened with its sign, since the parameter is a signed `long`.
2913        let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
2914        assert!(text.contains("sext"), "{text}");
2915
2916        // The first argument is a constant, so the second is not evaluated and `i` is still zero,
2917        // and neither is the third. What is left of each statement is the first argument widened,
2918        // which nothing reads and which the first pass that looks for dead code will take out.
2919        let one = "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 1\n    %2 = sext.i64 %1\n    return %0\n";
2920        assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
2921        let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
2922        assert_eq!(body(source), one);
2923
2924        // The first argument is not a constant, so the hint runs and `i` comes back one. There is
2925        // an increment in the body and the value it returns is the load after it, which is what
2926        // gcc gives for the same program, and the whole of tamnd/rucc#584 is that this used to
2927        // come out the same as the pair above.
2928        let kept = body("int f(int n) { int i = 0; __builtin_expect(n, i++); return i; }\n");
2929        assert!(kept.contains("add.nsw"), "the hint still runs: {kept}");
2930        assert!(kept.ends_with("return %3\n"), "and the answer is what it left behind: {kept}");
2931        let both = "int g(int n) { int i = 0; __builtin_expect_with_probability(n, i++, 0.5); return i; }\n";
2932        assert!(body(both).contains("add.nsw"), "and so does the one with three arguments");
2933    }
2934
2935    /// A point control does not arrive at, in both of the ways the compiler has one.
2936    ///
2937    /// `__builtin_unreachable()` is the promise written down, and a function whose body can run
2938    /// off the bottom is the walk arriving at the same place on its own. Neither writes an
2939    /// instruction, which is what gcc 16.2.0 does at `-O0`: it emits the epilogue and the `ret`
2940    /// for both of the functions below and nothing else, and the two of them come out byte for
2941    /// byte the same there.
2942    ///
2943    /// The `ret` is the part worth holding on to. It is not there because anything runs it, it is
2944    /// there because a function whose last instruction is not a return is one that falls into
2945    /// whatever the assembler puts after it.
2946    #[test]
2947    fn a_promise_that_control_does_not_arrive_writes_no_instruction() {
2948        let promised = "int f(int x) { if (x) return 1; __builtin_unreachable(); }\n";
2949        let text = ir(promised);
2950        assert!(text.contains("    unreachable_hint\n"), "{text}");
2951        assert!(!text.contains("call"), "it is not a call to anything:\n{text}");
2952
2953        // The statement after it is still lowered. Continuing to translate a path the program
2954        // promised is dead is one of the things a compiler may do with undefined behaviour, and
2955        // it is the one that keeps a program built at `-O0` behaving the way it was watched to.
2956        let after = body("int g(int x) { __builtin_unreachable(); return x; }\n");
2957        assert!(after.contains("return"), "{after}");
2958
2959        // Both functions are the same instructions, because the hint writes none of them and the
2960        // terminator underneath it writes none either.
2961        let text = asm(promised);
2962        let mine = text.split_once("\nf:\n").expect("a definition").1;
2963        let mine = mine.split_once("\t.size").expect("a definition").0;
2964        let plain = asm("int f(int x) { if (x) return 1; }\n");
2965        let plain = plain.split_once("\nf:\n").expect("a definition").1;
2966        let plain = plain.split_once("\t.size").expect("a definition").0;
2967        assert_eq!(mine, plain);
2968        assert!(mine.trim_end().ends_with("ret"), "{mine}");
2969        assert!(!mine.contains("ud2"), "{mine}");
2970    }
2971
2972    /// The two names stay apart, which is what having both of them is for.
2973    ///
2974    /// The one the program wrote is what the call is checked against and what a diagnostic about
2975    /// it says, and the one the library defines is what the call ends up carrying. A compiler
2976    /// that kept only the second would report this against `abort`, which is a function the
2977    /// program never mentions.
2978    #[test]
2979    fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
2980        let mut opts = options();
2981        opts.emit = EmitKind::Ir;
2982        let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
2983        assert!(
2984            messages.iter().any(|m| m.contains("__builtin_abort")),
2985            "expected the written name in {messages:?}"
2986        );
2987    }
2988
2989    /// A builtin nothing lowers is refused where it is written, rather than at the link.
2990    ///
2991    /// The names are one from each shape the table holds: a `__builtin_` with a prototype, one
2992    /// whose type comes from the call it was written in, and one from each of the two older
2993    /// families whose prefix is not `__builtin_`. What the message has to carry is the name,
2994    /// because the whole complaint about the link error this replaces is that the name in it was
2995    /// one the compiler chose.
2996    #[test]
2997    fn a_builtin_nothing_lowers_is_refused_by_name() {
2998        let mut opts = options();
2999        opts.emit = EmitKind::Ir;
3000        for (builtin, call) in [
3001            ("__builtin_return_address", "(int)(long)__builtin_return_address(0)"),
3002            ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
3003            ("__atomic_exchange_n", "__atomic_exchange_n(&counter, 1, 0)"),
3004            ("__sync_fetch_and_add", "(int)__sync_fetch_and_add(&counter, 1)"),
3005        ] {
3006            let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
3007            let messages = run(&opts, &source).messages;
3008            let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
3009            assert!(named, "expected {builtin} to be refused by name in {messages:?}");
3010        }
3011    }
3012
3013    /// The refusal is about a call and not about the name, so the rest of what C does with one
3014    /// still works.
3015    ///
3016    /// `sizeof` does not evaluate its operand, so nothing is called and there is nothing to
3017    /// refuse; the type of the call is what it asks for and that comes from the front end. A
3018    /// program that defines the name itself gets the function it wrote, which is not what this
3019    /// is for but is what a definition in front of us means.
3020    #[test]
3021    fn what_is_refused_is_the_call_and_not_the_name() {
3022        let text = ir("unsigned long n = sizeof(__builtin_return_address(0));\n");
3023        assert!(text.contains("global @n : i64 = 8,"), "{text}");
3024
3025        let text = ir(concat!(
3026            "void *__builtin_return_address(unsigned x) { return 0; }\n",
3027            "void *f(void) { return __builtin_return_address(0); }\n",
3028        ));
3029        assert!(text.contains("call @__builtin_return_address"), "{text}");
3030    }
3031
3032    /// A `static` function nothing refers to is not emitted, and one that is refered to is.
3033    ///
3034    /// The pair is written as one program so that the two answers come out of one walk. What
3035    /// makes the difference is the call in `main` and nothing else about either definition.
3036    #[test]
3037    fn a_static_function_nothing_refers_to_is_not_emitted() {
3038        let text = ir("static int dropped(void) { return 1; }\n\
3039                       static int kept(void) { return 2; }\n\
3040                       int main(void) { return kept(); }\n");
3041        assert!(text.contains("func @kept"), "{text}");
3042        assert!(!text.contains("dropped"), "{text}");
3043    }
3044
3045    /// The set is transitive, so two of them that only call each other are both dropped.
3046    ///
3047    /// Counting the references to a name would keep this pair, since each is named once, and
3048    /// that is the mistake this is here to catch: what decides it is whether a root reaches the
3049    /// definition, and a root is something the file has a reason to emit on its own.
3050    #[test]
3051    fn two_static_functions_that_only_call_each_other_are_both_dropped() {
3052        let text = ir("static int ping(void);\n\
3053                       static int pong(void) { return ping(); }\n\
3054                       static int ping(void) { return pong(); }\n\
3055                       int main(void) { return 0; }\n");
3056        assert!(!text.contains("ping"), "{text}");
3057        assert!(!text.contains("pong"), "{text}");
3058    }
3059
3060    /// Everything that names a function keeps it, whether or not the name is being called.
3061    ///
3062    /// An address taken in a body, an image that holds one, and a body that is only reached
3063    /// through another `static` function are three different ways for a definition to be needed
3064    /// and none of them is a call at the top level of a reachable function.
3065    #[test]
3066    fn naming_a_static_function_anywhere_keeps_it() {
3067        let text = ir("static int by_address(void) { return 1; }\n\
3068                       static int in_an_image(void) { return 2; }\n\
3069                       static int deeper(void) { return 3; }\n\
3070                       static int reaches_deeper(void) { return deeper(); }\n\
3071                       static int (*table[1])(void) = {in_an_image};\n\
3072                       int main(void) {\n\
3073                         int (*p)(void) = by_address;\n\
3074                         return p() + table[0]() + reaches_deeper();\n\
3075                       }\n");
3076        for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
3077            assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
3078        }
3079    }
3080
3081    /// An attribute that says something outside the file reaches it keeps the definition.
3082    ///
3083    /// None of the five is implemented as anything else yet, and this is the part of each of
3084    /// them that a program notices first: a symbol a linker script names or a function the
3085    /// run-up to `main` calls is not written about anywhere a C file can see.
3086    #[test]
3087    fn an_attribute_keeps_a_static_function_nothing_refers_to() {
3088        for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
3089            let source = format!(
3090                "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
3091                 int main(void) {{ return 0; }}\n"
3092            );
3093            let text = ir(&source);
3094            assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
3095        }
3096    }
3097
3098    /// A function with external linkage is emitted whatever this file does with it, because
3099    /// another one may call it, and that is what external linkage is.
3100    #[test]
3101    fn a_function_anything_could_call_is_emitted_without_being_called() {
3102        let text =
3103            ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
3104        assert!(text.contains("func @nobody_here_calls_it"), "{text}");
3105    }
3106
3107    /// Four of the classification builtins are operators C already has, and become those.
3108    ///
3109    /// What the standard's macro promises over the operator is that it does not raise the
3110    /// invalid operation exception on a quiet NaN. This compiler does not model floating point
3111    /// exceptions, so there is nothing left for a node of its own to carry and a second way of
3112    /// spelling a comparison would be a second thing every pass has to know about.
3113    #[test]
3114    fn a_classification_c_has_an_operator_for_is_that_operator() {
3115        for (builtin, operator) in [
3116            ("__builtin_isgreater", "binary >"),
3117            ("__builtin_isgreaterequal", "binary >="),
3118            ("__builtin_isless", "binary <"),
3119            ("__builtin_islessequal", "binary <="),
3120        ] {
3121            let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
3122            let text = tast(&source);
3123            assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
3124        }
3125    }
3126
3127    /// The rest of the family are comparisons in the IR and never a call to anything.
3128    ///
3129    /// `math.h` defines the macro of each of these names as the builtin of the same name, so
3130    /// there is no function under any of them for a call to reach. `isunordered` and
3131    /// `islessgreater` are predicates the IR's comparison already has, `isnan` is the value that
3132    /// is unordered with itself, and the two that ask about a magnitude are written against the
3133    /// infinities. `signbit` is the one that is not a question about the value, since a negative
3134    /// zero compares equal to a positive one, so its answer comes from the bits.
3135    #[test]
3136    fn the_classification_builtins_are_comparisons_and_not_calls() {
3137        let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
3138        assert_eq!(
3139            text,
3140            "block0(%0: f64, %1: f64):\n    %2 = fcmp uno %0, %1\n    %3 = zext.i32 \
3141                          %2\n    return %3\n"
3142        );
3143
3144        // Not `x != y`, which is true when the two are unordered and so is true of a NaN.
3145        let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
3146        assert!(text.contains("fcmp one %0, %1"), "{text}");
3147
3148        let text = body("int f(double x) { return __builtin_isnan(x); }\n");
3149        assert!(text.contains("fcmp uno %0, %0"), "{text}");
3150
3151        let text = body("int f(double x) { return __builtin_isinf(x); }\n");
3152        assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
3153        assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
3154        assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
3155        assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
3156        assert!(text.contains("%5 = or %3, %4"), "{text}");
3157
3158        // Strictly between the two infinities, which a NaN is not, because an ordered comparison
3159        // against either of them is false. That is what makes this one test rather than two.
3160        let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
3161        assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
3162        assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
3163        assert!(text.contains("%5 = and %3, %4"), "{text}");
3164
3165        let text = body("int f(double x) { return __builtin_signbit(x); }\n");
3166        assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
3167        assert!(text.contains("icmp slt %1, %2"), "{text}");
3168
3169        // The same question of a value in the target's widest format, where the bits are eighty
3170        // and the object they sit in is sixteen bytes.
3171        let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
3172        assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
3173
3174        // The operand is evaluated once however many times it is compared, which is the whole
3175        // reason these are nodes rather than a rewriting into the operators.
3176        let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
3177        assert_eq!(text.matches("call @g()").count(), 1, "{text}");
3178    }
3179
3180    /// A spelling that names a width converts its argument before it asks.
3181    ///
3182    /// gcc gives `__builtin_isinff` a `float` parameter and `__builtin_isinf` no parameter type
3183    /// at all, and the difference is visible rather than academic: `1e300` does not fit in a
3184    /// `float`, so converting it first is an infinity and not converting it is not. Both numbers
3185    /// here are what gcc 16 gives.
3186    #[test]
3187    fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
3188        let text = ir(concat!(
3189            "int a = __builtin_isinff(1e300);\n",
3190            "int b = __builtin_isinf(1e300);\n",
3191            // Folded here rather than compared at run time, because a question about a value has
3192            // an answer as soon as the value is a constant, and an initializer for an object
3193            // with static storage duration has to have one.
3194            "int c = __builtin_isnan(0.0);\n",
3195            "int d = __builtin_signbit(-0.0);\n",
3196            "int e = __builtin_islessgreater(1.0, 2.0);\n",
3197        ));
3198        assert!(text.contains("global @a : i32 = 1,"), "{text}");
3199        assert!(text.contains("global @b : i32 = 0,"), "{text}");
3200        assert!(text.contains("global @c : i32 = 0,"), "{text}");
3201        assert!(text.contains("global @d : i32 = 1,"), "{text}");
3202        assert!(text.contains("global @e : i32 = 1,"), "{text}");
3203    }
3204
3205    /// An argument that is not floating point is refused, in gcc's words.
3206    #[test]
3207    fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
3208        let mut opts = options();
3209        opts.emit = EmitKind::Ir;
3210        let source = concat!(
3211            "int a(int x) { return __builtin_isnan(x); }\n",
3212            "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
3213            "int c(double x) { return __builtin_isnan(x, x); }\n",
3214        );
3215        let messages = run(&opts, source).messages;
3216        assert_eq!(
3217            messages,
3218            [
3219                "/main.c:1:23: error: non-floating-point argument in call to function \
3220                 '__builtin_isnan' [E0685]",
3221                "/main.c:2:30: error: non-floating-point arguments in call to function \
3222                 '__builtin_isunordered' [E0685]",
3223                "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
3224            ]
3225        );
3226    }
3227
3228    /// The three of the family that need a constant of the format other than an infinity.
3229    ///
3230    /// `isnormal` is the one that needs the smallest normal, and it is asked of the magnitude, so
3231    /// the sign comes off first and what is left is the same shape as `isfinite`. `isinf_sign` is
3232    /// the one whose answer is a number: the two comparisons `isinf` builds, subtracted rather
3233    /// than combined. `fpclassify` is four questions of one value and five answers to pick from,
3234    /// and the picking is a mask because all five are constants and neither of them can have an
3235    /// effect.
3236    #[test]
3237    fn the_last_three_classification_builtins_are_comparisons_and_not_calls() {
3238        let text = body("int f(double x) { return __builtin_isnormal(x); }\n");
3239        // The sign off, which is the magnitude, and then the range, asked of the bits rather than
3240        // of the number, since the encoding of a value whose sign bit is clear rises with the
3241        // value in every format this compiles for.
3242        assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
3243        assert!(text.contains("%2 = iconst.i64 9223372036854775807"), "{text}");
3244        assert!(text.contains("%3 = and %1, %2"), "{text}");
3245        assert!(text.contains("%4 = iconst.i64 4503599627370496"), "{text}");
3246        assert!(text.contains("%5 = iconst.i64 9218868437227405312"), "{text}");
3247        assert!(text.contains("%6 = icmp uge %3, %4"), "{text}");
3248        assert!(text.contains("%7 = icmp ult %3, %5"), "{text}");
3249        assert!(text.contains("%8 = and %6, %7"), "{text}");
3250
3251        // The same question in the target's widest format, where the smallest normal has the
3252        // leading significand bit stored rather than implied, so its encoding is two bits and not
3253        // one.
3254        let text = body("int f(long double x) { return __builtin_isnormal(x); }\n");
3255        assert!(text.contains("%4 = iconst.i80 27670116110564327424"), "{text}");
3256        assert!(text.contains("%5 = iconst.i80 604453686435277732577280"), "{text}");
3257
3258        let text = body("int f(double x) { return __builtin_isinf_sign(x); }\n");
3259        assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
3260        assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
3261        assert!(text.contains("%7 = sub %5, %6"), "{text}");
3262
3263        let text = body("int f(double x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n");
3264        assert!(text.contains("fcmp uno %0, %0"), "{text}");
3265        assert!(text.contains("fcmp oeq %0, %6"), "{text}");
3266        // Four questions, each of them a bit widened into the type of the answer and then spread
3267        // into a mask that picks between the answer and whatever the questions after it settled
3268        // on. Nothing sign extends, because no rule lowers a sign extension out of one bit.
3269        assert_eq!(text.matches(" = zext.i32 ").count(), 4, "{text}");
3270        assert_eq!(text.matches(" = xor ").count(), 4, "{text}");
3271        assert!(!text.contains("call"), "{text}");
3272
3273        // The value is evaluated once however many questions are asked of it, which is the whole
3274        // reason `fpclassify` is a node rather than the chain of tests it turns into.
3275        let text = body(concat!(
3276            "double g(void);\n",
3277            "int f(void) { return __builtin_fpclassify(0, 1, 2, 3, 4, g()); }\n",
3278        ));
3279        assert_eq!(text.matches("call @g()").count(), 1, "{text}");
3280    }
3281
3282    /// Each of the three answers a constant where its operand is one.
3283    ///
3284    /// glibc's `fpclassify` macro is exactly this builtin, so a program that writes
3285    /// `fpclassify(0.0)` in a static initializer is writing this, and it has to have a value at
3286    /// translation time or the program is refused rather than merely compiled slowly. Every
3287    /// number here is what gcc 16 gives.
3288    #[test]
3289    fn the_last_three_classification_builtins_fold_where_their_operand_is_a_constant() {
3290        let text = ir(concat!(
3291            "int a = __builtin_isnormal(1.0);\n",
3292            "int b = __builtin_isnormal(0.0);\n",
3293            "int c = __builtin_isnormal(1.0 / 0.0);\n",
3294            "int d = __builtin_isinf_sign(-1.0 / 0.0);\n",
3295            "int e = __builtin_isinf_sign(1.0);\n",
3296            "int g = __builtin_fpclassify(0, 1, 2, 3, 4, 0.0);\n",
3297            "int h = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0);\n",
3298            "int i = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0 / 0.0);\n",
3299        ));
3300        assert!(text.contains("global @a : i32 = 1,"), "{text}");
3301        assert!(text.contains("global @b : i32 = 0,"), "{text}");
3302        assert!(text.contains("global @c : i32 = 0,"), "{text}");
3303        assert!(text.contains("global @d : i32 = -1,"), "{text}");
3304        assert!(text.contains("global @e : i32 = 0,"), "{text}");
3305        assert!(text.contains("global @g : i32 = 4,"), "{text}");
3306        assert!(text.contains("global @h : i32 = 2,"), "{text}");
3307        assert!(text.contains("global @i : i32 = 1,"), "{text}");
3308    }
3309
3310    /// `fpclassify` refuses what gcc refuses, in gcc's words.
3311    ///
3312    /// The five answers have to be integer constant expressions, because what the builtin does is
3313    /// pick one of them and a pick between values that are not known here would be a chain of
3314    /// conditionals over expressions the call has already evaluated.
3315    #[test]
3316    fn fpclassify_refuses_an_answer_that_is_not_an_integer_constant() {
3317        let mut opts = options();
3318        opts.emit = EmitKind::Ir;
3319        let source = concat!(
3320            "int a(double x, int n) { return __builtin_fpclassify(0, 1, n, 3, 4, x); }\n",
3321            "int b(double x) { return __builtin_fpclassify(0, 1, 2, 3, x); }\n",
3322            "int c(int x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n",
3323        );
3324        let messages = run(&opts, source).messages;
3325        assert_eq!(
3326            messages,
3327            [
3328                "/main.c:1:60: error: non-const integer argument 3 in call to function \
3329                 '__builtin_fpclassify' [E0687]",
3330                "/main.c:2:26: error: too few arguments to function '__builtin_fpclassify' \
3331                 [E0511]",
3332                "/main.c:3:23: error: non-floating-point argument in call to function \
3333                 '__builtin_fpclassify' [E0685]",
3334            ]
3335        );
3336    }
3337
3338    /// A builtin whose answer is a constant is one, and is not a call to the library.
3339    ///
3340    /// This is the reason the family is answered in the front end at all. `double x =
3341    /// __builtin_inf();` at file scope initializes an object with static storage duration, so
3342    /// there is no point in the program at which a call could be made, and a compiler that
3343    /// lowered it to one would reject a program gcc accepts. Every number here is the encoding
3344    /// gcc 16 gives on x86-64.
3345    #[test]
3346    fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
3347        let text = ir(concat!(
3348            "double a = __builtin_inf();\n",
3349            "float b = __builtin_huge_valf();\n",
3350            "long double c = __builtin_infl();\n",
3351            "double d = __builtin_huge_val();\n",
3352        ));
3353        assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
3354        assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
3355        assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
3356        assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
3357        assert!(!text.contains("call"), "{text}");
3358    }
3359
3360    /// A nan is written with the payload the program asked for.
3361    ///
3362    /// The string is read the way `strtoull` reads a number, which is what the library function
3363    /// of the same name does with it, and a string that is not one at all leaves the call for the
3364    /// library to answer at run time. A quiet nan has the high fraction bit set and a signalling
3365    /// one does not, except that a signalling nan with nothing in it would be an infinity, so it
3366    /// gets the next bit down instead. Every encoding here was measured against gcc 16, the two
3367    /// `long double` ones on a machine with the x87 format.
3368    #[test]
3369    fn a_nan_is_written_with_the_payload_the_program_asked_for() {
3370        let text = ir(concat!(
3371            "double a = __builtin_nan(\"\");\n",
3372            "double b = __builtin_nan(\"0x1\");\n",
3373            // Octal, since there is a leading zero, so this is eight and not ten.
3374            "double c = __builtin_nan(\"010\");\n",
3375            "double d = __builtin_nans(\"\");\n",
3376            "double e = __builtin_nans(\"0x1\");\n",
3377            "float f = __builtin_nanf(\"0x1\");\n",
3378            "float g = __builtin_nansf(\"\");\n",
3379            "long double h = __builtin_nansl(\"\");\n",
3380        ));
3381        assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
3382        assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
3383        assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
3384        assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
3385        assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
3386        assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
3387        assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
3388        assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
3389
3390        // A payload that is not a number, and one that is not known until run time, are both
3391        // left to the library, which is the same thing gcc emits for either of them.
3392        let text = ir(concat!(
3393            "double f(const char *p) { return __builtin_nan(p); }\n",
3394            "double g(void) { return __builtin_nans(\"1x\"); }\n",
3395        ));
3396        assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
3397        assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
3398    }
3399
3400    /// The length and the order of a string literal are known here.
3401    ///
3402    /// A program that asks for either of them is asking about something the translation already
3403    /// has in front of it, and folding is not only an optimization: `execute/921007-1.c` in the
3404    /// torture suite calls `__builtin_strcmp` in a file that defines its own `strcmp` with a
3405    /// different signature, so leaving the call behind is a name collision that gcc does not
3406    /// have. The comparison is over `unsigned char`, which is why the second one is negative.
3407    #[test]
3408    fn the_length_and_the_order_of_a_string_literal_are_known_here() {
3409        let text = ir(concat!(
3410            "unsigned long a = __builtin_strlen(\"hello\");\n",
3411            "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
3412            "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
3413            "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
3414            "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
3415        ));
3416        assert!(text.contains("global @a : i64 = 5,"), "{text}");
3417        assert!(text.contains("global @b : i64 = 1,"), "{text}");
3418        assert!(text.contains("global @c : i32 = 1,"), "{text}");
3419        assert!(text.contains("global @d : i32 = 0,"), "{text}");
3420        assert!(text.contains("global @e : i32 = 1,"), "{text}");
3421        assert!(!text.contains("call"), "{text}");
3422
3423        // An argument that is not a literal is the library's to answer, as it has to be.
3424        let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
3425        assert!(text.contains("call @strlen("), "{text}");
3426    }
3427
3428    /// A sign builtin is a mask over the bits, and is not a call.
3429    ///
3430    /// `fabs` and `copysign` are in the math library rather than the C one, so a program that
3431    /// only ever wrote the prefixed spelling never asked for `-lm` and a call left behind here
3432    /// would not link. Neither needs anything the library has: one clears the sign bit and the
3433    /// other takes it from the second operand, and every other bit goes through untouched.
3434    #[test]
3435    fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
3436        let text = body("double f(double x) { return __builtin_fabs(x); }\n");
3437        assert!(text.contains("bitcast.i64 %0"), "{text}");
3438        assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
3439        assert!(text.contains("and %1, %2"), "{text}");
3440        assert!(text.contains("bitcast.f64 %3"), "{text}");
3441        assert!(!text.contains("call"), "{text}");
3442
3443        let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
3444        assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
3445        assert!(text.contains("%8 = or %4, %7"), "{text}");
3446        assert!(!text.contains("call"), "{text}");
3447
3448        // The x87 format, whose value is eighty bits sitting in an object of sixteen. The mask is
3449        // as wide as the value and not as wide as the object, so the padding is not part of it.
3450        let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
3451        assert!(text.contains("bitcast.i80 %0"), "{text}");
3452        assert!(text.contains("bitcast.f80"), "{text}");
3453
3454        // The width a name does not spell out is `double`, so a `float` argument widens first and
3455        // the answer is a `double`, which is what gcc's declaration of it says.
3456        let text = body("double f(float x) { return __builtin_fabs(x); }\n");
3457        assert!(text.contains("fpext.f64 %0"), "{text}");
3458        assert!(text.contains("bitcast.i64 %1"), "{text}");
3459    }
3460
3461    /// The sign builtins answer a zero and a nan the way the bits say.
3462    ///
3463    /// This is why they are described over the bits rather than written with comparisons and
3464    /// negation. A negative zero compares equal to a positive one and has a sign bit to clear,
3465    /// and a nan compares equal to nothing at all and keeps its payload through both operations.
3466    /// `execute/ieee/copysign1.c` in the torture suite is the test that notices, because it
3467    /// compares its answers with `memcmp`. Every number here is what gcc 16 gives, the two in the
3468    /// x87 format measured on a machine that has it.
3469    #[test]
3470    fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
3471        let text = ir(concat!(
3472            "double a = __builtin_fabs(-3.5);\n",
3473            "double b = __builtin_copysign(1.0, -0.0);\n",
3474            "double c = __builtin_copysign(0.0, -2.0);\n",
3475            // The payload survives both, and only the sign bit moves.
3476            "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
3477            "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
3478            "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
3479            "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
3480            "long double i = __builtin_fabsl(-__builtin_infl());\n",
3481        ));
3482        assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
3483        assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
3484        assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
3485        assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
3486        assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
3487        assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
3488        assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
3489        assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
3490    }
3491
3492    /// A `constexpr` object is a named constant, which is the whole reason the keyword exists.
3493    ///
3494    /// C23 6.6p8 puts two of them on the list an integer constant expression is built from: one
3495    /// of an arithmetic type, and a member of one of a structure or union type. A subscript of
3496    /// one is not on the list and is a variably modified type in gcc 16 as well, and every
3497    /// number here is what gcc 16 gives on x86-64.
3498    #[test]
3499    fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
3500        let text = ir(concat!(
3501            "constexpr int side = 4;\n",
3502            "constexpr int wider = side + 1;\n",
3503            "constexpr double half = 1.5;\n",
3504            "struct point { int x; int y; };\n",
3505            "constexpr struct point origin = { 5, 6 };\n",
3506            "int square[side * side];\n",
3507            "int rectangle[wider];\n",
3508            "int rounded[(int)half * 2];\n",
3509            "int across[origin.y];\n",
3510            "enum named { four = side };\n",
3511            "int e = four;\n",
3512        ));
3513        assert!(text.contains("global @square : bytes 64 ="), "{text}");
3514        assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
3515        assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
3516        assert!(text.contains("global @across : bytes 24 ="), "{text}");
3517        assert!(text.contains("global @e : i32 = 4,"), "{text}");
3518
3519        // A `const` object is not one of them, which is what makes `int a[n];` a variable
3520        // length array in C and is the distinction the keyword was added to draw.
3521        let mut opts = options();
3522        opts.emit = EmitKind::Ir;
3523        let konst = "const int n = 1;\nint a[n];\n";
3524        let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
3525        assert_eq!(run(&opts, konst).messages, [message]);
3526
3527        // Nor is a subscript of one, which gcc 16 refuses in the same words.
3528        let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
3529        assert_eq!(run(&opts, subscript).messages, [message]);
3530
3531        // And `constexpr` implies `const`, so the address of one is an address of a `const`.
3532        let address = "constexpr int c = 3;\nint *p = &c;\n";
3533        let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
3534             pointer target type [E0514]";
3535        assert_eq!(run(&opts, address).messages, [warning]);
3536    }
3537
3538    /// A definition that names its parameters and then declares them under the list.
3539    ///
3540    /// The declarations say what the types are, 6.9.1p6, and what the function takes is those
3541    /// types with the default argument promotions over them, which is what a caller of an
3542    /// unprototyped function hands over. A prototype already in scope overrules the promoted
3543    /// types, since a header saying `int narrow(char);` over a definition written this way is
3544    /// the pairing all the code written this way relies on and 6.7.6.3p15 is read that way by
3545    /// every compiler.
3546    #[test]
3547    fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
3548        // C17, since the default dialect is the one that warns about the form and this is
3549        // about what it means rather than about the warning.
3550        let mut opts = options();
3551        opts.std = Std::C17;
3552        let source = concat!(
3553            "int add(a, b)\n",
3554            "int a;\n",
3555            "int b;\n",
3556            "{ return a + b; }\n",
3557            "int promoted(c)\n",
3558            "char c;\n",
3559            "{ return c; }\n",
3560            "int narrow(char);\n",
3561            "int narrow(c)\n",
3562            "char c;\n",
3563            "{ return c; }\n",
3564            "int first(a)\n",
3565            "int a[4];\n",
3566            "{ return a[0]; }\n",
3567        );
3568        let result = run(&opts, source);
3569        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
3570        let text = result.text();
3571        assert!(text.contains("add : int(int, int) function external defined"), "{text}");
3572        assert!(text.contains("promoted : int(int) function external defined"), "{text}");
3573        // The body still sees the `char` it was declared as, whatever the caller hands over.
3574        assert!(text.contains("c : char object automatic defined"), "{text}");
3575        assert!(text.contains("narrow : int(char) function external defined"), "{text}");
3576        // An array parameter is a pointer here as much as it is in a prototype.
3577        assert!(text.contains("first : int(int *) function external defined"), "{text}");
3578    }
3579
3580    /// What the two halves of an old-style parameter list can disagree about.
3581    ///
3582    /// Each of these is a sentence gcc 16 has, and every message below is the one it prints,
3583    /// read off it on x86-64 rather than reasoned about. The last two are the dialect: a name
3584    /// with no declaration is an `int` in C89 and a diagnostic from C99 on, and the whole form
3585    /// left the language in C23, where gcc still takes it and warns.
3586    #[test]
3587    fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
3588        let mut opts = options();
3589        opts.std = Std::C17;
3590        for (source, message) in [
3591            ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
3592            (
3593                "int f(a)\nint a;\nint b;\n{ return a; }\n",
3594                "3:5: error: declaration for parameter 'b' but no such parameter",
3595            ),
3596            ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
3597            ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
3598            (
3599                "int f(a)\nstatic int a;\n{ return a; }\n",
3600                "2:12: error: storage class specified for parameter 'a'",
3601            ),
3602            (
3603                "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
3604                "2:7: error: argument 'a' doesn't match prototype",
3605            ),
3606        ] {
3607            let result = run(&opts, source);
3608            assert!(result.failed(), "expected this to fail:\n{source}");
3609            assert!(result.messages[0].contains(message), "{:?}", result.messages);
3610        }
3611
3612        // A name the declarations never mention. C89 gave it an `int` and gcc still takes it
3613        // in that dialect, and every dialect after it made the same line a diagnostic.
3614        let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
3615        let mut older = options();
3616        older.std = Std::C89;
3617        assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
3618        let result = run(&opts, implicit);
3619        assert!(
3620            result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
3621            "{:?}",
3622            result.messages
3623        );
3624
3625        // C23 took the form out of the language and gcc kept accepting it with a warning, and
3626        // a warning is what this is, because the code written this way is not going to be
3627        // rewritten and refusing it would put the compiler out of reach of it.
3628        let mut newer = options();
3629        newer.std = Std::C23;
3630        let plain = "int f(a)\nint a;\n{ return a; }\n";
3631        let result = run(&newer, plain);
3632        assert!(!result.failed(), "{:?}", result.messages);
3633        assert_eq!(
3634            result.messages,
3635            ["/main.c:1:5: warning: old-style function definition [E0412]"]
3636        );
3637        assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
3638    }
3639
3640    /// A type nothing is ever an object of is a type `sizeof` still has to answer about, which
3641    /// is what `991014-1.c` in the gcc.c-torture execution suite asks.
3642    ///
3643    /// The limit is `PTRDIFF_MAX` and it is the same one for an array and for a record, so a
3644    /// record of every byte an object may have is laid out and one byte more is refused. All
3645    /// four numbers are what gcc 16 gives on x86-64.
3646    #[test]
3647    fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
3648        let text = ir(concat!(
3649            "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
3650            "struct brim { char buf[9223372036854775807L]; };\n",
3651            "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
3652            "unsigned long h = sizeof(struct huge_struct);\n",
3653            "unsigned long b = sizeof(struct brim);\n",
3654            "unsigned long y = sizeof(struct bitty);\n",
3655        ));
3656        assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
3657        assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
3658        assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
3659
3660        let mut opts = options();
3661        opts.emit = EmitKind::Ir;
3662        let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
3663        let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
3664        assert_eq!(run(&opts, over).messages, [message]);
3665        let array = "struct wide { short buf[1L << 62]; };\n";
3666        let message = "/main.c:1:25: error: size of array 'buf' exceeds \
3667             maximum object size '9223372036854775807' [E0537]";
3668        assert_eq!(run(&opts, array).messages[0], message);
3669    }
3670
3671    /// A byte in the source that is not part of a character, which only a literal may hold.
3672    ///
3673    /// The source cannot be a `&str` here, which is the whole point: a file is bytes and only
3674    /// mostly text.
3675    fn compile_bytes(source: &[u8]) -> Compiled {
3676        let mut opts = options();
3677        opts.emit = EmitKind::Ir;
3678        let mut fs = MemoryFileSystem::new();
3679        fs.insert("/main.c", source.to_vec());
3680        compile(&opts, "/main.c", &fs)
3681    }
3682
3683    /// A raw byte inside a string literal is that byte, which gcc has always taken and which is
3684    /// the only place in a source file where a byte does not have to be part of a character.
3685    /// Replacing it would give the object three bytes rather than one, since the replacement
3686    /// character is three bytes of UTF-8, so the object would not be the one that was written
3687    /// even where the diagnostic is ignored. Anywhere else the byte is still a mistake, which
3688    /// is where gcc draws the same line.
3689    #[test]
3690    fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
3691        let mut source = b"char s[] = \"a".to_vec();
3692        source.push(0xff);
3693        source.extend_from_slice(b"b\";\nchar c = '");
3694        source.push(0xff);
3695        source.extend_from_slice(b"';\n");
3696        let result = compile_bytes(&source);
3697        assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
3698        assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
3699        // Plain `char` is signed on this target, so the constant is minus one rather than 255.
3700        assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
3701
3702        let mut stray = b"int a".to_vec();
3703        stray.push(0xff);
3704        stray.extend_from_slice(b" = 1;\n");
3705        let result = compile_bytes(&stray);
3706        assert!(
3707            result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
3708            "{:?}",
3709            result.messages
3710        );
3711    }
3712
3713    #[test]
3714    fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
3715        let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
3716        assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
3717        let expected = "\
3718func @add(i32, i32) -> i32, linkage(external) {
3719block0(%0: i32, %1: i32):
3720    %2 = add.nsw %0, %1
3721    return %2
3722}
3723";
3724        assert!(text.contains(expected), "{text}");
3725    }
3726
3727    #[test]
3728    fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
3729        let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
3730        assert!(!text.contains("alloca"), "{text}");
3731        assert!(!text.contains("load"), "{text}");
3732        assert!(!text.contains("store"), "{text}");
3733    }
3734
3735    #[test]
3736    fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
3737        let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
3738        let expected = "\
3739block0:
3740    %0 = alloca, size 4, align 4
3741    %1 = iconst.i32 1
3742    store %1 -> %0, align 4
3743    %2 = call @g(%0) : (ptr) -> i32
3744    return %2
3745";
3746        assert_eq!(text, expected);
3747    }
3748
3749    #[test]
3750    fn a_loop_carries_what_it_changes_as_block_parameters() {
3751        // The whole point of building SSA during the walk rather than after it: `i` and
3752        // `total` are values that arrive on an edge, and neither has ever been in memory.
3753        let text = body(
3754            "int f(int n) {\n  int total = 0;\n  for (int i = 0; i < n; i++) total += i;\n  \
3755             return total;\n}\n",
3756        );
3757        assert!(!text.contains("alloca"), "{text}");
3758        assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
3759        assert!(text.contains("jump block1("), "{text}");
3760    }
3761
3762    #[test]
3763    fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
3764        let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
3765        assert!(text.contains("icmp slt %0, %1"), "{text}");
3766        assert!(!text.contains("zext"), "{text}");
3767    }
3768
3769    #[test]
3770    fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
3771        let text = body("int f(int a, int b) { return a && b; }\n");
3772        let expected = "\
3773block0(%0: i32, %1: i32):
3774    %2 = iconst.i32 0
3775    %3 = icmp ne %0, %2
3776    %4 = iconst.i1 0
3777    br_if %3, block1, block2(%4)
3778
3779block1:
3780    %5 = iconst.i32 0
3781    %6 = icmp ne %1, %5
3782    jump block2(%6)
3783
3784block2(%7: i1):
3785    %8 = zext.i32 %7
3786    return %8
3787";
3788        assert_eq!(text, expected);
3789    }
3790
3791    #[test]
3792    fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
3793        let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
3794        // Three blocks, the test and the two arms. The join the `return 3` would need is
3795        // never created, because a block nothing branches to is not a block.
3796        assert!(!text.contains("block3"), "{text}");
3797        assert!(!text.contains("iconst.i32 3"), "{text}");
3798    }
3799
3800    #[test]
3801    fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
3802        assert!(body("int main(void) { }\n").contains("iconst.i32 0\n    return"));
3803        assert_eq!(body("void f(void) { }\n"), "block0:\n    return\n");
3804        assert!(body("int f(void) { }\n").contains("unreachable"));
3805    }
3806
3807    #[test]
3808    fn a_structure_is_copied_rather_than_held_in_a_value() {
3809        let text = body(
3810            "struct point { int x, y; };\n\
3811             int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
3812        );
3813        assert!(text.contains("memcpy"), "{text}");
3814    }
3815
3816    #[test]
3817    fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
3818        let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
3819        assert!(text.contains("memset"), "{text}");
3820    }
3821
3822    #[test]
3823    fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
3824        let text = body(
3825            "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
3826             default: r = 4; } return r; }\n",
3827        );
3828        let expected = "\
3829block0(%0: i32):
3830    %1 = iconst.i32 0
3831    switch %0, block1, [1 => block2, 2 => block3(%1)]
3832
3833block1:
3834    %2 = iconst.i32 4
3835    jump block4(%2)
3836
3837block2:
3838    %3 = iconst.i32 1
3839    jump block3(%3)
3840
3841block3(%4: i32):
3842    %5 = iconst.i32 2
3843    %6 = add.nsw %4, %5
3844    jump block4(%6)
3845
3846block4(%7: i32):
3847    return %7
3848";
3849        assert_eq!(text, expected);
3850    }
3851
3852    #[test]
3853    fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
3854        // GNU's `case 1 ... 9`. Nine table entries would be nine here and four billion for the
3855        // range a program is allowed to write, so it is a subtraction and one unsigned compare.
3856        let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
3857        assert!(text.contains("%2 = sub %0, %1"), "{text}");
3858        assert!(text.contains("icmp ule"), "{text}");
3859        assert!(!text.contains("switch"), "{text}");
3860    }
3861
3862    #[test]
3863    fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
3864        let text = body(
3865            "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
3866             case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
3867        );
3868        // The `continue` goes to the step and the `break` goes to the `t++` after the switch,
3869        // which is also where the default falls out to.
3870        assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
3871        assert!(text.contains("block5:\n    jump block7("), "{text}");
3872        assert!(text.contains("block6:\n    jump block8("), "{text}");
3873    }
3874
3875    #[test]
3876    fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
3877        assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n    return\n");
3878    }
3879
3880    #[test]
3881    fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
3882        // A branch into the middle of a loop that nothing else reaches, the Duff's device shape.
3883        // The `while` is not reached in order, so the walk starts a block nothing branches to and
3884        // builds it from there. What comes out is the loop with an edge straight into its body,
3885        // and the header that nothing arrives at is pruned.
3886        let text = body(
3887            "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
3888             return n; }\n",
3889        );
3890        // `case 2` lands on the body, `case 1` and the default land on the return, and the test
3891        // at the bottom of the loop comes back round to the body.
3892        assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
3893        assert!(text.contains("block3(%3: i32):\n    %4 = iconst.i32 1"), "{text}");
3894        assert!(text.contains("block4:\n    jump block3("), "{text}");
3895    }
3896
3897    #[test]
3898    fn a_goto_into_a_loop_body_enters_it_without_the_test() {
3899        // The same thing through a `goto`. The first pass through the body runs whatever the
3900        // label is on, and only then does the loop reach its own test.
3901        let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
3902        assert!(text.starts_with("block0(%0: i32, %1: i32):\n    jump block1(%1)"), "{text}");
3903        assert!(text.contains("block1(%2: i32):\n    %3 = iconst.i32 1"), "{text}");
3904        assert!(text.contains("br_if %6, block2, block3"), "{text}");
3905    }
3906
3907    #[test]
3908    fn a_goto_is_a_jump_to_the_block_the_label_starts() {
3909        let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
3910        // Both edges into `out` carry what `r` holds on the way, and neither is a stack slot. The
3911        // block the `goto` jumps out of is empty and hands its edge on, which is what moves `out`
3912        // up the block list to second place.
3913        assert!(!text.contains("alloca"), "{text}");
3914        assert!(text.contains("block2(%4: i32):\n    return %4"), "{text}");
3915        assert_eq!(text.matches("jump block2(").count(), 2, "{text}");
3916    }
3917
3918    #[test]
3919    fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
3920        let text =
3921            body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
3922        assert!(!text.contains("alloca"), "{text}");
3923        assert!(text.contains("block1(%2: i32):"), "{text}");
3924        assert!(text.contains("jump block1(%5)"), "{text}");
3925    }
3926
3927    #[test]
3928    fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
3929        // A block nothing branches to is not a legal function, and which labels are dead is not
3930        // known until the last statement has been walked, since the `goto` is allowed to be it.
3931        assert_eq!(
3932            body("int f(int x) { return x; spare: return 0; }\n"),
3933            "block0(%0: i32):\n    return %0\n"
3934        );
3935    }
3936
3937    #[test]
3938    fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
3939        let text = body(
3940            "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
3941        );
3942        // One byte holds both fields, and the signed one needs no mask: shifting it down
3943        // arithmetically is what says its top bit is a sign.
3944        assert_eq!(
3945            text,
3946            "\
3947block0(%0: ptr):
3948    %1 = load.i8 %0, align 1
3949    %2 = iconst.i8 3
3950    %3 = ashr %1, %2
3951    %4 = sext.i32 %3
3952    return %4
3953"
3954        );
3955    }
3956
3957    #[test]
3958    fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
3959        // C11 says an ordinary member beside a bit-field is a memory location of its own, so
3960        // the four byte store this would take is a data race in a program that has none. The
3961        // three bytes of `a` go in as two and one, and `c` is not touched.
3962        let text =
3963            body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
3964        assert_eq!(
3965            text,
3966            "\
3967block0(%0: ptr, %1: i32):
3968    %2 = iconst.i32 16777215
3969    %3 = and %1, %2
3970    %4 = trunc.i16 %3
3971    store %4 -> %0, align 2
3972    %5 = iconst.i32 16
3973    %6 = lshr %3, %5
3974    %7 = trunc.i8 %6
3975    %8 = iconst.i64 2
3976    %9 = ptr_add %0, %8
3977    store %7 -> %9, align 1
3978    return
3979"
3980        );
3981    }
3982
3983    #[test]
3984    fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
3985        let text =
3986            body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
3987        // 33 does not fit in five bits, and 1 is both what goes in the field and what the
3988        // assignment is worth.
3989        assert!(text.contains("%3 = iconst.i8 31\n    %4 = and %2, %3"), "{text}");
3990        assert!(text.ends_with("%9 = zext.i32 %4\n    return %9\n"), "{text}");
3991    }
3992
3993    #[test]
3994    fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
3995        // The value of an assignment to a bit-field takes a shift to build, and a statement
3996        // has no use for it. Nothing here reads back what was stored.
3997        let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
3998        assert_eq!(text.matches("ashr").count(), 0, "{text}");
3999        assert!(text.ends_with("store %8 -> %0, align 1\n    return\n"), "{text}");
4000    }
4001
4002    #[test]
4003    fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
4004        // A bit-field writes part of a byte and leaves the rest of it alone, so the object has
4005        // to be zero before it goes in or what the initializer did not name is whatever the
4006        // stack held.
4007        let text = body(
4008            "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
4009        );
4010        assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
4011    }
4012
4013    #[test]
4014    fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
4015        // Two fields in one byte are not two entries in the image, because an image is written
4016        // in bytes: they are the byte they are both in.
4017        let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
4018        assert!(
4019            text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
4020            "{text}"
4021        );
4022    }
4023
4024    #[test]
4025    fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
4026        // `sizeof` answers without the array and the definition has to hold what was written, so
4027        // the object is the size of its image. gcc 16 gives these four, three and two bytes and
4028        // so does this. The image used to be written at the size the type had, which left the
4029        // verifier looking at twenty bytes going into four.
4030        let text = ir(concat!(
4031            "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
4032            "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
4033            "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
4034            "char s[2] = \"hi\";\n",
4035        ));
4036        assert!(
4037            text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
4038            "{text}"
4039        );
4040        assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
4041        assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
4042        // The array with a length of its own still cuts the literal down to it, which is the
4043        // one case in C where a string initializer drops its terminator.
4044        assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
4045    }
4046
4047    #[test]
4048    fn a_definition_takes_a_parameter_it_left_unnamed() {
4049        // The entry block's parameters are the definition's, and one the front end dropped for
4050        // having no name left the two lists different lengths, which the walk read as an
4051        // old-style definition and refused. gcc has taken these for far longer than C23 has.
4052        let text = ir("int f(int a, int) { return a; }\n");
4053        assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
4054        assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
4055
4056        // The unnamed one first, so that the named one is the second parameter of the entry
4057        // block and not the first: the list says the order and not only how many there are.
4058        let text = ir("int g(int, int n) { return n; }\n");
4059        assert!(text.contains("block0(%0: i32, %1: i32):\n    return %1\n"), "{text}");
4060    }
4061
4062    #[test]
4063    fn an_assignment_of_a_structure_is_the_object_it_wrote() {
4064        // `d = e = c` used to be refused, because the middle assignment is a value of structure
4065        // type and the walk had nowhere to read one from. What an assignment is worth is the
4066        // value it stored, so the object it stored into is the answer and the chain is three
4067        // copies out of the one source with no temporary in it.
4068        let text = body(concat!(
4069            "struct s { int f; int g; };\n",
4070            "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
4071            "{ *d = *e = a[0] = *c; }\n",
4072        ));
4073        assert_eq!(text.matches("memcpy").count(), 3, "{text}");
4074        assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
4075        assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
4076        assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
4077    }
4078
4079    #[test]
4080    fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
4081        // The excess used to be laid into the object anyway, so the row after was written over
4082        // and the image refused the entry that came to it. C 6.7.10p14 says the terminator goes
4083        // in only if there is room for it, and gcc discards the rest of a literal that is longer
4084        // still, which is what the first of these is and why it warns.
4085        let mut opts = options();
4086        opts.emit = EmitKind::Ir;
4087        let result = run(
4088            &opts,
4089            concat!(
4090                "const char a[2][3] = { \"1234\", \"xyz\" };\n",
4091                "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
4092                "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
4093                "const union u c = { { \"1234\", \"567\" } };\n",
4094            ),
4095        );
4096        let text = result.text();
4097        assert_eq!(
4098            result.messages,
4099            ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
4100              (5 chars into 3 available) [E0637]"]
4101        );
4102        assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
4103        assert!(
4104            text.contains(
4105                "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
4106                 bytes \"9\\00\", zero 3 }"
4107            ),
4108            "{text}"
4109        );
4110        // The eight bytes are four, three and a terminator, and then the byte the shorter
4111        // literal left for the string in the other member of the union to end at.
4112        assert!(
4113            text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
4114            "{text}"
4115        );
4116    }
4117
4118    #[test]
4119    fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
4120        // gcc accepts one and does nothing with it, which sema already had. Lowering asked for
4121        // the object under it and had no arm for a cast, so `(struct s)x` in an initializer was
4122        // refused with E0519. It is one copy out of the object named, not two.
4123        let text = body(concat!(
4124            "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
4125            "void g(struct v *);\n",
4126            "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
4127        ));
4128        assert_eq!(text.matches("memcpy").count(), 1, "{text}");
4129    }
4130
4131    #[test]
4132    fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
4133        // C 6.7.11p4 says a compound literal at file scope has static storage duration, which
4134        // makes it a constant element, and tcc and c-testsuite both write one. Sema used to call
4135        // it a non constant because reading it is a node of its own and the read was what it
4136        // looked at, and lowering had no way to put an object where it wanted a number.
4137        let text = ir(concat!(
4138            "struct s { int x; };\n",
4139            "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
4140            "int n = (int){ 7 };\n",
4141            "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
4142        ));
4143        assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
4144        assert!(text.contains("global @n : i32 = 7,"), "{text}");
4145        // The second literal names nothing, so what it puts in is the zeros of its own size and
4146        // not the tail of the object it went in, which would have been the same bytes by luck.
4147        assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
4148    }
4149
4150    #[test]
4151    fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
4152        // Nothing declares a compound literal, so the reference is the only thing that can ask
4153        // for it to be emitted. The image named `.Lanon.0` and the module defined no such
4154        // symbol, which the link would have been the first to find out.
4155        let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
4156        assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
4157        assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
4158    }
4159
4160    #[test]
4161    fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
4162        // A zero length array, which gcc allows and real code uses as the tail of a structure.
4163        // The image is there and holds nothing, which is not the global that has no image at
4164        // all, and the IR reader used to stop on the empty one.
4165        let text = ir("unsigned char foo[1][0];\n");
4166        assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
4167    }
4168
4169    #[test]
4170    fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
4171        // `NULL` in a static initializer, which every program has. The IR type is `ptr` and a
4172        // `ptr` has no width of its own, so the width the bits are cut to is the target's.
4173        let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
4174        assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
4175        assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
4176    }
4177
4178    #[test]
4179    fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
4180        // Which the verifier used to refuse, having read a declaration as a definition with
4181        // nothing in it. `extern const` is how a program names something in the library's read
4182        // only data, and glibc and Darwin both have one in a header a real program includes.
4183        let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
4184        assert!(
4185            text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
4186            "{text}"
4187        );
4188    }
4189
4190    #[test]
4191    fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
4192        // A structure is not a value in the IR, so the two arms cannot be joined as one. The
4193        // addresses can, and the answer is the address of whichever arm was taken rather than
4194        // a copy of it into a third place: both arms outlive the expression, so a copy would
4195        // be one nothing could observe. SQLite's parser writes one of these.
4196        let text = body(
4197            "\
4198struct s { int a, b; };
4199struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
4200",
4201        );
4202        // The join takes an address, each arm hands it the one it has, and nothing is copied.
4203        assert!(text.contains("block3(%7: ptr)"), "{text}");
4204        assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
4205        assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
4206    }
4207
4208    #[test]
4209    fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
4210        // `struct pair` is two eightbytes on SysV, one of them integer, so the signature says
4211        // one `i64` in each direction and the body takes the object apart and puts it back
4212        // together around the call.
4213        let text = ir("\
4214struct pair { int a, b; };
4215struct pair make(int a, int b);
4216struct pair twice(struct pair p) { return make(p.a, p.b); }
4217");
4218        assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
4219        assert!(text.contains("func @twice(i64) -> i64"), "{text}");
4220    }
4221
4222    #[test]
4223    fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
4224        // Over two eightbytes the caller passes the bytes in the argument area, which is
4225        // `byval`, and passes somewhere to write the return value, which is `sret`. Neither is
4226        // a parameter the program wrote and both are parameters the function has.
4227        let text = ir("\
4228struct big { double v[8]; };
4229struct big grow(struct big b);
4230struct big twice(struct big b) { return grow(grow(b)); }
4231");
4232        assert!(
4233            text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
4234            "{text}"
4235        );
4236        assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
4237        // The inner call writes into a slot and the outer one reads the same slot, so the
4238        // object between the two calls is never copied anywhere.
4239        assert_eq!(text.matches("call @grow").count(), 2, "{text}");
4240    }
4241
4242    #[test]
4243    fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
4244        // The bytes travel in the argument area the same way they would for a parameter, and
4245        // `printf` has no parameter there to say it on, so the call says it instead. The one
4246        // that fits in registers says nothing, because travelling as the registers it fits in
4247        // is what an argument does when nothing says otherwise.
4248        let text = ir("\
4249struct big { double v[8]; };
4250struct pair { int a, b; };
4251int p(const char *, ...);
4252int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
4253");
4254        assert!(
4255            text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
4256            "{text}"
4257        );
4258    }
4259
4260    #[test]
4261    fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
4262        // `make(1, 2).b` has no object to read a member of until one is made, and what makes it
4263        // is a slot the returned registers are written to.
4264        let body = body(
4265            "\
4266struct pair { int a, b; };
4267struct pair make(int a, int b);
4268int second(void) { return make(1, 2).b; }
4269",
4270        );
4271        assert!(body.starts_with("block0:\n    %0 = alloca, size 8, align 4\n"), "{body}");
4272        assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
4273    }
4274
4275    #[test]
4276    fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
4277        // The same declaration, classified by a different ABI: three `float` members are an
4278        // eightbyte of two of them and a half eightbyte of the third on SysV, and three vector
4279        // registers on AAPCS64.
4280        let source = "\
4281struct hfa { float x, y, z; };
4282int take(struct hfa h);
4283int give(struct hfa h) { return take(h); }
4284";
4285        assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
4286        let mut opts = options();
4287        opts.emit = EmitKind::Ir;
4288        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
4289        let result = run(&opts, source);
4290        assert_eq!(result.messages, Vec::<String>::new());
4291        assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
4292    }
4293
4294    #[test]
4295    fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
4296        // The size is a multiplication rather than a number, the slot is taken from the stack
4297        // where the declaration is, and the scope it was declared in gives it back.
4298        let source = "\
4299int use(int *);
4300void f(int n) {
4301  {
4302    int a[n];
4303    use(a);
4304  }
4305  use(0);
4306}
4307";
4308        let body = body(source);
4309        assert!(body.contains("mul.nsw"), "{body}");
4310        assert!(body.contains("stacksave"), "{body}");
4311        assert!(body.contains("alloca %"), "{body}");
4312        assert!(body.contains("stackrestore"), "{body}");
4313    }
4314
4315    #[test]
4316    fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
4317        // The label is outside the block the array is in, so arriving there means the array is
4318        // gone, and the restore that says so goes in front of the branch. The `goto` is written
4319        // before the walk knows where the label is, which is why the restore is put there at
4320        // the end rather than built where the branch was.
4321        let source = "\
4322int use(int *);
4323int f(int n) {
4324  {
4325    int a[n];
4326    if (use(a)) goto out;
4327    use(0);
4328  }
4329out:
4330  return 0;
4331}
4332";
4333        let body = body(source);
4334        // Two ways out of the block and a restore on each: the jump and the end of the block.
4335        assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
4336        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4337        assert!(after.starts_with(" %4\n    jump block"), "{body}");
4338    }
4339
4340    #[test]
4341    fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
4342        // The label is after the declaration and in the same block, so control that arrives
4343        // there arrives somewhere the array exists. Giving it back would be giving back an
4344        // object the next statement reads.
4345        let source = "\
4346int use(int *);
4347int f(int n) {
4348  int a[n];
4349again:
4350  if (use(a)) goto again;
4351  return 0;
4352}
4353";
4354        let body = body(source);
4355        assert!(body.contains("stacksave"), "{body}");
4356        assert!(!body.contains("stackrestore"), "{body}");
4357    }
4358
4359    #[test]
4360    fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
4361        // A loop written out of a `goto`, with the array made inside it. The label is in the
4362        // same block as the declaration and before it, which is a place where the array does
4363        // not exist yet, so the jump there leaves its scope and has to give the stack back. A
4364        // compiler that skips this restore grows the stack once per iteration.
4365        let source = "\
4366int use(int *);
4367int f(int n) {
4368again:
4369  {
4370    int a[n];
4371    if (use(a)) goto again;
4372  }
4373  return 0;
4374}
4375";
4376        let body = body(source);
4377        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
4378        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4379        assert!(after.starts_with(" %4\n    jump block1\n"), "{body}");
4380    }
4381
4382    #[test]
4383    fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
4384        // The scope opened for `for (int a[n];;)` used to stay open, and a scope left open is
4385        // not one mark nobody reads. The marks are a stack, so the next close took this one
4386        // instead of its own, and the body of the loop gave back nothing while the block after
4387        // the loop restored a pointer saved inside it. The verifier refused that, which is how
4388        // it was found.
4389        let source = "\
4390int f(void);
4391void t(void) {
4392  int count = 10;
4393  for (; count--;) {
4394    int b[f()];
4395    int i;
4396    for (i = 0; i < f(); i++) {
4397      b[i] = count;
4398    }
4399  }
4400}
4401";
4402        let body = body(source);
4403        // One save, in the body, and one restore for it, also in the body: the block the
4404        // restore is in is the one the inner loop leaves through, and it goes back round the
4405        // outer loop rather than out of it.
4406        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
4407        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4408        // The rest of the block the restore is in, which is the last block here, so there is not
4409        // always another one after it to split on.
4410        let next = after.split("\n\n").next().expect("the block the restore is in");
4411        assert!(next.contains("jump block1("), "{body}");
4412    }
4413
4414    #[test]
4415    fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
4416        // What C says about the length being evaluated once: `sizeof a` after `n` changed is
4417        // still as long as the array is, which is what `n` was when the array came into being.
4418        let source = "\
4419unsigned long f(int n) {
4420  int a[n];
4421  n = 0;
4422  return sizeof a;
4423}
4424";
4425        let body = body(source);
4426        // One read of the parameter, at the declaration, and the answer is built out of it.
4427        assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
4428    }
4429
4430    #[test]
4431    fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
4432        // GNU's statement expression: the statements happen where they are written and the last
4433        // one is the value, so the temporary in it never becomes a slot and never is copied.
4434        let source = "\
4435int use(int);
4436int f(int x) {
4437  return ({
4438    int t = use(x);
4439    t * t;
4440  });
4441}
4442";
4443        let expected = "\
4444block0(%0: i32):
4445    %1 = call @use(%0) : (i32) -> i32
4446    %2 = mul.nsw %1, %1
4447    return %2
4448";
4449        assert_eq!(body(source), expected);
4450    }
4451
4452    #[test]
4453    fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
4454        // A macro that always jumps, which is what this shape is in real code. The value is
4455        // never taken, and the block the rest of the expression would have been built in is
4456        // one nothing branches to, so it goes with the other unreachable blocks.
4457        let source = "int f(int x) { return ({ return x; 0; }); }\n";
4458        assert_eq!(body(source), "block0(%0: i32):\n    return %0\n");
4459    }
4460
4461    #[test]
4462    fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
4463        // What it becomes is the target's answer, and this is not where the target's answers
4464        // are, so the walk writes down which list and which type and leaves it at that. Two of
4465        // them are two instructions, since each moves the list on.
4466        let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
4467        let expected = "\
4468block0(%0: ptr):
4469    %1 = va_arg.f64 %0
4470    %2 = va_arg.f64 %0
4471    %3 = fadd %1, %2
4472    return %3
4473";
4474        assert_eq!(body(source), expected);
4475    }
4476
4477    #[test]
4478    fn one_that_reads_a_structure_answers_where_the_object_is() {
4479        // An aggregate is not a value, so there is nothing for the result of `va_arg` to be and
4480        // the object form is a second instruction. What it answers is an address, so it is a
4481        // place already and the walk copies nothing out of it: the copy here is the one the
4482        // initializer asks for, into the variable being declared. The size and the alignment
4483        // travel with it because they are what steps the list on and what a target that has to
4484        // put registers somewhere needs to know. So does the classification, which says the two
4485        // halves of this one arrived in general purpose registers: that is an answer about a C
4486        // type, and this is the last place that still has one.
4487        //
4488        // The slot is aligned to sixteen and the copy into it to eight, which is not a
4489        // disagreement. Sixteen is what a local aggregate of sixteen bytes gets whatever its
4490        // members ask for, and eight is what the type asks for and so what the copy may assume
4491        // about the object it is reading from.
4492        let source = "\
4493struct s { int a; long b; };
4494long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
4495";
4496        let expected = "\
4497block0(%0: ptr):
4498    %1 = alloca, size 16, align 16
4499    %2 = va_object %0, size 16, align 8, in(int 8 at 0, int 8 at 8)
4500    memcpy %1, %2, size 16, align 8
4501    %3 = iconst.i64 8
4502    %4 = ptr_add %1, %3
4503    %5 = load.i64 %4, align 8
4504    return %5
4505";
4506        assert_eq!(body(source), expected);
4507    }
4508
4509    /// Which register file each eightbyte arrived in is the whole of what the classification adds,
4510    /// and an object with no slots at all is one it sent to the caller's argument area, which is
4511    /// what everything over two eightbytes is whatever its members are.
4512    #[test]
4513    fn the_classification_says_which_registers_the_object_arrived_in() {
4514        let source = "\
4515struct s { double a; double b; };
4516double f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a; }
4517";
4518        assert!(
4519            body(source)
4520                .contains("va_object %0, size 16, align 8, in(float f64 at 0, float f64 at 8)"),
4521            "{}",
4522            body(source)
4523        );
4524
4525        let big = "\
4526struct s { long a[4]; };
4527long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a[0]; }
4528";
4529        assert!(body(big).contains("va_object %0, size 32, align 8\n"), "{}", body(big));
4530    }
4531
4532    #[test]
4533    fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
4534        // GNU's computed goto. Which label the address holds is not known here, so all of them
4535        // are listed, and the values arriving at one are passed on every edge the same way they
4536        // are on an ordinary branch.
4537        let source = "\
4538int f(int c) {
4539  void *p = c ? &&one : &&two;
4540  goto *p;
4541one:
4542  return 1;
4543two:
4544  return 2;
4545}
4546";
4547        let expected = "\
4548block0(%0: i32):
4549    %1 = iconst.i32 0
4550    %2 = icmp ne %0, %1
4551    br_if %2, block1, block2
4552
4553block1:
4554    %3 = block_addr block3
4555    jump block4(%3)
4556
4557block2:
4558    %4 = block_addr block5
4559    jump block4(%4)
4560
4561block3:
4562    %5 = iconst.i32 1
4563    return %5
4564
4565block4(%6: ptr):
4566    indirect_br %6, block3, block5
4567
4568block5:
4569    %7 = iconst.i32 2
4570    return %7
4571";
4572        assert_eq!(body(source), expected);
4573    }
4574
4575    #[test]
4576    fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
4577        // The address came from outside the function, and a jump to a label in another function
4578        // is undefined. The expression is still evaluated, since a call in it has to happen.
4579        let source = "void **next(void);
4580void f(void) { goto *next(); }
4581";
4582        let expected = "\
4583block0:
4584    %0 = call @next() : () -> ptr
4585    unreachable
4586";
4587        assert_eq!(body(source), expected);
4588    }
4589
4590    #[test]
4591    fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
4592        // Nothing reads a result, so the only thing that keeps it is that it is volatile, which
4593        // a basic asm implies.
4594        let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
4595        let expected = "\
4596block0:
4597    inline_asm.volatile \"mfence\", \"\", \"memory\"()
4598    return
4599";
4600        assert_eq!(body(source), expected);
4601    }
4602
4603    #[test]
4604    fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
4605        // The outputs first and then the inputs, which is the numbering `%0` and `%1` use. An
4606        // output in a register is a result, and one that is read as well is an argument too.
4607        let source = "\
4608int f(int x, int y) {
4609  int r;
4610  __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
4611  return r + y;
4612}
4613";
4614        let expected = "\
4615block0(%0: i32, %1: i32):
4616    %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
4617    %4 = add.nsw %2, %3
4618    return %4
4619";
4620        assert_eq!(body(source), expected);
4621    }
4622
4623    #[test]
4624    fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
4625        // The assembly is handed a pointer, so the object cannot live in a value, and the scan
4626        // that runs before the walk has to have known that or there would be nothing to point
4627        // at. A structure travels this way whatever else its constraint allows, since there is
4628        // no register that holds one.
4629        let source = "\
4630struct pair { int a, b; };
4631int f(int x) {
4632  int slot = x;
4633  struct pair p = { x, x };
4634  __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
4635  return slot + p.a;
4636}
4637";
4638        let text = body(source);
4639        assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
4640        assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
4641        assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
4642    }
4643
4644    #[test]
4645    fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
4646        // The output is only in scope where the instruction dominates, which is the fall through
4647        // block, so the edge to the label carries the value the object had before the assembly
4648        // ran. That is what document 11 asks for and it is what putting the fall through first
4649        // buys.
4650        let source = "\
4651int f(int x) {
4652  int r = 7;
4653  __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
4654  return r;
4655away:
4656  return r;
4657}
4658";
4659        let expected = "\
4660block0(%0: i32):
4661    %1 = iconst.i32 7
4662    %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
4663
4664block1:
4665    return %2
4666
4667block2:
4668    return %1
4669";
4670        assert_eq!(body(source), expected);
4671    }
4672
4673    #[test]
4674    fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
4675        // The operands are checked here rather than by the assembler, because by the time the
4676        // assembler sees the template the operands have become registers and it has nothing left
4677        // to say about the C that named them.
4678        let mut opts = options();
4679        opts.emit = EmitKind::Ir;
4680        for (source, expected) in [
4681            (
4682                "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
4683                "output operand constraint lacks '='",
4684            ),
4685            (
4686                "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
4687                "lvalue required in 'asm' statement",
4688            ),
4689            (
4690                "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
4691                "read-only variable 'g' used as 'asm' output",
4692            ),
4693            (
4694                "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
4695                "input operand constraint contains '='",
4696            ),
4697            (
4698                "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
4699                "memory input 0 is not directly addressable",
4700            ),
4701            ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
4702            (
4703                "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
4704                "duplicate asm operand name 'a'",
4705            ),
4706            ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
4707        ] {
4708            let result = run(&opts, source);
4709            assert!(result.failed(), "expected this to be reported:\n{source}");
4710            assert!(
4711                result.messages.iter().any(|m| m.contains(expected)),
4712                "{expected}\n{:?}",
4713                result.messages
4714            );
4715        }
4716    }
4717
4718    #[test]
4719    fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
4720        let mut opts = options();
4721        opts.emit = EmitKind::Ir;
4722        for source in [
4723            "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
4724            "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
4725        ] {
4726            let result = run(&opts, source);
4727            assert!(result.failed(), "expected this to be reported:\n{source}");
4728            assert!(
4729                result.messages.iter().any(|m| m.contains("not supported yet")),
4730                "{:?}",
4731                result.messages
4732            );
4733        }
4734    }
4735
4736    /// Compiles `source` to IR, reads that back as an input, and gives back both texts.
4737    fn round_trip(source: &str) -> (String, String) {
4738        let printed = ir(source);
4739        let mut opts = options();
4740        opts.emit = EmitKind::Ir;
4741        let mut fs = MemoryFileSystem::new();
4742        fs.insert("/main.ir", printed.clone().into_bytes());
4743        let result = compile_ir(&opts, "/main.ir", &fs);
4744        assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
4745        (printed, result.text().to_owned())
4746    }
4747
4748    #[test]
4749    fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
4750        // The other half of the round trip test below, through the driver rather than through
4751        // the library, which is what makes the property something to run over a real program
4752        // rather than over the modules a test builds.
4753        let (printed, again) = round_trip(
4754            "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",
4755        );
4756        assert_eq!(printed, again);
4757    }
4758
4759    #[test]
4760    fn ir_that_is_not_ir_says_which_line_stopped_it() {
4761        let mut opts = options();
4762        opts.emit = EmitKind::Ir;
4763        let mut fs = MemoryFileSystem::new();
4764        let text = "\
4765; ModuleID = 'a.c'
4766; format 0
4767target triple = \"x86_64-unknown-linux-gnu\"
4768target datalayout = \"e-p:64:64-i64:64-S128\"
4769
4770func @f(), linkage(external) {
4771block0:
4772    frobnicate
4773}
4774";
4775        fs.insert("/main.ir", text.as_bytes().to_vec());
4776        let result = compile_ir(&opts, "/main.ir", &fs);
4777        assert!(result.failed());
4778        assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
4779    }
4780
4781    #[test]
4782    fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
4783        // A module that a person edited has not been through the verifier, and the return of
4784        // an `i32` from a function that returns nothing is the kind of thing editing produces.
4785        let mut opts = options();
4786        opts.emit = EmitKind::Ir;
4787        let mut fs = MemoryFileSystem::new();
4788        let text = "\
4789; ModuleID = 'a.c'
4790; format 0
4791target triple = \"x86_64-unknown-linux-gnu\"
4792target datalayout = \"e-p:64:64-i64:64-S128\"
4793
4794func @f(), linkage(external) {
4795block0:
4796    %0 = iconst.i32 1
4797    return %0
4798}
4799";
4800        fs.insert("/main.ir", text.as_bytes().to_vec());
4801        let result = compile_ir(&opts, "/main.ir", &fs);
4802        assert!(result.failed());
4803        assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
4804    }
4805
4806    #[test]
4807    fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
4808        // The C that became this is not here any more, so there is nothing to print a tree of.
4809        let mut fs = MemoryFileSystem::new();
4810        fs.insert("/main.ir", Vec::new());
4811        let result = compile_ir(&options(), "/main.ir", &fs);
4812        assert!(result.failed());
4813        assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
4814    }
4815
4816    #[test]
4817    fn the_printed_ir_reads_back_as_the_same_module() {
4818        // The M2 exit criterion: the text is the module and nothing about it is lost by
4819        // writing it down. Anything the printer invents or the parser drops shows up here.
4820        let text = ir("\
4821struct point { int x, y; };
4822static const char greeting[] = \"hi\";
4823int table[4] = { 1, 2, 3 };
4824int puts(const char *);
4825double half(double x) { return x / 2.0; }
4826int f(int n) {
4827  int total = 0;
4828  for (int i = 0; i < n; i++) {
4829    if (i == 3) continue;
4830    total += table[i];
4831  }
4832  switch (n) {
4833    case 0: total = 1;
4834    case 1: total++; break;
4835    default: total = -total;
4836  }
4837  struct point p = { total, 1 };
4838  int *q = &p.y;
4839  puts(greeting);
4840  return p.x + *q;
4841}
4842int dispatch(int c) {
4843  void *p = c ? &&one : &&two;
4844  goto *p;
4845one:
4846  return 1;
4847two:
4848  return 2;
4849}
4850int assembly(int x, int *p) {
4851  int r;
4852  __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
4853  __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
4854  return r;
4855away:
4856  return 0;
4857}
4858");
4859        let mut names = Interner::new();
4860        let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
4861        assert_eq!(rucc_ir::print(&module, &names), text);
4862    }
4863}