rucc_driver/lib.rs
1//! The driver: command line parsing, the phase graph, job scheduling and the linker
2//! invocation.
3//!
4//! Design: `spec/04-driver-and-cli.md`. Layer rank 13, see `spec/18-package-layout.md`.
5//!
6//! This is the only crate that is allowed to know the process exists. It reads the command
7//! line, touches the file system, spawns the linker and writes to the terminal, and it hands
8//! everything below it a [`Session`]. The binary crate is a `main` that calls
9//! [`run`] and nothing else, so that the whole driver is reachable from a test.
10//!
11//! # Status
12//!
13//! `--help`, `--version` and `--print-config` are real, which is the `M0` exit criterion in
14//! `spec/17-milestones.md`. The phase graph is real and `-###` prints it, and the scheduler
15//! that will run it is real and tested.
16//!
17//! Two phases run. `-E` reads the file, runs phase 4 over it and writes the result, to `-o` or
18//! to standard output. `--emit=tast` carries on through phase 7, the parse and the checking,
19//! and writes the typed tree. The flags those two read are real with them, which is `-D`, `-U`,
20//! `-I`, `-I-`, `-iquote`, `-isystem`, `-idirafter`, `-iprefix`, `-iwithprefix`,
21//! `-iwithprefixbefore`, `-include`, `-imacros`, `--sysroot=`, `-isysroot`, `-P`, `-std=`,
22//! `-fgnuc-version=`, `-ansi`, `-ffreestanding`, `-fno-builtin`, `-fno-builtin-<name>`,
23//! `-fgnu89-inline`, `-pedantic` and `-Werror`.
24//! The phases after them still say they are not implemented.
25//!
26//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
27//! explicitly unstable and will change without a major version bump.
28
29#![doc(html_root_url = "https://docs.rs/rucc-driver/0.12.2")]
30
31pub mod assemble;
32pub mod cache;
33pub mod compile;
34pub mod deps;
35pub mod fetch;
36mod glibc;
37pub mod install;
38pub mod library;
39pub mod link;
40mod map;
41pub mod msvc;
42pub mod phase;
43pub mod preprocess;
44pub mod schedule;
45mod shapes;
46pub mod trace;
47mod warnings;
48
49use std::fmt::Write as _;
50use std::io::Write as _;
51use std::path::PathBuf;
52
53use rucc_codegen::coverage::{self, Fired};
54use rucc_codegen::lowering::Lowerings;
55use rucc_codegen::pressure::Pressure;
56use rucc_pp::Dependency;
57use rucc_session::{
58 Compress, Control, Dumps, EmitKind, Hook, Math, Options, Pic, PrefixMap, Preinclude, Protector,
59 SaveTemps, Session, Std, Wrapping, runtime,
60};
61use rucc_sysroot::{Manifest, Sysroot};
62use rucc_target::{ObjectFormat, Triple};
63use rucc_tuple::TargetTuple;
64
65use crate::link::LinkOptions;
66
67pub use crate::assemble::assemble;
68pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
69pub use crate::phase::{ArchiveJob, Input, InputKind, Job, LinkJob, Output, Phase, Plan, Role};
70pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
71pub use crate::schedule::Jobs;
72
73/// The compiler's version, taken from the workspace manifest.
74pub const VERSION: &str = env!("CARGO_PKG_VERSION");
75
76/// What the command line asked for.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum Action {
79 /// Print usage and exit successfully.
80 Help,
81 /// Print the version and exit successfully.
82 Version,
83 /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
84 ///
85 /// A build system asks these before it compiles anything, and what it does with the answer
86 /// is paste it into a path or into another command line, so each one is a single line with
87 /// no decoration around it.
88 Print(String),
89 /// Print the resolved configuration and exit successfully.
90 PrintConfig(Box<Options>),
91 /// Print the passes the level will run and exit successfully.
92 PrintPipeline(Box<Options>),
93 /// Print the phase plan and the link line and exit successfully, which is `-###`.
94 PrintPlan {
95 /// The resolved options, which is what says what the link line is for.
96 opts: Box<Options>,
97 /// What to do to each input, and in what order.
98 plan: Box<Plan>,
99 /// What the command line said about linking.
100 link: Box<LinkOptions>,
101 },
102 /// `--fetch <tuple>`, which gets the sysroot this release pins for a target and installs it.
103 ///
104 /// The only action in this compiler that may run another program to move bytes onto the
105 /// machine, which is `spec/cross-compile/13-distribution.md` section 13.8's rule rather than a
106 /// property of how this happens to be written: a compilation has no branch that reaches it.
107 Fetch {
108 /// The artifact, from the table in [`rucc_sysroot::artifact`]. Resolved here rather than where the
109 /// work happens, so that a target nothing is pinned for is a refusal from the parser like
110 /// every other thing a command line can ask for and not have.
111 what: &'static rucc_sysroot::Pinned,
112 /// The target, which names the directory under the cache the tree is installed at and is
113 /// checked against the record inside the artifact.
114 target: TargetTuple,
115 /// Where the cache is, read where everything else that needs it reads it.
116 cache: PathBuf,
117 },
118 /// `--fetch-msvc-sdk <tuple>`, which gets what is behind Microsoft's licence wall.
119 ///
120 /// The other action that may run another program to move bytes onto the machine, and the only
121 /// one that asks a person to accept somebody else's licence first.
122 /// `spec/cross-compile/13-distribution.md` section 13.4 is why it is a command of its own
123 /// rather than something `--fetch` does when it recognises the target: no release pins an
124 /// artifact for these, and nothing about this may ever happen because a compile wanted it to.
125 FetchMsvcSdk {
126 /// The target, which says which architecture's CRT library package is wanted.
127 target: TargetTuple,
128 /// Whether `--accept-licence` was on the command line. Without it the licence and the list
129 /// are printed and nothing is downloaded, which is the whole of what the flag is for.
130 accepted: bool,
131 /// Where the cache is, read where everything else that needs it reads it.
132 cache: PathBuf,
133 },
134 /// Compile the given inputs.
135 Compile {
136 /// The resolved options.
137 opts: Box<Options>,
138 /// What to do to each input, and in what order.
139 plan: Box<Plan>,
140 /// What the command line said about linking.
141 link: Box<LinkOptions>,
142 /// How many translation units to compile at once.
143 jobs: Jobs,
144 /// Whether `-v` asked for the plan to be printed while it runs.
145 verbose: bool,
146 /// What is worth saying about the command line before anything is compiled, printed as
147 /// warnings and once for the whole run rather than once per file.
148 ///
149 /// These are not diagnostics. A diagnostic is about a piece of source and has a span to
150 /// point at, and these are about the way two flags were combined, so there is nothing to
151 /// point at and nowhere below the driver that knows both halves. `-w` does not reach them
152 /// for the same reason it does not reach a refusal from the parser.
153 notes: Vec<String>,
154 },
155}
156
157/// Why a command line was rejected.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct CliError {
160 /// The message, lowercase and without a trailing period, in the same shape as any other
161 /// diagnostic.
162 pub message: String,
163}
164
165impl std::fmt::Display for CliError {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 f.write_str(&self.message)
168 }
169}
170
171impl std::error::Error for CliError {}
172
173fn err(message: impl Into<String>) -> CliError {
174 CliError { message: message.into() }
175}
176
177/// The two halves of one prefix mapping flag's argument, where `flag` includes its trailing `=`.
178///
179/// The split is at the last `=` in what follows the flag, not the first, which is gcc's rule and
180/// the only one that lets a directory whose name contains an `=` be the old half. It also means
181/// `-fmacro-prefix-map=a=b=c` rewrites `a=b` to `c` rather than `a` to `b=c`, which looks like a
182/// trap until you notice the alternative traps the far more common case.
183fn rewrite<'a>(arg: &'a str, flag: &str) -> Result<(&'a str, &'a str), CliError> {
184 let rest = &arg[flag.len()..];
185 PrefixMap::split(rest).ok_or_else(|| {
186 let flag = flag.trim_end_matches('=');
187 err(format!(
188 "`{rest}` is not a rewrite for `{flag}`, which is an old prefix, an `=` and a new one"
189 ))
190 })
191}
192
193/// A question the command line asked instead of asking for a compilation.
194///
195/// These are answered after the loop rather than where they are read, because every one of them
196/// is about the target or about the library search and the last word on both is the end of the
197/// command line.
198enum Query {
199 /// `-dumpmachine`, the triple.
200 Machine,
201 /// `-dumpversion`, the major number of the GCC release this compiler claims to be.
202 Version,
203 /// `-dumpfullversion`, the same release in all three numbers.
204 FullVersion,
205 /// `-print-multiarch`, the directory name a distribution files this target under.
206 Multiarch,
207 /// `-print-search-dirs`, in the three lines GCC prints.
208 SearchDirs,
209 /// `-print-sysroot`, the root the headers and the libraries are read under.
210 Sysroot,
211 /// `-print-sysroot-provenance`, what is in that root and where each of it came from.
212 SysrootProvenance,
213 /// `-print-sysroot-digest`, the one number that names all of it.
214 SysrootDigest,
215 /// `-print-file-name=<name>`, the full path of a library file.
216 FileName(String),
217 /// `-print-prog-name=<name>`, the full path of a program.
218 ProgName(String),
219 /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
220 Libgcc,
221}
222
223/// Usage text.
224///
225/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
226/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
227pub const USAGE: &str = "\
228rucc, an optimizing C compiler
229
230usage: rucc [options] file...
231
232options:
233 -c compile and assemble, do not link
234 -S compile only, emit assembly
235 -E preprocess only
236 -o <file> write output to <file>, or to standard output for -
237 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
238 -I <dir> add <dir> to the include search path
239 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
240 -I-, -iprefix <p>, -iwithprefix[before] <dir> the older spellings of those
241 -include <file>, -imacros <file> read <file> first, the second for its macros only
242 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
243 -P, -dM with -E: leave out the markers, or dump the macros
244 -M -MM -MD -MMD write a make rule for the source, the last two compile as well
245 -MF <file> -MT <t> -MQ <t> -MP where the rule goes, what it builds, targets with no recipe
246 -std=<dialect> c89 through c2y, and the gnu spellings
247 -fgnuc-version=<v> the GCC release to claim, default 16.0.0
248 -x <lang> treat later inputs as <lang>, or none to stop
249 -O<level> optimize: 0, 1, 2, 3, s, z, fast
250 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
251 -f[no-]sanitize=<what> the negative is taken, the positive is refused by name
252 -f[no-]safety-subobject a write has to stay inside the member it names
253 -f[no-]safety-restrict two restrict pointers of one block may not meet
254 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
255 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
256 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
257 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
258 -gz[=none|zlib|zlib-gnu|zstd] -gno-split-dwarf compress debug sections, one file not two
259 -flto[=auto|jobserver|<n>] -fno-lto -ffat-lto-objects read, and not done yet
260 -fprofile-use[=<path>] -fprofile-dir=<dir> read too, where -fprofile-generate is refused
261 -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
262 -ffunction-sections -fdata-sections a section per function or variable, for --gc-sections
263 -fvisibility=<what> default, hidden, internal or protected, when nothing in the source said
264 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
265 -fPIC -fpic -fPIE -fpie, -fno-common, -pipe what it does anyway
266 -f[no-]strict-aliasing, -f[no-]delete-null-pointer-checks what it assumes anyway
267 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
268 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
269 -Werror -pedantic -pedantic-errors -w -W[no-]system-headers how much to say, and how fatal
270 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
271 -pg -p, -mfentry -mno-fentry call a profiler on the way in, and where that call goes
272 -fpatchable-function-entry=<n>[,<m>] room at the top of every function to patch later
273 -fwrapv, -fwrapv-pointer, -fno-strict-overflow, -ftrapv overflow wraps, or stops the program
274 -f[no-]exceptions, -f[no-]non-call-exceptions let an exception unwind through the code
275 -f[no-]signed-char, -f[no-]unsigned-char, -f[no-]short-enums change the ABI
276 -ffp-contract=<how> fuse a multiply and an addition: fast, on or off
277 -f[no-]fast-math and each of its members, -f[no-]rounding-math, -fexcess-precision=<how>
278 -ffile-prefix-map=<old>=<new> rewrite that front of every path we put in the output
279 -fmacro-prefix-map= -fdebug-prefix-map= -fprofile-prefix-map= the same, one output each
280 -pthread build for more than one thread, and link the library for it
281 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
282 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
283 -print-sysroot the root the headers and the libraries are read under
284 -print-sysroot-provenance every input under it, where it came from and its licence
285 -print-sysroot-digest the sha256 of that record, which names the whole sysroot in one line
286 --fetch <tuple> get the sysroot this release pins for <tuple> and install it in the cache
287 --fetch-msvc-sdk <tuple> Microsoft's licence, then the SDK behind it with --accept-licence
288 --offline never download anything, which a compilation never does anyway
289 -j[n] compile n translation units at once, default all
290 -v, -### print each phase as it runs, or without running any
291 -save-temps[=cwd|obj], -fstack-usage, -time keep the .i and .s, write a .su, time each step
292 --target=<triple> generate code for <triple>, which a name like <triple>-rucc also does
293 --emit=<kind> exe, obj, archive, asm, preprocessed, tast, ir, mir-final,
294 safety-summary, type-granules
295 --print-config, --print-pipeline print the configuration or the pipeline, and exit
296 --version print the version and exit
297 -h, --help print this message and exit
298
299See spec/04-driver-and-cli.md for the full flag reference.
300";
301
302/// The argument of a flag that may be joined to it or may be the next word.
303///
304/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
305fn joined_or_next(
306 arg: &str,
307 at: usize,
308 args: &[String],
309 i: &mut usize,
310) -> Result<String, CliError> {
311 if arg.len() > at {
312 return Ok(arg[at..].to_owned());
313 }
314 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
315 *i += 1;
316 Ok(next.clone())
317}
318
319/// The smallest boundary a function is put on when the command line asked for no alignment at all.
320///
321/// Eight bytes, which is what gcc 16 gives `-fno-align-functions` on x86-64 and is a boundary every
322/// target this compiler has is happy with. It is not zero: a function still has to start somewhere
323/// an instruction may start, and the flag asks for the target's minimum rather than for none.
324const MIN_FUNC_ALIGN: u32 = 8;
325
326/// What `-falign-functions=N` asks for, as a power of two, or `None` for the target's own answer.
327///
328/// Zero and one both mean the default, which is gcc's reading of them, and everything else is
329/// rounded up to the next power of two, which is also gcc's: `-falign-functions=3` puts a function
330/// on a four byte boundary rather than being refused. Gives back `Err` shaped as an outer `None`
331/// only when the text is not a number, since that is the one thing gcc will not read either. A
332/// number larger than any alignment makes sense at is clamped rather than refused, for the same
333/// reason: this is a preference about speed and a build that wrote a silly one still deserves to
334/// compile.
335fn function_alignment(text: &str) -> Option<Option<u32>> {
336 // gcc takes `N:M:N2:M2`, where everything after the first number is about how far it is willing
337 // to go to reach the boundary. Only the boundary is answerable here, so the rest is read to
338 // check that it is numbers and then dropped.
339 let mut parts = text.split(':');
340 let first = parts.next()?;
341 if parts.any(|part| part.parse::<u64>().is_err()) {
342 return None;
343 }
344 let want: u64 = first.parse().ok()?;
345 if want <= 1 {
346 return Some(None);
347 }
348 let bytes = want.min(1 << 16).next_power_of_two();
349 Some(Some(u32::try_from(bytes).ok()?))
350}
351
352/// Every name that may follow `-fsanitize=`, which is gcc 16's list and three of this compiler's
353/// own.
354///
355/// The three are on it because `spec/07-types-and-semantics.md` section 7.7 already promises them:
356/// each undefined behaviour this compiler exploits is listed there with the check that detects it,
357/// and `alias`, `restrict` and `memory` are checks gcc has no spelling for. gcc refuses `memory`
358/// outright, since the sanitizer of that name is clang's. A name being here means it is a name
359/// rather than a typo, and nothing more than that: every one of them is refused after the loop,
360/// because none of them is implemented.
361///
362/// `all` is deliberately absent. gcc takes it only in the negative, so it is handled where each of
363/// those two spellings is read rather than by being on this list.
364const SANITIZERS: [&str; 34] = [
365 "address",
366 "kernel-address",
367 "hwaddress",
368 "kernel-hwaddress",
369 "pointer-compare",
370 "pointer-subtract",
371 "thread",
372 "leak",
373 "undefined",
374 "shift",
375 "shift-base",
376 "shift-exponent",
377 "integer-divide-by-zero",
378 "unreachable",
379 "vla-bound",
380 "null",
381 "return",
382 "signed-integer-overflow",
383 "bounds",
384 "bounds-strict",
385 "alignment",
386 "object-size",
387 "float-divide-by-zero",
388 "float-cast-overflow",
389 "nonnull-attribute",
390 "returns-nonnull-attribute",
391 "bool",
392 "enum",
393 "vptr",
394 "pointer-overflow",
395 "builtin",
396 "alias",
397 "restrict",
398 "memory",
399];
400
401/// The command line with every `@file` replaced by the words in the file, the way gcc does it.
402///
403/// Meson writes the link of a large target this way, so that a command line holding a thousand
404/// objects stays under the limit the system puts on one. Postgres's `postgres` executable is the
405/// one link in its tree that meson writes as `@postgres.rsp`, and before this the name went to
406/// the linker as it was. GNU ld reads response files itself, so it opened the file and found
407/// `-Wl,--as-needed` in it, which is a driver flag it has never heard of.
408///
409/// The rules are libiberty's `expandargv`, since that is what gcc and every other GNU tool read
410/// these files with. Words are split on white space, a single or a double quote keeps white
411/// space in a word until the matching quote, and a backslash makes the character after it an
412/// ordinary one, inside quotes as well as outside. A word the file gives that starts with `@` is
413/// read as a response file in turn. A name that cannot be opened is left on the command line as
414/// it was, which is what gcc does and which is how a file really called `@x.c` still reaches the
415/// loop, where it is refused as an unknown input rather than swallowed. The depth is capped so a
416/// file that names itself is an error and not a hang.
417fn response_files(args: &[String]) -> Result<Vec<String>, CliError> {
418 const DEEPEST: usize = 64;
419 fn expand(args: &[String], depth: usize, out: &mut Vec<String>) -> Result<(), CliError> {
420 for arg in args {
421 let Some(name) = arg.strip_prefix('@') else {
422 out.push(arg.clone());
423 continue;
424 };
425 let Ok(text) = std::fs::read_to_string(name) else {
426 out.push(arg.clone());
427 continue;
428 };
429 if depth == DEEPEST {
430 return Err(err(format!("response file '{name}' is nested too deeply")));
431 }
432 expand(&response_words(&text), depth + 1, out)?;
433 }
434 Ok(())
435 }
436 if !args.iter().any(|arg| arg.starts_with('@')) {
437 return Ok(args.to_vec());
438 }
439 let mut out = Vec::with_capacity(args.len());
440 expand(args, 0, &mut out)?;
441 Ok(out)
442}
443
444/// The words of one response file, split the way libiberty's `buildargv` splits them.
445fn response_words(text: &str) -> Vec<String> {
446 let mut words = Vec::new();
447 let mut word = String::new();
448 // Whether a word has begun, which is not the same as `word` having something in it: `''` is
449 // an empty word of its own and has to reach the command line as one.
450 let mut begun = false;
451 let mut quote: Option<char> = None;
452 let mut chars = text.chars();
453 while let Some(c) = chars.next() {
454 match c {
455 '\\' => {
456 if let Some(next) = chars.next() {
457 word.push(next);
458 }
459 begun = true;
460 }
461 _ if quote == Some(c) => quote = None,
462 _ if quote.is_some() => word.push(c),
463 '\'' | '"' => {
464 quote = Some(c);
465 begun = true;
466 }
467 _ if c.is_whitespace() => {
468 if begun {
469 words.push(std::mem::take(&mut word));
470 begun = false;
471 }
472 }
473 _ => {
474 word.push(c);
475 begun = true;
476 }
477 }
478 }
479 if begun {
480 words.push(word);
481 }
482 words
483}
484
485/// The command line with every `-Wp,` this compiler understands spelled as its own flags.
486///
487/// The preprocessor is inside this compiler, so what a build hands it through `-Wp,` has to be
488/// read here. Kbuild is the reason: every object in the Linux kernel and in busybox is compiled
489/// with `-Wp,-MD,dir/.name.o.d`, which is cpp's spelling of `-MD -MF dir/.name.o.d`. cpp's `-MD`
490/// and `-MMD` take the file as their next word where the driver's do not, and the rest are the
491/// same flags in both. A `-Wp,` holding anything else is left as it was so the loop refuses it,
492/// because dropping part of what a build asked the preprocessor for would be the silent kind of
493/// wrong.
494fn preprocessor_args(args: &[String]) -> Vec<String> {
495 let mut out = Vec::with_capacity(args.len());
496 for arg in args {
497 let Some(list) = arg.strip_prefix("-Wp,") else {
498 out.push(arg.clone());
499 continue;
500 };
501 let words: Vec<&str> = list.split(',').collect();
502 let mut spelled = Vec::new();
503 let mut i = 0;
504 let understood = loop {
505 let Some(&word) = words.get(i) else {
506 break true;
507 };
508 i += 1;
509 match word {
510 "-MD" | "-MMD" | "-MF" | "-MT" | "-MQ" => {
511 let Some(&value) = words.get(i) else {
512 break false;
513 };
514 i += 1;
515 if word == "-MD" || word == "-MMD" {
516 spelled.extend([word.to_owned(), "-MF".to_owned()]);
517 } else {
518 spelled.push(word.to_owned());
519 }
520 spelled.push(value.to_owned());
521 }
522 "-MP" => spelled.push(word.to_owned()),
523 _ if word.len() > 2
524 && (word.starts_with("-D")
525 || word.starts_with("-U")
526 || word.starts_with("-I")) =>
527 {
528 spelled.push(word.to_owned());
529 }
530 _ => break false,
531 }
532 };
533 if understood {
534 out.extend(spelled);
535 } else {
536 out.push(arg.clone());
537 }
538 }
539 out
540}
541
542/// The extension a `-m` flag names and whether it turns it on, when it names one.
543///
544/// `-mno-` is the off form of every one of them, which is also how gcc spells it. A flag that is
545/// not an extension, `-mno-red-zone` say, is `None` and is left to the rest of the parser.
546fn isa_name(arg: &str) -> Option<(&str, rucc_target::Feature, bool)> {
547 let rest = arg.strip_prefix("-m")?;
548 let (name, on) = match rest.strip_prefix("no-") {
549 Some(name) => (name, false),
550 None => (rest, true),
551 };
552 let known =
553 if on { rucc_target::Feature::named(name) } else { rucc_target::Feature::named_off(name) };
554 known.map(|feature| (name, feature, on))
555}
556
557/// The extensions the machine running the compiler has, which is what `-march=native` means.
558///
559/// Asked of the processor with `cpuid`, through the standard library, and only when the compiler
560/// is running on an x86-64 at all. Anywhere else there is no processor to ask about an x86-64 one,
561/// and gcc on such a machine builds for the baseline, which is what this does. The list is the
562/// extensions whose names are stable in the standard library at this workspace's minimum Rust
563/// version, which covers everything [`rucc_target::Feature::honoured`] says yes to and a good deal
564/// that it does not.
565fn native_isa() -> rucc_target::Isa {
566 let base = rucc_target::Isa::baseline();
567 #[cfg(target_arch = "x86_64")]
568 {
569 let mut isa = rucc_target::Choices::new();
570 macro_rules! asked {
571 ($($detected:tt => $name:literal),* $(,)?) => {
572 $(if std::arch::is_x86_feature_detected!($detected) {
573 isa.read($name).expect("a name gcc knows");
574 })*
575 };
576 }
577 asked! {
578 "sse3" => "sse3",
579 "ssse3" => "ssse3",
580 "sse4.1" => "sse4.1",
581 "sse4.2" => "sse4.2",
582 "sse4a" => "sse4a",
583 "popcnt" => "popcnt",
584 "avx" => "avx",
585 "avx2" => "avx2",
586 "fma" => "fma",
587 "f16c" => "f16c",
588 "bmi1" => "bmi",
589 "bmi2" => "bmi2",
590 "lzcnt" => "lzcnt",
591 "xsave" => "xsave",
592 "aes" => "aes",
593 "pclmulqdq" => "pclmul",
594 "sha" => "sha",
595 "cmpxchg16b" => "cx16",
596 "adx" => "adx",
597 "rdrand" => "rdrnd",
598 "rdseed" => "rdseed",
599 }
600 isa.over(base)
601 }
602 #[cfg(not(target_arch = "x86_64"))]
603 base
604}
605
606/// Parses a command line, without the program name.
607///
608/// # Errors
609///
610/// Returns the message to print when the arguments do not name a compilation this compiler
611/// can attempt.
612pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
613 let expanded = preprocessor_args(&response_files(args)?);
614 let args = expanded.as_slice();
615 let host = Triple::host()
616 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
617 let mut opts = Options::new(host);
618 // Where the compiler is running, which is what `DW_AT_comp_dir` is and what a debugger joins a
619 // relative file name onto. Asked here rather than where the debug sections are written, because
620 // this is the one layer that is allowed to look at the process it is in, and because a command
621 // line that compiles four files should give the same answer for all four.
622 opts.working_dir = std::env::current_dir().ok().map(|dir| dir.to_string_lossy().into_owned());
623 let mut inputs: Vec<Input> = Vec::new();
624 let mut print_config = false;
625 let mut print_pipeline = false;
626 let mut print_plan = false;
627 let mut verbose = false;
628 let mut jobs = Jobs::default();
629 let mut nostdinc = false;
630 let mut sysroot: Option<PathBuf> = None;
631 // What the command line is worth warning about, filled in after the loop rather than during it,
632 // because every question of this kind is about two flags and the last word on both of them is
633 // the end of the loop.
634 let mut notes: Vec<String> = Vec::new();
635 // The whole ten field target, kept beside the three field one because `--target=` can pin a
636 // libc version and `Triple` has nowhere to put it. It decides `__GLIBC_MINOR__` and nothing
637 // else today, and `None` is a command line that named no target, which is this machine.
638 let mut pinned: Option<TargetTuple> = None;
639 let mut min_version: Option<rucc_tuple::Version> = None;
640 let mut output = None;
641 let mut link = LinkOptions::default();
642 let mut query: Option<Query> = None;
643 // What `--fetch` named, and whether `--offline` forbade it. Both are weighed after the loop
644 // because either can be written after the other.
645 let mut fetch: Option<String> = None;
646 // The other fetch, kept apart from the one above because they are different commands with
647 // different rules, and weighed after the loop for the same reason that one is.
648 let mut fetch_msvc: Option<String> = None;
649 let mut accepted = false;
650 let mut offline = false;
651 let mut threads = false;
652 // Which sanitizers are still asked for by the end of the command line. Accumulated across the
653 // loop rather than answered where it was read, because `-fno-sanitize=` turns one off and a
654 // build that asks for a check and then takes it back has asked for nothing. What happens to a
655 // set that is not empty is decided after the loop.
656 let mut sanitizers: Vec<&str> = Vec::new();
657 // The `-ffast-math` family in the order it was written, replayed after the loop on top of
658 // what `-Ofast` implies. gcc applies a level's defaults before any flag and the flags in order
659 // after that, so `-fno-fast-math -Ofast` is not fast math, and only a replay can say so.
660 let mut math_flags: Vec<&str> = Vec::new();
661 let mut ofast = false;
662 // `-mdaz-ftz` and `-mno-daz-ftz`, which decide the startup file directly and outrank the
663 // family on that one question.
664 let mut daz_ftz: Option<bool> = None;
665 // The instruction set extensions the `-m` flags named, in order, and the processor `-march`
666 // named last. Both are weighed after the loop, because a processor supplies only what no flag
667 // spoke for whichever order they came in, and because `--target=` may come after either and
668 // decide that neither means anything. See `rucc_target::isa`.
669 let mut isa = rucc_target::Choices::new();
670 let mut isa_flag: Option<&str> = None;
671 let mut march: Option<&str> = None;
672 // What `-fexceptions` and `-fno-exceptions` last said, if either was written. It is kept apart
673 // from the field because `-fnon-call-exceptions` turns exceptions on only when neither was,
674 // which is gcc's rule and is why `-fno-exceptions -fnon-call-exceptions` defines no
675 // `__EXCEPTIONS` whichever order the two come in.
676 let mut exceptions: Option<bool> = None;
677 // `-x` applies to inputs that come after it and stays in effect until the next one, which
678 // is why it is tracked across the loop rather than attached to a single argument.
679 let mut forced: Option<InputKind> = None;
680 // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
681 // the flags after it and not the ones before, so a command line may set it more than once.
682 // GCC's default is its own installed header directory with the last component taken off,
683 // which is a path a cross compiler's build system knows and passes; there is no equivalent
684 // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
685 // outright.
686 let mut iprefix = String::new();
687
688 let mut i = 0;
689 while i < args.len() {
690 let arg = args[i].as_str();
691 i += 1;
692 match arg {
693 "-h" | "--help" => return Ok(Action::Help),
694 "--version" => return Ok(Action::Version),
695 // The sysroot fetch, which is weighed after the loop rather than acted on here, because
696 // `--offline` written after it has to be able to forbid it. Both spellings, since a
697 // flag that takes a tuple gets written both ways and neither is a guess at what the
698 // other meant.
699 "--fetch" => {
700 let value = args
701 .get(i)
702 .ok_or_else(|| err("--fetch requires the target to get a sysroot for"))?;
703 i += 1;
704 fetch = Some(value.clone());
705 }
706 _ if arg.starts_with("--fetch=") => {
707 fetch = Some(arg["--fetch=".len()..].to_owned());
708 }
709 // The other fetch, which is section 13.4's. Same two spellings for the same reason,
710 // and weighed after the loop so that `--offline` and `--accept-licence` written after
711 // it are read whichever order somebody put them in.
712 "--fetch-msvc-sdk" => {
713 let value = args.get(i).ok_or_else(|| {
714 err("--fetch-msvc-sdk requires the target to get the SDK for")
715 })?;
716 i += 1;
717 fetch_msvc = Some(value.clone());
718 }
719 _ if arg.starts_with("--fetch-msvc-sdk=") => {
720 fetch_msvc = Some(arg["--fetch-msvc-sdk=".len()..].to_owned());
721 }
722 // Both spellings of the word, because the compiler's own prose uses one of them and
723 // most of the people typing this will reach for the other, and being told that a flag
724 // is not a flag over the letter in the middle of it is a puzzle rather than a message.
725 "--accept-licence" | "--accept-license" => accepted = true,
726 // Accepted on any command line and only ever read by the fetch, because an ordinary
727 // compile downloads nothing with or without it. So this flag takes nothing away today,
728 // which is the property section 13.2 asks for rather than an omission: a build that
729 // passes it is saying what it expects of this compiler, and what it expects is already
730 // true.
731 "--offline" => offline = true,
732 "--print-config" => print_config = true,
733 "--print-pipeline" => print_pipeline = true,
734 "-###" => print_plan = true,
735 "-v" => verbose = true,
736 // The files a compilation goes through, kept rather than thrown away. The bare
737 // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
738 // gcc 16 does; `SaveTemps::Object` carries the measurement.
739 "-save-temps" => opts.save_temps = SaveTemps::Object,
740 _ if arg.starts_with("-save-temps=") => {
741 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
742 }
743 // A `.su` beside every file compiled, one line per function saying how much stack it
744 // takes. Where the file goes is the plan's business, see `Job::stack_usage`.
745 "-fstack-usage" => opts.stack_usage = true,
746 "-fno-stack-usage" => opts.stack_usage = false,
747 // How long each step took. A misspelling of this is worth rejecting rather than
748 // ignoring, since a run that says nothing looks like a compilation that took no time.
749 "-time" => opts.time = true,
750 "-c" => opts.emit = EmitKind::Object,
751 "-S" => opts.emit = EmitKind::Asm,
752 "-E" => opts.emit = EmitKind::Preprocessed,
753 "-fsyntax-only" => opts.emit = EmitKind::SyntaxOnly,
754 "-g" => opts.debug_info = true,
755 // GCC's own levels of how much debug information to write. Zero is none and every
756 // other number is some, and this compiler has one amount, so the numbers above zero
757 // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
758 // debugger on the machine prefers, which is what we emit anyway.
759 "-g0" => opts.debug_info = false,
760 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
761 opts.debug_info = true;
762 }
763 // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
764 // asks for another version is told rather than handed a file it cannot read.
765 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
766 _ if arg.starts_with("-gdwarf-") => {
767 return Err(err(format!(
768 "{arg}: this compiler writes DWARF 5 and no other version, see \
769 spec/11-debug-info.md"
770 )));
771 }
772 // Whether the debug information goes in a file of its own beside the object. gcc
773 // writes that `.dwo` whether or not it found anything to put in it, which means a
774 // build system that declares the file as an output gets one and a make rule that
775 // depends on it fires. Refused for that reason rather than taken: section 4.1 takes a
776 // flag that changes nothing and refuses one that changes what is produced, and a file
777 // that does not appear is the plainest change of that kind there is. The negative
778 // spelling is taken, because putting it all in the object is what happens anyway.
779 "-gno-split-dwarf" => {}
780 "-gsplit-dwarf" => {
781 return Err(err(format!(
782 "{arg}: this compiler writes no separate `.dwo` file, and a build that \
783 expects one beside each object would wait for a file that never arrives, \
784 see spec/11-debug-info.md"
785 )));
786 }
787 // How the debug sections are compressed. There are none yet, so every answer produces
788 // the same bytes and taking the flag promises nothing that is not kept. The value is
789 // still checked, because a typo in a distribution's flags is worth finding when the
790 // compiler reads it rather than when somebody later wonders why nothing got smaller.
791 // Bare `-gz` means `zlib`, which the manual leaves for the reader to discover.
792 "-gz" => opts.compress = Compress::Zlib,
793 _ if arg.starts_with("-gz=") => {
794 let how = &arg["-gz=".len()..];
795 opts.compress = how.parse().map_err(|()| {
796 err(format!(
797 "`{how}` is not a way to compress debug sections, which is none, zlib, \
798 zlib-gnu or zstd"
799 ))
800 })?;
801 }
802 "-Werror" => opts.warnings_are_errors = true,
803 // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
804 // through rather than here, so that a warning `-w` dropped is not counted either.
805 "-w" => opts.warnings = false,
806 // Off by default, the way gcc has it off. A header that came with the machine is not
807 // one the person compiling can change, so a warning about it is noise, and under
808 // `-Werror` it is a build that stops on a line nobody in the project wrote. Somebody
809 // porting a header does want to hear all of it, which is what the flag is for.
810 "-Wsystem-headers" => opts.system_header_warnings = true,
811 "-Wno-system-headers" => opts.system_header_warnings = false,
812 "-pedantic-errors" => {
813 opts.pedantic = true;
814 opts.warnings_are_errors = true;
815 }
816 "-P" => opts.line_markers = false,
817 // The dependency family, which section 4.4 calls required because every build system
818 // that generates its own makefiles asks for it. The two that end in `D` write a file
819 // beside the object and let the compilation happen, and the two that do not write to
820 // standard output and stop after it. Nothing here turns the system headers back on
821 // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
822 // `-MM`: the flag asking for fewer of them is the one with something to say.
823 "-M" => {
824 opts.deps.emit = true;
825 opts.deps.instead_of_compiling = true;
826 }
827 "-MM" => {
828 opts.deps.emit = true;
829 opts.deps.instead_of_compiling = true;
830 opts.deps.system_headers = false;
831 }
832 "-MD" => opts.deps.emit = true,
833 "-MMD" => {
834 opts.deps.emit = true;
835 opts.deps.system_headers = false;
836 }
837 "-MP" => opts.deps.phony = true,
838 // These three take a word and only in the separated form, which is how GCC spells
839 // them and how every build system writes them.
840 "-MF" | "-MT" | "-MQ" => {
841 let value =
842 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
843 i += 1;
844 match arg {
845 "-MF" => opts.deps.file = Some(value.clone()),
846 // The whole of the difference between the two. `-MT` is for a build that has
847 // already escaped what it is passing, and `-MQ` is for one that has a name
848 // and wants it to arrive as that name.
849 "-MT" => opts.deps.targets.push(value.clone()),
850 _ => opts.deps.targets.push(deps::escaped(value)),
851 }
852 }
853 // The questions a build system asks before it compiles anything. Answered after the
854 // loop, because each one is about the target or the library search and the command
855 // line has not finished saying what those are.
856 "-dumpmachine" => query = Some(Query::Machine),
857 // Both answer with the GCC release in `__GNUC__` rather than our own version, because
858 // what asks is a build script deciding which GCC it is talking to, and `0.11` reads as
859 // a GCC too old to have anything. GCC 7 and later print only the major number for the
860 // first one, and that is the shape the scripts were written against.
861 "-dumpversion" => query = Some(Query::Version),
862 "-dumpfullversion" => query = Some(Query::FullVersion),
863 "-print-multiarch" => query = Some(Query::Multiarch),
864 "-print-search-dirs" => query = Some(Query::SearchDirs),
865 "-print-sysroot" => query = Some(Query::Sysroot),
866 // Both spellings, because this one is ours rather than GCC's and our own documents
867 // write it both ways: section 13.5 of `spec/cross-compile/13-distribution.md` gives it
868 // two dashes like the other flags we invented, and document 12's table gives it one
869 // like the `-print-` family it sits in. A person who reads either and types what it
870 // says is right, so neither is refused.
871 "-print-sysroot-provenance" | "--print-sysroot-provenance" => {
872 query = Some(Query::SysrootProvenance);
873 }
874 "-print-sysroot-digest" | "--print-sysroot-digest" => {
875 query = Some(Query::SysrootDigest);
876 }
877 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
878 _ if arg.starts_with("-print-file-name=") => {
879 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
880 }
881 _ if arg.starts_with("-print-prog-name=") => {
882 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
883 }
884 // A program built to run in more than one thread. On every platform this compiler
885 // targets that is a macro the library's headers read and one more library on the
886 // link line, and the library is added after the loop so that it lands after the
887 // objects that refer to it.
888 "-pthread" | "-pthreads" => {
889 opts.defines.push("_REENTRANT".to_owned());
890 threads = true;
891 }
892 "-ansi" => {
893 opts.std = Std::C89;
894 opts.gnu_extensions = false;
895 }
896 // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
897 // the spelling a build system that groups its warning flags tends to write.
898 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
899 // Both directions, because a build that needs this for one directory turns it back
900 // off for the next one rather than leaving it on for the whole tree.
901 "-fpermissive" => opts.permissive = true,
902 "-fno-permissive" => opts.permissive = false,
903 "-ffreestanding" => opts.hosted = false,
904 "-fhosted" => opts.hosted = true,
905 "-fno-builtin" => opts.builtins = false,
906 "-fbuiltin" => opts.builtins = true,
907 // The C89 dialects are under GNU's reading whatever this says, so turning it off
908 // there is turning off something the dialect asked for, which is accepted and does
909 // nothing. gcc refuses that command line, and there is nothing it could have meant.
910 "-fgnu89-inline" => opts.gnu89_inline = true,
911 "-fno-gnu89-inline" => opts.gnu89_inline = false,
912 // Both directions of each, because a build system that wants one of these usually
913 // writes it beside the flag that turns it back off for one directory.
914 "-fno-omit-frame-pointer" => opts.frame_pointer = Some(true),
915 "-fomit-frame-pointer" => opts.frame_pointer = Some(false),
916 // Both directions again, for the same reason, and a third answer for a command line
917 // that wrote neither: see `reorder_blocks` in `rucc_session`.
918 "-freorder-blocks" => opts.reorder_blocks = Some(true),
919 "-fno-reorder-blocks" => opts.reorder_blocks = Some(false),
920 // gcc's name for the scheduler that runs after the registers are handed out, which is
921 // the only one rucc has: see `schedule_insns` in `rucc_session`. gcc also takes
922 // `-fschedule-insns` for the pass before allocation, and taking that one here would be
923 // a flag that says a pass ran when none did.
924 "-fschedule-insns2" => opts.schedule_insns = Some(true),
925 "-fno-schedule-insns2" => opts.schedule_insns = Some(false),
926 // A call in tail position as a jump: see `sibling_calls` in `rucc_session`.
927 "-foptimize-sibling-calls" => opts.sibling_calls = Some(true),
928 "-fno-optimize-sibling-calls" => opts.sibling_calls = Some(false),
929 "-mno-red-zone" => opts.red_zone = false,
930 "-mred-zone" => opts.red_zone = true,
931 // Four flags rather than one with an argument, which is how gcc spells them and how
932 // every build line writes them. Last one wins, because a package build puts
933 // `-fstack-protector-strong` in its global flags and a directory that cannot have one
934 // turns it back off on the line after.
935 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
936 opts.protector = Protector::None;
937 }
938 "-fstack-protector" => opts.protector = Protector::Buffers,
939 "-fstack-protector-strong" => opts.protector = Protector::Strong,
940 "-fstack-protector-all" => opts.protector = Protector::All,
941 // The other half of what a hardened build asks for, and it is a question about the
942 // frame rather than about the function, so it is a switch rather than a level.
943 "-fstack-clash-protection" => opts.stack_clash = true,
944 "-fno-stack-clash-protection" => opts.stack_clash = false,
945 // The third of them, and the one that is a question with an argument rather than a
946 // family of spellings, because what it asks about is which of the two edges of a
947 // control flow transfer is checked. Bare is both of them, which is what gcc does.
948 "-fcf-protection" => opts.control = Control::Full,
949 "-fno-cf-protection" => opts.control = Control::None,
950 // Two spellings of the same request, which is what gcc has as well. `-p` was the older
951 // profiler and `-pg` the one that also recorded who called whom, and on every platform
952 // this compiler targets there is now one hook and both ask for it.
953 "-pg" | "-p" => {
954 opts.profile = true;
955 link.profile = true;
956 }
957 // Accepted on their own and doing nothing on their own, which is gcc's behaviour: they
958 // say where the call goes and a command line that asked for no call has nowhere to put
959 // one. That matters because a build system that sets `-mfentry` globally and `-pg` per
960 // directory is a build system that would otherwise fail on every other directory.
961 "-mfentry" => opts.hook = Hook::Early,
962 "-mno-fentry" => opts.hook = Hook::Late,
963 // GCC drops its own include directory along with the system ones, because its
964 // headers are half of a pair with the library's and half a pair is worse than
965 // none. A build that passes this is supplying the whole set itself.
966 "-nostdinc" => nostdinc = true,
967 "-o" => {
968 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
969 i += 1;
970 }
971 // What the files kept beside an output are named after, which is `-save-temps` and
972 // `-fstack-usage` so far. gcc takes each of the three in the separated form only, and
973 // its driver passes them to every compilation it runs, so a build that copied a
974 // command line out of gcc's `-v` has them. See `phase::aux_base` for what they do.
975 "-dumpbase" | "-dumpbase-ext" | "-dumpdir" => {
976 let value =
977 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?.clone();
978 i += 1;
979 match arg {
980 "-dumpbase" => opts.dump_base = Some(value),
981 "-dumpbase-ext" => opts.dump_base_ext = Some(value),
982 _ => opts.dump_dir = Some(value),
983 }
984 }
985 // The flags that take a directory only in the separated form. GCC spells them
986 // this way and nothing writes `-iquotedir`, so accepting the joined form would
987 // mean guessing at a path that starts with the flag's own letters.
988 // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
989 // two mean the same thing here: the configured directories are under there rather
990 // than under the root.
991 "-isysroot" => {
992 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
993 i += 1;
994 sysroot = Some(PathBuf::from(dir));
995 }
996 "-iquote" | "-isystem" | "-idirafter" => {
997 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
998 i += 1;
999 match arg {
1000 "-iquote" => opts.search.push_quote(dir.clone()),
1001 "-isystem" => opts.search.push_system(dir.clone()),
1002 _ => opts.search.push_after(dir.clone()),
1003 }
1004 }
1005 "-iprefix" => {
1006 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
1007 i += 1;
1008 }
1009 // Where GCC puts these is not where its manual says it puts them, and this is the
1010 // measured answer rather than the documented one: `-iwithprefix` lands in the
1011 // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
1012 // the `-I` slot. A cross build that uses them is relying on the behaviour, since
1013 // that is the compiler it was developed against.
1014 "-iwithprefix" | "-iwithprefixbefore" => {
1015 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1016 i += 1;
1017 let dir = format!("{iprefix}{dir}");
1018 if arg == "-iwithprefix" {
1019 opts.search.push_system(dir);
1020 } else {
1021 opts.search.push_bracket(dir);
1022 }
1023 }
1024 "-include" | "-imacros" => {
1025 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1026 i += 1;
1027 opts.preincludes
1028 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
1029 }
1030 // The flag `-iquote` was introduced to replace, still passed by build systems old
1031 // enough to predate the replacement. It is not a directory: it says that every `-I`
1032 // so far is for quoted includes only, and that a quoted include stops looking next
1033 // to the file that wrote it.
1034 "-I-" => opts.search.split_quote_chain(),
1035 // `-x c` and `-xc`, both of which gcc takes. busybox and toybox probe the compiler
1036 // with the joined one.
1037 _ if arg.starts_with("-x") => {
1038 let lang = joined_or_next(arg, 2, args, &mut i)?;
1039 forced = if lang == "none" {
1040 None
1041 } else {
1042 Some(InputKind::from_x_arg(&lang).map_err(|e| err(format!("{e}")))?)
1043 };
1044 }
1045 // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
1046 // translation units in one process rather than making the build system fork, and
1047 // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
1048 // to exist and has to be spelled the way `make` spells it.
1049 // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
1050 // and a build system may produce either, so both are read here rather than
1051 // being normalised by whatever generated the command line.
1052 _ if arg.starts_with("-D") => {
1053 let value = joined_or_next(arg, 2, args, &mut i)?;
1054 opts.defines.push(value);
1055 }
1056 _ if arg.starts_with("-U") => {
1057 let value = joined_or_next(arg, 2, args, &mut i)?;
1058 opts.undefines.push(value);
1059 }
1060 _ if arg.starts_with("-I") => {
1061 let dir = joined_or_next(arg, 2, args, &mut i)?;
1062 opts.search.push_bracket(dir);
1063 }
1064 _ if arg.starts_with("-std=") => {
1065 let name = &arg["-std=".len()..];
1066 let (std, gnu) = Std::from_flag(name)
1067 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
1068 opts.std = std;
1069 opts.gnu_extensions = gnu;
1070 }
1071 // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
1072 // handed, so a differential run that does not set it is comparing two compilers
1073 // that believe they are different compilers.
1074 // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
1075 // that we have not written yet are accepted and ignored, because a dump is a
1076 // debugging aid and a build that asks for one should still compile. A letter
1077 // outside the family falls through to the unknown option error, which is what
1078 // keeps `-dumpversion` from being read as a dump of nothing.
1079 _ if Dumps::is_family(arg) => {
1080 opts.dumps.add(&arg[2..]);
1081 }
1082 // One name at a time, which is what a build that means its own `memcpy` and the
1083 // library's everything else writes. The name is not checked against a list, because
1084 // the flag is about what the program means by a name and a program is allowed to mean
1085 // something by a name this compiler has never heard of.
1086 _ if arg.starts_with("-fno-builtin-") => {
1087 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
1088 }
1089 _ if arg.starts_with("-fgnuc-version=") => {
1090 let v = &arg["-fgnuc-version=".len()..];
1091 opts.gnuc = v.parse().map_err(err)?;
1092 }
1093 // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
1094 // than the unknown option one, because a build reaching for it is asking for a feature
1095 // and deserves to be told it is not coming rather than told the spelling is wrong.
1096 // The negative form is what this compiler does anyway, so it is taken and dropped.
1097 "-fnested-functions" => {
1098 return Err(err(
1099 "nested functions are not supported: a call to one goes through a trampoline \
1100 written on the stack, which no target that enforces an unexecutable stack \
1101 allows",
1102 ));
1103 }
1104 "-fno-nested-functions" => {}
1105 // Which of the two links the output is for, which is a real difference and not a
1106 // description of what happens anyway. Everything here is position independent either
1107 // way, and what these decide is whether a name may be one another object defines or
1108 // replaces, because a link that produces an executable puts every name in the same
1109 // program and a link that produces a shared library does not.
1110 //
1111 // It matters that they are accepted at all, whatever they then do. Every autoconf and
1112 // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
1113 // be the `CC` of a project that has a configure script, whatever else it can do. That
1114 // is how this was found: building SQLite's test fixture stopped on it.
1115 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
1116 // Not a synonym of the pair above, which is what they were treated as until #756. The
1117 // library is the expensive answer and gcc makes it the one that has to be asked for,
1118 // so this is also what nothing at all means.
1119 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
1120 // A different question from the pair above, and the one every distribution build of a
1121 // shared library answers. `-fPIC` decides how an address is reached, and this decides
1122 // whether the optimizer may believe a body it can see, because an exported name is one
1123 // the dynamic linker may find another definition of first. On by default, which is
1124 // gcc's arrangement and is the honest answer, and off is a promise the build makes and
1125 // nothing checks.
1126 "-fsemantic-interposition" => opts.interposition = true,
1127 "-fno-semantic-interposition" => opts.interposition = false,
1128 // Two requests rather than one, and the same table answers both, so what decides is
1129 // whether either of them is standing. gcc arranges it the same way: the asynchronous
1130 // one is the default here and it implies the other, and a line that asks for a table
1131 // and against an asynchronous one gets a table.
1132 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
1133 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
1134 "-funwind-tables" => opts.unwind_tables = true,
1135 "-fno-unwind-tables" => opts.unwind_tables = false,
1136 // The other direction is a request, not a description, and it is one this compiler
1137 // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
1138 // option error. Answering it by carrying on would be answering a different question:
1139 // the code would still be position independent, which is correct everywhere an
1140 // ordinary program runs and is wrong in a kernel, where the flag is written precisely
1141 // because there is no loader to fill a global offset table in.
1142 "-fno-pic" | "-fno-pie" => {
1143 return Err(err(
1144 "position dependent code is not supported: an address that may be in another \
1145 object is loaded out of the global offset table, and nothing here emits the \
1146 absolute form this asks for. Use -no-pie if what you meant was how to link",
1147 ));
1148 }
1149 // A section per function and a section per variable, which is what makes
1150 // `--gc-sections` able to drop anything: a linker can leave out a section nothing
1151 // reaches and cannot leave out half of one. Both directions are taken, and the off
1152 // one is the default rather than a refusal, since a build that writes it is asking
1153 // for what happens anyway.
1154 "-ffunction-sections" => opts.function_sections = true,
1155 "-fno-function-sections" => opts.function_sections = false,
1156 "-fdata-sections" => opts.data_sections = true,
1157 "-fno-data-sections" => opts.data_sections = false,
1158 // Another description of what this compiler does. A file scope declaration with no
1159 // initializer is written into `.bss` as an ordinary defined symbol, not offered to the
1160 // linker as a common one for it to merge, which is what `-fno-common` asks for and what
1161 // gcc has done by default since 10. Nothing in the front end produces `Linkage::Common`
1162 // at all.
1163 "-fno-common" => {}
1164 // What overflows rather than being undefined. Every one of these takes something away
1165 // from the optimizer rather than asking it to do anything, which is why the negative
1166 // spellings are the interesting ones and the positive spellings are the default.
1167 //
1168 // `-fno-strict-overflow` is both of the others, which is gcc's own reading of it: its
1169 // help text for `-fstrict-overflow` says "negated as -fwrapv -fwrapv-pointer". So it is
1170 // written here as the pair rather than kept as a third thing to test everywhere.
1171 //
1172 // `-ftrapv` is the exception and is the one that asks for something. It is the other
1173 // answer to the question `-fwrapv` answers, so the two cannot both hold and each clears
1174 // the other, which makes the last one on the command line the one that counts. That is
1175 // gcc 16's behaviour and was measured rather than read: `-ftrapv -fwrapv` emits no
1176 // checked calls and `-fwrapv -ftrapv` emits them. The positive spelling of the pointer
1177 // question is left alone by both, because neither has anything to say about it.
1178 "-fwrapv" => {
1179 opts.wrapping.signed = true;
1180 opts.wrapping.trap = false;
1181 }
1182 "-fno-wrapv" => opts.wrapping.signed = false,
1183 "-fwrapv-pointer" => opts.wrapping.pointer = true,
1184 "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
1185 "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
1186 // Which does not clear the checked one, because gcc does not: `-ftrapv
1187 // -fstrict-overflow` still emits the calls. It says what is assumed and not what
1188 // happens.
1189 "-fstrict-overflow" => {
1190 opts.wrapping.signed = false;
1191 opts.wrapping.pointer = false;
1192 }
1193 "-ftrapv" => {
1194 opts.wrapping.trap = true;
1195 opts.wrapping.signed = false;
1196 }
1197 "-fno-trapv" => opts.wrapping.trap = false,
1198 // The two flags that say what a plain `char` is, which is one question with two
1199 // spellings each: gcc reads `-fno-signed-char` as `-funsigned-char` and
1200 // `-fno-unsigned-char` as `-fsigned-char`, so there are four ways to write two
1201 // answers and the last one written wins. Nothing is set until one of them is given,
1202 // because the target's own ABI is the answer otherwise and it is not the same answer
1203 // everywhere: x86-64 and Apple's arm64 are signed, Linux's arm64 is not.
1204 "-fsigned-char" | "-fno-unsigned-char" => opts.char_signed = Some(true),
1205 "-funsigned-char" | "-fno-signed-char" => opts.char_signed = Some(false),
1206 // And the size of an enumeration, which is the other thing in this group that changes
1207 // the ABI rather than the code.
1208 "-fshort-enums" => opts.short_enums = true,
1209 "-fno-short-enums" => opts.short_enums = false,
1210 // And Microsoft's reading of an anonymous member, which changes the layout of every
1211 // record that writes a tag on one. Nothing is set until one of them is given, because
1212 // the target is the answer otherwise: gcc's mingw build has this on and its Linux
1213 // build has it off.
1214 "-fms-extensions" => opts.ms_extensions = Some(true),
1215 "-fno-ms-extensions" => opts.ms_extensions = Some(false),
1216 // And the request, which is the one that cannot be granted. It is a real difference and
1217 // not a preference: two files each writing `int g;` link under `-fcommon` and are a
1218 // duplicate definition without it, which is the whole reason the flag survives.
1219 "-fcommon" => {
1220 return Err(err(
1221 "a tentative definition is written into .bss as its own symbol here, and \
1222 nothing emits the common symbol this asks the linker to merge. Give the \
1223 variable a definition in one file and declare it extern in the others",
1224 ));
1225 }
1226 // Both directions of this one are recorded, and what they decide is whether lowering
1227 // names the type each access goes through. Turning it off is the front end leaving the
1228 // name off rather than a pass being told to ignore one it can see, which is one
1229 // condition in one place, and it is the reading that survives link time optimization:
1230 // a unit built with the flag off keeps its own answer when its bodies end up in a
1231 // module beside bodies that were not.
1232 //
1233 // Nothing in the pipeline reads those names yet. Layer 3 of the alias analysis does
1234 // and is tested, and no pass at any level asks the alias analysis anything today, so
1235 // no program compiles differently for having passed this. The flag is wired anyway,
1236 // because the change that makes a pass ask is not the change anybody will remember to
1237 // wire it in, and a flag that is taken and dropped once the names mean something is
1238 // the miscompilation `spec/04-driver-and-cli.md` section 4.1 warns about in as many
1239 // words.
1240 "-fstrict-aliasing" => opts.strict_aliasing = true,
1241 "-fno-strict-aliasing" => opts.strict_aliasing = false,
1242 // The same shape of answer for the same reason, and the flag the kernel writes beside
1243 // the one above it.
1244 //
1245 // Nothing here concludes that a pointer is not null from the fact that it was
1246 // dereferenced. There is no such conclusion to draw from, because no pass records one:
1247 // a load says where it read and nothing else, and a comparison against null is an
1248 // ordinary comparison of two values the optimizer has no fact about. So a function
1249 // that reads through a pointer and then tests it keeps the test, which is what the
1250 // kernel wants and what `-fno-delete-null-pointer-checks` asks for, and what gcc has
1251 // to be asked for because it draws the conclusion by default.
1252 //
1253 // `-fdelete-null-pointer-checks` is the request to draw it, and it goes the way
1254 // `-fstrict-aliasing` does: assuming less than was asked for costs speed and not
1255 // correctness, and `-O2` implies it, so refusing it would stop builds for nothing.
1256 "-fdelete-null-pointer-checks" | "-fno-delete-null-pointer-checks" => {}
1257 // The floating point group, which goes the same way and for the same reason, and which
1258 // is worth writing out because the reason is easy to get backwards.
1259 //
1260 // Each of these has a restrictive spelling and a permissive one. The restrictive ones,
1261 // `-frounding-math` and `-ftrapping-math`, say that the rounding mode may have been
1262 // changed and that an exception raised by an operation may be looked at, so an
1263 // arithmetic the compiler folds at compile time is an arithmetic whose rounding and
1264 // whose exception the program does not get. Nothing here folds any floating point
1265 // arithmetic in a function body: `0.1 + 0.2` is an `fadd` and `1.0 / 0.0` is a divide
1266 // that runs, at every level. So both of those describe what already happens.
1267 //
1268 // The permissive ones are the other half, and they are licences rather than requests
1269 // for an answer. `-fno-rounding-math` says the rounding mode is the default one and
1270 // `-fno-trapping-math` says nothing looks at the exceptions, which together are
1271 // permission to fold. Not folding is the conservative side of that permission and is
1272 // what a program is entitled to whichever was written, so `-fno-rounding-math` costs
1273 // speed and not correctness, which is the test section 4.1 puts a licence through.
1274 "-frounding-math" | "-fno-rounding-math" => {}
1275 // `-fno-trapping-math` is the one of the four that is kept, because there is one
1276 // conversion this compiler does not fold and gcc folds under it, and the two answers
1277 // differ. Converting a constant floating value to an integer type it does not fit in
1278 // is undefined behaviour rather than a value: left to the hardware it is one
1279 // instruction and the answer is the integer indefinite value, and folded it is the
1280 // nearest end of the integer's range. Both compilers leave it to the instruction by
1281 // default and gcc folds it under this flag, so a program built with it and compiled
1282 // without it gets a different number rather than a slower one. `-ftrapping-math` is
1283 // gcc's default, so a build spelling it out is asking for what it already has.
1284 //
1285 // The rest of the family goes with it, `-ffast-math` included, and all of them are
1286 // taken now. Each is a licence rather than a request and nothing here folds floating
1287 // point arithmetic, so the code does not change. What does change is the macros gcc
1288 // defines for each licence, which a header reads, and the startup file `-ffast-math`
1289 // links, which puts the hardware in flush to zero mode. Both are done after the loop,
1290 // because the family is a set of switches over the same fields and the last word on
1291 // each of them is the end of the command line.
1292 "-ftrapping-math"
1293 | "-fno-trapping-math"
1294 | "-ffast-math"
1295 | "-fno-fast-math"
1296 | "-funsafe-math-optimizations"
1297 | "-fno-unsafe-math-optimizations"
1298 | "-fmath-errno"
1299 | "-fno-math-errno"
1300 | "-ffinite-math-only"
1301 | "-fno-finite-math-only"
1302 | "-fsigned-zeros"
1303 | "-fno-signed-zeros"
1304 | "-freciprocal-math"
1305 | "-fno-reciprocal-math"
1306 | "-fassociative-math"
1307 | "-fno-associative-math" => math_flags.push(arg),
1308 // Whether the startup file that sets flush to zero is linked, asked directly. gcc
1309 // links it for a shared object too when this is written, which the family does not.
1310 "-mdaz-ftz" => daz_ftz = Some(true),
1311 "-mno-daz-ftz" => daz_ftz = Some(false),
1312 // About temporary files rather than about code. There is nothing between the phases of
1313 // one compilation here to write to a file in the first place.
1314 "-pipe" => {}
1315 // Preprocess the input, which a C compile always does. GCC has it for Fortran, and
1316 // meson writes it when it asks a compiler for its predefined macros.
1317 "-cpp" => {}
1318 // Nothing here writes colour, so all of these are the same answer, and it is the answer
1319 // that costs nothing: the diagnostics come out plain either way and no build depends on
1320 // an escape sequence being there. Taken rather than refused because cmake writes
1321 // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
1322 // makes this the second most common flag after `-fPIC` to stop a build over a question
1323 // about how the text looks.
1324 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
1325 _ if arg.starts_with("-fdiagnostics-color=") => {}
1326 // The link flags. None of them changes the compilation, which is why they are
1327 // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
1328 // error: it is a thing said to a linker that is not going to run.
1329 "-static" => link.is_static = true,
1330 "-shared" => link.shared = true,
1331 "-r" => link.relocatable = true,
1332 "-pie" => link.pie = Some(true),
1333 "-no-pie" | "-nopie" => link.pie = Some(false),
1334 "-nostdlib" => link.no_stdlib = true,
1335 "-nostartfiles" => link.no_startfiles = true,
1336 "-nodefaultlibs" => link.no_defaultlibs = true,
1337 "-fno-builtins-lib" => link.no_builtins_lib = true,
1338 "-fbuiltins-lib" => link.no_builtins_lib = false,
1339 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
1340 "-s" => link.strip = true,
1341 // mingw-w64's three. `-mwindows` and `-mconsole` pick the subsystem, last one wins,
1342 // and `-municode` picks the start file and tells the headers through `UNICODE`, which is
1343 // what gcc's spec does with it. All three are taken and ignored for other targets, as gcc
1344 // built for mingw is the only gcc that knows them and a Makefile written for it is what
1345 // passes them.
1346 "-mwindows" => link.gui = true,
1347 "-mconsole" => link.gui = false,
1348 "-municode" => {
1349 link.unicode = true;
1350 opts.defines.push("UNICODE".to_owned());
1351 }
1352 // Into the ordered input list rather than a list of its own, because a great many of
1353 // the linker's options are a bracket around the files after them and an option that
1354 // lost its place among them says nothing. `--whole-archive` is the one that found this.
1355 "-Xlinker" => {
1356 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
1357 i += 1;
1358 inputs.push(Input::linker(next));
1359 }
1360 _ if arg.starts_with("-Wl,") => {
1361 // Commas separate arguments rather than being part of one, which is what makes
1362 // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
1363 inputs.extend(arg["-Wl,".len()..].split(',').map(Input::linker));
1364 }
1365 _ if arg.starts_with("-fuse-ld=") => {
1366 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
1367 }
1368 _ if arg.starts_with("-l") && arg.len() > 2 => {
1369 inputs.push(Input::library(&arg[2..]));
1370 }
1371 "-l" => {
1372 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
1373 i += 1;
1374 inputs.push(Input::library(next));
1375 }
1376 _ if arg.starts_with("-L") => {
1377 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1378 }
1379 _ if arg.starts_with("-B") => {
1380 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1381 }
1382 _ if arg.starts_with("-j") => {
1383 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
1384 }
1385 _ if arg.starts_with("--sysroot=") => {
1386 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
1387 }
1388 _ if arg.starts_with("--target=") => {
1389 let t = &arg["--target=".len()..];
1390 // The same string again, as the model that has room for a libc version. A spelling
1391 // the three field parser took and this one does not is not an error, because the
1392 // one that decides what is compiled has already accepted it and the only thing
1393 // lost is a version nobody asked for.
1394 pinned = t.parse().ok();
1395 // The other way round is a deployment target the three field parser has no room
1396 // for, `aarch64-macos.13`, and the triple is the one the tuple narrows to.
1397 opts.target = match t.parse() {
1398 Ok(triple) => triple,
1399 Err(e) => {
1400 pinned.and_then(Triple::from_tuple).ok_or_else(|| err(format!("{e}")))?
1401 }
1402 };
1403 }
1404 _ if arg.starts_with("--emit=") => {
1405 let k = &arg["--emit=".len()..];
1406 opts.emit = k
1407 .parse()
1408 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
1409 }
1410 // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
1411 // to write. `-Og` is GCC's level for a build somebody is going to step through, and
1412 // it is `-O1` with the transformations that move code around left out; this compiler
1413 // has no such level yet, so it is the nearest one and `--print-pipeline` says what
1414 // that came to rather than the flag pretending otherwise.
1415 "-O" | "-Og" => {
1416 opts.opt_level = rucc_session::OptLevel::O1;
1417 ofast = false;
1418 }
1419 // The union of `-O3` and `-ffast-math`. The second half is a default rather than a
1420 // flag, which is why it is remembered here and applied after the loop: a later level
1421 // takes it back, and so does a `-fno-fast-math` written on either side of it.
1422 "-Ofast" => {
1423 opts.opt_level = rucc_session::OptLevel::O3;
1424 ofast = true;
1425 }
1426 _ if arg.starts_with("-O") => {
1427 ofast = false;
1428 opts.opt_level = arg[2..]
1429 .parse()
1430 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
1431 }
1432 // How far a multiply and an addition may be fused into one rounding. Before the
1433 // optimizer's `-f` family below for the reason the ones under it are, and kept rather
1434 // than dropped because it is the one flag in its group this compiler could act on: it
1435 // rides into the IR as an attribute on each function with a body, so the day the code
1436 // generator forms an `fma` it already knows which functions were given permission.
1437 // Nothing forms one today, under any value of this and under any `-march=`.
1438 _ if arg.starts_with("-ffp-contract=") => {
1439 let how = &arg["-ffp-contract=".len()..];
1440 opts.fp_contract = how.parse().map_err(|()| {
1441 err(format!("`{how}` is not a contraction, which is fast, on or off"))
1442 })?;
1443 }
1444 // How much of an expression may be computed wider than it was written. The values are
1445 // gcc's and so is the refusal of anything else, and none of the three changes anything
1446 // here: an operation is computed in the type C says it is on every target this compiler
1447 // has a back end for, so `__FLT_EVAL_METHOD__` is 0 and `standard` is already what
1448 // happens. `fast` and `16` are permission to be wider, which is a licence this takes
1449 // and does not use, the same way the two above are. The flag is worth taking because
1450 // glibc's headers and a good deal of configure output write it, and because the answer
1451 // it asks about is one this compiler can state rather than guess at: there is no x87
1452 // target here, which is the machine the whole question was invented for.
1453 // Whether a local and a spilled value that are never both wanted may be the same bytes
1454 // of the frame. gcc's three values, and two of them mean the same thing here: what rucc
1455 // shares is a local whose address provably never leaves the function, which is narrower
1456 // than `named_vars` and narrower still than `all`, so both of them get it. `none` is
1457 // the one that changes anything, and it is the flag a program that reads a local
1458 // through a pointer it kept past the end of the block writes.
1459 _ if arg.starts_with("-fstack-reuse=") => {
1460 let how = &arg["-fstack-reuse=".len()..];
1461 opts.stack_reuse = match how {
1462 "all" | "named_vars" => Some(true),
1463 "none" => Some(false),
1464 _ => {
1465 return Err(err(format!(
1466 "`{how}` is not a stack reuse, which is all, named_vars or none"
1467 )));
1468 }
1469 };
1470 }
1471 _ if arg.starts_with("-fexcess-precision=") => {
1472 let how = &arg["-fexcess-precision=".len()..];
1473 if !matches!(how, "16" | "fast" | "standard") {
1474 return Err(err(format!(
1475 "`{how}` is not an excess precision, which is 16, fast or standard"
1476 )));
1477 }
1478 }
1479 // Which front of a path is rewritten before it reaches the output, which is how a
1480 // build gets the same bytes out of two different directories. The four spellings are
1481 // one flag each into three lists, and `-ffile-prefix-map=` is the three of them at
1482 // once. Only the macro list does anything today, because `__FILE__` is the only place
1483 // a path reaches the output: there is no DWARF and no profile data yet, so the other
1484 // two are recorded for the work that will read them. The argument splits at the last
1485 // `=` rather than the first, which is gcc's rule and is what lets a directory with an
1486 // `=` in its name be the old half.
1487 _ if arg.starts_with("-fmacro-prefix-map=") => {
1488 let (old, new) = rewrite(arg, "-fmacro-prefix-map=")?;
1489 opts.prefix_map.macros.push(old, new);
1490 }
1491 _ if arg.starts_with("-fdebug-prefix-map=") => {
1492 let (old, new) = rewrite(arg, "-fdebug-prefix-map=")?;
1493 opts.prefix_map.debug.push(old, new);
1494 }
1495 _ if arg.starts_with("-fprofile-prefix-map=") => {
1496 let (old, new) = rewrite(arg, "-fprofile-prefix-map=")?;
1497 opts.prefix_map.profile.push(old, new);
1498 }
1499 _ if arg.starts_with("-ffile-prefix-map=") => {
1500 let (old, new) = rewrite(arg, "-ffile-prefix-map=")?;
1501 opts.prefix_map.macros.push(old, new);
1502 opts.prefix_map.debug.push(old, new);
1503 opts.prefix_map.profile.push(old, new);
1504 }
1505 // A whole optimization rather than a flag, and the family is taken rather than
1506 // refused because of what ignoring it does. There is none of it here yet, so a build
1507 // that asks for it gets a program that is correct and slower than it could have been,
1508 // which is what section 4.1 means by a hint about speed and what every compilation at
1509 // `-O0` already is. The objects settle the rest of the argument: gcc's `-flto` object
1510 // holds the bytecode and no machine code at all, and every object here holds the code,
1511 // which is exactly what `-ffat-lto-objects` asks gcc for. So a build passing `-flto`
1512 // to this compiler gets objects that are more usable than the ones it asked for rather
1513 // than different ones. Every value is still checked against gcc's, because somebody
1514 // who wrote `-flto=thin` meant clang and had better hear about it here.
1515 "-flto" => opts.lto.requested = true,
1516 "-fno-lto" => opts.lto.requested = false,
1517 _ if arg.starts_with("-flto=") => {
1518 let how = &arg["-flto=".len()..];
1519 opts.lto.jobs = how.parse().map_err(|()| {
1520 err(format!(
1521 "`{how}` is not a number of link time jobs, which is auto, jobserver or a \
1522 count above zero"
1523 ))
1524 })?;
1525 opts.lto.requested = true;
1526 }
1527 _ if arg.starts_with("-flto-partition=") => {
1528 let how = &arg["-flto-partition=".len()..];
1529 opts.lto.partition = how.parse().map_err(|()| {
1530 err(format!(
1531 "`{how}` is not a partitioning model, which is balanced, 1to1, one, max \
1532 or none"
1533 ))
1534 })?;
1535 }
1536 _ if arg.starts_with("-flto-compression-level=") => {
1537 let how = &arg["-flto-compression-level=".len()..];
1538 let level =
1539 how.parse::<u8>().ok().filter(|level| *level <= 19).ok_or_else(|| {
1540 err(format!("`{how}` is not a compression level, 0 to 19"))
1541 })?;
1542 opts.lto.compression = Some(level);
1543 }
1544 // Whether the object keeps its machine code as well as the bytecode. It always does
1545 // here, so the first of these describes what happens and the second asks for an object
1546 // with less in it, which is a smaller file and not a different program, so both are
1547 // taken.
1548 "-ffat-lto-objects" | "-fno-fat-lto-objects" => {}
1549 // Whether the linker is handed a plugin that does the link time work. The design in
1550 // `spec/09-optimizer.md` has this driver doing that work itself and never loading a
1551 // plugin into anybody, so neither answer is a question it has to hold.
1552 "-fuse-linker-plugin" | "-fno-use-linker-plugin" => {}
1553 // Reading a profile back. Taken for the reason the family above it is: nothing here
1554 // reads one, so a build that asks gets the program it would have got anyway, and gcc
1555 // itself produces a byte for byte identical object from `-fprofile-use` when there are
1556 // no counts beside the file. The path is recorded for the pass that will read it. The
1557 // warning gcc prints when it looked and found nothing is deliberately not copied,
1558 // because nothing here looks, and a warning about a file that was never opened would
1559 // fire on the builds that have a perfectly good profile as well as on the ones that
1560 // do not.
1561 "-fprofile-use" => opts.profile_data.requested = true,
1562 "-fno-profile-use" => opts.profile_data.requested = false,
1563 _ if arg.starts_with("-fprofile-use=") => {
1564 opts.profile_data.path = Some(arg["-fprofile-use=".len()..].to_string());
1565 opts.profile_data.requested = true;
1566 }
1567 _ if arg.starts_with("-fprofile-dir=") => {
1568 opts.profile_data.dir = Some(arg["-fprofile-dir=".len()..].to_string());
1569 }
1570 "-fprofile-abs-path" => opts.profile_data.absolute = true,
1571 "-fno-profile-abs-path" => opts.profile_data.absolute = false,
1572 "-fprofile-correction" => opts.profile_data.correction = true,
1573 "-fno-profile-correction" => opts.profile_data.correction = false,
1574 "-fprofile-partial-training" => opts.profile_data.partial_training = true,
1575 "-fno-profile-partial-training" => opts.profile_data.partial_training = false,
1576 // Writing the counts rather than reading them, which is refused rather than taken and
1577 // is the same line `-gsplit-dwarf` falls on the far side of. Ignoring these means a
1578 // file a build declared as an output never appears: the instrumented program writes a
1579 // `.gcda` as it exits and `-ftest-coverage` writes a `.gcno` beside the object, and a
1580 // two stage build that got neither would go on to optimize against no counts at all
1581 // and report coverage of nothing, with nothing along the way saying so. The objects
1582 // say the rest: gcc's `-fprofile-generate` object holds 375 bytes of code where a
1583 // plain one holds 71, and 296 bytes of counters that a plain one does not have, so
1584 // this is a flag that changes the output rather than a hint about speed.
1585 "-fprofile-arcs"
1586 | "--coverage"
1587 | "-fcondition-coverage"
1588 | "-fpath-coverage"
1589 | "-fprofile-generate" => {
1590 return Err(err(format!(
1591 "{arg}: this compiler does not instrument for profiling, and a build that \
1592 expects the counts a run of the instrumented program writes would optimize \
1593 against nothing on its second pass, see spec/04-driver-and-cli.md"
1594 )));
1595 }
1596 _ if arg.starts_with("-fprofile-generate=") => {
1597 return Err(err(format!(
1598 "{arg}: this compiler does not instrument for profiling, and a build that \
1599 expects the counts a run of the instrumented program writes would optimize \
1600 against nothing on its second pass, see spec/04-driver-and-cli.md"
1601 )));
1602 }
1603 "-ftest-coverage" => {
1604 return Err(err(format!(
1605 "{arg}: this compiler writes no `.gcno` file beside the object, and a build \
1606 that expects one would wait for a file that never arrives, see \
1607 spec/04-driver-and-cli.md"
1608 )));
1609 }
1610 // The rest of the family describes instrumentation that is refused above, so what is
1611 // left to do with them is check them and drop them. They are checked because a
1612 // misspelling in a distribution's flags is worth finding here rather than on the day
1613 // the instrumentation lands, and dropped because there is nothing for an answer about
1614 // how a counter is written to be an answer about.
1615 _ if arg.starts_with("-fprofile-update=") => {
1616 let how = &arg["-fprofile-update=".len()..];
1617 if !matches!(how, "single" | "atomic" | "prefer-atomic") {
1618 return Err(err(format!(
1619 "`{how}` is not a profile update method, which is single, atomic or \
1620 prefer-atomic"
1621 )));
1622 }
1623 }
1624 _ if arg.starts_with("-fprofile-reproducible=") => {
1625 let how = &arg["-fprofile-reproducible=".len()..];
1626 if !matches!(how, "serial" | "parallel-runs" | "multithreaded") {
1627 return Err(err(format!(
1628 "`{how}` is not a profile reproducibility method, which is serial, \
1629 parallel-runs or multithreaded"
1630 )));
1631 }
1632 }
1633 "-fprofile-values" | "-fno-profile-values" | "-fprofile-info-section" => {}
1634 "-fno-test-coverage" | "-fno-profile-arcs" | "-fno-profile-generate" => {}
1635 _ if arg.starts_with("-fprofile-filter-files=")
1636 || arg.starts_with("-fprofile-exclude-files=")
1637 || arg.starts_with("-fprofile-note=") => {}
1638 // What every name gets when nothing in the source said, which the attribute in the
1639 // source overrides rather than the other way round. Before the optimizer's `-f`
1640 // family below for the reason the tier below it is.
1641 _ if arg.starts_with("-fvisibility=") => {
1642 let seen = &arg["-fvisibility=".len()..];
1643 opts.visibility = seen.parse().map_err(|()| {
1644 err(format!(
1645 "`{seen}` is not a visibility, which is default, hidden, internal or \
1646 protected"
1647 ))
1648 })?;
1649 }
1650 // Which edges of a control flow transfer are checked. Before the optimizer's `-f`
1651 // family below for the reason the two above it are, and last of the three so that the
1652 // bare spelling and the negative one are matched exactly rather than by this.
1653 _ if arg.starts_with("-fcf-protection=") => {
1654 let edges = &arg["-fcf-protection=".len()..];
1655 opts.control = edges.parse().map_err(|()| {
1656 err(format!(
1657 "`{edges}` is not a control flow protection, which is full, branch, \
1658 return, none or check"
1659 ))
1660 })?;
1661 }
1662 // How much room every function opens with for something to be written over later.
1663 // Before the optimizer's `-f` family below for the reason the ones above it are.
1664 _ if arg.starts_with("-fpatchable-function-entry=") => {
1665 let room = &arg["-fpatchable-function-entry=".len()..];
1666 opts.patchable = room.parse().map_err(|()| {
1667 err(format!(
1668 "`{room}` is not an amount of room to reserve, which is a number of bytes and then, after a comma, how many of them go in front of the function's own label"
1669 ))
1670 })?;
1671 }
1672 // The memory safety monitor, from section 15.4 of
1673 // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
1674 // because a pass that took the name `safety=detect` would otherwise be handed the
1675 // flag, and the tier is not a pass.
1676 _ if arg.starts_with("-fsafety=") => {
1677 let tier = &arg["-fsafety=".len()..];
1678 opts.safety = tier.parse().map_err(|()| {
1679 err(format!(
1680 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
1681 ))
1682 })?;
1683 }
1684 // Whether padding participates, from section 9.3 of document 09. Spelled out rather
1685 // than folded into the tier because it is a departure somebody who has read that
1686 // section makes, and the two defaults it describes are a property of what is being
1687 // built rather than of how much checking is wanted.
1688 _ if arg.starts_with("-fsafety-init=") => {
1689 let mode = &arg["-fsafety-init=".len()..];
1690 opts.padding = mode.parse().map_err(|()| {
1691 err(format!("`{mode}` is not a padding mode, which is padding or nopadding"))
1692 })?;
1693 }
1694 // Row S4, from section 9.4 of document 09. A bare flag with no value, because the
1695 // strict form of that section needs a member id the front end does not name yet and
1696 // accepting the spelling for it would be accepting a promise this build cannot keep.
1697 // Before `-fno-` is looked at below, for the reason the tier is.
1698 "-fsafety-subobject" => opts.subobject = rucc_session::Subobject::Members,
1699 "-fno-safety-subobject" => opts.subobject = rucc_session::Subobject::Off,
1700 _ if arg.starts_with("-fsafety-subobject=") => {
1701 let form = &arg["-fsafety-subobject=".len()..];
1702 return Err(err(format!(
1703 "`{form}` is not a form of -fsafety-subobject. The flag takes no value, and \
1704 the strict form of section 9.4 is tamnd/rucc#967"
1705 )));
1706 }
1707 // Row Y8, from section 9.6 of document 09. A bare flag with no value, for the reason
1708 // the one above has none: there is one form of this check and a spelling that suggested
1709 // otherwise would be promising something. Before `-fno-` is looked at below, the same
1710 // way.
1711 "-fsafety-restrict" => opts.promise = rucc_session::Promise::Blocks,
1712 "-fno-safety-restrict" => opts.promise = rucc_session::Promise::Off,
1713 _ if arg.starts_with("-fsafety-restrict=") => {
1714 let form = &arg["-fsafety-restrict=".len()..];
1715 return Err(err(format!(
1716 "`{form}` is not a form of -fsafety-restrict. The flag takes no value."
1717 )));
1718 }
1719 // Section 9.5's races, which take a value because the section gives them three modes
1720 // and the difference between two of them is which classes get reported rather than how
1721 // much is recorded. `-fno-` is the same as `=off` and is spelled out here for the same
1722 // reason the two above spell theirs out.
1723 _ if arg.starts_with("-fsafety-races=") => {
1724 let mode = &arg["-fsafety-races=".len()..];
1725 opts.races = mode.parse().map_err(|()| {
1726 err(format!("`{mode}` is not a race mode, which is off, metadata or pointer"))
1727 })?;
1728 }
1729 "-fno-safety-races" => opts.races = rucc_session::Races::Off,
1730 // The sanitizers of document 12, which are checks at run time rather than a way of
1731 // generating the same program. Each name is held to gcc 16's list, and what is still
1732 // asked for by the end of the line is answered after the loop, so that a command line
1733 // which turns one on and then off again is a command line that asked for nothing.
1734 //
1735 // Before the optimizer's `-f` family below, for the reason the tier above it is.
1736 _ if arg.starts_with("-fsanitize=") => {
1737 for one in arg["-fsanitize=".len()..].split(',') {
1738 if one == "all" {
1739 // gcc takes `all` only in the negative, because turning every check on at
1740 // once includes checks that contradict each other.
1741 return Err(err(
1742 "`-fsanitize=all` is not a gcc option, only `-fno-sanitize=all` is",
1743 ));
1744 }
1745 if !SANITIZERS.contains(&one) {
1746 return Err(err(format!(
1747 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1748 )));
1749 }
1750 if !sanitizers.contains(&one) {
1751 sanitizers.push(one);
1752 }
1753 }
1754 }
1755 _ if arg.starts_with("-fno-sanitize=") => {
1756 for one in arg["-fno-sanitize=".len()..].split(',') {
1757 if one == "all" {
1758 sanitizers.clear();
1759 continue;
1760 }
1761 if !SANITIZERS.contains(&one) {
1762 return Err(err(format!(
1763 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1764 )));
1765 }
1766 sanitizers.retain(|asked| *asked != one);
1767 }
1768 }
1769 // What a check does when it fires, and where the records about the checked objects go.
1770 // Each of them is an answer about the sanitizers refused after the loop, so there is
1771 // nothing left for them to change here. The names are still held to the list, because
1772 // a misspelling in a build's flags is worth finding when the compiler reads it.
1773 _ if arg.starts_with("-fsanitize-recover=")
1774 || arg.starts_with("-fno-sanitize-recover=")
1775 || arg.starts_with("-fsanitize-trap=")
1776 || arg.starts_with("-fno-sanitize-trap=") =>
1777 {
1778 // The guard above matched on a spelling that has an `=` in it, so the tail is
1779 // whatever follows the first one.
1780 let how = arg.split_once('=').map_or("", |(_, rest)| rest);
1781 for one in how.split(',') {
1782 if one != "all" && !SANITIZERS.contains(&one) {
1783 return Err(err(format!(
1784 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1785 )));
1786 }
1787 }
1788 }
1789 "-fsanitize-undefined-trap-on-error"
1790 | "-fsanitize-address-use-after-scope"
1791 | "-fno-sanitize-address-use-after-scope" => {}
1792 _ if arg.starts_with("-fsanitize-sections=") => {}
1793 // Counting which edges a run reached, which is how a fuzzer knows an input was worth
1794 // keeping. Refused rather than dropped, because a fuzzer whose calls into
1795 // `__sanitizer_cov_*` were never generated runs blind and reports coverage of nothing,
1796 // and there is no point in the campaign where that announces itself.
1797 _ if arg.starts_with("-fsanitize-coverage=") => {
1798 let how = &arg["-fsanitize-coverage=".len()..];
1799 for one in how.split(',') {
1800 if !matches!(one, "trace-pc" | "trace-cmp") {
1801 return Err(err(format!(
1802 "`{one}` is not a coverage instrumentation, which is trace-pc or \
1803 trace-cmp"
1804 )));
1805 }
1806 }
1807 return Err(err(format!(
1808 "{arg}: this compiler generates no coverage callbacks, and a fuzzer built \
1809 with it would run without any feedback at all, see \
1810 spec/04-driver-and-cli.md section 4.7"
1811 )));
1812 }
1813 // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
1814 // after every `-f` the rest of the compiler answers to, so a pass can never take a
1815 // name that already means something else on the command line.
1816 _ if arg.starts_with("-fpass-fuel=") => {
1817 let (name, count) = arg["-fpass-fuel=".len()..]
1818 .split_once('=')
1819 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
1820 if rucc_opt::pass::find(name).is_none() {
1821 return Err(err(format!(
1822 "`{name}` is not a pass this compiler has, see --print-pipeline"
1823 )));
1824 }
1825 let count: u32 = count
1826 .parse()
1827 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1828 opts.pass_fuel.push((name.to_owned(), count));
1829 }
1830 _ if arg.starts_with("-fpass-fuel-global=") => {
1831 let count = &arg["-fpass-fuel-global=".len()..];
1832 let count: u32 = count
1833 .parse()
1834 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1835 opts.pass_fuel_global = Some(count);
1836 }
1837 _ if arg.starts_with("-frucc-trace=") => {
1838 let path = &arg["-frucc-trace=".len()..];
1839 if path.is_empty() {
1840 return Err(err("-frucc-trace= needs a file to write to"));
1841 }
1842 opts.trace = Some(path.to_owned());
1843 }
1844 // Everything from `-fopt-info` to the end of the argument, which is optional
1845 // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
1846 // where the remarks are printed, because by then the compilation somebody wanted
1847 // to hear about is over.
1848 _ if arg == "-fopt-info"
1849 || arg.starts_with("-fopt-info=")
1850 || arg.starts_with("-fopt-info-") =>
1851 {
1852 let rest = &arg["-fopt-info".len()..];
1853 let (kinds, file) = match rest.split_once('=') {
1854 Some((kinds, file)) => (kinds, Some(file)),
1855 None => (rest, None),
1856 };
1857 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
1858 rucc_opt::Wants::none().add(kinds).map_err(err)?;
1859 opts.opt_info.push(kinds.to_owned());
1860 if let Some(file) = file {
1861 if file.is_empty() {
1862 return Err(err("-fopt-info= was given no file to write to"));
1863 }
1864 opts.opt_info_file = Some(file.to_owned());
1865 }
1866 }
1867 _ if arg.starts_with("-fdump-ir=") => {
1868 // Checked here rather than where the dumps are taken, because the compilation
1869 // that would have been dumped is over by then.
1870 let spec = &arg["-fdump-ir=".len()..];
1871 rucc_opt::Dumps::default().add(spec).map_err(err)?;
1872 opts.dump_ir.push(spec.to_owned());
1873 }
1874 // Before the bare `-f<pass>` below, because a pass called `enable-something` would
1875 // otherwise take the flag away from the gate. Checked here rather than where the
1876 // pipeline reads it, for the reason that applies to all of these: a misspelled pass
1877 // name that quietly gated nothing looks exactly like a pass that is not the guilty
1878 // one, and a bisection would carry on past the thing it was looking for.
1879 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
1880 let on = arg.starts_with("-fenable-");
1881 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
1882 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
1883 opts.pass_gates.push((on, spec.to_owned()));
1884 }
1885 // gcc's spelling for a pass this compiler has under a shorter name. It goes above the
1886 // two arms below rather than into the pile of gcc pass names further down, because the
1887 // pass is here: dropping the flag would leave a build that asked for unrolling without
1888 // it, and refusing it stops the build outright, which is what libtommath's makefile
1889 // ran into. `-funroll-all-loops` is deliberately not in here: gcc's is the one that
1890 // unrolls without a trip count, which is a different and usually worse thing.
1891 "-funroll-loops" => opts.passes.push(("unroll".to_owned(), true)),
1892 "-fno-unroll-loops" => opts.passes.push(("unroll".to_owned(), false)),
1893 // Here rather than through the two arms below, because what this names is not a
1894 // `rucc_opt::Pass`. Section 34.6's propagation is a module at a time and everything in
1895 // the pass list is one function at a time. `-fipa-cp-clone` is deliberately not here:
1896 // gcc turns that one on at `-O3` and it is in the list of what M4 does not build.
1897 "-fipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), true)),
1898 "-fno-ipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), false)),
1899 // The other half of the same section, here for the same reason, and `-fipa-sra` in gcc
1900 // is the aggregate splitting as well as the parameter removal. Asking for it gets the
1901 // half that is built.
1902 "-fipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), true)),
1903 "-fno-ipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), false)),
1904 // And the printf family fold, which is a module at a time for the same reason and so is
1905 // not a `rucc_opt::Pass` either. gcc has no flag of its own for this one, since
1906 // `-fno-builtin` already turns it off along with everything else the standard names
1907 // mean. This spelling is for taking one thing away during a bisection without taking
1908 // the rest of section 20.1 away with it.
1909 "-flibcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), true)),
1910 "-fno-libcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), false)),
1911 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1912 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
1913 }
1914 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1915 opts.passes.push((arg["-f".len()..].to_owned(), true));
1916 }
1917 // The flags that name a pass of gcc's own. They arrive from the torture suite, where a
1918 // program reduced from a miscompilation usually names the pass that miscompiled it on
1919 // its `dg-options` line, and they arrive from hand written build files for the same
1920 // reason. Section 4.1 sorts a flag by what the output would be without it, and by that
1921 // rule these are one pile: a flag that turns one of gcc's passes on or off is asking
1922 // for a compiler that does not exist here, and the program it is attached to is a
1923 // correctness test that passes either way. Turning on a pass we do not have costs
1924 // speed, turning off a pass we do not have costs nothing, and neither changes what the
1925 // program computes.
1926 //
1927 // rucc's own pass names are matched above this, so `-fno-dce` turns off the dce this
1928 // compiler has rather than landing here, and the day one of these names becomes a pass
1929 // here it stops being taken and dropped without anybody editing this list.
1930 //
1931 // Two of them are prefixes rather than names, which is the one place this file takes a
1932 // family instead of a flag. gcc files its gimple passes under `-ftree-` and its
1933 // interprocedural passes under `-fipa-`, both namespaces are pass selection and
1934 // nothing else, and there is no member of either that changes the meaning of a program
1935 // that was already correct. The rest are written out one at a time, because they live
1936 // in the flat `-f` namespace where the neighbours do change meanings.
1937 _ if arg.starts_with("-ftree-") || arg.starts_with("-fno-tree-") => {}
1938 _ if arg.starts_with("-fipa-") || arg.starts_with("-fno-ipa-") => {}
1939 "-fexpensive-optimizations" | "-fno-expensive-optimizations" => {}
1940 "-fmodulo-sched" | "-fno-modulo-sched" => {}
1941 "-fvect-cost-model" | "-fno-vect-cost-model" => {}
1942 _ if arg.starts_with("-fvect-cost-model=") || arg.starts_with("-fsimd-cost-model=") => {
1943 }
1944 "-fearly-inlining" | "-fno-early-inlining" => {}
1945 // The one of the family that does reach the optimizer, since the step it names is built:
1946 // `-fno-inline` stops a function declared `inline` from being inlined and leaves
1947 // `always_inline` alone, which is what it does in gcc.
1948 "-finline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), true)),
1949 "-fno-inline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), false)),
1950 // The called once half of the same step, on its own, which leaves the `inline` hint and
1951 // `always_inline` as they are. tamnd/rucc#1966.
1952 "-finline-functions-called-once" => {
1953 opts.passes.push((rucc_opt::inline::ONCE.to_owned(), true));
1954 }
1955 "-fno-inline-functions-called-once" => {
1956 opts.passes.push((rucc_opt::inline::ONCE.to_owned(), false));
1957 }
1958 "-finline-functions"
1959 | "-fno-inline-functions"
1960 | "-finline-small-functions"
1961 | "-fno-inline-small-functions" => {}
1962 "-foptimize-strlen" | "-fno-optimize-strlen" => {}
1963 "-fira-share-spill-slots" | "-fno-ira-share-spill-slots" => {}
1964 // Where a function starts, which is a thing this compiler already decides and so is a
1965 // request it can answer rather than one it has to drop. The bare form asks for the
1966 // target's default and the default here is the sixteen bytes gcc also gives, so it
1967 // says nothing; a number is a floor under every function that did not ask for more
1968 // itself; and the negative form asks for the smallest boundary the target has. gcc 16
1969 // rounds a number that is not a power of two up rather than refusing it, which is what
1970 // `=3` giving `.p2align 2` on x86-64 means, so this rounds too.
1971 "-falign-functions" => opts.align_functions = None,
1972 "-fno-align-functions" => opts.align_functions = Some(MIN_FUNC_ALIGN),
1973 _ if arg.starts_with("-falign-functions=") => {
1974 opts.align_functions = function_alignment(&arg["-falign-functions=".len()..])
1975 .ok_or_else(|| {
1976 err(format!("{arg}: the alignment has to be a number of bytes"))
1977 })?;
1978 }
1979 // The head of every hot loop, which is padded when this is asked for so that a loop that
1980 // fits in a 64 byte line does not cross one. Both directions of the plain form are
1981 // answered. A number is taken and says nothing, because the boundary here is the
1982 // line's and a build that names another is asking for speed rather than for a
1983 // different program.
1984 "-falign-loops" => opts.align_loops = Some(true),
1985 "-fno-align-loops" => opts.align_loops = Some(false),
1986 // The other two of the family, which are about padding in front of any label and in
1987 // front of a label only a jump reaches. This compiler writes neither, and what they
1988 // ask for is speed: a label on a boundary computes what a label off one computes. So
1989 // they are taken and dropped for the reason `-march=` is, and the numbered form of
1990 // the loop flag with them.
1991 _ if arg.starts_with("-falign-labels")
1992 || arg.starts_with("-falign-loops=")
1993 || arg.starts_with("-falign-jumps")
1994 || arg.starts_with("-fno-align-labels")
1995 || arg.starts_with("-fno-align-jumps") => {}
1996 // The charset flags are not in that pile, because an encoding is a statement about
1997 // what the bytes of the source mean rather than about how fast the output is. The
1998 // preprocessor reads UTF-8 and has no converter, so the one name that describes what
1999 // already happens is taken and every other name is refused. Spelled without regard to
2000 // case and with both of the spellings iconv answers to, since a build writes whichever
2001 // one its author typed.
2002 _ if arg.starts_with("-finput-charset=") => {
2003 let name = &arg["-finput-charset=".len()..];
2004 if !name.eq_ignore_ascii_case("utf-8") && !name.eq_ignore_ascii_case("utf8") {
2005 return Err(err(format!(
2006 "-finput-charset={name}: the preprocessor reads UTF-8 and has no \
2007 converter, so a file in another encoding would be read as though it were \
2008 UTF-8 rather than converted",
2009 )));
2010 }
2011 }
2012 // What C has of exceptions, which is a `cleanup` handler an unwind has to run and the
2013 // `__EXCEPTIONS` that tells a header so. The walk is what turns down the handler it has
2014 // no landing pad for, so a unit with none of them is taken whole.
2015 "-fexceptions" => exceptions = Some(true),
2016 "-fno-exceptions" => exceptions = Some(false),
2017 "-fnon-call-exceptions" => opts.non_call_exceptions = true,
2018 "-fno-non-call-exceptions" => opts.non_call_exceptions = false,
2019 // Whether an instruction that could raise one may still be deleted when nothing uses
2020 // what it computes. Nothing here keeps a dead one, and neither does gcc in a C unit
2021 // with no handler around it, so both spellings describe the code as it is.
2022 "-fdelete-dead-exceptions" | "-fno-delete-dead-exceptions" => {}
2023 "-finstrument-functions" => opts.instrument_functions = true,
2024 "-fno-instrument-functions" => opts.instrument_functions = false,
2025 // The unstable options, spelled the way rustc spells them and carrying the same
2026 // promise, which is none: one of these may change or go away in any release. They are
2027 // measurements and debugging aids rather than things a build asks for, which is why
2028 // none of them is in the usage text and all of them are in section 4.11 of
2029 // `spec/04-driver-and-cli.md`.
2030 "-Zverify-each" => opts.verify_each = true,
2031 _ if arg.starts_with("-Zrule-coverage=") => {
2032 let file = &arg["-Zrule-coverage=".len()..];
2033 if file.is_empty() {
2034 return Err(err("-Zrule-coverage= needs a file to write to"));
2035 }
2036 opts.rule_coverage = Some(file.to_owned());
2037 }
2038 _ if arg.starts_with("-Zcycle-accurate-model=") => {
2039 let value = &arg["-Zcycle-accurate-model=".len()..];
2040 opts.cycle_accurate_model = match value {
2041 "yes" | "1" => Some(true),
2042 "no" | "0" => Some(false),
2043 _ => {
2044 return Err(err("-Zcycle-accurate-model= takes yes or no"));
2045 }
2046 };
2047 }
2048 _ if arg.starts_with("-Zregalloc=") => {
2049 opts.backtracking = match &arg["-Zregalloc=".len()..] {
2050 "backtracking" => Some(true),
2051 "single" => Some(false),
2052 _ => return Err(err("-Zregalloc= takes backtracking or single")),
2053 };
2054 }
2055 _ if arg.starts_with("-Zswitch=") => {
2056 let shape = &arg["-Zswitch=".len()..];
2057 if rucc_codegen::switch::Force::named(shape).is_none() {
2058 return Err(err("-Zswitch= takes table, tree or walk"));
2059 }
2060 opts.switch_shape = Some(shape.to_owned());
2061 }
2062 _ if arg.starts_with("-Zlowering=") => {
2063 let file = &arg["-Zlowering=".len()..];
2064 if file.is_empty() {
2065 return Err(err("-Zlowering= needs a file to write to"));
2066 }
2067 opts.lowering_dump = Some(file.to_owned());
2068 }
2069 _ if arg.starts_with("-Zregister-pressure=") => {
2070 let file = &arg["-Zregister-pressure=".len()..];
2071 if file.is_empty() {
2072 return Err(err("-Zregister-pressure= needs a file to write to"));
2073 }
2074 opts.register_pressure = Some(file.to_owned());
2075 }
2076 _ if arg.starts_with("-Z") => {
2077 return Err(err(format!(
2078 "`{arg}` is not an unstable option this compiler has, see \
2079 spec/04-driver-and-cli.md section 4.11 for the ones it does"
2080 )));
2081 }
2082 // The word size, which is a statement about the target and is taken as one. A build
2083 // that says the size the target already has is saying nothing, and one that says the
2084 // other size is asking for a target this compiler does not have, which it is told
2085 // rather than being given the wrong one.
2086 "-m64" | "-m32" | "-mx32" => {
2087 let want: u32 = match arg {
2088 "-m64" => 64,
2089 _ => 32,
2090 };
2091 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
2092 if have != want {
2093 return Err(err(format!(
2094 "{arg} asks for a {want} bit target and {} is {have} bit, use \
2095 --target= to name the one you mean",
2096 opts.target
2097 )));
2098 }
2099 }
2100 // One extension of the x86-64 instruction set, on or off, which is `-msse4.2` and its
2101 // relatives. Only the ones this compiler has the intrinsics for may be turned on for a
2102 // whole unit, because what turning one on does here is define the macro, and a macro
2103 // is a promise to a header that the names behind it exist. Turning one off is taken
2104 // for any name gcc knows, since nothing is promised by it, except for the baseline:
2105 // SSE2 is where the psABI passes a `double`, so a unit without it is a different
2106 // calling convention and not a smaller instruction set.
2107 _ if isa_name(arg).is_some() => {
2108 let Some((_, feature, on)) = isa_name(arg) else { continue };
2109 if on && !feature.honoured() {
2110 return Err(err(format!(
2111 "{arg}: this compiler has no intrinsics for {} yet, so it cannot build a \
2112 whole unit for it",
2113 feature.name()
2114 )));
2115 }
2116 if !on && rucc_target::Isa::baseline().has(feature) {
2117 return Err(err(format!(
2118 "{arg}: {} is part of the x86-64 baseline and the psABI passes values in \
2119 it, so a unit built without it would call and be called differently",
2120 feature.name()
2121 )));
2122 }
2123 isa.read(&arg["-m".len()..]).map_err(|_| err(format!("unknown option `{arg}`")))?;
2124 isa_flag.get_or_insert(arg);
2125 }
2126 // Which processor in the family to build for. What it decides is the extensions of
2127 // the instruction set the unit may assume, which is the macros, and only on x86-64;
2128 // see `rucc_target::isa`. A processor it has no list for is built for as the
2129 // baseline, which is a program that could have been faster rather than a program
2130 // that is wrong, and the same goes for every other target's processors. `-mtune=`
2131 // says what to schedule for and changes nothing a program can see.
2132 _ if arg.starts_with("-march=") => march = Some(&arg["-march=".len()..]),
2133 _ if arg.starts_with("-mtune=") || arg.starts_with("-mcpu=") => {}
2134 // The calling convention, which is not safe to ignore. Taken when it names the one
2135 // the target already uses and refused otherwise.
2136 _ if arg.starts_with("-mabi=") => {
2137 let want = &arg["-mabi=".len()..];
2138 let have = match opts.target.arch {
2139 rucc_target::Arch::X86_64 => "sysv",
2140 rucc_target::Arch::Aarch64 => "lp64",
2141 rucc_target::Arch::Riscv64 => "lp64d",
2142 };
2143 if want != have {
2144 return Err(err(format!(
2145 "{arg}: {} uses the {have} convention and this compiler has no other",
2146 opts.target
2147 )));
2148 }
2149 }
2150 // How far apart the pieces of the program may be. The small model is what we emit and
2151 // it is every hosted program's default; the kernel model is a different one and a
2152 // build that asks for it and does not get it links and then does not run.
2153 "-mcmodel=small" => {}
2154 // clang's spellings of the deployment target, which it takes over a version in the
2155 // tuple. gcc on a Mac takes the first. A target that is not Apple ignores it, as
2156 // clang does, so a makefile that always passes it still builds for Linux.
2157 _ if arg.starts_with("-mmacosx-version-min=")
2158 || arg.starts_with("-mmacos-version-min=") =>
2159 {
2160 let text = &arg[arg.find('=').map_or(arg.len(), |i| i + 1)..];
2161 let version = rucc_tuple::Version::parse(text)
2162 .ok_or_else(|| err(format!("`{text}` in `{arg}` is not a version")))?;
2163 min_version = Some(version);
2164 }
2165 _ if arg.starts_with("-mcmodel=") => {
2166 return Err(err(format!(
2167 "{arg}: this compiler emits the small code model and no other, see \
2168 spec/12-targets.md"
2169 )));
2170 }
2171 // GCC's own scripting language for how the driver builds a command line.
2172 // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
2173 // build reaching for it is told which flags do the same job.
2174 _ if arg.starts_with("-specs=") => {
2175 return Err(err(
2176 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
2177 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
2178 section 4.4",
2179 ));
2180 }
2181 // Arguments meant for a separate assembler, which this compiler does not have: it is
2182 // inside it and does not read a command line. Refused rather than dropped, because
2183 // every one of these says something about the output and a build that asked for
2184 // `-Wa,--noexecstack` and was silently given an executable stack got the opposite of
2185 // what it asked for. The `-Wp,` ones this compiler understands were turned into its
2186 // own flags before the loop, so one that reaches here is one it does not.
2187 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
2188 return Err(err(format!(
2189 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
2190 are inside this compiler rather than programs it runs"
2191 )));
2192 }
2193 "-Xassembler" | "-Xpreprocessor" => {
2194 return Err(err(format!(
2195 "{arg} hands an argument to a separate assembler or preprocessor, and both \
2196 are inside this compiler rather than programs it runs"
2197 )));
2198 }
2199 // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
2200 // this one as a rule about build systems rather than about warnings: autoconf and
2201 // meson find out whether a warning flag exists by passing it and looking at the exit
2202 // status, so the answer has to be gcc's. A name gcc knows is accepted, and one it does
2203 // not is refused, the way gcc refuses clang's names. `-Wno-` of a name nobody knows is
2204 // accepted, because gcc accepts it too, but `-Werror=` and `-Wno-error=` of one are
2205 // not. None of them turns anything on yet, which #485 is about.
2206 _ if arg.starts_with("-W") => {
2207 let name = &arg["-W".len()..];
2208 let named = name.strip_prefix("error=").or_else(|| name.strip_prefix("no-error="));
2209 if let Some(named) = named {
2210 if !warnings::known(named) {
2211 return Err(err(format!("`{arg}`: no option `-W{named}`")));
2212 }
2213 } else if !name.is_empty() && !name.starts_with("no-") && !warnings::known(name) {
2214 return Err(err(format!("unknown option `{arg}`")));
2215 }
2216 }
2217 // Flags that name something this compiler does not do and would not do differently
2218 // if it did. `-fno-ident` is about a comment in the output that we do not write
2219 // either way, and the others are about a way of ordering the compilation that has
2220 // been GCC's only way for twenty years. `-mthreads` is mingw's, and what it links is
2221 // `libmingwthrd.a`, which mingw-w64 keeps as an empty archive because its CRT does the
2222 // thread cleanup for every program. Section 4.1 asks for the list to be short and for
2223 // adding to it to be deliberate, which is why it is written out here.
2224 "-fno-ident"
2225 | "-fident"
2226 | "-funit-at-a-time"
2227 | "-fno-unit-at-a-time"
2228 | "-shared-libgcc"
2229 | "-static-libgcc"
2230 | "-mthreads"
2231 | "-fpch-deps"
2232 | "-fno-pch-deps" => {}
2233 _ if arg.starts_with('-') && arg.len() > 1 => {
2234 // Silently ignoring an unknown flag is how a build ends up not doing what
2235 // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
2236 // for the flags that change code generation, and the safe default until the
2237 // flag table is populated is to reject everything we do not know.
2238 return Err(err(format!("unknown option `{arg}`")));
2239 }
2240 _ => inputs.push(Input { path: arg.to_owned(), forced, role: Role::File }),
2241 }
2242 }
2243
2244 // The fetch, before anything that resolves a compilation, because `--fetch` does not describe
2245 // one. It is here rather than in the loop so that `--offline` can forbid it whichever order the
2246 // two were written in, and it is before the refusals below so that a command line asking for a
2247 // sysroot is not told about a sanitizer.
2248 if let Some(named) = fetch {
2249 if fetch_msvc.is_some() {
2250 return Err(err(
2251 "--fetch and --fetch-msvc-sdk are two different commands and this command line \
2252 asked for both. --fetch gets a sysroot this release pins by URL and by hash, and \
2253 --fetch-msvc-sdk gets what is behind Microsoft's licence wall, which no release \
2254 pins and which nobody may republish. Run whichever one you meant",
2255 ));
2256 }
2257 return fetch_action(&named, offline, &inputs);
2258 }
2259 if let Some(named) = fetch_msvc {
2260 return fetch_msvc_action(&named, offline, accepted, &inputs);
2261 }
2262 if accepted {
2263 return Err(err(
2264 "--accept-licence says that Microsoft's Visual Studio Build Tools licence is accepted, \
2265 and nothing on this command line asked for anything that licence covers. \
2266 --fetch-msvc-sdk <tuple> is the command it belongs to, and an ordinary compile \
2267 downloads nothing with it or without it",
2268 ));
2269 }
2270
2271 // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
2272 // order: a directory the user names outranks the compiler's own, and the compiler's own
2273 // outranks the library's. It is pushed after the loop rather than before it because
2274 // `SearchPath` appends within a group and the position is what the order is.
2275 // The same directory the headers were looked for under, because a sysroot is a statement
2276 // about a whole installation and not about half of one.
2277 // After the loop, because `-fno-sanitize=` can take back what an earlier flag asked for and a
2278 // command line that turns a check on and off again has asked for nothing. What is left is
2279 // refused rather than dropped, and it is the one place in this parser where the reason is not
2280 // that the output would differ. A sanitizer is a promise that the program is watched while it
2281 // runs, so a build that asks for one and is quietly given a program with no checks in it does
2282 // not get a slower program or a bigger file, it gets a test suite that passes for the wrong
2283 // reason. `-fsafety=` is the checking this compiler does have, and the message says so, because
2284 // somebody reaching for `-fsanitize=address` wants the nearest thing rather than a list of
2285 // options.
2286 if let Some(first) = sanitizers.first() {
2287 return Err(err(format!(
2288 "-fsanitize={first}: this compiler has no sanitizer instrumentation, and a build that \
2289 asked for one and got none would run its tests unchecked, see \
2290 spec/04-driver-and-cli.md section 4.7. `-fsafety=detect` is the memory checking this \
2291 compiler does have"
2292 )));
2293 }
2294 // The fast math family, replayed in order on top of what `-Ofast` implies. The startup file is
2295 // gcc's spec rather than the fields: it is linked when `-Ofast`, `-ffast-math` or
2296 // `-funsafe-math-optimizations` is still in force at the end of the line, whatever a later
2297 // member took back, and `-mdaz-ftz` decides it outright.
2298 let mut math = Math::default();
2299 let mut trapping = if ofast { math.set_fast(true) } else { true };
2300 for flag in &math_flags {
2301 match *flag {
2302 "-ftrapping-math" => trapping = true,
2303 "-fno-trapping-math" => trapping = false,
2304 "-ffast-math" => trapping = math.set_fast(true),
2305 "-fno-fast-math" => trapping = math.set_fast(false),
2306 "-funsafe-math-optimizations" => trapping = math.set_unsafe(true),
2307 "-fno-unsafe-math-optimizations" => trapping = math.set_unsafe(false),
2308 "-fmath-errno" => math.errno = true,
2309 "-fno-math-errno" => math.errno = false,
2310 "-ffinite-math-only" => math.finite_only = true,
2311 "-fno-finite-math-only" => math.finite_only = false,
2312 "-fsigned-zeros" => math.signed_zeros = true,
2313 "-fno-signed-zeros" => math.signed_zeros = false,
2314 "-freciprocal-math" => math.reciprocal = true,
2315 "-fno-reciprocal-math" => math.reciprocal = false,
2316 "-fassociative-math" => math.associative = true,
2317 "-fno-associative-math" => math.associative = false,
2318 _ => unreachable!("{flag} is not in the family"),
2319 }
2320 }
2321 opts.trapping_math = trapping;
2322 opts.math = math;
2323 let last = |on: &str, off: &str| {
2324 math_flags.iter().rev().find(|f| **f == on || **f == off).is_some_and(|f| *f == on)
2325 };
2326 link.fast_math = ofast
2327 || last("-ffast-math", "-fno-fast-math")
2328 || last("-funsafe-math-optimizations", "-fno-unsafe-math-optimizations");
2329 link.daz_ftz = daz_ftz;
2330 // The extensions, now that the target is known. On x86-64 the processor supplies whatever no
2331 // flag said. Anywhere else there are none to have, and a flag naming one is gcc's unknown
2332 // option there too, so it is refused the same way it would have been had it not looked like
2333 // an x86 flag.
2334 match opts.target.arch {
2335 rucc_target::Arch::X86_64 => {
2336 let base = match march {
2337 Some("native") => native_isa(),
2338 Some(name) => {
2339 rucc_target::Isa::level(name).unwrap_or_else(rucc_target::Isa::baseline)
2340 }
2341 None => rucc_target::Isa::baseline(),
2342 };
2343 opts.isa = isa.over(base);
2344 }
2345 rucc_target::Arch::Aarch64 | rucc_target::Arch::Riscv64 => {
2346 if let Some(flag) = isa_flag {
2347 return Err(err(format!("unknown option `{flag}`")));
2348 }
2349 opts.isa = rucc_target::Isa::NONE;
2350 }
2351 }
2352 opts.exceptions = exceptions.unwrap_or(opts.non_call_exceptions);
2353 link.sysroot = sysroot.clone();
2354 // Where a sysroot for a target that is not this machine would be. Read once, here, rather than
2355 // inside the link line, because a link line that read the environment could only be tested on a
2356 // machine whose environment said the right thing, and the link line is the last thing that
2357 // touches a binary. `spec/cross-compile/13-distribution.md` section 13.2 owns the answer.
2358 link.cache = Some(cache::dir());
2359 // And where a distribution's cross packages would have put a tree for the target, which is only
2360 // read when the target is not this machine and there is no sysroot of ours for it.
2361 link.usr = Some(PathBuf::from("/usr"));
2362 // And the ten field spelling of the target, because the release on it decides two things the
2363 // three field one cannot say: whether a target that is this architecture is still a cross
2364 // compile, and which directory under the cache it is against. After the loop because the last
2365 // `--target=` on the command line is the one that counts.
2366 link.pinned = pinned;
2367 // The deployment target, from the flag if there was one and from the tuple otherwise. Only an
2368 // Apple platform has one: anywhere else a version on the tuple is a libc or a preview number.
2369 if opts.target.os == rucc_target::Os::Darwin {
2370 opts.os_version = min_version.or_else(|| pinned.and_then(TargetTuple::os_version));
2371 link.os_version = opts.os_version;
2372 }
2373 // After the loop rather than where `-pthread` was read, so that it lands after the objects
2374 // that refer to it. A static link takes the definitions it needs from a library when it
2375 // reaches it and not afterwards, so a library before the objects is a library that answers
2376 // nothing.
2377 if threads {
2378 inputs.push(Input::library("pthread"));
2379 }
2380 if let Some(query) = query {
2381 return Ok(Action::Print(answer(&query, &opts, &link)?));
2382 }
2383 // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
2384 // else the command line asked for. Read here rather than where the flag was, because a `-c`
2385 // written after it has to lose and the loop cannot know that until it has ended. The output
2386 // file is where the rule goes rather than where an object would have gone, and the last
2387 // phase being the preprocessor is what makes that true without a second rule for it.
2388 if opts.deps.instead_of_compiling {
2389 opts.emit = EmitKind::Preprocessed;
2390 }
2391 if !nostdinc {
2392 opts.search.push_system(runtime::DIR);
2393 // And the library's after ours, which is the other half of the same order. They go on
2394 // here rather than at the point `--target=` or `--sysroot=` was read because either
2395 // one changes the answer and the last word on both is the end of the loop.
2396 //
2397 // Which library's is the question `link::cross_sysroot` answers, and it is asked here so
2398 // that the headers and the libraries come from the same place. A target that is this
2399 // machine reads this machine's headers, and a target that is not reads the ones in the
2400 // sysroot for it rather than the ones next door.
2401 let cross = link::cross_sysroot(opts.target, &link);
2402 let kernel = link::cross_kernel(opts.target, &link);
2403 let distro = link::distro_cross(opts.target, &link);
2404 // And the version of those headers, which only the bundled tree has an answer for. A host
2405 // glibc and a tree the user named both define `__GLIBC_MINOR__` in their own `features.h`,
2406 // and a second definition with a different value is a warning on every file, so the
2407 // condition is the same one that chose the directories.
2408 if cross.is_some() {
2409 let target = pinned.unwrap_or_else(|| opts.target.tuple());
2410 opts.glibc_minor = rucc_sysroot::bundled_glibc_minor(target).map_err(|skew| {
2411 err(format!(
2412 "{skew}; pin a release the tree has, or name a tree that has that one \
2413 with --sysroot"
2414 ))
2415 })?;
2416 }
2417 let system = library::header_dirs(
2418 opts.target,
2419 sysroot.as_deref(),
2420 cross.as_ref(),
2421 kernel.as_ref(),
2422 distro.as_ref(),
2423 );
2424 // The two licence walls of `spec/cross-compile/13-distribution.md` section 13.4, which are
2425 // the only way step 3 comes back with nothing on a hosted target. Section 8.6 asks for the
2426 // answer to name the licence and the lawful ways to get what is behind it, rather than
2427 // leaving a person with an `#include` that failed as though a directory had gone missing.
2428 //
2429 // It is left on the search path instead of refused here, because a program that includes
2430 // none of the library needs none of the SDK and section 8.6 is explicit that targeting the
2431 // platform has to keep working. So the reason waits until an include has actually failed,
2432 // which is the only moment it helps and the only moment it is true.
2433 //
2434 // The condition is that step 3 found nothing at all, so an `SDKROOT`, an `INCLUDE` or a mac
2435 // with Xcode on it all pass through untouched, and `-nostdinc` never reaches this block. A
2436 // `--sysroot` or `-isysroot` passes through as well, even when the tree it names turns out to
2437 // be empty or absent: somebody who wrote a path has already answered the question this
2438 // message asks, and answering it again over the top of a mistyped directory would hide the
2439 // mistake behind a licence notice.
2440 if system.is_empty() && sysroot.is_none() {
2441 let tuple = pinned.unwrap_or_else(|| opts.target.tuple());
2442 if let Some(wall) = rucc_sysroot::Wall::of(tuple) {
2443 opts.search.explain_missing_system(wall.no_headers(&tuple.to_canonical_string()));
2444 }
2445 }
2446 // And whether the tree somebody named is the release they asked for, which is the one
2447 // question left once the directories are settled and the only place both halves of it are
2448 // known. Only for a named tree, because that is the case where the release in the target
2449 // stops deciding anything, and `crate::glibc` is where the rest of the reasoning is.
2450 if sysroot.is_some() {
2451 notes.extend(glibc::skew(opts.target, pinned, &system));
2452 }
2453 for dir in system {
2454 opts.search.push_system(dir);
2455 }
2456 }
2457 // Once, here, rather than as each directory is pushed. A `-I` that names a system
2458 // directory has to lose to the system entry and the system entry is added last, so the
2459 // question cannot be answered until the whole path is known.
2460 opts.search.remove_duplicates();
2461
2462 // The COFF writer has no DWARF sections yet, and refusing `-g` stops every build system at its
2463 // first compile, since they all pass it by default. So it is dropped with one warning and the
2464 // object is written without debug information, which is what the program would have run as
2465 // anyway. This goes when DWARF in COFF lands.
2466 if opts.debug_info && opts.target.os.object_format() == ObjectFormat::Coff {
2467 opts.debug_info = false;
2468 notes.push(format!(
2469 "-g is ignored for {}, because this compiler does not write debug information into \
2470 COFF objects yet",
2471 opts.target.tuple().to_canonical_string()
2472 ));
2473 }
2474
2475 // The target has to be resolved before the configuration is printed, so this check comes
2476 // after the loop rather than at the point `--print-config` was seen.
2477 if print_config {
2478 return Ok(Action::PrintConfig(Box::new(opts)));
2479 }
2480 if print_pipeline {
2481 return Ok(Action::PrintPipeline(Box::new(opts)));
2482 }
2483 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
2484 if print_plan {
2485 return Ok(Action::PrintPlan {
2486 opts: Box::new(opts),
2487 plan: Box::new(plan),
2488 link: Box::new(link),
2489 });
2490 }
2491 Ok(Action::Compile {
2492 opts: Box::new(opts),
2493 plan: Box::new(plan),
2494 link: Box::new(link),
2495 jobs,
2496 verbose,
2497 notes,
2498 })
2499}
2500
2501/// What `--fetch <tuple>` asked for, or why it is not a thing that can be done.
2502///
2503/// The lookup happens here rather than at the point the bytes would move, so that a target this
2504/// release pins nothing for is a refusal from the parser and the only code that runs a downloader is
2505/// code that already knows what it is getting.
2506///
2507/// # Errors
2508///
2509/// [`CliError`] when `--offline` forbade it, when there are input files as well, when the tuple is
2510/// not a target this compiler knows, when its sysroot is behind one of section 13.4's licence walls,
2511/// and when this release pins no artifact for it.
2512fn fetch_action(named: &str, offline: bool, inputs: &[Input]) -> Result<Action, CliError> {
2513 // Not a precedence question. Section 13.2 says `--offline` forbids a fetch entirely, so a
2514 // command line that writes both has asked for two opposite things and the answer is to say so
2515 // rather than to pick one of them.
2516 if offline {
2517 return Err(err(
2518 "--fetch asks for a download and --offline forbids every download, so this command \
2519 line asks for two opposite things. Drop one of them: --offline is how a build says it \
2520 will not reach the network, and --fetch is one of the two things in this compiler \
2521 that reaches it",
2522 ));
2523 }
2524 if let Some(first) = inputs.first() {
2525 return Err(err(format!(
2526 "--fetch gets a sysroot and compiles nothing, so `{}` on the same command line is an \
2527 input that nothing would read",
2528 first.path
2529 )));
2530 }
2531 let target: TargetTuple = named
2532 .parse()
2533 .map_err(|why| err(format!("--fetch {named}: {why}, so there is no sysroot to get")))?;
2534 // The canonical spelling, because that is what a row is named by and what the directory under
2535 // the cache is called, and a person is free to write a tuple the long way round.
2536 let tuple = target.to_canonical_string();
2537 // Before the table is consulted, because a target behind a licence wall is not a row that has not
2538 // been written yet. Section 13.4 is that no release pins one of these ever, so the message says
2539 // the licence and the two lawful ways rather than naming the producer that will publish the rest.
2540 if let Some(wall) = rucc_sysroot::Wall::of(target) {
2541 return Err(err(format!("--fetch {tuple}: {}", wall.no_fetch(&tuple))));
2542 }
2543 let Some(what) = rucc_sysroot::pinned_for_target(target) else {
2544 return Err(err(unpinned(&tuple)));
2545 };
2546 Ok(Action::Fetch { what, target, cache: cache::dir() })
2547}
2548
2549/// What `--fetch-msvc-sdk <tuple>` asks for, weighed the same way the fetch above is.
2550///
2551/// The target is resolved here rather than where the work happens, so that a tuple this compiler
2552/// does not know and a target that is not behind Microsoft's wall are refusals from the parser like
2553/// every other thing a command line can ask for and not have. Whether the licence was accepted is
2554/// carried rather than acted on, because what it changes is what the command does and not whether
2555/// the command line made sense.
2556///
2557/// # Errors
2558///
2559/// [`CliError`] when `--offline` forbade it, when there are input files as well, and when the tuple
2560/// is not a target this compiler knows.
2561fn fetch_msvc_action(
2562 named: &str,
2563 offline: bool,
2564 accepted: bool,
2565 inputs: &[Input],
2566) -> Result<Action, CliError> {
2567 if offline {
2568 return Err(err(
2569 "--fetch-msvc-sdk asks for a download and --offline forbids every download, so this \
2570 command line asks for two opposite things. Drop one of them: --offline is how a build \
2571 says it will not reach the network",
2572 ));
2573 }
2574 if let Some(first) = inputs.first() {
2575 return Err(err(format!(
2576 "--fetch-msvc-sdk gets an SDK and compiles nothing, so `{}` on the same command line \
2577 is an input that nothing would read",
2578 first.path
2579 )));
2580 }
2581 let target: TargetTuple = named.parse().map_err(|why| {
2582 err(format!("--fetch-msvc-sdk {named}: {why}, so there is no SDK to get"))
2583 })?;
2584 Ok(Action::FetchMsvcSdk { target, accepted, cache: cache::dir() })
2585}
2586
2587/// Why there is nothing to fetch for a target, which is a different sentence when the table is
2588/// empty.
2589///
2590/// A release that pins nothing and a release that pins eleven targets and not this one are two
2591/// situations, and a message that did not tell them apart would send somebody looking for a typo in
2592/// their tuple when the answer is that this work is not finished.
2593fn unpinned(tuple: &str) -> String {
2594 let pinned = rucc_sysroot::pinned_targets();
2595 if pinned.is_empty() {
2596 return format!(
2597 "this release pins no sysroot for {tuple}, and it pins none for any target yet. A \
2598 sysroot is built and published by the producer in tamnd/rucc-cross, per \
2599 spec/cross-compile/13-distribution.md section 13.8, and a release of this compiler \
2600 names one by URL and by hash afterwards. Until then, pass --sysroot=<dir> to compile \
2601 against a tree you have already"
2602 );
2603 }
2604 format!(
2605 "this release pins no sysroot for {tuple}. What it pins is {}. Pass --sysroot=<dir> to \
2606 compile against a tree you have already",
2607 pinned.join(", ")
2608 )
2609}
2610
2611/// Gets the artifact and installs it, saying what each step did.
2612///
2613/// The steps are section 13.8's and so are the messages: the transport is somebody else's program
2614/// and the check is ours, so a person reading this wants to know which downloader ran, that the
2615/// bytes matched, how many files the record named and where the tree ended up. A fetch of something
2616/// that is already there says that instead and moves nothing.
2617///
2618/// A Linux target is two artifacts, its own sysroot and the kernel header tree every Linux target
2619/// shares, and `kernel` is the second one when the target reads it. It is fetched after the sysroot
2620/// and by the same two steps, so a machine that has fetched one Linux target already has it and a
2621/// second target's fetch says so and moves nothing.
2622fn fetch_sysroot(
2623 what: &rucc_sysroot::Pinned,
2624 kernel: Option<&rucc_sysroot::Pinned>,
2625 target: TargetTuple,
2626 cache: &std::path::Path,
2627) -> i32 {
2628 let tuple = target.to_canonical_string();
2629 let say = |line: &str| println!("rucc: {tuple}: {line}");
2630 if let Err(why) = bring(what, cache, &say) {
2631 return complain(why);
2632 }
2633 let archive = what.archive_in(cache);
2634 match install::install(&archive, what.sha256, target, cache) {
2635 Ok(done) => report(&done, "sysroot", &say),
2636 Err(why) => return complain(why),
2637 }
2638 let Some(kernel) = kernel else { return 0 };
2639 if let Err(why) = bring(kernel, cache, &say) {
2640 return complain(why);
2641 }
2642 match install::install_kernel(&kernel.archive_in(cache), kernel.sha256, cache) {
2643 Ok(done) => {
2644 report(&done, "kernel header tree", &say);
2645 0
2646 }
2647 Err(why) => complain(why),
2648 }
2649}
2650
2651/// The download half of a fetch, for one artifact.
2652fn bring(
2653 what: &rucc_sysroot::Pinned,
2654 cache: &std::path::Path,
2655 say: &impl Fn(&str),
2656) -> Result<(), CliError> {
2657 let archive = what.archive_in(cache);
2658 match fetch::fetch(what.url, what.sha256, &archive)? {
2659 fetch::Fetched::AlreadyThere => {
2660 say(&format!("{} is already here and matches the hash", archive.display()));
2661 }
2662 fetch::Fetched::Downloaded(by) => {
2663 say(&format!("downloaded {} with {}", what.url, by.program()));
2664 }
2665 }
2666 Ok(())
2667}
2668
2669/// What an install did, in the words a person reading a fetch wants.
2670fn report(done: &install::Installed, what: &str, say: &impl Fn(&str)) {
2671 match &done.before {
2672 install::Before::Nothing => {
2673 say(&format!("{} files installed at {}", done.files, done.root.display()));
2674 }
2675 install::Before::TheSame => {
2676 say(&format!(
2677 "the same {what} is already at {}, so nothing moved",
2678 done.root.display()
2679 ));
2680 }
2681 install::Before::Different(was) => {
2682 say(&format!(
2683 "{} files installed at {}, over a tree whose record digested to {was}",
2684 done.files,
2685 done.root.display()
2686 ));
2687 }
2688 }
2689 say(&format!("the {what}'s record digests to {}", done.digest));
2690}
2691
2692/// What one of the `-dump` and `-print` flags prints.
2693///
2694/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
2695/// which is what makes the answer safe to paste into a link line whether or not the file is
2696/// there, and this does the same.
2697fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> Result<String, CliError> {
2698 let found = |name: &str| {
2699 link::find_in_search(link, opts.target, name)
2700 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
2701 };
2702 Ok(match query {
2703 Query::Machine => opts.target.to_string(),
2704 Query::Version => opts.gnuc.major.to_string(),
2705 Query::FullVersion => {
2706 format!("{}.{}.{}", opts.gnuc.major, opts.gnuc.minor, opts.gnuc.patch)
2707 }
2708 Query::Multiarch => link::multiarch(opts.target),
2709 // The three lines GCC prints, in its order and with its punctuation, because what reads
2710 // them is a script written against that shape. There is no installation directory to
2711 // report: this compiler is one binary that works wherever it is copied, and the headers
2712 // it ships are inside it, so `install` is where the binary is and nothing is under it.
2713 Query::SearchDirs => {
2714 let here = std::env::current_exe()
2715 .ok()
2716 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
2717 .unwrap_or_default();
2718 let list = |dirs: &[PathBuf]| {
2719 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
2720 };
2721 let libraries = link::search_dirs(link, opts.target);
2722 format!(
2723 "install: {}\nprograms: ={}\nlibraries: ={}",
2724 here.display(),
2725 list(&link.prefixes),
2726 list(&libraries)
2727 )
2728 }
2729 // The root the rest of the answers are under, which a build system asks for when it wants
2730 // to find a file itself rather than ask for one by name, and which is the first thing to
2731 // look at when a cross build read a header nobody expected. A native compile has no
2732 // sysroot and the answer is the empty line, which is what GCC prints when it was
2733 // configured without one. `--sysroot` wins over ours because it wins everywhere else.
2734 Query::Sysroot => {
2735 sysroot_root(opts, link).map(|root| root.display().to_string()).unwrap_or_default()
2736 }
2737 // Section 13.5 of `spec/cross-compile/13-distribution.md`: for every input that is not this
2738 // compiler's own code, what it is, where it was got, its hash, its licence and whether it
2739 // was bundled, generated or fetched. What is printed is the manifest the sysroot already
2740 // carries rather than a second format saying the same things, because the three uses 13.5
2741 // gives for this are a licence notice, a reproducibility check and a security audit, and all
2742 // three are somebody else parsing it. One format is one parser to write.
2743 // Read and rendered rather than copied out, so that what comes back is the format this
2744 // build understands. The last newline comes off because whatever prints an answer adds
2745 // one, the way it does for every other query here. Keeping it would put a blank line at
2746 // the end of the one answer that is a file somebody diffs against the file it came from.
2747 Query::SysrootProvenance => match sysroot_manifest(opts, link)? {
2748 Some(manifest) => manifest.render().trim_end_matches('\n').to_string(),
2749 None => String::new(),
2750 },
2751 // Section 13.2 of the same document, which asks for the hash of a cache directory's
2752 // contents in the directory's name. A name cannot carry one, because the path has to be
2753 // computable before anything has been read, by the producer about to write the files and by
2754 // the compiler about to read them, and neither has the contents when it asks. So the number
2755 // is here instead, and it is the sha256 of the record rather than of a walk of the tree,
2756 // which means `sha256sum` over the manifest answers the same thing.
2757 Query::SysrootDigest => match sysroot_manifest(opts, link)? {
2758 Some(manifest) => manifest.digest(),
2759 None => String::new(),
2760 },
2761 Query::FileName(name) => found(name),
2762 // The name GCC gives the library of routines a compiler's output calls that the C
2763 // library does not have. Ours is built in and there is no file, so the answer is the
2764 // name itself, which is what GCC prints when it cannot find one either.
2765 Query::Libgcc => found("libgcc.a"),
2766 // A program rather than a library: the linker and the archiver are the ones a build asks
2767 // about, and this compiler finds them on the path or under `-B` rather than shipping
2768 // them, so the name back is the honest answer unless a `-B` prefix holds one.
2769 Query::ProgName(name) => link
2770 .prefixes
2771 .iter()
2772 .map(|dir| dir.join(name))
2773 .find(|path| path.is_file())
2774 .map_or_else(|| name.clone(), |path| path.display().to_string()),
2775 })
2776}
2777
2778/// The root every sysroot answer is about.
2779///
2780/// One function rather than a copy in each, because the other flags exist to say what is inside the
2781/// tree this one names, and two answers that disagreed about which tree that is would be a
2782/// difference nobody would think to look for. `--sysroot` wins over ours because it wins everywhere
2783/// else.
2784fn sysroot_root(opts: &Options, link: &LinkOptions) -> Option<PathBuf> {
2785 link.sysroot
2786 .clone()
2787 .or_else(|| link::cross_sysroot(opts.target, link).map(|at| at.root().to_path_buf()))
2788}
2789
2790/// The record of the sysroot this command line reads, when there is one to read.
2791///
2792/// [`None`] covers two cases that both print nothing, and they are different things. A compile for
2793/// this machine has no sysroot at all, and a tree somebody laid out themselves and pointed
2794/// `--sysroot` at carries no manifest, so nothing here knows where any of it came from. Saying
2795/// nothing is the only honest answer to either, and a reader can tell it from a manifest with no
2796/// inputs in it because that one still has its header lines.
2797///
2798/// # Errors
2799///
2800/// A manifest this build cannot parse, and anything else that went wrong reading the file. Passing a
2801/// record we could not read on to whoever asked would make their parser the one that finds the
2802/// problem, and every use section 13.5 gives for these two flags is somebody else reading the
2803/// output.
2804fn sysroot_manifest(opts: &Options, link: &LinkOptions) -> Result<Option<Manifest>, CliError> {
2805 let Some(root) = sysroot_root(opts, link) else {
2806 return Ok(None);
2807 };
2808 let path = Sysroot::at(root, opts.target.tuple()).manifest_path();
2809 match std::fs::read_to_string(&path) {
2810 Ok(text) => Manifest::parse(&text)
2811 .map(Some)
2812 .map_err(|why| err(format!("{}: {why}", path.display()))),
2813 Err(why) if why.kind() == std::io::ErrorKind::NotFound => Ok(None),
2814 Err(why) => Err(err(format!("{}: {why}", path.display()))),
2815 }
2816}
2817
2818/// Renders the passes this level will run, in order, with what each one does.
2819///
2820/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
2821/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
2822/// emerges from which flags happen to be set, and this is how that list is read.
2823#[must_use]
2824pub fn print_pipeline(opts: &Options) -> String {
2825 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
2826 settings.toggles.clone_from(&opts.passes);
2827 settings.global_fuel = opts.pass_fuel_global;
2828 for (on, spec) in &opts.pass_gates {
2829 // Every spelling was checked while the arguments were parsed, so there is nothing here
2830 // this can refuse, and a listing is not the place to report it if there were.
2831 let _ = settings.gates.add(*on, spec);
2832 }
2833 rucc_opt::pipeline::print(&settings)
2834}
2835
2836/// Renders the resolved configuration.
2837///
2838/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
2839/// this output is diffed across hosts in CI and a reordering would read as a change.
2840#[must_use]
2841pub fn print_config(opts: &Options) -> String {
2842 let sess = Session::new(opts.clone());
2843 let t = &sess.target;
2844 let mut out = String::new();
2845 let _ = writeln!(out, "version: {VERSION}");
2846 // The three field triple the driver was given rather than the ten field tuple it widens to,
2847 // because this output is what a build system reads to find out what it asked for. The tuple is
2848 // the compiler's model of the machine and this line is a receipt for a command line.
2849 let _ = writeln!(out, "target: {}", opts.target);
2850 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
2851 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
2852 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
2853 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
2854 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
2855 let _ = writeln!(out, "long-width: {}", t.long_width);
2856 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
2857 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
2858 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
2859 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
2860 // The register file as a count per class, which is enough to tell a target whose registers
2861 // are described from one whose are not without printing sixteen names nobody asked for.
2862 let regs: Vec<String> = t
2863 .regs
2864 .classes()
2865 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
2866 .collect();
2867 let _ = writeln!(
2868 out,
2869 "registers: {}",
2870 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
2871 );
2872 // What the schedule was chosen with, which is a sentence rather than a name on purpose: two
2873 // runs of a benchmark that disagree are usually two models and not two compilers.
2874 let _ = writeln!(out, "timing-model: {}", t.timing.map_or("none", |timing| timing.model));
2875 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
2876 let _ = writeln!(out, "safety: {}", sess.opts.safety);
2877 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
2878 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
2879 let _ = writeln!(out, "frame-pointer: {}", sess.opts.keeps_frame_pointer());
2880 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
2881 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
2882 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
2883 let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
2884 let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
2885 let _ = writeln!(out, "profile: {}", sess.opts.profile);
2886 let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
2887 // Last because it is the one key with more than one line under it, and the only one
2888 // whose value is a property of the machine rather than of the command line.
2889 for dir in sess.opts.search.dirs() {
2890 let system = if dir.is_system { " (system)" } else { "" };
2891 let _ = writeln!(out, "include: {}{system}", dir.path.display());
2892 }
2893 out
2894}
2895
2896/// The output name the make target is taken from, which is the `-o` argument or nothing.
2897///
2898/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
2899/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
2900/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
2901/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
2902/// `-S` on the argument does name what the rule builds, and it is used as written.
2903fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
2904 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
2905}
2906
2907/// Writes to a path the command line named rather than one the plan derived, where `-` is
2908/// standard output.
2909fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
2910 if path == "-" {
2911 return write_out(&Output::Stdout, bytes);
2912 }
2913 write_out(&Output::File(path.to_owned()), bytes)
2914}
2915
2916/// Writes the make rule for one input, and reports whether it got there.
2917///
2918/// A rule with no file of its own goes where the compilation it replaced would have written,
2919/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
2920/// `$@`, and the same line with the `-o` left off puts it on standard output.
2921fn write_deps(
2922 opts: &Options,
2923 plan: &Plan,
2924 job: &Job,
2925 found: &[Dependency],
2926 stderr: &mut impl std::io::Write,
2927) -> bool {
2928 let targets = if opts.deps.targets.is_empty() {
2929 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
2930 } else {
2931 opts.deps.targets.clone()
2932 };
2933 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
2934 // The file, on the other hand, is named after the `-o` in every mode that still has one to
2935 // spend, which is every mode except the two that spend it on the rule.
2936 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
2937 // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
2938 // named empty rather than absent, because a makefile that named it as a target of its
2939 // own is a makefile that will look for it.
2940 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
2941 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
2942 }),
2943 None => write_out(&job.output, rule.as_bytes()),
2944 };
2945 if let Err(e) = wrote {
2946 let _ = writeln!(stderr, "rucc: error: {e}");
2947 return false;
2948 }
2949 true
2950}
2951
2952/// Runs phase 4 over every input that has one, and writes what came out.
2953///
2954/// One input that fails does not stop the others. A build that reports every file it could
2955/// not preprocess in one run is worth more than one that stops at the first, and the exit
2956/// status is still a failure either way.
2957fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
2958 let fs = OsFileSystem::new();
2959 let mut stderr = std::io::stderr().lock();
2960 let mut failed = false;
2961 for job in &plan.jobs {
2962 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
2963 // An input that is already preprocessed, or an object file. GCC passes these
2964 // through untouched, and the plan has already said so in its notes.
2965 continue;
2966 }
2967 let started = std::time::Instant::now();
2968 let result = preprocess(opts, &job.input, &fs);
2969 if opts.time {
2970 say_time(&job.input, started.elapsed(), &mut stderr);
2971 }
2972 for message in &result.messages {
2973 let _ = writeln!(stderr, "{message}");
2974 }
2975 if result.failed() {
2976 failed = true;
2977 continue;
2978 }
2979 if opts.deps.emit {
2980 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2981 // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
2982 // to write. The other two asked for both and fall through to the text below.
2983 if opts.deps.instead_of_compiling {
2984 continue;
2985 }
2986 }
2987 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
2988 let _ = writeln!(stderr, "rucc: error: {e}");
2989 failed = true;
2990 }
2991 }
2992 i32::from(failed)
2993}
2994
2995/// Whether this job is a file of assembly that has to be assembled and that nothing here assembles.
2996///
2997/// The phases rather than the kind, because there are two kinds of assembly input and one of them
2998/// is preprocessed first, and because an object file also has no compile phase and is not this: it
2999/// has no phases at all and goes to the linker as it is. A `.s` on a `-c` line has exactly
3000/// [`Phase::Assemble`] left, and a `.S` has the preprocessor in front of it, and neither has
3001/// anything the front end can do.
3002fn needs_an_assembler(job: &Job) -> bool {
3003 job.phases.contains(&Phase::Assemble) && !job.phases.contains(&Phase::Compile)
3004}
3005
3006/// Whether the preprocessor runs over it on the way in, which is the whole difference between the
3007/// two kinds of assembly input.
3008fn assembly_wants_cpp(job: &Job) -> bool {
3009 job.phases.contains(&Phase::Preprocess)
3010}
3011
3012/// Runs the front end over every input that has a compile phase, and writes what came out.
3013///
3014/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
3015/// exit status is a failure either way. An input that is already assembly or an object has no
3016/// compile phase and is passed over here, which the plan has already said in its notes.
3017fn compile_all(opts: &Options, plan: &Plan) -> i32 {
3018 let fs = OsFileSystem::new();
3019 let mut stderr = std::io::stderr().lock();
3020 let mut failed = false;
3021 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3022 failed |= !ok;
3023 let mut fired = Fired::new();
3024 let mut pressure = Pressure::new();
3025 let mut lowerings = Lowerings::new();
3026 for job in &plan.jobs {
3027 if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
3028 continue;
3029 }
3030 // An input of IR is read back rather than compiled, since the C it came from is not
3031 // here any more. A file of assembly does not go through the front end at all and is
3032 // read by the assembler instead. Everything after this is the same for all three, so
3033 // the paths meet again at the messages and the file the result is written to.
3034 let started = std::time::Instant::now();
3035 let result = if needs_an_assembler(job) {
3036 assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3037 } else if job.kind == InputKind::Ir {
3038 compile_ir(opts, &job.input, &fs)
3039 } else {
3040 compile(opts, &job.input, &fs)
3041 };
3042 if opts.time {
3043 say_time(&job.input, started.elapsed(), &mut stderr);
3044 }
3045 failed |= !write_trace(opts, job, started, &result, &mut stderr);
3046 fired.merge(&result.fired);
3047 pressure.merge(&result.pressure);
3048 lowerings.merge(&result.lowerings);
3049 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3050 failed |= !remarks.write(&result.remarks, &mut stderr);
3051 for message in &result.messages {
3052 let _ = writeln!(stderr, "{message}");
3053 }
3054 // Before the failure below, because a compilation that stopped in the back end is exactly
3055 // the one whose preprocessed source somebody wants to look at.
3056 failed |= !write_temps(job, &result.temps, &mut stderr);
3057 // Before it as well, because gcc leaves an empty report for a file that did not compile
3058 // and a build that looks for one beside every object should find one.
3059 failed |= !write_stack_usage(job, &result.stack_usage, &mut stderr);
3060 if result.failed() {
3061 failed = true;
3062 continue;
3063 }
3064 // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
3065 // this is the one path where both files come out of the same run. An input of IR has no
3066 // dependencies to report and produces an empty list, which produces a rule naming only
3067 // itself, and that is the honest answer rather than a missing file.
3068 if opts.deps.emit {
3069 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3070 }
3071 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
3072 let _ = writeln!(stderr, "rucc: error: {e}");
3073 failed = true;
3074 }
3075 }
3076 failed |= !write_coverage(opts, &fired, &mut stderr);
3077 failed |= !write_pressure(opts, &pressure, &mut stderr);
3078 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3079 i32::from(failed)
3080}
3081
3082/// A directory for the object files only the link step ever sees, removed when it goes away.
3083///
3084/// `-c` writes its object where the user can see it and linking does not, which is the whole of
3085/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
3086/// every other compiler. Removing them on drop rather than at the end of a function is so that a
3087/// link that failed leaves nothing behind either.
3088struct Scratch {
3089 /// Where the objects go.
3090 dir: PathBuf,
3091}
3092
3093impl Scratch {
3094 /// Makes one, under whatever the platform calls its temporary directory.
3095 ///
3096 /// The name carries the process id so that two compilers running at once do not share a
3097 /// directory, which they would otherwise do the moment two of them compiled a file of the
3098 /// same name.
3099 fn new() -> Result<Scratch, String> {
3100 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
3101 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
3102 Ok(Scratch { dir })
3103 }
3104}
3105
3106impl Drop for Scratch {
3107 fn drop(&mut self) {
3108 let _ = std::fs::remove_dir_all(&self.dir);
3109 }
3110}
3111
3112/// The link line the plan describes, for `-###`.
3113///
3114/// The names in it are the hints the plan carries rather than the temporaries a real compilation
3115/// would choose, because `-###` prints the line without having compiled anything and so has
3116/// nothing to point at. That also makes the printed line readable rather than naming a directory
3117/// that only exists while a compilation is running.
3118fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
3119 let linker = link::find(opts.target, link)?;
3120 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
3121 Ok(link::render(&linker, &args))
3122}
3123
3124/// Compiles everything, then links it.
3125///
3126/// The objects go in a directory that is removed afterwards, which is why this is not
3127/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
3128/// and does not say where, because where is a question that only has an answer once something is
3129/// running.
3130fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
3131 let Some(job) = &plan.link else {
3132 // Every path into here comes from a plan whose last phase is the link, and such a plan
3133 // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
3134 let mut stderr = std::io::stderr().lock();
3135 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
3136 return 1;
3137 };
3138 // Before anything is compiled, because a linker that is not on the machine is worth knowing
3139 // about in the second it takes to look rather than after the compilation.
3140 // And before that, whether this link has a line at all and whether what it reads is on the
3141 // machine. Both are answerable now, and a target whose sysroot has not been built is worth
3142 // saying so about before the compilation rather than after it.
3143 if let Err(why) = link::preflight(opts.target, link) {
3144 return complain(why);
3145 }
3146 let linker = match link::find(opts.target, link) {
3147 Ok(linker) => linker,
3148 Err(why) => return complain(why),
3149 };
3150 // Whether the one that was found can do this link is asked inside the search, which moves on
3151 // past an lld that is too old to a newer one somewhere else and refuses only when there is none.
3152 // The glibc stubs, which are the one part of a cross sysroot written here rather than fetched.
3153 // Before compiling for the same reason as the rest, and never for `-###`, which writes nothing.
3154 if let Err(why) = link::write_stubs(opts.target, link) {
3155 return complain(why);
3156 }
3157
3158 let scratch = match Scratch::new() {
3159 Ok(scratch) => scratch,
3160 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
3161 };
3162
3163 let fs = OsFileSystem::new();
3164 let mut failed = false;
3165 // One per job, in job order, which is what lets the link line below be rebuilt with the real
3166 // paths in it: every job contributes exactly one file to the line and does so in this order.
3167 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
3168 let mut fired = Fired::new();
3169 let mut pressure = Pressure::new();
3170 let mut lowerings = Lowerings::new();
3171 {
3172 let mut stderr = std::io::stderr().lock();
3173 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3174 failed |= !ok;
3175 for (at, job) in plan.jobs.iter().enumerate() {
3176 let out = match &job.output {
3177 Output::Temporary(hint) => {
3178 // The index because two inputs in different directories can have the same
3179 // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
3180 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
3181 }
3182 Output::File(path) => path.clone(),
3183 // A job feeding the linker never writes to standard output, since the plan gives
3184 // it a temporary. This is here so that the match is total rather than a panic.
3185 Output::Stdout => continue,
3186 };
3187 produced.push(out.clone());
3188 if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
3189 continue;
3190 }
3191 let started = std::time::Instant::now();
3192 let result = if needs_an_assembler(job) {
3193 assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3194 } else if job.kind == InputKind::Ir {
3195 compile_ir(opts, &job.input, &fs)
3196 } else {
3197 compile(opts, &job.input, &fs)
3198 };
3199 if opts.time {
3200 say_time(&job.input, started.elapsed(), &mut stderr);
3201 }
3202 failed |= !write_trace(opts, job, started, &result, &mut stderr);
3203 fired.merge(&result.fired);
3204 pressure.merge(&result.pressure);
3205 lowerings.merge(&result.lowerings);
3206 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3207 failed |= !remarks.write(&result.remarks, &mut stderr);
3208 for message in &result.messages {
3209 let _ = writeln!(stderr, "{message}");
3210 }
3211 failed |= !write_temps(job, &result.temps, &mut stderr);
3212 failed |= !write_stack_usage(job, &result.stack_usage, &mut stderr);
3213 if result.failed() {
3214 failed = true;
3215 continue;
3216 }
3217 // A `-MD` on a command line that links writes the rule next to the executable and
3218 // names the executable as its target, since that is the file this source builds
3219 // here. The object it went through is in a temporary directory and is gone by the
3220 // time `make` reads any of this.
3221 if opts.deps.emit {
3222 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3223 }
3224 if !matches!(result.artifact, Artifact::Object { .. }) {
3225 // Worth saying rather than writing whatever it is and letting the linker read it.
3226 // An empty file is a valid empty linker script, so a link handed one gets as far
3227 // as reporting every symbol of this file undefined, which is a page of messages
3228 // about something that went wrong here.
3229 let _ = writeln!(
3230 stderr,
3231 "rucc: internal error: {}: no object file was produced for the link",
3232 job.input
3233 );
3234 failed = true;
3235 continue;
3236 }
3237 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
3238 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
3239 failed = true;
3240 }
3241 }
3242 failed |= !write_coverage(opts, &fired, &mut stderr);
3243 failed |= !write_pressure(opts, &pressure, &mut stderr);
3244 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3245 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3246 }
3247 if failed {
3248 // Nothing is linked from a compilation that did not finish. A linker run over the objects
3249 // that did compile would report every function of the file that did not as undefined,
3250 // which is a page of messages about a mistake already reported once.
3251 return 1;
3252 }
3253
3254 // The items in command line order with the temporaries filled in. A library and a word for the
3255 // linker contribute no job and pass through, and every file item takes the next job's real
3256 // output, which is what keeps whatever was written between two objects between them here.
3257 let mut outputs = produced.into_iter();
3258 let mut items = Vec::with_capacity(job.inputs.len());
3259 for item in &job.inputs {
3260 match item {
3261 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
3262 link::Item::Linker(arg) => items.push(link::Item::Linker(arg.clone())),
3263 link::Item::File(_) => match outputs.next() {
3264 Some(path) => items.push(link::Item::File(path)),
3265 None => return complain("the plan asks the linker for a file nothing produced"),
3266 },
3267 }
3268 }
3269
3270 let args = match link::line(opts.target, link, &items, &job.output) {
3271 Ok(args) => args,
3272 Err(why) => return complain(why),
3273 };
3274 if verbose {
3275 let mut stderr = std::io::stderr().lock();
3276 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
3277 }
3278 let started = std::time::Instant::now();
3279 let ran = link::run(&linker, &args);
3280 if opts.time {
3281 // The one step of a compilation that really is another program, so this line is the same
3282 // measurement gcc's is and names the linker the way gcc names `collect2`.
3283 let mut stderr = std::io::stderr().lock();
3284 say_time(&linker.name, started.elapsed(), &mut stderr);
3285 }
3286 match ran {
3287 Ok(()) => 0,
3288 // The linker has already said what was wrong on its own error output, and repeating that
3289 // linking failed would only push its message further up the screen.
3290 Err(link::Error::Refused { .. }) => 1,
3291 Err(why) => complain(why),
3292 }
3293}
3294
3295/// Compiles everything and writes the objects into one static library.
3296///
3297/// No temporary directory and no second program. The objects never reach the file system at all:
3298/// they go from the compiler into the archive writer, which is both faster than writing a directory
3299/// of files for an `ar` to read back and the reason the symbol index can be written at all. A
3300/// member's index entries are the names the object writer says it wrote, and the only thing that
3301/// knows those is the run that wrote it.
3302///
3303/// `-save-temps` is the exception. It asked for the objects to be kept, the plan gave them names a
3304/// person can find, and they are written there as well as put in the archive.
3305fn archive_all(opts: &Options, plan: &Plan) -> i32 {
3306 let Some(job) = &plan.archive else {
3307 // Every path into here comes from a plan whose last phase is the archive, and such a plan
3308 // has an archive job. Saying so is cheaper than an unwrap that would have to be explained.
3309 return complain("there is nothing to put in an archive");
3310 };
3311 // Before anything is compiled, because a format this has no container for is worth knowing
3312 // about in the second it takes to look rather than after the whole compilation.
3313 let flavour = match opts.target.os.object_format() {
3314 ObjectFormat::Elf => rucc_archive::Flavour::Gnu,
3315 ObjectFormat::Coff => rucc_archive::Flavour::Coff,
3316 ObjectFormat::MachO => rucc_archive::Flavour::Bsd,
3317 // Wasm has no archives of its own at all.
3318 format @ ObjectFormat::Wasm => {
3319 return complain(format!(
3320 "there is no archive format for {} objects in this compiler yet",
3321 format.as_str()
3322 ));
3323 }
3324 };
3325
3326 let fs = OsFileSystem::new();
3327 let mut failed = false;
3328 let mut members: Vec<rucc_archive::Member> = Vec::with_capacity(plan.jobs.len());
3329 let mut names = job.members.iter();
3330 let mut fired = Fired::new();
3331 let mut pressure = Pressure::new();
3332 let mut lowerings = Lowerings::new();
3333 {
3334 let mut stderr = std::io::stderr().lock();
3335 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3336 failed |= !ok;
3337 for plan_job in &plan.jobs {
3338 // What the plan called this member. The two lists are walked together rather than the
3339 // name being worked out again here, so that what `-###` printed and what goes in the
3340 // file cannot come apart.
3341 let Some(member) = names.next() else {
3342 return complain("the plan asks the archive for a member nothing produced");
3343 };
3344 if !plan_job.phases.contains(&Phase::Compile) && !needs_an_assembler(plan_job) {
3345 // Neither something to compile nor something to assemble, so there is nothing to
3346 // put in, and an archive quietly missing a member is worse than a message.
3347 let _ = writeln!(
3348 &mut stderr,
3349 "rucc: error: {}: this compiler makes an archive out of what it compiles, and \
3350 there is nothing here for it to do",
3351 plan_job.input
3352 );
3353 failed = true;
3354 continue;
3355 }
3356 let started = std::time::Instant::now();
3357 let result = if needs_an_assembler(plan_job) {
3358 assemble(opts, &plan_job.input, assembly_wants_cpp(plan_job), &fs)
3359 } else if plan_job.kind == InputKind::Ir {
3360 compile_ir(opts, &plan_job.input, &fs)
3361 } else {
3362 compile(opts, &plan_job.input, &fs)
3363 };
3364 if opts.time {
3365 say_time(&plan_job.input, started.elapsed(), &mut stderr);
3366 }
3367 failed |= !write_trace(opts, plan_job, started, &result, &mut stderr);
3368 fired.merge(&result.fired);
3369 pressure.merge(&result.pressure);
3370 lowerings.merge(&result.lowerings);
3371 failed |= !write_dumps(&plan_job.input, &result.dumps, &mut stderr);
3372 failed |= !remarks.write(&result.remarks, &mut stderr);
3373 for message in &result.messages {
3374 let _ = writeln!(stderr, "{message}");
3375 }
3376 failed |= !write_temps(plan_job, &result.temps, &mut stderr);
3377 failed |= !write_stack_usage(plan_job, &result.stack_usage, &mut stderr);
3378 if result.failed() {
3379 failed = true;
3380 continue;
3381 }
3382 if opts.deps.emit {
3383 failed |= !write_deps(opts, plan, plan_job, &result.deps, &mut stderr);
3384 }
3385 let Artifact::Object { bytes, defines } = result.artifact else {
3386 let _ = writeln!(
3387 stderr,
3388 "rucc: internal error: {}: no object file was produced for the archive",
3389 plan_job.input
3390 );
3391 failed = true;
3392 continue;
3393 };
3394 // Under `-save-temps` the plan gave the object a name a person can find, so it is
3395 // written there too. Otherwise it is only ever a member and never a file.
3396 if let Output::File(path) = &plan_job.output {
3397 if let Err(e) = std::fs::write(path, &bytes) {
3398 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3399 failed = true;
3400 }
3401 }
3402 members.push(rucc_archive::Member { name: member.clone(), body: bytes, defines });
3403 }
3404 failed |= !write_coverage(opts, &fired, &mut stderr);
3405 failed |= !write_pressure(opts, &pressure, &mut stderr);
3406 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3407 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3408 }
3409 if failed {
3410 // Nothing is written from a compilation that did not finish, for the reason the link gives:
3411 // an archive missing the file that failed is one a link reports every name of as undefined,
3412 // which is a page of messages about a mistake already reported once.
3413 return 1;
3414 }
3415
3416 let bytes = match rucc_archive::write(flavour, &members) {
3417 Ok(bytes) => bytes,
3418 // Every one of these is a bug here rather than a program's mistake: the names came from the
3419 // object writer and the bodies came from this process.
3420 Err(why) => return complain(format!("the archive could not be written: {why}")),
3421 };
3422 match std::fs::write(&job.output, &bytes) {
3423 Ok(()) => 0,
3424 Err(e) => complain(format!("{}: {e}", job.output)),
3425 }
3426}
3427
3428/// Prints one driver level message and gives back the exit status that goes with it.
3429fn complain(why: impl std::fmt::Display) -> i32 {
3430 let mut stderr = std::io::stderr().lock();
3431 let _ = writeln!(stderr, "rucc: error: {why}");
3432 1
3433}
3434
3435/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
3436///
3437/// Once for the whole command line rather than once per input, because the question is which
3438/// lowering rules this run of the compiler reached and a file per input would leave the reader
3439/// unioning files to find out something one process already knew.
3440///
3441/// A file that could not be written is a failure and not a warning. What asks for this is a
3442/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
3443fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
3444 let Some(path) = &opts.rule_coverage else { return true };
3445 let Some(table) = coverage::table(opts.target.arch) else {
3446 let _ = writeln!(
3447 stderr,
3448 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
3449 to report",
3450 opts.target
3451 );
3452 return false;
3453 };
3454 match std::fs::write(path, fired.listing(table)) {
3455 Ok(()) => true,
3456 Err(e) => {
3457 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3458 false
3459 }
3460 }
3461}
3462
3463/// Writes what `-Zregister-pressure=FILE` asked for, and says whether it could.
3464///
3465/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3466/// not be written is a failure for the reason it gives too. There is no equivalent of the missing
3467/// rule table here, since every target this compiles for has an allocator, and a run that reached
3468/// no back end at all writes an empty listing rather than nothing: a measurement of a build that
3469/// produced no code is still an answer and it is the honest one.
3470fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
3471 let Some(path) = &opts.register_pressure else { return true };
3472 match std::fs::write(path, pressure.listing()) {
3473 Ok(()) => true,
3474 Err(e) => {
3475 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3476 false
3477 }
3478 }
3479}
3480
3481/// Writes what `-Zlowering=FILE` asked for, and says whether it could.
3482///
3483/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3484/// not be written is a failure for the reason it gives too. A run that reached no back end writes
3485/// an empty listing rather than nothing, the way [`write_pressure`] does and for the same reason.
3486fn write_lowering(opts: &Options, lowerings: &Lowerings, stderr: &mut impl std::io::Write) -> bool {
3487 let Some(path) = &opts.lowering_dump else { return true };
3488 match std::fs::write(path, lowerings.listing()) {
3489 Ok(()) => true,
3490 Err(e) => {
3491 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3492 false
3493 }
3494 }
3495}
3496
3497/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
3498///
3499/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
3500/// A file rather than the diagnostic stream is what a harness wants: the corpus in
3501/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
3502/// a few thousand remarks mixed into that would bury it.
3503struct Remarks {
3504 /// The file, if there is one.
3505 file: Option<String>,
3506 /// Whether anything has been written to it yet, which decides between truncating and
3507 /// appending. One file holds the whole run rather than the last input in it.
3508 started: bool,
3509}
3510
3511impl Remarks {
3512 /// Prepares the destination, emptying the file if there is one.
3513 ///
3514 /// Emptied here rather than at the first remark, because a run where no pass had anything to
3515 /// say should leave an empty file and not yesterday's. An absent file and an empty one are
3516 /// different facts and something reading this will act on the difference.
3517 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
3518 let mut ok = true;
3519 if let Some(path) = file {
3520 if let Err(e) = std::fs::write(path, "") {
3521 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3522 ok = false;
3523 }
3524 }
3525 (Self { file: file.cloned(), started: false }, ok)
3526 }
3527
3528 /// Writes one input's remarks, and says whether that worked.
3529 ///
3530 /// A file that cannot be written is a failure and not a warning, for the reason
3531 /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
3532 /// where nothing happened.
3533 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
3534 if text.is_empty() {
3535 return true;
3536 }
3537 let Some(path) = &self.file else {
3538 let _ = write!(stderr, "{text}");
3539 return true;
3540 };
3541 let opened = std::fs::OpenOptions::new()
3542 .write(true)
3543 .append(self.started)
3544 .truncate(!self.started)
3545 .create(true)
3546 .open(path);
3547 self.started = true;
3548 let result =
3549 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
3550 if let Err(e) = result {
3551 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3552 return false;
3553 }
3554 true
3555 }
3556}
3557
3558/// Writes what `-fdump-ir=` asked to see, one file per dump.
3559///
3560/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
3561/// after a run is the passes in the order they ran, per input. They go in the working directory
3562/// rather than beside the output, because a dump is something a person asked for at a prompt and
3563/// the working directory is where that person is.
3564///
3565/// A file that could not be written is a failure and not a warning, for the reason
3566/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
3567/// quietly did not happen looks exactly like a pass that did not run.
3568fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
3569 let stem = std::path::Path::new(input)
3570 .file_name()
3571 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
3572 let mut ok = true;
3573 for dump in dumps {
3574 let path = format!("{stem}.{}.ir", dump.name);
3575 if let Err(e) = std::fs::write(&path, &dump.text) {
3576 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3577 ok = false;
3578 }
3579 }
3580 ok
3581}
3582
3583/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
3584///
3585/// A file that could not be written is a failure rather than a warning, for the reason
3586/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
3587/// looks like a compilation that never went through that step.
3588fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
3589 let mut ok = true;
3590 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
3591 for (path, text) in kept {
3592 // A step the compilation did not reach has nothing to keep, and a job that is not keeping
3593 // that step has nowhere to put it. Either way there is no file here.
3594 let (Some(path), Some(text)) = (path, text) else { continue };
3595 if let Err(e) = std::fs::write(&path, text) {
3596 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3597 ok = false;
3598 }
3599 }
3600 ok
3601}
3602
3603/// Writes the `.su` file `-fstack-usage` asked for, where the plan said it goes.
3604///
3605/// Written even when it is empty, because gcc writes an empty `.su` for a file with no functions,
3606/// for `-fsyntax-only` and for a file that did not compile, and a tool that looks for one beside
3607/// every object should find one.
3608fn write_stack_usage(job: &Job, text: &str, stderr: &mut impl std::io::Write) -> bool {
3609 let Some(path) = &job.stack_usage else { return true };
3610 if let Err(e) = std::fs::write(path, text) {
3611 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3612 return false;
3613 }
3614 true
3615}
3616
3617/// Appends the file's line to the `-frucc-trace` file, when there is one.
3618///
3619/// Returns whether that went well, and says why on standard error when it did not.
3620fn write_trace(
3621 opts: &Options,
3622 job: &Job,
3623 started: std::time::Instant,
3624 result: &Compiled,
3625 stderr: &mut impl std::io::Write,
3626) -> bool {
3627 let Some(path) = &opts.trace else {
3628 return true;
3629 };
3630 let output = match &job.output {
3631 Output::Stdout => "-",
3632 Output::File(path) | Output::Temporary(path) => path,
3633 };
3634 let record = trace::Record {
3635 input: &job.input,
3636 output,
3637 ok: !result.failed(),
3638 total: started.elapsed(),
3639 timing: &result.timing,
3640 };
3641 match trace::append(path, &record) {
3642 Ok(()) => true,
3643 Err(e) => {
3644 let _ = writeln!(stderr, "rucc: error: {e}");
3645 false
3646 }
3647 }
3648}
3649
3650/// One line of `-time`, which is what a step was called and how long it took.
3651///
3652/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
3653/// no subprocess for anything but the link, so what is measured here is the wall clock of the
3654/// step and the second column is always zero. The shape of the line is kept because a person
3655/// reading it next to gcc's should not have to work out which column is which.
3656fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
3657 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
3658}
3659
3660/// Writes one job's result where the plan said it goes.
3661///
3662/// # Errors
3663///
3664/// Returns the message to print, which names the file when there is one, because "permission
3665/// denied" on its own does not say which file was refused.
3666fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
3667 match output {
3668 Output::Stdout => {
3669 let mut stdout = std::io::stdout().lock();
3670 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
3671 }
3672 Output::File(path) | Output::Temporary(path) => {
3673 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
3674 }
3675 }
3676}
3677
3678/// The target a program name asks for, the way `aarch64-linux-gnu-gcc` is gcc for that target.
3679///
3680/// `program` is the path the compiler was started as. The name without its directory and without a
3681/// trailing `.exe` has to end in `-rucc`, and what comes before that has to be a target this
3682/// compiler knows, or there is no answer and the name means nothing. A link named `my-rucc` is
3683/// therefore just rucc and not an error.
3684pub fn target_from_program(program: &str) -> Option<String> {
3685 let name = program.rsplit(['/', '\\']).next()?;
3686 let name = name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name);
3687 let triple = name.strip_suffix("-rucc")?;
3688 triple.parse::<Triple>().ok()?;
3689 Some(triple.to_owned())
3690}
3691
3692/// [`run`] for a compiler started as `program`, which is `argv[0]`.
3693///
3694/// A target taken from the name goes in front of `args`, so a `--target=` written on the command
3695/// line comes later and wins, which is what gcc and clang do with a prefixed name.
3696pub fn run_as(program: &str, args: &[String]) -> i32 {
3697 match target_from_program(program) {
3698 Some(triple) => {
3699 let mut all = Vec::with_capacity(args.len() + 1);
3700 all.push(format!("--target={triple}"));
3701 all.extend_from_slice(args);
3702 run(&all)
3703 }
3704 None => run(args),
3705 }
3706}
3707
3708/// What `--version` prints.
3709///
3710/// The first line is ours and is the one every harness we have reads. The second is for build
3711/// systems that decide what kind of compiler they have by reading this text. Meson takes the GNU
3712/// path only when it finds "Free Software Foundation" here, and otherwise stops with "Unknown
3713/// compiler" before it has asked a single question, which is how the whole of a meson build is
3714/// lost to one sentence. Past that point meson reads the version from `__GNUC__` and asks the
3715/// preprocessor everything else, so the line decides the path and nothing more. It says what is
3716/// true, that rucc speaks the dialect of GCC 16, and it does not claim to be GCC.
3717fn banner() -> String {
3718 format!(
3719 "rucc {VERSION}\nA C compiler for the GNU C dialect of GCC 16 from the Free Software Foundation.\nThis is free software under the Apache License 2.0. There is NO warranty.\n"
3720 )
3721}
3722
3723/// Runs the driver and returns the process exit code.
3724///
3725/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
3726/// is the one place in the compiler that is true.
3727pub fn run(args: &[String]) -> i32 {
3728 match parse_args(args) {
3729 Ok(Action::Help) => {
3730 print!("{USAGE}");
3731 0
3732 }
3733 Ok(Action::Version) => {
3734 print!("{}", banner());
3735 0
3736 }
3737 Ok(Action::Print(line)) => {
3738 println!("{line}");
3739 0
3740 }
3741 Ok(Action::PrintConfig(opts)) => {
3742 print!("{}", print_config(&opts));
3743 0
3744 }
3745 Ok(Action::PrintPipeline(opts)) => {
3746 print!("{}", print_pipeline(&opts));
3747 0
3748 }
3749 Ok(Action::PrintPlan { opts, plan, link }) => {
3750 print!("{}", plan.render());
3751 // The line as it would be typed, which is the half of `-###` that section 4.3 says
3752 // arrives with the link. It is printed even when the linker is not on this machine,
3753 // because what a build wants from `-###` is what the compiler would do.
3754 if let Some(job) = &plan.link {
3755 match link_line(&opts, &link, job) {
3756 Ok(line) => println!("{line}"),
3757 Err(why) => {
3758 let mut stderr = std::io::stderr().lock();
3759 let _ = writeln!(stderr, "rucc: error: {why}");
3760 return 1;
3761 }
3762 }
3763 }
3764 0
3765 }
3766 Ok(Action::Fetch { what, target, cache }) => {
3767 let kernel = rucc_sysroot::Kernel::for_target(&cache, target)
3768 .map(|_| &rucc_sysroot::KERNEL_HEADERS);
3769 fetch_sysroot(what, kernel, target, &cache)
3770 }
3771 Ok(Action::FetchMsvcSdk { target, accepted, cache }) => {
3772 msvc::fetch_msvc_sdk(target, accepted, &cache)
3773 }
3774 Ok(Action::Compile { opts, plan, link, jobs, verbose, notes }) => {
3775 {
3776 let mut stderr = std::io::stderr().lock();
3777 // Before the plan rather than after it, because a note is about the command line
3778 // and the plan is what the command line was read as, so the reader wants the two
3779 // in that order.
3780 for note in ¬es {
3781 let _ = writeln!(stderr, "rucc: warning: {note}");
3782 }
3783 if verbose {
3784 let _ = write!(stderr, "{}", plan.render());
3785 let _ = writeln!(stderr, "workers: {}", jobs.count());
3786 // What `gcc -v` says about headers, because meson and cmake read it to find the
3787 // system directories.
3788 let _ = write!(stderr, "{}", opts.search.render_gcc());
3789 }
3790 }
3791 if opts.emit == EmitKind::Preprocessed {
3792 return preprocess_all(&opts, &plan);
3793 }
3794 if opts.emit == EmitKind::Archive {
3795 return archive_all(&opts, &plan);
3796 }
3797 if opts.emit != EmitKind::Executable {
3798 return compile_all(&opts, &plan);
3799 }
3800 link_all(&opts, &plan, &link, verbose)
3801 }
3802 Err(e) => {
3803 let mut stderr = std::io::stderr().lock();
3804 let _ = writeln!(stderr, "rucc: error: {e}");
3805 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
3806 1
3807 }
3808 }
3809}
3810
3811#[cfg(test)]
3812mod tests {
3813 use rucc_session::{
3814 Contract, GnucVersion, IncludeForm, LtoJobs, OptLevel, Partition, Patchable, Visibility,
3815 };
3816
3817 use super::*;
3818
3819 fn args(s: &[&str]) -> Vec<String> {
3820 s.iter().map(|x| (*x).to_owned()).collect()
3821 }
3822
3823 /// A target to write down where the host would otherwise decide, for the tests whose answer
3824 /// would be a different one on a different machine.
3825 ///
3826 /// Most of the tests here never name a target, which is right, because most of what the driver
3827 /// does with a command line is the same wherever it runs and a test that pinned one would be
3828 /// saying so in every case for the sake of the two that need it. The two that need it are the
3829 /// ones whose answer comes off the target rather than off the command line: the name an object
3830 /// gets, which is `a.o` here and `a.obj` on Windows, and whether Microsoft's reading of a
3831 /// nameless member is on, which is off here and on there. Both are the compiler being right, and
3832 /// a test that leaves the target to the host is asking a question with two correct answers.
3833 const LINUX: &str = "--target=x86_64-unknown-linux-gnu";
3834
3835 #[test]
3836 fn a_response_file_is_split_the_way_libiberty_splits_one() {
3837 let words = response_words("-Wl,--as-needed 'a b' \"c d\"\ne\\ f '' \"it's\" g\\\\h\n");
3838 assert_eq!(words, ["-Wl,--as-needed", "a b", "c d", "e f", "", "it's", "g\\h"]);
3839 assert!(response_words(" \n\t").is_empty());
3840 }
3841
3842 #[test]
3843 fn a_response_file_on_the_command_line_is_read_in_its_place() {
3844 let dir = std::env::temp_dir().join(format!("rucc-rsp-{}", std::process::id()));
3845 std::fs::create_dir_all(&dir).unwrap();
3846 let inner = dir.join("inner.rsp");
3847 std::fs::write(&inner, "-lm\n").unwrap();
3848 let outer = dir.join("outer.rsp");
3849 std::fs::write(&outer, format!("-o 'my prog' -Wl,--as-needed @{}\n", inner.display()))
3850 .unwrap();
3851 let line = args(&["x.o", &format!("@{}", outer.display()), "@no-such-file"]);
3852 assert_eq!(
3853 response_files(&line).unwrap(),
3854 args(&["x.o", "-o", "my prog", "-Wl,--as-needed", "-lm", "@no-such-file"])
3855 );
3856 let itself = dir.join("itself.rsp");
3857 std::fs::write(&itself, format!("@{}", itself.display())).unwrap();
3858 let looped = response_files(&args(&[&format!("@{}", itself.display())]));
3859 assert!(looped.is_err(), "a file that names itself should be refused");
3860 std::fs::remove_dir_all(&dir).unwrap();
3861 }
3862
3863 #[test]
3864 fn help_and_version_win_over_everything_else() {
3865 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
3866 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
3867 }
3868
3869 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
3870 match parse_args(&args(s)).expect("expected a compilation") {
3871 Action::Compile { opts, plan, .. } => (opts, plan),
3872 other => panic!("expected a compilation, got {other:?}"),
3873 }
3874 }
3875
3876 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
3877 match parse_args(&args(s)).expect("expected a compilation") {
3878 Action::Compile { link, plan, .. } => (link, plan),
3879 other => panic!("expected a compilation, got {other:?}"),
3880 }
3881 }
3882
3883 fn notes(s: &[&str]) -> Vec<String> {
3884 match parse_args(&args(s)).expect("expected a compilation") {
3885 Action::Compile { notes, .. } => notes,
3886 other => panic!("expected a compilation, got {other:?}"),
3887 }
3888 }
3889
3890 /// The ordinary command line has nothing to say about itself, which is the property that makes
3891 /// a note worth reading when there is one.
3892 #[test]
3893 fn a_command_line_with_nothing_wrong_with_it_carries_no_notes() {
3894 assert_eq!(notes(&["-c", "a.c"]), Vec::<String>::new());
3895 }
3896
3897 /// `-g` for Windows is dropped with a warning rather than failing the compile, until the COFF
3898 /// writer has DWARF sections to put it in.
3899 #[test]
3900 fn debug_information_for_coff_is_dropped_with_a_warning() {
3901 let said = notes(&["--target=x86_64-windows-gnu", "-g", "-c", "a.c"]);
3902 assert_eq!(said.len(), 1, "{said:?}");
3903 assert!(said[0].starts_with("-g is ignored for x86_64-windows-gnu"), "{said:?}");
3904 let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-g", "-c", "a.c"]);
3905 assert!(!opts.debug_info);
3906 assert_eq!(notes(&["--target=x86_64-linux-gnu", "-g", "-c", "a.c"]), Vec::<String>::new());
3907 }
3908
3909 /// A directory that is not there contributes nothing to the search path, so there is no tree to
3910 /// read a release out of and nothing to compare the pin against. Said as a test because this is
3911 /// the shape a hermetic machine takes: the probe reads the disk and every other machine has a
3912 /// different disk, so what can be asserted here is the silence.
3913 #[test]
3914 fn a_named_tree_that_is_not_on_the_machine_is_not_a_release_mismatch() {
3915 let said =
3916 notes(&["--target=x86_64-linux-gnu.2.28", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
3917 assert_eq!(said, Vec::<String>::new());
3918 }
3919
3920 #[test]
3921 fn collects_inputs_and_flags() {
3922 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
3923 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
3924 assert_eq!(paths, vec!["a.c", "b.c"]);
3925 assert_eq!(opts.opt_level, OptLevel::O2);
3926 assert_eq!(opts.emit, EmitKind::Object);
3927 assert!(opts.debug_info);
3928 }
3929
3930 /// The unstable options, which are spelled apart from everything else on purpose: what is
3931 /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
3932 #[test]
3933 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
3934 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
3935 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
3936
3937 let (plain, _) = compile(&["-c", "a.c"]);
3938 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
3939
3940 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
3941 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
3942 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
3943 }
3944
3945 /// The other measurement written to a file, which reads the same way and fails the same way.
3946 #[test]
3947 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
3948 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
3949 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
3950
3951 let (plain, _) = compile(&["-c", "a.c"]);
3952 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
3953
3954 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
3955 }
3956
3957 /// Which register allocator runs, asked for by name, and left to the level when it is not.
3958 #[test]
3959 fn the_register_allocator_is_asked_for_by_name() {
3960 let (opts, _) = compile(&["-c", "-O2", "-Zregalloc=backtracking", "a.c"]);
3961 assert_eq!(opts.backtracking, Some(true));
3962 let (opts, _) = compile(&["-c", "-O2", "-Zregalloc=single", "a.c"]);
3963 assert_eq!(opts.backtracking, Some(false));
3964 let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3965 assert_eq!(plain.backtracking, None, "the level decides unless it was asked for");
3966 assert!(parse_args(&args(&["-Zregalloc=graph", "a.c"])).is_err(), "not an allocator");
3967 }
3968
3969 /// The third one, which says what the pre-selection lowering group did.
3970 #[test]
3971 fn a_switch_shape_is_forced_by_name_and_only_by_one_it_has() {
3972 let (opts, _) = compile(&["-c", "-O2", "-Zswitch=walk", "a.c"]);
3973 assert_eq!(opts.switch_shape.as_deref(), Some("walk"));
3974 let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3975 assert_eq!(plain.switch_shape, None, "nothing is forced unless it was asked for");
3976 assert!(parse_args(&args(&["-Zswitch=bit-test", "a.c"])).is_err(), "not a shape it forces");
3977 }
3978
3979 #[test]
3980 fn where_the_lowering_dump_goes_is_asked_for_the_same_way() {
3981 let (opts, _) = compile(&["-c", "-O2", "-Zlowering=/tmp/lowering.txt", "a.c"]);
3982 assert_eq!(opts.lowering_dump.as_deref(), Some("/tmp/lowering.txt"));
3983
3984 let (plain, _) = compile(&["-c", "a.c"]);
3985 assert_eq!(plain.lowering_dump, None, "nothing is dumped unless it was asked for");
3986
3987 assert!(parse_args(&args(&["-Zlowering=", "a.c"])).is_err(), "no file named");
3988 }
3989
3990 /// Scheduling, which has the three way answer every optimization flag has: on, off, and
3991 /// nothing said, which is whatever the optimization level asks for. The name is gcc's, and
3992 /// gcc's has a two in it because gcc has a scheduler before allocation and one after and this
3993 /// is the one after.
3994 #[test]
3995 fn scheduling_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
3996 let (on, _) = compile(&["-c", "-O0", "-fschedule-insns2", "a.c"]);
3997 assert_eq!(on.schedule_insns, Some(true));
3998
3999 let (off, _) = compile(&["-c", "-O2", "-fno-schedule-insns2", "a.c"]);
4000 assert_eq!(off.schedule_insns, Some(false));
4001
4002 let (quiet, _) = compile(&["-c", "-O2", "a.c"]);
4003 assert_eq!(quiet.schedule_insns, None, "nothing said, so the level decides");
4004 assert!(quiet.opt_level.schedules(), "and at this level the level says yes");
4005
4006 let (none, _) = compile(&["-c", "a.c"]);
4007 assert!(!none.opt_level.schedules(), "at no optimization it says no");
4008 }
4009
4010 /// Tail calls, which gcc spells as sibling calls and turns on at `-O2` and `-Os`.
4011 #[test]
4012 fn sibling_calls_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
4013 let (on, _) = compile(&["-c", "-O1", "-foptimize-sibling-calls", "a.c"]);
4014 assert_eq!(on.sibling_calls, Some(true));
4015
4016 let (off, _) = compile(&["-c", "-O2", "-fno-optimize-sibling-calls", "a.c"]);
4017 assert_eq!(off.sibling_calls, Some(false));
4018
4019 let (quiet, _) = compile(&["-c", "-Os", "a.c"]);
4020 assert_eq!(quiet.sibling_calls, None, "nothing said, so the level decides");
4021 assert!(quiet.opt_level.sibling_calls(), "and at this level the level says yes");
4022
4023 let (one, _) = compile(&["-c", "-O1", "a.c"]);
4024 assert!(!one.opt_level.sibling_calls(), "gcc leaves them off at -O1");
4025 }
4026
4027 /// Whether the timing model is worth holding an instruction back over, which is a `-Z` because
4028 /// it is a question about a target's description rather than about the program being compiled.
4029 #[test]
4030 fn whether_the_timing_model_is_cycle_accurate_can_be_overridden() {
4031 let (yes, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=yes", "a.c"]);
4032 assert_eq!(yes.cycle_accurate_model, Some(true));
4033
4034 let (no, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=no", "a.c"]);
4035 assert_eq!(no.cycle_accurate_model, Some(false));
4036
4037 let (plain, _) = compile(&["-c", "-O2", "a.c"]);
4038 assert_eq!(plain.cycle_accurate_model, None, "the target's own answer stands");
4039
4040 let bad = parse_args(&args(&["-Zcycle-accurate-model=maybe", "a.c"]))
4041 .expect_err("it takes yes or no");
4042 assert!(bad.message.contains("yes or no"), "{}", bad.message);
4043 }
4044
4045 #[test]
4046 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
4047 let (opts, _) = compile(&["-O", "a.c"]);
4048 assert_eq!(opts.opt_level, OptLevel::O1);
4049 }
4050
4051 #[test]
4052 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
4053 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
4054 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
4055 assert_eq!(plan.jobs[1].kind, InputKind::C);
4056 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
4057 }
4058
4059 #[test]
4060 fn dash_x_can_be_joined_to_its_language() {
4061 let (_, plan) = compile(&["a.o", "-xc", "b.txt", "-xnone", "c.o"]);
4062 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
4063 assert_eq!(plan.jobs[1].kind, InputKind::C);
4064 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
4065 }
4066
4067 #[test]
4068 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
4069 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
4070 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
4071 other => panic!("expected a compilation, got {other:?}"),
4072 };
4073 assert_eq!(jobs.count(), 4);
4074
4075 let default = match parse_args(&args(&["a.c"])).unwrap() {
4076 Action::Compile { jobs, .. } => jobs,
4077 other => panic!("expected a compilation, got {other:?}"),
4078 };
4079 assert_eq!(default, Jobs::available());
4080 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
4081 }
4082
4083 #[test]
4084 fn triple_hash_prints_the_plan_and_runs_nothing() {
4085 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
4086 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
4087 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
4088 }
4089
4090 #[test]
4091 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
4092 // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
4093 // this, and following the compiler is what makes a build that reads either of them find
4094 // the files where they are.
4095 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
4096 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
4097 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
4098 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
4099 // The last one on the line decides, the way it does for every other flag with an
4100 // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
4101 // nothing and said nothing looks exactly like one where the files were not produced.
4102 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
4103 assert_eq!(opts.save_temps, SaveTemps::Cwd);
4104 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
4105 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
4106 }
4107
4108 #[test]
4109 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
4110 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
4111 let (plain, without) = compile(&["-c", "a.c"]);
4112 assert!(opts.time);
4113 assert!(!plain.time);
4114 // Against the same line without the flag rather than against a spelling of the object's
4115 // name, since what the object is called is the host's business and this is not about that.
4116 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4117 }
4118
4119 #[test]
4120 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
4121 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
4122 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
4123 }
4124
4125 /// What `--fetch` says for a target this release pins nothing for, which today is every target
4126 /// but the three windows-gnu ones, the four musl ones and the eight glibc ones.
4127 #[test]
4128 fn a_fetch_of_a_target_nothing_is_pinned_for_says_so_rather_than_reaching_the_network() {
4129 let e = parse_args(&args(&["--fetch", "x86_64-linux-gnux32"])).unwrap_err();
4130 assert!(e.message.contains("pins no sysroot for x86_64-linux-gnux32"), "{}", e.message);
4131 // And what it does pin, because a release with some rows in the table and a release with
4132 // none are two situations and the second sentence is what tells them apart.
4133 assert!(e.message.contains("x86_64-windows-gnu"), "{}", e.message);
4134 // The joined spelling is the same flag.
4135 let joined = parse_args(&args(&["--fetch=x86_64-linux-gnux32"])).unwrap_err();
4136 assert_eq!(joined, e);
4137 }
4138
4139 /// The two targets a release will never pin, which is a different answer from the one above.
4140 ///
4141 /// Section 13.4. A person who reads "this release pins no sysroot yet" waits for a release that
4142 /// does, and no release of this compiler can ship either of these, so the message names the
4143 /// licence that decides it and what to do instead.
4144 #[test]
4145 fn a_fetch_of_a_target_behind_a_licence_wall_says_so_rather_than_saying_not_yet() {
4146 let e = parse_args(&args(&["--fetch", "aarch64-macos"])).unwrap_err();
4147 assert!(e.message.contains("Xcode licence"), "{}", e.message);
4148 assert!(e.message.contains("there never will be"), "{}", e.message);
4149 assert!(!e.message.contains("tamnd/rucc-cross"), "{}", e.message);
4150
4151 let e = parse_args(&args(&["--fetch", "x86_64-windows-msvc"])).unwrap_err();
4152 assert!(e.message.contains("redistributed"), "{}", e.message);
4153 // The way out of this one is a target rather than a download, and it is the default already.
4154 assert!(e.message.contains("mingw-w64"), "{}", e.message);
4155 // And the mingw-w64 target next to it is ours to ship and published, so the same flag has
4156 // something to get rather than a licence to explain.
4157 let action = parse_args(&args(&["--fetch", "x86_64-windows-gnu"])).expect("it is pinned");
4158 let Action::Fetch { what, .. } = action else { panic!("{action:?}") };
4159 assert_eq!(what.tuple, "x86_64-windows-gnu");
4160 }
4161
4162 #[test]
4163 fn the_other_fetch_takes_a_target_behind_microsofts_wall_and_carries_the_acceptance() {
4164 // Both spellings of the flag, because a flag that takes a tuple gets written both ways.
4165 for line in [
4166 vec!["--fetch-msvc-sdk", "x86_64-windows-msvc"],
4167 vec!["--fetch-msvc-sdk=x86_64-windows-msvc"],
4168 ] {
4169 let action = parse_args(&args(&line)).expect("that is a target behind the wall");
4170 let Action::FetchMsvcSdk { target, accepted, .. } = action else {
4171 panic!("{action:?}")
4172 };
4173 assert_eq!(target.to_canonical_string(), "x86_64-windows-msvc");
4174 // Nothing on the line accepted anything, so nothing did.
4175 assert!(!accepted);
4176 }
4177
4178 // And both spellings of the word, because the prose here uses one and most of the people
4179 // typing this will reach for the other.
4180 for word in ["--accept-licence", "--accept-license"] {
4181 let action = parse_args(&args(&["--fetch-msvc-sdk", "aarch64-windows-msvc", word]))
4182 .expect("that is a target behind the wall");
4183 let Action::FetchMsvcSdk { target, accepted, .. } = action else {
4184 panic!("{action:?}")
4185 };
4186 assert_eq!(target.to_canonical_string(), "aarch64-windows-msvc");
4187 assert!(accepted, "{word} should have been read");
4188 }
4189 }
4190
4191 #[test]
4192 fn the_other_fetch_refuses_the_command_lines_that_do_not_mean_anything() {
4193 // A tuple is what it gets, so a flag with nothing after it is not a command.
4194 let e = parse_args(&args(&["--fetch-msvc-sdk"])).unwrap_err();
4195 assert!(e.message.contains("requires the target"), "{}", e.message);
4196 let e = parse_args(&args(&["--fetch-msvc-sdk", "not-a-target"])).unwrap_err();
4197 assert!(e.message.contains("there is no SDK to get"), "{}", e.message);
4198
4199 // `--offline` forbids every download and this one asks for one, whichever order they came
4200 // in, which is the same answer `--fetch` gives.
4201 for line in [
4202 vec!["--offline", "--fetch-msvc-sdk", "x86_64-windows-msvc"],
4203 vec!["--fetch-msvc-sdk", "x86_64-windows-msvc", "--offline"],
4204 ] {
4205 let e = parse_args(&args(&line)).unwrap_err();
4206 assert!(e.message.contains("two opposite things"), "{}", e.message);
4207 }
4208
4209 // It gets an SDK and compiles nothing, so a file on the same line would be read by nothing.
4210 let e = parse_args(&args(&["--fetch-msvc-sdk", "x86_64-windows-msvc", "a.c"])).unwrap_err();
4211 assert!(e.message.contains("compiles nothing"), "{}", e.message);
4212
4213 // The two fetches are two commands and a line that asked for both asked for neither.
4214 let e = parse_args(&args(&[
4215 "--fetch",
4216 "x86_64-windows-gnu",
4217 "--fetch-msvc-sdk",
4218 "x86_64-windows-msvc",
4219 ]))
4220 .unwrap_err();
4221 assert!(e.message.contains("two different commands"), "{}", e.message);
4222
4223 // And an acceptance with nothing to accept for is a command line that says something about
4224 // a licence no part of it goes near.
4225 let e = parse_args(&args(&["--accept-licence", "-c", "a.c"])).unwrap_err();
4226 assert!(e.message.contains("--fetch-msvc-sdk <tuple> is the command"), "{}", e.message);
4227 }
4228
4229 /// An Apple target on a machine with no SDK, which is section 8.6's other host.
4230 ///
4231 /// Not run on a mac, where the SDK this is about is installed and the compile is the ordinary one
4232 /// that uses it. What the reason says is asserted in `rucc_sysroot::wall` and where it is printed
4233 /// is asserted in `rucc-pp`, so what is left here is that the driver works it out and leaves it
4234 /// where the preprocessor will find it, and that neither way past the wall leaves one behind.
4235 #[test]
4236 fn an_apple_target_with_no_sdk_anywhere_carries_the_licence_rather_than_a_missing_directory() {
4237 if cfg!(target_os = "macos") || std::env::var_os("SDKROOT").is_some() {
4238 return;
4239 }
4240 let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4241 let why = opts.search.missing_system().expect("the wall is the reason there are none");
4242 assert!(why.contains("aarch64-macos needs a macOS SDK"), "{why}");
4243 assert!(why.contains("Xcode licence"), "{why}");
4244 assert!(why.contains("-isysroot"), "{why}");
4245
4246 // A program that includes none of the library needs none of the SDK, which is what section
4247 // 8.6 means by being able to target the platform without one, so there is nothing to explain.
4248 let (opts, _) = compile(&["--target=aarch64-macos", "-nostdinc", "-c", "a.c"]);
4249 assert_eq!(opts.search.missing_system(), None);
4250 // And naming a path is the other way through, whether or not the path is there: a mistyped
4251 // directory is a mistake to report on its own terms rather than a licence to explain.
4252 let (opts, _) = compile(&["--target=aarch64-macos", "-isysroot", "/opt/sdk", "-c", "a.c"]);
4253 assert_eq!(opts.search.missing_system(), None);
4254 }
4255
4256 /// The same wall on the compile side of an MSVC target, where the way past it is a tuple.
4257 ///
4258 /// Not run on Windows, for the same reason the one above is not run on a mac: the wall stands in
4259 /// front of an SDK this machine does not have, and a Windows machine is the kind that does. The
4260 /// driver asks `vswhere` where Visual Studio is and takes the newest kit under it, so on a box
4261 /// with the build tools installed there are headers, no wall and nothing here to be about.
4262 /// `INCLUDE` is the other way a machine has one and is the other half of the guard, since a
4263 /// person can set that anywhere while Visual Studio is only found on the platform it runs on.
4264 #[test]
4265 fn an_msvc_target_with_no_sdk_named_says_which_environment_needs_nothing_installed() {
4266 if cfg!(target_os = "windows") || std::env::var_os("INCLUDE").is_some() {
4267 return;
4268 }
4269 let (opts, _) = compile(&["--target=x86_64-windows-msvc", "-c", "a.c"]);
4270 let why = opts.search.missing_system().expect("the wall is the reason there are none");
4271 assert!(why.contains("the Windows SDK and its universal CRT"), "{why}");
4272 assert!(why.contains("mingw-w64"), "{why}");
4273 // And the mingw-w64 target has its headers from us, so nothing is missing to explain.
4274 let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-c", "a.c"]);
4275 assert_eq!(opts.search.missing_system(), None);
4276 }
4277
4278 #[test]
4279 fn a_fetch_with_no_target_and_a_fetch_of_a_tuple_that_is_not_one_both_say_which() {
4280 let e = parse_args(&args(&["--fetch"])).unwrap_err();
4281 assert!(e.message.contains("--fetch requires"), "{}", e.message);
4282 let e = parse_args(&args(&["--fetch", "sparc64-solaris-gnu"])).unwrap_err();
4283 assert!(e.message.contains("--fetch sparc64-solaris-gnu"), "{}", e.message);
4284 assert!(e.message.contains("no sysroot to get"), "{}", e.message);
4285 }
4286
4287 /// Both flags on one line ask for opposite things, in either order.
4288 #[test]
4289 fn a_fetch_and_offline_together_is_a_refusal_whichever_way_round_they_are_written() {
4290 for line in [
4291 vec!["--offline", "--fetch", "x86_64-linux-musl"],
4292 vec!["--fetch", "x86_64-linux-musl", "--offline"],
4293 ] {
4294 let e = parse_args(&args(&line)).unwrap_err();
4295 assert!(e.message.contains("two opposite things"), "{}", e.message);
4296 }
4297 }
4298
4299 #[test]
4300 fn a_fetch_does_not_compile_anything_and_says_so_when_it_is_handed_a_file() {
4301 let e = parse_args(&args(&["--fetch", "x86_64-linux-musl", "a.c"])).unwrap_err();
4302 assert!(e.message.contains("compiles nothing"), "{}", e.message);
4303 assert!(e.message.contains("a.c"), "{}", e.message);
4304 }
4305
4306 /// `--offline` on its own is accepted and changes nothing, because an ordinary compile
4307 /// downloads nothing with or without it. A build that passes it everywhere is the case this is
4308 /// for, and it must not lose the compilation it was passed beside.
4309 #[test]
4310 fn offline_on_a_compilation_is_the_same_compilation() {
4311 let (opts, plan) = compile(&["-c", "--offline", "a.c"]);
4312 let (plain, without) = compile(&["-c", "a.c"]);
4313 assert_eq!(opts.target, plain.target);
4314 assert_eq!(plan.jobs.len(), without.jobs.len());
4315 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4316 }
4317
4318 #[test]
4319 fn a_deployment_target_comes_from_the_tuple_or_from_the_flag() {
4320 let version = |v: &str| rucc_tuple::Version::parse(v);
4321 let (opts, _) = compile(&["--target=aarch64-macos.13", "-c", "a.c"]);
4322 assert_eq!(opts.target, "aarch64-apple-darwin".parse().unwrap());
4323 assert_eq!(opts.os_version, version("13"));
4324 // The flag wins over the tuple, as it does under clang, and either spelling of it works.
4325 let (opts, _) =
4326 compile(&["--target=aarch64-macos.13", "-mmacosx-version-min=14.2", "-c", "a.c"]);
4327 assert_eq!(opts.os_version, version("14.2"));
4328 let (opts, _) = compile(&["--target=x86_64-macos", "-mmacos-version-min=12", "-c", "a.c"]);
4329 assert_eq!(opts.os_version, version("12"));
4330 // Nothing said leaves the platform's default to the target description.
4331 let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4332 assert_eq!(opts.os_version, None);
4333 // A Linux build that always passes the flag is not an Apple build because of it.
4334 let (opts, _) =
4335 compile(&["--target=aarch64-linux-gnu", "-mmacosx-version-min=13", "-c", "a.c"]);
4336 assert_eq!(opts.os_version, None);
4337 let e = parse_args(&args(&["-mmacosx-version-min=thirteen", "a.c"])).unwrap_err();
4338 assert!(e.message.contains("is not a version"), "{}", e.message);
4339 }
4340
4341 #[test]
4342 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
4343 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
4344 assert!(e.message.contains("unknown option"), "{}", e.message);
4345 }
4346
4347 /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
4348 /// one directory needs the older rules and the rest of the tree does not.
4349 #[test]
4350 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
4351 let (opts, _) = compile(&["-c", "a.c"]);
4352 assert!(!opts.permissive, "off unless it is asked for");
4353
4354 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
4355 assert!(opts.permissive);
4356
4357 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
4358 assert!(!opts.permissive);
4359 }
4360
4361 #[test]
4362 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
4363 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
4364 assert!(e.message.contains("trampoline"), "{}", e.message);
4365 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
4366 }
4367
4368 #[test]
4369 fn the_flag_every_configure_script_writes_is_taken() {
4370 // All four spellings, because a build writes whichever one its macros picked and a
4371 // compiler that takes three of them is a compiler that fails on the fourth.
4372 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
4373 let (opts, _) = compile(&["-c", flag, "a.c"]);
4374 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4375 }
4376 }
4377
4378 #[test]
4379 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
4380 let (opts, _) = compile(&["-c", "a.c"]);
4381 assert!(opts.unwinds(), "the default is off");
4382 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
4383 assert!(!opts.unwinds(), "the build was not taken at its word");
4384 let (opts, _) = compile(&[
4385 "-c",
4386 "-fno-asynchronous-unwind-tables",
4387 "-fasynchronous-unwind-tables",
4388 "a.c",
4389 ]);
4390 assert!(opts.unwinds(), "the last flag did not win");
4391 // The weaker request, which the same table answers, so a line that asks for a table and
4392 // against an asynchronous one gets one. That is gcc's arrangement and it turns up when a
4393 // build turns the asynchronous one off globally and a directory asks for a table back.
4394 let (opts, _) =
4395 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
4396 assert!(opts.unwinds(), "the weaker request was dropped");
4397 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
4398 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
4399 let (opts, _) =
4400 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
4401 assert!(!opts.unwinds(), "both were turned off and one stayed on");
4402 }
4403
4404 #[test]
4405 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
4406 // Every one of these is on a real build line somewhere and every one of them was an
4407 // unknown option. What they have in common is that the answer rucc gives is the answer
4408 // they ask for, so there is nothing to implement and nothing to refuse.
4409 for flag in [
4410 "-fno-common",
4411 "-fstrict-aliasing",
4412 "-fno-strict-aliasing",
4413 "-fdelete-null-pointer-checks",
4414 "-fno-delete-null-pointer-checks",
4415 "-frounding-math",
4416 "-fno-rounding-math",
4417 "-fexcess-precision=standard",
4418 "-fexcess-precision=fast",
4419 "-fexcess-precision=16",
4420 "-pipe",
4421 "-cpp",
4422 "-fdiagnostics-color",
4423 "-fno-diagnostics-color",
4424 "-fdiagnostics-color=always",
4425 "-fdiagnostics-color=never",
4426 "-fdiagnostics-color=auto",
4427 ] {
4428 let (opts, _) = compile(&["-c", flag, "a.c"]);
4429 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4430 }
4431 }
4432
4433 #[test]
4434 fn whether_an_exception_is_looked_at_is_kept_and_defaults_to_gccs_answer() {
4435 let (opts, _) = compile(&["-c", "a.c"]);
4436 assert!(opts.trapping_math, "the default was not gcc's");
4437 let (opts, _) = compile(&["-c", "-fno-trapping-math", "a.c"]);
4438 assert!(!opts.trapping_math);
4439 let (opts, _) = compile(&["-c", "-ftrapping-math", "a.c"]);
4440 assert!(opts.trapping_math, "spelling out the default turned it off");
4441 // The last one written wins, which is how a build line that inherits a flag from one
4442 // place and overrides it in another is read.
4443 let (opts, _) = compile(&["-c", "-fno-trapping-math", "-ftrapping-math", "a.c"]);
4444 assert!(opts.trapping_math);
4445 }
4446
4447 /// The flags a torture program writes on its own `dg-options` line, which is where most of
4448 /// these come from: a program reduced from a miscompilation names the pass that miscompiled
4449 /// it. Eighteen programs in the suite stopped on the driver before anything read them, and
4450 /// tamnd/rucc#1019 is the list.
4451 #[test]
4452 fn no_inline_turns_off_the_inlining_of_a_function_declared_inline() {
4453 let (opts, _) = compile(&["-c", "-O2", "-fno-inline", "a.c"]);
4454 assert_eq!(opts.passes, [(rucc_opt::inline::NAME.to_owned(), false)]);
4455 }
4456
4457 #[test]
4458 fn inlining_a_function_called_once_is_turned_off_and_on_by_its_own_flag() {
4459 for level in ["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz", "-Og"] {
4460 let (opts, _) = compile(&["-c", level, "-fno-inline-functions-called-once", "a.c"]);
4461 assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), false)], "{level}");
4462 let (opts, _) = compile(&["-c", level, "-finline-functions-called-once", "a.c"]);
4463 assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), true)], "{level}");
4464 }
4465 }
4466
4467 #[test]
4468 fn the_flags_that_name_a_pass_of_gccs_own_are_taken_and_dropped() {
4469 for flag in [
4470 "-fno-tree-ccp",
4471 "-fno-tree-dominator-opts",
4472 "-fno-tree-vrp",
4473 "-fno-tree-bit-ccp",
4474 "-fno-tree-coalesce-vars",
4475 "-ftree-vectorize",
4476 "-ftree-loop-distribution",
4477 "-fipa-pta",
4478 "-fmodulo-sched",
4479 "-fno-vect-cost-model",
4480 "-fvect-cost-model=unlimited",
4481 "-fsimd-cost-model=cheap",
4482 "-fexpensive-optimizations",
4483 "-fno-early-inlining",
4484 "-finline-functions",
4485 "-foptimize-strlen",
4486 "-fno-ira-share-spill-slots",
4487 ] {
4488 let (opts, _) = compile(&["-c", flag, "a.c"]);
4489 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4490 assert!(opts.passes.is_empty(), "{flag} named a pass of gcc's and not one of ours");
4491 }
4492 }
4493
4494 /// The two namespaces are taken whole, so a name neither this test nor gcc 16 has heard of
4495 /// goes the same way as the ones above rather than stopping a build on the day gcc adds it.
4496 #[test]
4497 fn a_pass_name_in_either_family_is_taken_whether_or_not_it_is_one_gcc_has() {
4498 for flag in ["-ftree-no-such-pass", "-fno-ipa-no-such-pass"] {
4499 let (opts, _) = compile(&["-c", flag, "a.c"]);
4500 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4501 }
4502 }
4503
4504 /// A pass this compiler has keeps its flag, since the arms that read the registry are above
4505 /// the family arms. `dce` is the one both compilers have a name for, and `execute/pr97421-2.c`
4506 /// is the program that writes it.
4507 #[test]
4508 fn a_pass_name_this_compiler_has_is_still_read_as_a_pass() {
4509 let (opts, _) = compile(&["-c", "-fno-dce", "a.c"]);
4510 assert_eq!(opts.passes, vec![("dce".to_owned(), false)]);
4511 }
4512
4513 /// gcc's name for the unroller reaches the unroller, in both directions. libtommath puts
4514 /// `-funroll-loops` in `CFLAGS` unconditionally, and before this it was an unknown option and
4515 /// the build stopped on its first file.
4516 #[test]
4517 fn the_gcc_spelling_of_the_unroller_turns_the_unroller_on_and_off() {
4518 let (opts, _) = compile(&["-c", "-funroll-loops", "a.c"]);
4519 assert_eq!(opts.passes, vec![("unroll".to_owned(), true)]);
4520 let (opts, _) = compile(&["-c", "-fno-unroll-loops", "a.c"]);
4521 assert_eq!(opts.passes, vec![("unroll".to_owned(), false)]);
4522 }
4523
4524 /// The three transformations that are a module at a time are named by a flag as well, even
4525 /// though none of them is a `rucc_opt::Pass` and so none is reached by the generic arms.
4526 ///
4527 /// A bisection over a miscompilation turns one thing off at a time, and a transformation with
4528 /// no spelling of its own cannot be the one turned off.
4529 #[test]
4530 fn the_transformations_that_are_not_passes_are_still_named_by_a_flag() {
4531 let (opts, _) = compile(&["-c", "-fno-ipa-cp", "-fipa-sra", "-fno-libcall", "a.c"]);
4532 assert_eq!(
4533 opts.passes,
4534 vec![
4535 (rucc_opt::ipcp::NAME.to_owned(), false),
4536 (rucc_opt::ipasra::NAME.to_owned(), true),
4537 (rucc_opt::libcall::NAME.to_owned(), false),
4538 ]
4539 );
4540 let (opts, _) = compile(&["-c", "-flibcall", "a.c"]);
4541 assert_eq!(opts.passes, vec![(rucc_opt::libcall::NAME.to_owned(), true)]);
4542 }
4543
4544 /// Where a function starts is a question this compiler answers, so the flag that asks about it
4545 /// is answered rather than dropped. femtolisp's Makefile writes the bare form on every compile
4546 /// of the project, and before this it was an unknown option and the build stopped on its first
4547 /// file. The numbers are gcc 16's, read off `-S` on x86-64: nothing and the bare form both
4548 /// give `.p2align 4`, `=32` gives 5, `=3` gives 2, and the negative form gives `.align 8`.
4549 #[test]
4550 fn the_alignment_of_a_function_is_a_request_this_compiler_can_answer() {
4551 let (opts, _) = compile(&["-c", "-falign-functions", "a.c"]);
4552 assert_eq!(opts.align_functions, None, "the bare form asks for the default");
4553
4554 let (opts, _) = compile(&["-c", "-falign-functions=32", "a.c"]);
4555 assert_eq!(opts.align_functions, Some(32));
4556
4557 let (opts, _) = compile(&["-c", "-falign-functions=3", "a.c"]);
4558 assert_eq!(opts.align_functions, Some(4), "rounded up rather than refused");
4559
4560 let (opts, _) = compile(&["-c", "-falign-functions=32:8", "a.c"]);
4561 assert_eq!(opts.align_functions, Some(32), "the boundary is the answerable half");
4562
4563 for flag in ["-falign-functions=0", "-falign-functions=1"] {
4564 let (opts, _) = compile(&["-c", flag, "a.c"]);
4565 assert_eq!(opts.align_functions, None, "{flag} means the default");
4566 }
4567
4568 let (opts, _) = compile(&["-c", "-fno-align-functions", "a.c"]);
4569 assert_eq!(opts.align_functions, Some(8), "the smallest boundary the target has");
4570
4571 // The last one on the line wins, which is how gcc reads a repeated flag.
4572 let (opts, _) = compile(&["-c", "-falign-functions=32", "-falign-functions", "a.c"]);
4573 assert_eq!(opts.align_functions, None);
4574
4575 let e = parse_args(&args(&["-c", "-falign-functions=big", "a.c"])).unwrap_err();
4576 assert!(e.message.contains("number of bytes"), "{}", e.message);
4577 }
4578
4579 /// The other three of the family are about padding inside a body, so none of them is about
4580 /// where a function starts. Every spelling of each, since a build writes whichever one its
4581 /// author typed.
4582 #[test]
4583 fn the_alignment_flags_about_the_inside_of_a_body_are_taken_and_say_nothing() {
4584 for flag in [
4585 "-falign-labels",
4586 "-falign-loops",
4587 "-falign-jumps",
4588 "-falign-loops=16",
4589 "-falign-labels=32",
4590 "-fno-align-loops",
4591 "-fno-align-labels",
4592 "-fno-align-jumps",
4593 ] {
4594 let (opts, _) = compile(&["-c", flag, "a.c"]);
4595 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4596 assert_eq!(opts.align_functions, None, "{flag} is not about where a function starts");
4597 }
4598 }
4599
4600 /// The loop flag in either direction is an answer, and a command line that wrote neither
4601 /// leaves the level to decide.
4602 #[test]
4603 fn the_loop_alignment_flag_is_answered_both_ways() {
4604 assert_eq!(compile(&["-c", "-O2", "a.c"]).0.align_loops, None);
4605 assert_eq!(compile(&["-c", "-O0", "-falign-loops", "a.c"]).0.align_loops, Some(true));
4606 assert_eq!(compile(&["-c", "-O2", "-fno-align-loops", "a.c"]).0.align_loops, Some(false));
4607 assert_eq!(compile(&["-c", "-falign-loops=32", "a.c"]).0.align_loops, None, "a number");
4608 }
4609
4610 /// The encoding of the source is not a question about speed, so the one name that describes
4611 /// what the preprocessor does is taken and every other name is refused.
4612 #[test]
4613 fn the_input_charset_is_taken_when_it_names_the_one_that_is_read() {
4614 for flag in ["-finput-charset=utf-8", "-finput-charset=UTF-8", "-finput-charset=utf8"] {
4615 let (opts, _) = compile(&["-c", flag, "a.c"]);
4616 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4617 }
4618
4619 let e = parse_args(&args(&["-c", "-finput-charset=latin1", "a.c"])).unwrap_err();
4620 assert!(e.message.contains("latin1"), "{}", e.message);
4621 assert!(e.message.contains("UTF-8"), "what is read is worth saying: {}", e.message);
4622 }
4623
4624 /// `-fnon-call-exceptions` turns exceptions on unless `-fexceptions` or `-fno-exceptions` was
4625 /// written, and the one written wins whichever side of it it is on, which is gcc 16's reading.
4626 #[test]
4627 fn exceptions_are_on_when_asked_for_and_non_call_ones_ask_unless_told_not_to() {
4628 let (opts, _) = compile(&["-c", "a.c"]);
4629 assert!(!opts.exceptions && !opts.non_call_exceptions, "gcc's default for C is off");
4630 let (opts, _) = compile(&["-c", "-fexceptions", "a.c"]);
4631 assert!(opts.exceptions && !opts.non_call_exceptions);
4632 let (opts, _) = compile(&["-c", "-fexceptions", "-fno-exceptions", "a.c"]);
4633 assert!(!opts.exceptions);
4634 let (opts, _) = compile(&["-c", "-fnon-call-exceptions", "a.c"]);
4635 assert!(opts.exceptions && opts.non_call_exceptions);
4636 for line in [
4637 ["-fno-exceptions", "-fnon-call-exceptions"],
4638 ["-fnon-call-exceptions", "-fno-exceptions"],
4639 ] {
4640 let (opts, _) = compile(&["-c", line[0], line[1], "a.c"]);
4641 assert!(!opts.exceptions && opts.non_call_exceptions, "{line:?}");
4642 }
4643 let (opts, _) =
4644 compile(&["-c", "-fnon-call-exceptions", "-fno-non-call-exceptions", "a.c"]);
4645 assert!(!opts.exceptions && !opts.non_call_exceptions);
4646 let (opts, _) = compile(&["-c", "-fno-delete-dead-exceptions", "a.c"]);
4647 assert_eq!(opts.emit, EmitKind::Object);
4648 }
4649
4650 /// `-ffast-math` used to be refused beside it and is the family it names now, with each
4651 /// member settable on its own and the last word on each winning, which is gcc's reading.
4652 #[test]
4653 fn fast_math_is_the_family_it_names_and_the_last_word_on_each_member_wins() {
4654 let both = |line: &[&str]| {
4655 let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4656 let (link, _) = linking(&[line, &["a.c"]].concat());
4657 (opts, link)
4658 };
4659 let (opts, link) = both(&[]);
4660 assert_eq!(opts.math, Math::default());
4661 assert!(opts.trapping_math);
4662 assert!(!link.fast_math);
4663
4664 let (opts, link) = both(&["-ffast-math"]);
4665 assert!(opts.math.fast(opts.trapping_math), "{:?}", opts.math);
4666 assert!(!opts.trapping_math, "fast math turns trapping off");
4667 assert!(link.fast_math, "and it links the startup file");
4668
4669 // Taking one member back leaves the rest, and the whole is not fast math any more.
4670 let (opts, link) = both(&["-ffast-math", "-fno-finite-math-only"]);
4671 assert!(!opts.math.finite_only);
4672 assert!(!opts.math.errno && !opts.math.signed_zeros && opts.math.reciprocal);
4673 assert!(!opts.math.fast(opts.trapping_math));
4674 assert!(link.fast_math, "gcc's spec reads the flag and not the fields");
4675
4676 let (opts, _) = both(&["-ffast-math", "-ftrapping-math"]);
4677 assert!(opts.trapping_math);
4678 assert!(!opts.math.fast(opts.trapping_math));
4679 assert!(!opts.math.associative(opts.trapping_math));
4680
4681 let (opts, link) = both(&["-ffast-math", "-fno-fast-math"]);
4682 assert_eq!(opts.math, Math::default());
4683 assert!(opts.trapping_math);
4684 assert!(!link.fast_math);
4685
4686 // A member written alone is only that member.
4687 let (opts, link) = both(&["-fno-math-errno"]);
4688 assert_eq!(opts.math, Math { errno: false, ..Math::default() });
4689 assert!(opts.math.iec_559(opts.trapping_math), "errno is not an IEC 60559 question");
4690 assert!(!link.fast_math);
4691
4692 let (opts, link) = both(&["-funsafe-math-optimizations"]);
4693 assert!(opts.math.unsafe_math && opts.math.associative(opts.trapping_math));
4694 assert!(opts.math.errno && !opts.math.finite_only);
4695 assert!(link.fast_math);
4696 }
4697
4698 /// `-Ofast` is `-O3` with fast math as a default, which a later level and a
4699 /// `-fno-fast-math` on either side of it both take back.
4700 #[test]
4701 fn ofast_is_o3_with_fast_math_as_a_default_a_flag_can_take_back() {
4702 let both = |line: &[&str]| {
4703 let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4704 let (link, _) = linking(&[line, &["a.c"]].concat());
4705 (opts, link)
4706 };
4707 let (opts, link) = both(&["-Ofast"]);
4708 assert_eq!(opts.opt_level, OptLevel::O3);
4709 assert!(opts.math.fast(opts.trapping_math));
4710 assert!(link.fast_math);
4711
4712 for line in [&["-Ofast", "-O2"][..], &["-fno-fast-math", "-Ofast"]] {
4713 let (opts, _) = both(line);
4714 assert!(!opts.math.fast(opts.trapping_math), "{line:?}");
4715 }
4716
4717 let (_, link) = both(&["-Ofast", "-mno-daz-ftz"]);
4718 assert_eq!(link.daz_ftz, Some(false));
4719 }
4720
4721 /// `-finstrument-functions` used to be refused beside those two, and it is taken now that the
4722 /// hooks are called. The last of it and its negative is the one that counts, as with any pair.
4723 #[test]
4724 fn instrument_functions_is_taken_and_the_last_of_the_pair_wins() {
4725 let (opts, _) = compile(&["-c", "-finstrument-functions", "a.c"]);
4726 assert!(opts.instrument_functions);
4727 let (opts, _) =
4728 compile(&["-c", "-finstrument-functions", "-fno-instrument-functions", "a.c"]);
4729 assert!(!opts.instrument_functions);
4730 }
4731
4732 #[test]
4733 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
4734 // The one of that family that is a request rather than a description, and it is a real
4735 // difference: two files each writing `int g;` link under it and do not without it.
4736 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
4737 assert!(e.message.contains(".bss"), "{}", e.message);
4738 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
4739 }
4740
4741 #[test]
4742 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
4743 for flag in ["-fno-pic", "-fno-pie"] {
4744 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
4745 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
4746 // The one it may have meant, since the two are a letter apart and one of them is
4747 // about linking and is taken.
4748 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
4749 }
4750 }
4751
4752 #[test]
4753 fn a_program_name_with_a_known_target_in_front_of_rucc_picks_that_target() {
4754 let t = |p: &str| target_from_program(p);
4755 assert_eq!(t("aarch64-linux-gnu-rucc").as_deref(), Some("aarch64-linux-gnu"));
4756 assert_eq!(t("/usr/bin/riscv64-linux-musl-rucc").as_deref(), Some("riscv64-linux-musl"));
4757 assert_eq!(t(r"C:\bin\x86_64-windows-gnu-rucc.exe").as_deref(), Some("x86_64-windows-gnu"));
4758 assert_eq!(t("rucc"), None);
4759 assert_eq!(t("/usr/local/bin/rucc"), None);
4760 assert_eq!(t("my-rucc"), None);
4761 assert_eq!(t("sparc64-linux-gnu-rucc"), None);
4762 assert_eq!(t("aarch64-linux-gnu-gcc"), None);
4763 }
4764
4765 #[test]
4766 fn an_unsupported_target_names_itself() {
4767 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
4768 assert!(e.message.contains("sparc64"), "{}", e.message);
4769 }
4770
4771 #[test]
4772 fn no_inputs_is_an_error_but_print_config_needs_none() {
4773 assert!(parse_args(&args(&[])).is_err());
4774 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
4775 }
4776
4777 #[test]
4778 fn print_config_reports_the_target_it_was_given_not_the_host() {
4779 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
4780 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
4781 let text = print_config(&opts);
4782 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
4783 assert!(text.contains("char-signed: false"), "{text}");
4784 assert!(text.contains("object-format: elf"), "{text}");
4785 assert!(text.contains("va-list: void-pointer"), "{text}");
4786 // RISC-V has a register file and this compiler has not written it down yet, and the
4787 // dump says which of those two it is rather than leaving the line out.
4788 assert!(text.contains("registers: none"), "{text}");
4789 assert!(text.contains("timing-model: none"), "{text}");
4790 }
4791
4792 /// The model the schedule was chosen with, which is a receipt anybody comparing two runs of a
4793 /// benchmark needs: two numbers that disagree are usually two models and not two compilers.
4794 #[test]
4795 fn print_config_names_the_model_the_schedule_was_chosen_with() {
4796 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4797 let text = print_config(&opts);
4798 let line = text.lines().find(|l| l.starts_with("timing-model:")).expect("the model");
4799 assert!(line.contains("Skylake"), "{line}");
4800 assert!(line.contains("published"), "a sentence saying where it came from: {line}");
4801 }
4802
4803 #[test]
4804 fn print_config_has_one_key_per_line_and_a_fixed_order() {
4805 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4806 let text = print_config(&opts);
4807 let keys: Vec<&str> =
4808 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
4809 assert_eq!(keys[0], "version");
4810 assert_eq!(keys[1], "target");
4811 assert_eq!(keys.len(), 26);
4812 assert!(text.ends_with('\n'));
4813 }
4814
4815 #[test]
4816 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4817 let (opts, _) = compile(&["a.c"]);
4818 assert_eq!(opts.safety, rucc_session::Safety::Off);
4819
4820 for (flag, tier) in [
4821 ("-fsafety=detect", rucc_session::Safety::Detect),
4822 ("-fsafety=enforce", rucc_session::Safety::Enforce),
4823 ("-fsafety=kernel", rucc_session::Safety::Kernel),
4824 ("-fsafety=off", rucc_session::Safety::Off),
4825 ] {
4826 let (opts, _) = compile(&[flag, "a.c"]);
4827 assert_eq!(opts.safety, tier, "{flag}");
4828 }
4829
4830 // The last one wins, the way every other repeated flag on this command line does.
4831 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
4832 assert_eq!(opts.safety, rucc_session::Safety::Off);
4833
4834 // A misspelled tier is refused rather than ignored. Silently compiling without the
4835 // monitor a build asked for is the one failure mode this feature cannot have.
4836 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
4837 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
4838 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
4839 }
4840
4841 #[test]
4842 fn the_padding_mode_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4843 // The default is the one section 9.3 of document 09 gives library code, which is that
4844 // padding does not participate, so a record filled a member at a time is not reported.
4845 let (opts, _) = compile(&["a.c"]);
4846 assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4847
4848 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-init=padding", "a.c"]);
4849 assert_eq!(opts.padding, rucc_session::Padding::Tracked);
4850
4851 let (opts, _) = compile(&["-fsafety-init=padding", "-fsafety-init=nopadding", "a.c"]);
4852 assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4853
4854 // The tier is still a tier. A flag whose name starts the same way must not be eaten by
4855 // the one above it, which is the thing worth pinning about a pair of names like these.
4856 let (opts, _) = compile(&["-fsafety-init=padding", "a.c"]);
4857 assert_eq!(opts.safety, rucc_session::Safety::Off);
4858
4859 let e = parse_args(&args(&["-fsafety-init=some", "a.c"])).unwrap_err();
4860 assert!(e.message.contains("is not a padding mode"), "{}", e.message);
4861 }
4862
4863 #[test]
4864 fn whether_a_write_has_to_stay_inside_its_member_is_read_off_the_command_line() {
4865 // Off by default, because a store to allocated storage sets its effective type and C 6.5
4866 // lets a program reuse a buffer as something else. Row S4 is a build opting out of that.
4867 let (opts, _) = compile(&["a.c"]);
4868 assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4869
4870 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-subobject", "a.c"]);
4871 assert_eq!(opts.subobject, rucc_session::Subobject::Members);
4872
4873 let (opts, _) = compile(&["-fsafety-subobject", "-fno-safety-subobject", "a.c"]);
4874 assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4875
4876 // It takes no value. The form that would take one is the strict reading of section 9.4,
4877 // which is not written yet, so say so rather than accept a spelling that does nothing.
4878 let e = parse_args(&args(&["-fsafety-subobject=strict", "a.c"])).unwrap_err();
4879 assert!(e.message.contains("tamnd/rucc#967"), "{}", e.message);
4880 }
4881
4882 #[test]
4883 fn whether_two_restrict_pointers_may_meet_is_read_off_the_command_line() {
4884 // Off by default, because the record a block keeps is the union of what each pointer
4885 // reached, so two pointers striding through one array without landing on the same byte are
4886 // reported and by the letter of the standard those are different objects. Row Y8 is a build
4887 // deciding it would rather know.
4888 let (opts, _) = compile(&["a.c"]);
4889 assert_eq!(opts.promise, rucc_session::Promise::Off);
4890
4891 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-restrict", "a.c"]);
4892 assert_eq!(opts.promise, rucc_session::Promise::Blocks);
4893
4894 let (opts, _) = compile(&["-fsafety-restrict", "-fno-safety-restrict", "a.c"]);
4895 assert_eq!(opts.promise, rucc_session::Promise::Off);
4896
4897 // The tier is still a tier, which is the thing worth pinning about a pair of names where
4898 // one is the front of the other.
4899 let (opts, _) = compile(&["-fsafety-restrict", "a.c"]);
4900 assert_eq!(opts.safety, rucc_session::Safety::Off);
4901
4902 let e = parse_args(&args(&["-fsafety-restrict=blocks", "a.c"])).unwrap_err();
4903 assert!(e.message.contains("takes no value"), "{}", e.message);
4904 }
4905
4906 #[test]
4907 fn safety_races_takes_a_mode_and_defaults_to_watching_nothing() {
4908 // Three modes rather than a bare flag, because section 9.5 gives two answers that record
4909 // the same thing and report different classes, so a flag with no value could not say which
4910 // was wanted. Off by default for the reason on `rucc_session::Races`, which is not a cost
4911 // argument: this is the one plane where an edge nobody interposed costs a false report.
4912 let (opts, _) = compile(&["a.c"]);
4913 assert_eq!(opts.races, rucc_session::Races::Off);
4914
4915 let (opts, _) = compile(&["-fsafety-races=metadata", "a.c"]);
4916 assert_eq!(opts.races, rucc_session::Races::Metadata);
4917
4918 let (opts, _) = compile(&["-fsafety-races=pointer", "a.c"]);
4919 assert_eq!(opts.races, rucc_session::Races::Pointer);
4920
4921 // Last one wins, as it does for every other mode flag here.
4922 let (opts, _) = compile(&["-fsafety-races=pointer", "-fno-safety-races", "a.c"]);
4923 assert_eq!(opts.races, rucc_session::Races::Off);
4924
4925 let e = parse_args(&args(&["-fsafety-races=all", "a.c"])).unwrap_err();
4926 assert!(e.message.contains("off, metadata or pointer"), "{}", e.message);
4927 }
4928
4929 #[test]
4930 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
4931 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
4932 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4933 let text = print_pipeline(&opts);
4934 assert!(text.starts_with("level: -O2\n"), "{text}");
4935 assert!(text.contains("fold"), "{text}");
4936
4937 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
4938 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4939 // Two passes run at `-O0` and neither is an optimization. The first moves what
4940 // `__builtin_expect` said onto the branch and takes the instruction away, so that nothing
4941 // past the optimizer has to know the instruction exists. The second removes code nothing
4942 // reaches. See issue 359.
4943 assert!(print_pipeline(&opts).contains("1: expect,"), "{}", print_pipeline(&opts));
4944 assert!(print_pipeline(&opts).contains("2: simplify-cfg,"), "{}", print_pipeline(&opts));
4945
4946 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
4947 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4948 // The second turns off and the first does not, because nothing below the optimizer lowers
4949 // what it removes, so `-fno-expect` is a compile that stops rather than one that runs.
4950 let text = print_pipeline(&opts);
4951 assert!(text.contains("1: expect,"), "{text}");
4952 assert!(!text.contains("simplify-cfg"), "{text}");
4953 }
4954
4955 #[test]
4956 fn print_pipeline_takes_the_toggles_into_account() {
4957 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
4958 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4959 let text = print_pipeline(&opts);
4960 // The one that was named is gone and the rest of the level is not, which is the whole
4961 // of what a toggle promises.
4962 assert!(!text.contains("fold"), "{text}");
4963 assert!(text.contains("dce"), "{text}");
4964
4965 // Every pass the compiler has, named off. Built from the registry rather than written
4966 // out, so a pass added later is turned off here too and this keeps testing the thing it
4967 // is about, which is that the toggles can empty a level down to the passes that are not
4968 // optional. Those are named, because a listing that is all of them is a level nobody
4969 // emptied and the assertion would pass while saying nothing.
4970 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
4971 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
4972 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
4973 let a = parse_args(&args(&spelled)).unwrap();
4974 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4975 let text = print_pipeline(&opts);
4976 let left: Vec<&str> =
4977 rucc_opt::PASSES.iter().filter(|p| p.required()).map(|p| p.name()).collect();
4978 assert_eq!(left, vec!["expect", "constant-p"], "{text}");
4979 for (at, name) in left.iter().enumerate() {
4980 assert!(text.contains(&format!("{}: {name},", at + 1)), "{text}");
4981 }
4982 assert!(!text.contains("dce"), "{text}");
4983 }
4984
4985 #[test]
4986 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
4987 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
4988 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4989 assert!(!print_pipeline(&opts).contains("global fuel"));
4990
4991 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
4992 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4993 let text = print_pipeline(&opts);
4994 // Because the listing is the answer to what this compilation will do, and a run that
4995 // stops after four rewrites is not doing what the level says it does.
4996 assert!(text.contains("global fuel: 4"), "{text}");
4997 }
4998
4999 /// A pass is turned on and off by its own name, and the order the flags were given in is
5000 /// kept, because the last spelling of a name is the one that decides.
5001 #[test]
5002 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
5003 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
5004 assert_eq!(
5005 opts.passes,
5006 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
5007 );
5008
5009 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
5010 assert!(e.message.contains("unknown option"), "{}", e.message);
5011 }
5012
5013 #[test]
5014 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
5015 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
5016 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
5017
5018 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
5019 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
5020 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
5021 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
5022 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
5023 assert!(e.message.contains("not a number"), "{}", e.message);
5024 }
5025
5026 #[test]
5027 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
5028 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
5029 assert_eq!(opts.pass_fuel_global, None);
5030
5031 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
5032 assert_eq!(opts.pass_fuel_global, Some(12));
5033 // And it is not the per pass flag with a longer name, so neither spelling swallows the
5034 // other.
5035 assert!(opts.pass_fuel.is_empty());
5036
5037 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
5038 assert!(e.message.contains("not a number"), "{}", e.message);
5039 }
5040
5041 #[test]
5042 fn the_trace_file_is_taken_from_the_flag_and_an_empty_one_is_refused() {
5043 let (opts, _) = compile(&["-c", "a.c"]);
5044 assert_eq!(opts.trace, None);
5045 let (opts, _) = compile(&["-c", "-frucc-trace=/tmp/compile.jsonl", "a.c"]);
5046 assert_eq!(opts.trace.as_deref(), Some("/tmp/compile.jsonl"));
5047 let e = parse_args(&args(&["-frucc-trace=", "a.c"])).unwrap_err();
5048 assert!(e.message.contains("needs a file"), "{}", e.message);
5049 }
5050
5051 #[test]
5052 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
5053 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
5054 assert_eq!(
5055 opts.pass_gates,
5056 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
5057 "the order is what decides, so it has to survive the parse"
5058 );
5059
5060 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
5061 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
5062 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
5063 assert!(e.message.contains("ends before it starts"), "{}", e.message);
5064 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
5065 assert!(e.message.contains("is empty"), "{}", e.message);
5066 }
5067
5068 #[test]
5069 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
5070 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
5071 let text = print_pipeline(&opts);
5072 assert!(text.contains("fold, "), "{text}");
5073 assert!(text.contains("[off for main]"), "{text}");
5074 }
5075
5076 /// The spelling is checked while the arguments are read, because a dump that names a pass
5077 /// this compiler does not have is a typo, and a typo found after the compilation has run is
5078 /// found too late to be any use.
5079 #[test]
5080 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
5081 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
5082 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
5083
5084 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
5085 assert!(e.message.contains("nosuch"), "{}", e.message);
5086 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
5087 }
5088
5089 /// Every spelling `-fopt-info` takes, and the one it does not.
5090 ///
5091 /// The keywords are checked here for the same reason a dump's pass name is: a person who
5092 /// misspelled one gets no output, and no output is also what a compilation where nothing
5093 /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
5094 #[test]
5095 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
5096 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
5097 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
5098 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
5099
5100 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
5101 assert_eq!(opts.opt_info, ["missed-note"]);
5102
5103 // Two flags add up rather than the second replacing the first, and the file is the last
5104 // one that named a file, which is how GCC treats both.
5105 let (opts, _) =
5106 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
5107 assert_eq!(opts.opt_info, ["missed", "all"]);
5108 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
5109
5110 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
5111 assert!(e.message.contains("vectorized"), "{}", e.message);
5112 assert!(e.message.contains("`missed`"), "{}", e.message);
5113 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
5114 assert!(e.message.contains("no file"), "{}", e.message);
5115 }
5116
5117 #[test]
5118 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
5119 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
5120 assert!(opts.verify_each);
5121 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
5122 }
5123
5124 #[test]
5125 fn dash_o_needs_an_argument() {
5126 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
5127 assert_eq!(e.message, "-o requires an argument");
5128 }
5129
5130 #[test]
5131 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
5132 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
5133 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
5134 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
5135 }
5136
5137 #[test]
5138 fn the_include_flags_land_on_the_chain_each_one_names() {
5139 // A sysroot with nothing under it, so that the library's own directories are the
5140 // same on every machine this test runs on, which is none of them.
5141 let (opts, _) = compile(&[
5142 "-Ii",
5143 "-iquote",
5144 "q",
5145 "-isystem",
5146 "sys",
5147 "-idirafter",
5148 "after",
5149 "--sysroot=/nowhere-at-all",
5150 "a.c",
5151 ]);
5152 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5153 // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
5154 // which is where GCC puts its own: a directory the user named outranks ours.
5155 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
5156 assert!(!opts.search.dirs()[1].is_system);
5157 assert!(opts.search.dirs()[2].is_system);
5158 }
5159
5160 #[test]
5161 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
5162 // Which machine this runs on decides what is on the path, so the test is about the
5163 // order rather than about the names: ours is on it, the library's follow it, and
5164 // `-nostdinc` is the one flag that takes both halves of the pair off at once.
5165 let (opts, _) = compile(&["a.c"]);
5166 let dirs = opts.search.dirs();
5167 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
5168 assert_eq!(ours, Some(0), "{dirs:?}");
5169 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
5170 let (bare, _) = compile(&["-nostdinc", "a.c"]);
5171 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
5172 }
5173
5174 #[test]
5175 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
5176 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
5177 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5178 assert_eq!(dirs, ["sys", runtime::DIR]);
5179 }
5180
5181 #[test]
5182 fn a_cross_compile_reads_the_targets_own_headers_rather_than_the_ones_next_door() {
5183 // The target is not the machine this test runs on wherever it runs, so the answer is the
5184 // same on all of them: the libc's two include directories for that target, the kernel's
5185 // two, and nothing from here. A header read from here is the quiet failure of section 8.5, a
5186 // program that builds on the build machine and is wrong everywhere else.
5187 let (opts, _) = compile(&["--target=riscv64-linux-musl", "-c", "a.c"]);
5188 let dirs: Vec<&std::path::Path> =
5189 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5190 let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
5191 let kernel = cache::dir().join("kernel-headers");
5192 assert_eq!(dirs.len(), 5, "{dirs:?}");
5193 assert_eq!(dirs[0], std::path::Path::new(runtime::DIR));
5194 assert_eq!(dirs[1], root.join("include").join("riscv64"));
5195 assert_eq!(dirs[2], root.join("include").join("generic"));
5196 // The kernel's, which are beside the sysroots rather than inside one, because every target
5197 // that shares an architecture reads the same files.
5198 assert_eq!(dirs[3], kernel.join("riscv"));
5199 assert_eq!(dirs[4], kernel.join("generic"));
5200 }
5201
5202 #[test]
5203 fn a_cross_compile_to_something_that_is_not_linux_reads_no_kernel_headers() {
5204 // The other side of the same answer. Windows has its own system headers and no `linux/` at
5205 // all, so the list is the libc's own and the question never arises, which is the `None` that
5206 // `link::cross_kernel` returns rather than a directory nothing would be found in.
5207 //
5208 // The libc's own is one directory rather than two here, because mingw-w64 publishes a single
5209 // header tree for every architecture and `Sysroot::splits_by_arch` says so.
5210 let (opts, _) = compile(&["--target=x86_64-pc-windows-gnu", "-c", "a.c"]);
5211 let dirs: Vec<&std::path::Path> =
5212 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5213 assert_eq!(dirs.len(), 2, "{dirs:?}");
5214 assert!(!dirs.iter().any(|dir| dir.ends_with("kernel-headers")), "{dirs:?}");
5215 }
5216
5217 #[test]
5218 fn the_glibc_version_macro_goes_with_the_bundled_tree_and_with_nothing_else() {
5219 // One tree serves every glibc release, so the release is what the target supplies, and the
5220 // condition is the same one that chose the directories. A host glibc and a tree somebody
5221 // named both define `__GLIBC_MINOR__` in their own `features.h`, and two definitions with
5222 // different values is a warning on every compilation of every file.
5223 //
5224 // The architecture is chosen against this machine's rather than written down, because the
5225 // bundled tree is only in effect for a target that is not this machine. The first version of
5226 // this test said x86_64-linux-gnu, which is a cross compile on a mac and this machine on a
5227 // Linux runner, so it passed here and failed there.
5228 //
5229 // Unless this machine has the distribution's cross packages for it and nothing fetched, and
5230 // then those are the headers and their own `features.h` says the release, as it does for a
5231 // tree somebody named.
5232 let gnu = format!("--target={}-linux-gnu", cross_arch());
5233 let (bundled, _) = compile(&[&gnu, "-c", "a.c"]);
5234 let (link, _) = linking(&[&gnu, "-c", "a.c"]);
5235 let distro = link::distro_cross(bundled.target, &link).is_some();
5236 assert_eq!(bundled.glibc_minor, if distro { None } else { Some(44) });
5237 let pin = format!("{gnu}.2.28");
5238 let (pinned, _) = compile(&[&pin, "-c", "a.c"]);
5239 assert_eq!(pinned.glibc_minor, Some(28));
5240
5241 let (named, _) = compile(&[&gnu, "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5242 assert_eq!(named.glibc_minor, None);
5243 let (none, _) = compile(&[&gnu, "-nostdinc", "-c", "a.c"]);
5244 assert_eq!(none.glibc_minor, None);
5245 let musl = format!("--target={}-linux-musl", cross_arch());
5246 let (musl, _) = compile(&[&musl, "-c", "a.c"]);
5247 assert_eq!(musl.glibc_minor, None);
5248
5249 // And this machine's own target gets nothing, whatever this machine is, because its headers
5250 // come from the machine and its own `features.h` defines the macro. On a glibc Linux box
5251 // that is the case this test had backwards; on a mac it is true for the other reason, which
5252 // is that Darwin is not a glibc target at all.
5253 if let Some(host) = Triple::host() {
5254 let native = format!("--target={}", host.tuple());
5255 let (native, _) = compile(&[&native, "-c", "a.c"]);
5256 assert_eq!(native.glibc_minor, None);
5257 }
5258 }
5259
5260 #[test]
5261 fn a_pinned_release_on_this_machines_own_target_reads_the_bundled_tree() {
5262 // The end to end half of the answer in `link::cross_for`. A release named for this machine's
5263 // own target is a cross compile, so the headers are the bundled tree's and the macro says
5264 // what was asked for rather than what this machine has.
5265 //
5266 // Only on a glibc box, because a release is a glibc release: a mac has no `__GLIBC_MINOR__`
5267 // to get wrong and nothing to pin. That makes this a test the Linux runners carry, which is
5268 // where the case lives.
5269 let Some(host) = Triple::host() else { return };
5270 if host.env != rucc_target::Env::Gnu {
5271 return;
5272 }
5273 let pin = format!("--target={}.2.28", host.tuple());
5274 let (opts, _) = compile(&[&pin, "-c", "a.c"]);
5275 assert_eq!(opts.glibc_minor, Some(28));
5276 let root = cache::dir().join("sysroots").join(format!("{}.2.28", host.tuple()));
5277 let dirs: Vec<&std::path::Path> =
5278 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5279 assert!(dirs.iter().any(|dir| dir.starts_with(&root)), "{dirs:?}");
5280 // And nothing of this machine's, which is the failure this was: a program compiled against
5281 // 2.44 declarations and told it was 2.28.
5282 assert!(!dirs.iter().any(|dir| *dir == std::path::Path::new("/usr/include")), "{dirs:?}");
5283 }
5284
5285 /// An architecture that is not this machine's, out of the three the driver has targets for.
5286 ///
5287 /// A test about the bundled sysroot has to name a target that is not the host, because a target
5288 /// that is the host reads the host's own headers and libraries. Asking which machine this is
5289 /// beats picking a row and hoping, and it is two lines.
5290 fn cross_arch() -> &'static str {
5291 match Triple::host().map(|host| host.arch) {
5292 Some(rucc_target::Arch::X86_64) => "aarch64",
5293 _ => "x86_64",
5294 }
5295 }
5296
5297 #[test]
5298 fn a_glibc_newer_than_the_bundled_tree_is_refused_by_name() {
5299 // Both versions in the message, because the two things a person can do about it are pin a
5300 // release the tree has and name a sysroot that has the one they asked for, and neither is a
5301 // choice they can make without knowing which release the tree is.
5302 //
5303 // Not this machine's architecture, for the reason the test above gives: the refusal is about
5304 // the bundled tree, and the bundled tree is not what a target that is this machine reads.
5305 let target = format!("--target={}-linux-gnu.2.99", cross_arch());
5306 let message = refused(&[&target, "-c", "a.c"]);
5307 assert!(message.contains("asked for glibc 2.99"), "{message}");
5308 assert!(message.contains("bundled headers are glibc 2.44"), "{message}");
5309 assert!(message.contains("--sysroot"), "{message}");
5310 }
5311
5312 #[test]
5313 fn a_sysroot_the_user_named_is_still_what_a_cross_compile_reads() {
5314 // The tree somebody assembled beats the one we would build, on the headers as on the
5315 // libraries. It is empty here, which is why the list comes out short: the directories under
5316 // it are checked for rather than assumed, and a tree that is not there offers nothing.
5317 let (opts, _) =
5318 compile(&["--target=riscv64-linux-musl", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5319 let dirs: Vec<&std::path::Path> =
5320 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5321 assert_eq!(dirs, [std::path::Path::new(runtime::DIR)]);
5322 }
5323
5324 #[test]
5325 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
5326 let (opts, _) =
5327 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
5328 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5329 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
5330 // An angled include sees only what came after the flag.
5331 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
5332 assert!(!opts.search.searches_current_dir());
5333 }
5334
5335 #[test]
5336 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
5337 let (opts, _) = compile(&[
5338 "-iprefix",
5339 "/tools/",
5340 "-iwithprefix",
5341 "late",
5342 "-iwithprefixbefore",
5343 "early",
5344 "-iprefix",
5345 "/other/",
5346 "-iwithprefix",
5347 "last",
5348 "-nostdinc",
5349 "a.c",
5350 ]);
5351 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5352 // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
5353 // puts them rather than where its manual says it does.
5354 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
5355 assert!(!opts.search.dirs()[0].is_system);
5356 assert!(opts.search.dirs()[1].is_system);
5357 }
5358
5359 #[test]
5360 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
5361 let (opts, _) =
5362 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
5363 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
5364 assert_eq!(names, ["one.h", "two.h", "3.h"]);
5365 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
5366 }
5367
5368 #[test]
5369 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
5370 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
5371 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5372 assert_eq!(dirs, ["i"]);
5373 }
5374
5375 #[test]
5376 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
5377 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
5378 assert_eq!(opts.std, Std::C11);
5379 assert!(opts.gnu_extensions);
5380
5381 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
5382 assert_eq!(opts.std, Std::C99);
5383 assert!(!opts.gnu_extensions);
5384
5385 let (opts, _) = compile(&["-ansi", "a.c"]);
5386 assert_eq!(opts.std, Std::C89);
5387 assert!(!opts.gnu_extensions);
5388
5389 let (opts, _) = compile(&["-std=gnu2y", "a.c"]);
5390 assert_eq!(opts.std, Std::C2y);
5391 assert!(opts.gnu_extensions);
5392
5393 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
5394 assert!(e.message.contains("unknown dialect"), "{}", e.message);
5395 }
5396
5397 #[test]
5398 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
5399 let (opts, _) = compile(&["-dM", "a.c"]);
5400 assert!(opts.dumps.macros);
5401
5402 // Packed, the way GCC takes them, and a letter in the family we have not written yet
5403 // is accepted and does nothing rather than failing a build.
5404 let (opts, _) = compile(&["-dDM", "a.c"]);
5405 assert!(opts.dumps.macros);
5406 let (opts, _) = compile(&["-dD", "a.c"]);
5407 assert!(!opts.dumps.macros);
5408
5409 let (opts, _) = compile(&["a.c"]);
5410 assert!(!opts.dumps.any());
5411
5412 // `-dumpversion` is a different flag that happens to start the same way, and it is read
5413 // as itself rather than as a dump of nothing.
5414 assert_eq!(printed(&["-dumpversion", "a.c"]), "16");
5415 }
5416
5417 #[test]
5418 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
5419 let (opts, _) = compile(&["a.c"]);
5420 assert_eq!(
5421 opts.gnuc,
5422 GnucVersion { major: 16, minor: 0, patch: 0 },
5423 "the release this compiler is written against, and the earliest one of that series"
5424 );
5425
5426 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
5427 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
5428
5429 // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
5430 // patchlevel and a harness that pastes that back has to be understood.
5431 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
5432 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
5433
5434 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
5435 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
5436
5437 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
5438 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
5439
5440 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
5441 assert!(e.message.contains("more than three"), "{}", e.message);
5442 }
5443
5444 #[test]
5445 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
5446 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
5447 assert!(opts.pedantic);
5448 assert_eq!(opts.std, Std::C17);
5449
5450 // The `-W` family's name for it, which is what a build that groups its warning flags
5451 // tends to write.
5452 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
5453 assert!(opts.pedantic);
5454
5455 let (opts, _) = compile(&["-std=c17", "a.c"]);
5456 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
5457 }
5458
5459 #[test]
5460 fn dash_p_and_dash_ffreestanding_reach_the_options() {
5461 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
5462 assert!(!opts.line_markers);
5463 assert!(!opts.hosted);
5464 assert_eq!(opts.emit, EmitKind::Preprocessed);
5465 }
5466
5467 /// The two ways a build says it means its own function by a name the C library also has.
5468 ///
5469 /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
5470 /// build writes when it means its own `memcpy` and the library's everything else. The name is
5471 /// kept as it was written and not checked against anything, because a program is allowed to
5472 /// mean something by a name this compiler has never heard of.
5473 #[test]
5474 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
5475 let (opts, _) = compile(&["-c", "a.c"]);
5476 assert!(opts.builtins, "a library name means the library function by default");
5477 assert!(opts.no_builtin.is_empty());
5478
5479 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
5480 assert!(!opts.builtins);
5481
5482 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
5483 assert!(opts.builtins, "the last mention decides");
5484
5485 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
5486 assert!(opts.builtins, "one name is not the family");
5487 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
5488 }
5489
5490 /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
5491 /// and which was refused as an unknown option until now.
5492 ///
5493 /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
5494 /// the address across a component boundary, and nothing derives anything from that promise
5495 /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
5496 /// over a distinction this compiler does not make.
5497 #[test]
5498 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
5499 let (opts, _) = compile(&["-c", "a.c"]);
5500 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
5501
5502 for (written, wanted) in [
5503 ("default", Visibility::Default),
5504 ("hidden", Visibility::Hidden),
5505 ("internal", Visibility::Hidden),
5506 ("protected", Visibility::Protected),
5507 ] {
5508 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
5509 assert_eq!(opts.visibility, wanted, "{written}");
5510 }
5511
5512 // The last mention decides, which is what every other flag of this shape does and what a
5513 // build that turns something off for one directory relies on.
5514 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
5515 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
5516
5517 // A spelling gcc does not take is refused rather than read as the default, because a
5518 // build that meant hidden and got exported is a library with the wrong interface and
5519 // nothing said about it anywhere.
5520 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
5521 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
5522 }
5523
5524 /// `-ffp-contract=`, which is the one flag in the floating point group that is kept rather than
5525 /// described, and the values are gcc 16's three.
5526 #[test]
5527 fn how_far_a_multiply_and_an_addition_may_be_fused_is_asked_for() {
5528 let (opts, _) = compile(&["-c", "a.c"]);
5529 assert_eq!(opts.fp_contract, Contract::Off, "a licence nobody granted is not assumed");
5530
5531 for (written, wanted) in
5532 [("off", Contract::Off), ("on", Contract::On), ("fast", Contract::Fast)]
5533 {
5534 let (opts, _) = compile(&["-c", &format!("-ffp-contract={written}"), "a.c"]);
5535 assert_eq!(opts.fp_contract, wanted, "{written}");
5536 }
5537
5538 let (opts, _) = compile(&["-c", "-ffp-contract=fast", "-ffp-contract=off", "a.c"]);
5539 assert_eq!(opts.fp_contract, Contract::Off, "the last mention decides");
5540
5541 // Refused rather than read as one of the three, because a build that asked for no fusing
5542 // and was given the default would be one whose numbers change and whose command line says
5543 // they should not. gcc refuses the same spellings and names the same three in its message.
5544 for bad in ["-ffp-contract=none", "-ffp-contract=", "-ffp-contract=Fast"] {
5545 let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5546 assert!(failed.to_string().contains("is not a contraction"), "{bad}: {failed}");
5547 }
5548
5549 // And the other one that takes a value, which is taken and kept nowhere: every operation
5550 // here is computed in the type it was written in, so `standard` is what happens and the
5551 // other two are permission to do something this does not do.
5552 let failed = parse_args(&args(&["-fexcess-precision=long", "a.c"])).expect_err("refused");
5553 assert!(failed.to_string().contains("is not an excess precision"), "{failed}");
5554 }
5555
5556 /// The four prefix mapping flags, which are what a distribution passes to get the same bytes
5557 /// out of `/build/pkg-1.2` and out of `/home/someone/pkg-1.2`. Three lists rather than one
5558 /// because gcc has three, and `-ffile-prefix-map=` is the three of them at once.
5559 #[test]
5560 fn a_prefix_mapping_flag_goes_on_the_list_its_spelling_names() {
5561 let (opts, _) = compile(&["-c", "a.c"]);
5562 assert!(opts.prefix_map.macros.is_empty(), "nothing is rewritten unless it is asked for");
5563 assert!(opts.prefix_map.debug.is_empty(), "nor here");
5564 assert!(opts.prefix_map.profile.is_empty(), "nor here");
5565
5566 let (opts, _) = compile(&["-c", "-fmacro-prefix-map=/build=.", "a.c"]);
5567 assert_eq!(opts.prefix_map.macros.apply("/build/a.c"), "./a.c", "the one it names");
5568 assert!(opts.prefix_map.debug.is_empty(), "and not the two it does not");
5569
5570 let (opts, _) = compile(&["-c", "-fdebug-prefix-map=/build=.", "a.c"]);
5571 assert_eq!(opts.prefix_map.debug.apply("/build/a.c"), "./a.c", "the one it names");
5572 assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5573
5574 let (opts, _) = compile(&["-c", "-fprofile-prefix-map=/build=.", "a.c"]);
5575 assert_eq!(opts.prefix_map.profile.apply("/build/a.c"), "./a.c", "the one it names");
5576 assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5577
5578 let (opts, _) = compile(&["-c", "-ffile-prefix-map=/build=.", "a.c"]);
5579 for list in [&opts.prefix_map.macros, &opts.prefix_map.debug, &opts.prefix_map.profile] {
5580 assert_eq!(list.apply("/build/a.c"), "./a.c", "all three at once");
5581 }
5582
5583 // Every mention is kept and the last one that matches wins, unlike the flags above whose
5584 // last mention replaces the earlier ones. A build writes one of these per source root and
5585 // expects all of them to be in force, which is the whole point of a list.
5586 let (opts, _) =
5587 compile(&["-c", "-ffile-prefix-map=/a=one", "-ffile-prefix-map=/b=two", "a.c"]);
5588 assert_eq!(opts.prefix_map.macros.apply("/a/x.c"), "one/x.c", "the earlier one still acts");
5589 assert_eq!(opts.prefix_map.macros.apply("/b/x.c"), "two/x.c", "and so does the later one");
5590
5591 // An argument with no `=` is refused rather than ignored, because a build whose paths were
5592 // meant to be rewritten and were not is one that ships the build directory's name and says
5593 // nothing about it. gcc refuses the same thing.
5594 for bad in ["-fmacro-prefix-map=nope", "-ffile-prefix-map=", "-fdebug-prefix-map=/build"] {
5595 let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5596 assert!(failed.to_string().contains("is not a rewrite for"), "{bad}: {failed}");
5597 }
5598 }
5599
5600 /// `-ffunction-sections` and `-fdata-sections`, which are what make `--gc-sections` able to
5601 /// drop anything: a linker can leave out a section nothing reaches and cannot leave out half of
5602 /// one. A kernel and an embedded image are both linked that way.
5603 ///
5604 /// Two flags rather than one because gcc has two, and a build that asks for one of them and not
5605 /// the other is a build that measured something: splitting the code is nearly free at link time
5606 /// and splitting the data can defeat the linker's ordering of what is next to what.
5607 #[test]
5608 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
5609 let (opts, _) = compile(&["-c", "a.c"]);
5610 assert!(!opts.function_sections, "one text section unless something says otherwise");
5611 assert!(!opts.data_sections);
5612
5613 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
5614 assert!(opts.function_sections);
5615 assert!(!opts.data_sections, "one flag is not the other");
5616
5617 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
5618 assert!(opts.data_sections);
5619 assert!(!opts.function_sections);
5620
5621 // Both directions taken, and the off one is what happens anyway rather than a refusal,
5622 // since a build that writes it is asking for the default.
5623 let (opts, _) = compile(&[
5624 "-c",
5625 "-ffunction-sections",
5626 "-fno-function-sections",
5627 "-fdata-sections",
5628 "-fno-data-sections",
5629 "a.c",
5630 ]);
5631 assert!(!opts.function_sections, "the last mention decides");
5632 assert!(!opts.data_sections, "the last mention decides");
5633 }
5634
5635 /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
5636 /// line, since the dialect asks for GNU's reading further in rather than through this.
5637 #[test]
5638 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
5639 let (opts, _) = compile(&["-c", "a.c"]);
5640 assert!(!opts.gnu89_inline, "C's reading of inline by default");
5641
5642 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
5643 assert!(opts.gnu89_inline);
5644
5645 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
5646 assert!(!opts.gnu89_inline, "the last mention decides");
5647
5648 // The C89 dialects are under GNU's reading whether this was written or not, so the flag
5649 // stays off there and the dialect is what the checker and the macro set both ask. That is
5650 // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
5651 // dialect already has. gcc refuses that command line, which is measured in the issue.
5652 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
5653 assert!(!opts.gnu89_inline);
5654 }
5655
5656 /// Both spellings of both frame flags, since a build that wants one usually writes the
5657 /// other beside it for the one file that has to be compiled the ordinary way.
5658 #[test]
5659 fn the_two_frame_flags_are_read_in_both_directions() {
5660 let (opts, _) = compile(&["-c", "a.c"]);
5661 assert_eq!(opts.frame_pointer, None, "nothing said, so the level decides");
5662 assert!(opts.keeps_frame_pointer(), "and at -O0 gcc keeps one, so this does too");
5663 let (opts, _) = compile(&["-c", "-O1", "a.c"]);
5664 assert!(!opts.keeps_frame_pointer(), "gcc omits it above -O0 and so does this");
5665 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
5666
5667 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
5668 assert_eq!(opts.frame_pointer, Some(true));
5669 assert!(!opts.red_zone);
5670
5671 let (opts, _) = compile(&[
5672 "-c",
5673 "-fno-omit-frame-pointer",
5674 "-fomit-frame-pointer",
5675 "-mno-red-zone",
5676 "-mred-zone",
5677 "a.c",
5678 ]);
5679 assert_eq!(opts.frame_pointer, Some(false), "the last one wins, as it does in gcc");
5680 assert!(!opts.keeps_frame_pointer(), "and it wins over the level too");
5681 assert!(opts.red_zone);
5682 }
5683
5684 /// Four flags rather than one with an argument, which is how gcc spells them, and the negative
5685 /// spelled three ways because a build that turns one off writes whichever it turned on.
5686 #[test]
5687 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
5688 let (opts, _) = compile(&["-c", "a.c"]);
5689 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
5690
5691 for (flag, want) in [
5692 ("-fstack-protector", Protector::Buffers),
5693 ("-fstack-protector-strong", Protector::Strong),
5694 ("-fstack-protector-all", Protector::All),
5695 ] {
5696 let (opts, _) = compile(&["-c", flag, "a.c"]);
5697 assert_eq!(opts.protector, want, "{flag}");
5698 }
5699
5700 // What a package build does: the strong one in the global flags and one directory that
5701 // cannot have a protector turning it off on the line after.
5702 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
5703 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
5704 assert_eq!(opts.protector, Protector::None, "{off}");
5705 }
5706 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
5707 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
5708 }
5709
5710 /// A switch rather than a level, because how a frame is taken is one question and which
5711 /// functions get a canary is another, and gcc spells it that way for the same reason.
5712 #[test]
5713 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
5714 let (opts, _) = compile(&["-c", "a.c"]);
5715 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
5716
5717 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
5718 assert!(opts.stack_clash);
5719
5720 // The same shape a package build uses for the protector: on in the global flags and off
5721 // for the one directory that cannot have it.
5722 let (opts, _) =
5723 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
5724 assert!(!opts.stack_clash);
5725 let (opts, _) =
5726 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
5727 assert!(opts.stack_clash, "the last one wins either way round");
5728
5729 // The two are independent, since one is about the frame and the other about the function.
5730 let (opts, _) =
5731 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
5732 assert!(opts.stack_clash);
5733 assert_eq!(opts.protector, Protector::Strong);
5734 }
5735
5736 /// One flag with an argument rather than a family of spellings, because what it asks about is
5737 /// which of the two edges of a control flow transfer is checked and the two are not separate
5738 /// questions to the hardware.
5739 #[test]
5740 fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
5741 let (opts, _) = compile(&["-c", "a.c"]);
5742 assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
5743
5744 for (arg, want) in [
5745 ("-fcf-protection", Control::Full),
5746 ("-fcf-protection=full", Control::Full),
5747 ("-fcf-protection=branch", Control::Branch),
5748 ("-fcf-protection=return", Control::Return),
5749 ("-fcf-protection=none", Control::None),
5750 ("-fcf-protection=check", Control::Check),
5751 ] {
5752 let (opts, _) = compile(&["-c", arg, "a.c"]);
5753 assert_eq!(opts.control, want, "{arg}");
5754 }
5755
5756 // The shape a package build uses: on in the global flags and off for the one directory
5757 // that cannot have it, whichever of the two spellings of off it reaches for.
5758 let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
5759 assert_eq!(opts.control, Control::None);
5760 let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
5761 assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
5762 }
5763
5764 /// The profiler is asked for by two spellings, and where its hook goes by two more.
5765 ///
5766 /// The two halves are separate on purpose. `-mfentry` on its own says where a call would go and
5767 /// asks for no call, which is what gcc does with it, and a build system that sets it globally
5768 /// and asks for the profile per directory needs that to be true rather than an error.
5769 ///
5770 /// The link is asserted alongside, because the flag changes it too and a build that compiled
5771 /// with it and linked without it is a program that calls the hook everywhere and never writes a
5772 /// profile.
5773 #[test]
5774 fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
5775 let (opts, _) = compile(&["-c", "a.c"]);
5776 assert!(!opts.profile);
5777 assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
5778
5779 for arg in ["-pg", "-p"] {
5780 let (opts, _) = compile(&["-c", arg, "a.c"]);
5781 assert!(opts.profile, "{arg}");
5782 let (link, _) = linking(&[arg, "a.c"]);
5783 assert!(link.profile, "{arg} changes the link as well");
5784 }
5785
5786 for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
5787 let (opts, _) = compile(&["-c", arg, "a.c"]);
5788 assert_eq!(opts.hook, want, "{arg}");
5789 assert!(!opts.profile, "{arg} asks for no call of its own");
5790 }
5791
5792 let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
5793 assert_eq!(opts.hook, Hook::Late, "the last one wins");
5794 assert!(opts.profile);
5795 }
5796
5797 /// How much room a patcher is promised, which is one number or two.
5798 ///
5799 /// A command line that did not ask is asserted alongside, because the flag has to be written to
5800 /// mean anything and a build that reserved room nobody asked for would grow every function in
5801 /// it for nothing.
5802 #[test]
5803 fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
5804 let (opts, _) = compile(&["-c", "a.c"]);
5805 assert_eq!(opts.patchable, Patchable::default());
5806 assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
5807
5808 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
5809 assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
5810
5811 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
5812 assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
5813 assert_eq!(opts.patchable.after(), 2);
5814
5815 // The last one wins, which is what every other flag of this shape does and what a build
5816 // that adds one to a command line it did not write is relying on.
5817 let (opts, _) = compile(&[
5818 "-c",
5819 "-fpatchable-function-entry=5,3",
5820 "-fpatchable-function-entry=2",
5821 "a.c",
5822 ]);
5823 assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
5824 }
5825
5826 /// And a request nothing could satisfy is refused rather than rounded into one that can be.
5827 #[test]
5828 fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
5829 for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
5830 let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
5831 assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
5832 }
5833 }
5834
5835 /// What wraps rather than being undefined, which is two questions and three flags.
5836 ///
5837 /// The older flag is the pair of the newer two, which is gcc's own reading of it, so a build
5838 /// that writes `-fno-strict-overflow` gets both and a build that writes one of the others gets
5839 /// only what it asked for.
5840 #[test]
5841 fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
5842 let (opts, _) = compile(&["-c", "a.c"]);
5843 assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
5844
5845 let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
5846 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5847
5848 let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
5849 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
5850
5851 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
5852 assert_eq!(opts.wrapping, Wrapping::ALL);
5853
5854 // And the last one wins, in both directions. A build that turns one of these on globally
5855 // and off for one directory is relying on that, and so is one that writes the pair and
5856 // then takes half of it back.
5857 let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
5858 assert_eq!(opts.wrapping, Wrapping::NONE);
5859
5860 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
5861 assert_eq!(opts.wrapping, Wrapping::NONE);
5862
5863 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
5864 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5865 }
5866
5867 /// And the other answer to the signed question cannot be held at the same time as the first.
5868 ///
5869 /// A program cannot both wrap and stop, so writing both is writing a contradiction, and gcc
5870 /// resolves it by letting the last one win rather than by reporting anything. That was measured
5871 /// against gcc 16 rather than read out of the manual, which says nothing about it: `-ftrapv
5872 /// -fwrapv` emits no checked calls and `-fwrapv -ftrapv` emits them.
5873 #[test]
5874 fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
5875 let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
5876 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5877
5878 let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
5879 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5880
5881 let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
5882 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5883
5884 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
5885 assert_eq!(opts.wrapping, Wrapping::ALL);
5886
5887 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
5888 assert_eq!(opts.wrapping, Wrapping::NONE);
5889
5890 // And the flag that says what may be assumed says nothing about what happens, so it leaves
5891 // this alone where it takes the wrapping away. gcc does the same.
5892 let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
5893 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5894 }
5895
5896 /// What a plain `char` is, which is four spellings of two answers and nothing by default.
5897 ///
5898 /// Nothing is the target's own answer and has to stay distinct from both of the others, since
5899 /// the same command line means a signed `char` on x86-64 and an unsigned one on Linux's arm64.
5900 /// The negative spellings are the other flag rather than a way of asking for the default, which
5901 /// was measured against gcc 16: `-fno-signed-char` defines `__CHAR_UNSIGNED__` and
5902 /// `-fno-unsigned-char` does not.
5903 #[test]
5904 fn the_signedness_of_a_plain_char_is_asked_for_in_four_ways() {
5905 let (opts, _) = compile(&["-c", "a.c"]);
5906 assert_eq!(opts.char_signed, None);
5907
5908 for flag in ["-fsigned-char", "-fno-unsigned-char"] {
5909 let (opts, _) = compile(&["-c", flag, "a.c"]);
5910 assert_eq!(opts.char_signed, Some(true), "{flag}");
5911 }
5912
5913 for flag in ["-funsigned-char", "-fno-signed-char"] {
5914 let (opts, _) = compile(&["-c", flag, "a.c"]);
5915 assert_eq!(opts.char_signed, Some(false), "{flag}");
5916 }
5917
5918 // And the last one wins, which is what a build that sets one globally and the other for a
5919 // directory relies on.
5920 let (opts, _) = compile(&["-c", "-funsigned-char", "-fsigned-char", "a.c"]);
5921 assert_eq!(opts.char_signed, Some(true));
5922
5923 // And what is asked for reaches the target, because that is what every other part of the
5924 // compiler asks. The triple is one whose own answer is the opposite, so a session that
5925 // ignored the flag would still read as signed here.
5926 let (opts, _) =
5927 compile(&["-c", "--target=aarch64-unknown-linux-gnu", "-fsigned-char", "a.c"]);
5928 assert!(Session::new(*opts).target.char_is_signed);
5929 let (opts, _) = compile(&["-c", "--target=aarch64-unknown-linux-gnu", "a.c"]);
5930 assert!(!Session::new(*opts).target.char_is_signed);
5931 }
5932
5933 /// And the size of an enumeration, which is one question with two spellings.
5934 #[test]
5935 fn the_smallest_enumeration_is_asked_for_and_taken_back() {
5936 let (opts, _) = compile(&["-c", "a.c"]);
5937 assert!(!opts.short_enums);
5938
5939 let (opts, _) = compile(&["-c", "-fshort-enums", "a.c"]);
5940 assert!(opts.short_enums);
5941
5942 let (opts, _) = compile(&["-c", "-fshort-enums", "-fno-short-enums", "a.c"]);
5943 assert!(!opts.short_enums);
5944
5945 let (opts, _) = compile(&["-c", "-fno-short-enums", "-fshort-enums", "a.c"]);
5946 assert!(opts.short_enums);
5947 }
5948
5949 /// And Microsoft's reading of an anonymous member, which the target answers where the command
5950 /// line said nothing. gcc's mingw build has it on and its Linux build has it off, so a header
5951 /// that closes a nameless union with a macro that expands to nothing is read the way the
5952 /// compiler that platform ships would read it.
5953 #[test]
5954 fn the_microsoft_reading_of_a_member_follows_the_target_until_it_is_asked_for() {
5955 // Named rather than left to the host, since the answer this asks for is the one a target
5956 // that is not Windows gives and on a Windows machine the host is not one of those.
5957 let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
5958 assert!(!Session::new(*opts).ms_extensions());
5959
5960 let (opts, _) = compile(&["-c", "--target=x86_64-pc-windows-gnu", "a.c"]);
5961 assert!(Session::new(*opts).ms_extensions());
5962
5963 let (opts, _) = compile(&["-c", "-fms-extensions", "a.c"]);
5964 assert!(Session::new(*opts).ms_extensions());
5965
5966 let (opts, _) =
5967 compile(&["-c", "--target=x86_64-pc-windows-gnu", "-fno-ms-extensions", "a.c"]);
5968 assert!(!Session::new(*opts).ms_extensions());
5969 }
5970
5971 /// And a value nothing means is refused rather than taken for the nearest thing it looks like.
5972 ///
5973 /// `-fcf-protection=all` is the spelling somebody writes from memory, and a compiler that read
5974 /// it as `full` would be guessing, while one that let it fall through to the optimizer's `-f`
5975 /// family would report it as an unknown pass. Neither is the news the build wants.
5976 #[test]
5977 fn a_control_flow_protection_nothing_means_is_refused() {
5978 let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
5979 assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
5980 assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
5981 }
5982
5983 #[test]
5984 fn mingw_subsystem_and_unicode_flags_are_taken_last_one_winning() {
5985 let (link, _) = linking(&["-mwindows", "-municode", "-mthreads", "-static-libgcc", "a.c"]);
5986 assert!(link.gui && link.unicode);
5987 let (link, _) = linking(&["-mwindows", "-mconsole", "a.c"]);
5988 assert!(!link.gui);
5989 let (opts, _) = compile(&["-municode", "-c", "a.c"]);
5990 assert!(opts.defines.iter().any(|define| define == "UNICODE"), "{:?}", opts.defines);
5991 }
5992
5993 #[test]
5994 fn the_link_flags_are_collected_apart_from_the_compilation() {
5995 let (link, _) = linking(&[
5996 "-static",
5997 "-nostartfiles",
5998 "-rdynamic",
5999 "-s",
6000 "-fuse-ld=mold",
6001 "-L/opt/lib",
6002 "-B",
6003 "/opt/tools",
6004 "a.c",
6005 ]);
6006 assert!(link.is_static);
6007 assert!(link.no_startfiles);
6008 assert!(link.export_dynamic);
6009 assert!(link.strip);
6010 assert_eq!(link.use_ld.as_deref(), Some("mold"));
6011 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
6012 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
6013 }
6014
6015 #[test]
6016 fn a_comma_in_dash_wl_separates_two_arguments() {
6017 // The target is written down because the name of the object is derived from it, and `a.o`
6018 // on a Linux host is `a.obj` on a Windows one. What is under test is the splitting of the
6019 // argument, which has nothing to do with either.
6020 let (_, plan) = linking(&[LINUX, "-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
6021 let link = plan.link.expect("expected a link step");
6022 assert_eq!(
6023 link.inputs,
6024 vec![
6025 link::Item::Linker("-rpath".into()),
6026 link::Item::Linker("/opt/lib".into()),
6027 link::Item::Linker("--as-needed".into()),
6028 link::Item::File("a.o".into()),
6029 ]
6030 );
6031 }
6032
6033 #[test]
6034 fn a_word_for_the_linker_keeps_its_place_among_the_files_too() {
6035 // What libtool writes around a set of convenience archives, and what #1279 was. Both words
6036 // are about the files between them, so the pair collected out of the line and appended to
6037 // the end is two options that bracket nothing and an archive that went in empty.
6038 let (_, plan) = linking(&[
6039 "--target=x86_64-unknown-linux-gnu",
6040 "a.c",
6041 "-Wl,--whole-archive",
6042 "libaesni.a",
6043 "-Wl,--no-whole-archive",
6044 "-lm",
6045 ]);
6046 let link = plan.link.expect("expected a link step");
6047 assert_eq!(
6048 link.inputs,
6049 vec![
6050 link::Item::File("a.o".into()),
6051 link::Item::Linker("--whole-archive".into()),
6052 link::Item::File("libaesni.a".into()),
6053 link::Item::Linker("--no-whole-archive".into()),
6054 link::Item::Library("m".into()),
6055 ]
6056 );
6057 // And it is not a job, because there is nothing to compile in a word for the linker.
6058 assert_eq!(plan.jobs.len(), 2);
6059 }
6060
6061 #[test]
6062 fn a_word_for_the_linker_on_a_dash_c_line_is_dropped_without_a_word() {
6063 // GCC says nothing about one either. `-Wl,` on a compile line is what a build system
6064 // writes when one variable holds the flags for both, and a note here would be a note on
6065 // every compile of every autotools project.
6066 let (_, plan) = linking(&["-c", "-Wl,--as-needed", "a.c"]);
6067 assert!(plan.link.is_none());
6068 assert!(plan.notes.is_empty(), "{:?}", plan.notes);
6069 assert_eq!(plan.jobs.len(), 1);
6070 }
6071
6072 #[test]
6073 fn a_library_keeps_its_place_between_the_objects() {
6074 // Link order is semantic: `-lm` written between two files resolves for the one before
6075 // it and not for the one after, so a library cannot be collected into a list of its own.
6076 // The target is named because the suffix of an object is the target's and this asserts
6077 // on the names: the same command line on a Windows host plans two `.obj` files.
6078 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
6079 let link = plan.link.expect("expected a link step");
6080 assert_eq!(
6081 link.inputs,
6082 vec![
6083 link::Item::File("a.o".into()),
6084 link::Item::Library("m".into()),
6085 link::Item::File("b.o".into()),
6086 ]
6087 );
6088 // And it is not a job, because there is nothing to compile in a library.
6089 assert_eq!(plan.jobs.len(), 2);
6090 }
6091
6092 #[test]
6093 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
6094 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
6095 assert!(plan.link.is_none());
6096 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
6097 }
6098
6099 #[test]
6100 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
6101 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
6102 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
6103 }
6104
6105 fn printed(s: &[&str]) -> String {
6106 match parse_args(&args(s)).expect("expected an answer") {
6107 Action::Print(line) => line,
6108 other => panic!("expected an answer, got {other:?}"),
6109 }
6110 }
6111
6112 fn refused(s: &[&str]) -> String {
6113 parse_args(&args(s)).expect_err("expected a refusal").message
6114 }
6115
6116 #[test]
6117 fn a_warning_flag_gcc_knows_is_taken_even_though_nothing_reads_it() {
6118 // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
6119 // out whether a warning flag exists by passing it and looking at the exit status, so a
6120 // compiler that refuses one gcc knows fails a script written for gcc.
6121 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
6122 assert!(!opts.warnings_are_errors);
6123 assert!(opts.warnings);
6124 // The two spellings that do mean something are still read.
6125 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
6126 assert!(opts.warnings_are_errors);
6127 let (opts, _) = compile(&["-w", "-c", "a.c"]);
6128 assert!(!opts.warnings);
6129 // Off without being asked, the way gcc has it off, and both spellings are read.
6130 let (opts, _) = compile(&["-c", "a.c"]);
6131 assert!(!opts.system_header_warnings);
6132 let (opts, _) = compile(&["-Wsystem-headers", "-c", "a.c"]);
6133 assert!(opts.system_header_warnings);
6134 let (opts, _) = compile(&["-Wsystem-headers", "-Wno-system-headers", "-c", "a.c"]);
6135 assert!(!opts.system_header_warnings);
6136 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
6137 assert!(opts.pedantic && opts.warnings_are_errors);
6138 }
6139
6140 #[test]
6141 fn a_warning_flag_gcc_refuses_is_refused_here_too() {
6142 // Postgres's meson build probes these, and with rucc taking them it ended up passing four
6143 // clang warnings that the gcc build had dropped.
6144 for flag in ["-Wcast-function-type-strict", "-Wunused-command-line-argument"] {
6145 assert_eq!(refused(&[flag, "-c", "a.c"]), format!("unknown option `{flag}`"));
6146 }
6147 assert_eq!(
6148 refused(&["-Werror=unguarded-availability-new", "-c", "a.c"]),
6149 "`-Werror=unguarded-availability-new`: no option `-Wunguarded-availability-new`"
6150 );
6151 assert!(refused(&["-Wno-error=nonsense", "-c", "a.c"]).contains("no option `-Wnonsense`"));
6152 // gcc takes `-Wno-` of a name it does not know, and says nothing unless something else
6153 // is said, and it takes C++ and Fortran names on a C compile.
6154 for flag in
6155 ["-Wno-cast-function-type-strict", "-Werror=format", "-Wformat=2", "-Wabi-tag", "-W"]
6156 {
6157 compile(&[flag, "-c", "a.c"]);
6158 }
6159 }
6160
6161 #[test]
6162 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
6163 // Every one of these says something about the output, so the wrong answer is silence.
6164 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
6165 assert!(refused(&["-Wp,-C", "-c", "a.c"]).contains("separate assembler"));
6166 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
6167 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
6168 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
6169 // The word size the target does not have, which is a target this compiler was not asked
6170 // for rather than a flag it does not know.
6171 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
6172 assert!(no32.contains("32 bit target"), "{no32}");
6173 }
6174
6175 /// `-gz` and the two spellings of the split, which are the two questions about the shape of
6176 /// the debug output rather than about how much of it there is.
6177 ///
6178 /// Both answers here are about what happens when there is debug information to shape, and
6179 /// there is none yet, so what is being asserted is that the flags are read and remembered
6180 /// rather than that anything changed in the output. That is the whole of what taking them
6181 /// claims, and it is worth a test because the day `rucc-debug` writes a section this is where
6182 /// it comes to find out what the command line said.
6183 #[test]
6184 fn the_shape_of_the_debug_output_is_recorded_even_where_there_is_none_of_it() {
6185 let (opts, _) = compile(&["-c", "a.c"]);
6186 assert_eq!(opts.compress, Compress::None, "uncompressed unless somebody asks");
6187
6188 // Bare `-gz` is `-gz=zlib`, measured against gcc 16 rather than read out of the manual,
6189 // which describes the flag without ever saying which algorithm it picks.
6190 assert_eq!(compile(&["-gz", "-c", "a.c"]).0.compress, Compress::Zlib);
6191 for (spelling, want) in [
6192 ("none", Compress::None),
6193 ("zlib", Compress::Zlib),
6194 ("zlib-gnu", Compress::ZlibGnu),
6195 ("zstd", Compress::Zstd),
6196 ] {
6197 let (opts, _) = compile(&[&format!("-gz={spelling}"), "-c", "a.c"]);
6198 assert_eq!(opts.compress, want, "{spelling}");
6199 }
6200
6201 // A value nothing here has heard of is refused rather than rounded to the nearest one,
6202 // because a build that asked for `zstd` and quietly got `zlib` would ship a file its
6203 // reader may not understand and would have no way of finding out.
6204 for bad in ["-gz=gzip", "-gz="] {
6205 let failed = refused(&[bad, "-c", "a.c"]);
6206 assert!(failed.contains("is not a way to compress"), "{bad}: {failed}");
6207 }
6208
6209 // The split is refused in the direction that would have written a file and taken in the
6210 // direction that describes what happens. A build system that names the `.dwo` as an
6211 // output has to hear about it now rather than at the point the file is missing.
6212 let (opts, _) = compile(&["-gno-split-dwarf", "-g", "-c", "a.c"]);
6213 assert!(opts.debug_info, "the negative spelling says nothing about how much");
6214 let failed = refused(&["-gsplit-dwarf", "-c", "a.c"]);
6215 assert!(failed.contains(".dwo"), "the refusal names the file it would have written");
6216 }
6217
6218 /// The `-flto` family, which is the whole of an optimization this compiler does not do.
6219 ///
6220 /// Taken rather than refused because ignoring it gives a correct program that is slower than
6221 /// it could have been, which is section 4.1's hint about speed. The values are still held to
6222 /// gcc's, so a command line written for clang is told rather than quietly taken.
6223 #[test]
6224 fn the_link_time_family_is_read_and_checked_and_nothing_is_done_about_it() {
6225 let (opts, _) = compile(&["-c", "a.c"]);
6226 assert!(!opts.lto.requested, "nothing asks unless the command line does");
6227
6228 let (opts, _) = compile(&["-flto", "-c", "a.c"]);
6229 assert!(opts.lto.requested);
6230 assert_eq!(opts.lto.jobs, LtoJobs::One, "bare -flto is one process, the way gcc reads it");
6231
6232 // The last of the two directions wins, the same as every other pair of `-f` spellings.
6233 assert!(!compile(&["-flto", "-fno-lto", "-c", "a.c"]).0.lto.requested);
6234 assert!(compile(&["-fno-lto", "-flto", "-c", "a.c"]).0.lto.requested);
6235
6236 // A count is a count, and asking for one implies asking for the optimization.
6237 for (spelling, want) in [
6238 ("auto", LtoJobs::Auto),
6239 ("jobserver", LtoJobs::Jobserver),
6240 ("1", LtoJobs::One),
6241 ("8", LtoJobs::Count(8)),
6242 ] {
6243 let (opts, _) = compile(&[&format!("-flto={spelling}"), "-c", "a.c"]);
6244 assert_eq!(opts.lto.jobs, want, "{spelling}");
6245 assert!(opts.lto.requested, "{spelling} asks for it too");
6246 }
6247
6248 // gcc refuses a zero rather than reading it as `-fno-lto`, and `thin` is clang's spelling
6249 // of a question gcc answers with `-flto-partition=`, so somebody who wrote it meant a
6250 // different compiler and gets told so here rather than getting a serial link.
6251 for bad in ["-flto=0", "-flto=thin", "-flto=full", "-flto=-1"] {
6252 let failed = refused(&[bad, "-c", "a.c"]);
6253 assert!(failed.contains("link time jobs"), "{bad}: {failed}");
6254 }
6255
6256 // How the program is cut up before the work is spread over it.
6257 assert_eq!(compile(&["-c", "a.c"]).0.lto.partition, Partition::Balanced, "gcc's default");
6258 for (spelling, want) in [
6259 ("balanced", Partition::Balanced),
6260 ("1to1", Partition::OneToOne),
6261 ("one", Partition::One),
6262 ("max", Partition::Max),
6263 ("none", Partition::None),
6264 ] {
6265 let (opts, _) = compile(&[&format!("-flto-partition={spelling}"), "-c", "a.c"]);
6266 assert_eq!(opts.lto.partition, want, "{spelling}");
6267 }
6268 assert!(refused(&["-flto-partition=big", "-c", "a.c"]).contains("partitioning model"));
6269
6270 // And how hard the bytecode is compressed on its way into the object, which is zstd's
6271 // range of levels and is the range gcc checks an argument against.
6272 assert_eq!(compile(&["-c", "a.c"]).0.lto.compression, None, "whatever it does by default");
6273 assert_eq!(compile(&["-flto-compression-level=0", "-c", "a.c"]).0.lto.compression, Some(0));
6274 let (opts, _) = compile(&["-flto-compression-level=19", "-c", "a.c"]);
6275 assert_eq!(opts.lto.compression, Some(19));
6276 for bad in ["-flto-compression-level=20", "-flto-compression-level=-1"] {
6277 let failed = refused(&[bad, "-c", "a.c"]);
6278 assert!(failed.contains("compression level"), "{bad}: {failed}");
6279 }
6280
6281 // The two pairs that describe an arrangement rather than ask for one. Every object here
6282 // holds its machine code, so the fat spelling is what already happens and the other is a
6283 // smaller file rather than a different program, and the plugin pair is about a tool the
6284 // design in `spec/09-optimizer.md` never loads.
6285 for taken in [
6286 "-ffat-lto-objects",
6287 "-fno-fat-lto-objects",
6288 "-fuse-linker-plugin",
6289 "-fno-use-linker-plugin",
6290 ] {
6291 let (opts, _) = compile(&[taken, "-c", "a.c"]);
6292 assert!(!opts.lto.requested, "{taken} says nothing about whether to do it");
6293 }
6294 }
6295
6296 /// The profile family, which is the only one here that splits down the middle.
6297 ///
6298 /// Reading a profile is taken and writing one is refused, and the line between them is the one
6299 /// section 4.1 draws: ignoring a request to read the counts gives a correct program that is
6300 /// slower than it could have been, and ignoring a request to write them means a file the build
6301 /// declared as an output never appears.
6302 #[test]
6303 fn reading_a_profile_is_taken_and_writing_one_is_refused() {
6304 let (opts, _) = compile(&["-c", "a.c"]);
6305 assert!(!opts.profile_data.requested, "nothing asks unless the command line does");
6306 assert_eq!(opts.profile_data.path, None);
6307
6308 let (opts, _) = compile(&["-fprofile-use", "-c", "a.c"]);
6309 assert!(opts.profile_data.requested);
6310 assert_eq!(opts.profile_data.path, None, "beside the object, the way gcc looks");
6311
6312 let (opts, _) = compile(&["-fprofile-use=/counts", "-c", "a.c"]);
6313 assert!(opts.profile_data.requested, "naming a path asks for it too");
6314 assert_eq!(opts.profile_data.path.as_deref(), Some("/counts"));
6315
6316 // The last of the two directions wins, the same as every other pair of `-f` spellings.
6317 assert!(
6318 !compile(&["-fprofile-use", "-fno-profile-use", "-c", "a.c"]).0.profile_data.requested
6319 );
6320 assert!(
6321 compile(&["-fno-profile-use", "-fprofile-use", "-c", "a.c"]).0.profile_data.requested
6322 );
6323
6324 // The rest of the reading half, which is where the files are and three answers about what
6325 // to make of what is in them.
6326 let (opts, _) = compile(&[
6327 "-fprofile-dir=/build/profiles",
6328 "-fprofile-abs-path",
6329 "-fprofile-correction",
6330 "-fprofile-partial-training",
6331 "-c",
6332 "a.c",
6333 ]);
6334 assert_eq!(opts.profile_data.dir.as_deref(), Some("/build/profiles"));
6335 assert!(opts.profile_data.absolute);
6336 assert!(opts.profile_data.correction);
6337 assert!(opts.profile_data.partial_training);
6338
6339 // Writing one, which is refused by name. The first four instrument the program and the
6340 // last writes a file beside the object, and a build that got neither and no message would
6341 // go on to optimize against counts that were never gathered.
6342 for writing in [
6343 "-fprofile-generate",
6344 "-fprofile-generate=/build/profiles",
6345 "-fprofile-arcs",
6346 "--coverage",
6347 "-fcondition-coverage",
6348 "-fpath-coverage",
6349 ] {
6350 let failed = refused(&[writing, "-c", "a.c"]);
6351 assert!(failed.contains("instrument"), "{writing}: {failed}");
6352 }
6353 assert!(refused(&["-ftest-coverage", "-c", "a.c"]).contains(".gcno"), "it names the file");
6354
6355 // The negative spellings of the refused half are what already happens, so they are taken.
6356 for taken in ["-fno-profile-generate", "-fno-profile-arcs", "-fno-test-coverage"] {
6357 let (opts, _) = compile(&[taken, "-c", "a.c"]);
6358 assert!(!opts.profile_data.requested, "{taken} asks for nothing");
6359 }
6360
6361 // And the flags that describe the instrumentation that is refused above, which are checked
6362 // and dropped. Checked because a typo is worth finding here rather than on the day the
6363 // instrumentation lands.
6364 for taken in [
6365 "-fprofile-update=single",
6366 "-fprofile-update=atomic",
6367 "-fprofile-update=prefer-atomic",
6368 "-fprofile-reproducible=serial",
6369 "-fprofile-reproducible=parallel-runs",
6370 "-fprofile-reproducible=multithreaded",
6371 "-fprofile-values",
6372 "-fno-profile-values",
6373 "-fprofile-info-section",
6374 "-fprofile-filter-files=a.c",
6375 "-fprofile-exclude-files=b.c",
6376 "-fprofile-note=a.gcno",
6377 ] {
6378 let (opts, _) = compile(&[taken, "-c", "a.c"]);
6379 assert!(!opts.profile_data.requested, "{taken} says nothing about reading one");
6380 }
6381 assert!(refused(&["-fprofile-update=none", "-c", "a.c"]).contains("update method"));
6382 assert!(refused(&["-fprofile-reproducible=any", "-c", "a.c"]).contains("reproducibility"));
6383 }
6384
6385 /// The sanitizers, which are refused by name and are the one family refused for a reason that
6386 /// is not about the bytes.
6387 ///
6388 /// A sanitizer is a promise that the program is watched while it runs, so a build that asked
6389 /// for one and was quietly given a program with no checks in it gets a test suite that passes
6390 /// for the wrong reason rather than a slower program.
6391 #[test]
6392 fn a_sanitizer_that_is_still_asked_for_at_the_end_of_the_line_is_refused_by_name() {
6393 for asked in ["address", "undefined", "thread", "kernel-address", "leak", "memory"] {
6394 let failed = refused(&[&format!("-fsanitize={asked}"), "-c", "a.c"]);
6395 assert!(failed.contains(asked), "the refusal names what was asked for: {failed}");
6396 assert!(failed.contains("-fsafety=detect"), "and the nearest thing: {failed}");
6397 }
6398
6399 // A list is every name in it, and the first one still standing is the one named.
6400 let failed = refused(&["-fsanitize=address,undefined", "-c", "a.c"]);
6401 assert!(failed.contains("address"), "{failed}");
6402
6403 // A name that is not one, which is worth its own message: somebody who wrote `-fsanitize`
6404 // with a typo in it has a different problem from somebody who wrote a real one.
6405 for bad in ["-fsanitize=bogus", "-fsanitize=address,bogus", "-fno-sanitize=bogus"] {
6406 let failed = refused(&[bad, "-c", "a.c"]);
6407 assert!(failed.contains("is not a sanitizer"), "{bad}: {failed}");
6408 }
6409
6410 // gcc takes `all` only in the negative, and so does this.
6411 assert!(refused(&["-fsanitize=all", "-c", "a.c"]).contains("only `-fno-sanitize=all`"));
6412
6413 // Asking and then taking it back is asking for nothing, which is why the answer waits for
6414 // the end of the line. A build whose shared flags turn a check on and whose rule for one
6415 // file turns it off again compiles that file here.
6416 for pair in [
6417 ["-fsanitize=address", "-fno-sanitize=address"],
6418 ["-fsanitize=address,undefined", "-fno-sanitize=all"],
6419 ["-fsanitize=undefined", "-fno-sanitize=undefined"],
6420 ] {
6421 let (opts, _) = compile(&[pair[0], pair[1], "-c", "a.c"]);
6422 assert_eq!(opts.safety, rucc_session::Safety::Off, "{pair:?} asked for nothing");
6423 }
6424 // And the other order still asks, because the last word is the one that counts.
6425 assert!(!refused(&["-fno-sanitize=address", "-fsanitize=address", "-c", "a.c"]).is_empty());
6426
6427 // What a check does when it fires is an answer about checks that are refused, so there is
6428 // nothing left for it to change and it is taken.
6429 for taken in [
6430 "-fsanitize-recover=undefined",
6431 "-fno-sanitize-recover=all",
6432 "-fsanitize-trap=undefined",
6433 "-fno-sanitize-trap=all",
6434 "-fsanitize-undefined-trap-on-error",
6435 "-fsanitize-address-use-after-scope",
6436 "-fno-sanitize-address-use-after-scope",
6437 "-fsanitize-sections=.data",
6438 ] {
6439 let (opts, _) = compile(&[taken, "-c", "a.c"]);
6440 assert_eq!(opts.safety, rucc_session::Safety::Off, "{taken} asks for no checking");
6441 }
6442 assert!(refused(&["-fsanitize-recover=bogus", "-c", "a.c"]).contains("is not a sanitizer"));
6443
6444 // Coverage instrumentation is refused rather than dropped, because a fuzzer with no
6445 // feedback runs blind and never says so.
6446 let failed = refused(&["-fsanitize-coverage=trace-pc", "-c", "a.c"]);
6447 assert!(failed.contains("feedback"), "{failed}");
6448 let failed = refused(&["-fsanitize-coverage=trace-pc-guard", "-c", "a.c"]);
6449 assert!(failed.contains("trace-pc or trace-cmp"), "gcc takes two of them: {failed}");
6450 }
6451
6452 #[test]
6453 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
6454 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6455 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6456 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
6457 }
6458
6459 #[test]
6460 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
6461 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
6462 let (opts, _) =
6463 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
6464 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
6465 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
6466 assert!(wrong.contains("sysv convention"), "{wrong}");
6467 }
6468
6469 /// Whether a unit built with that command line has the extension called `name`.
6470 fn has(line: &[&str], name: &str) -> bool {
6471 let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6472 let (opts, _) = compile(&[&x86[..], line].concat());
6473 opts.isa.has(rucc_target::Feature::named(name).expect("a feature"))
6474 }
6475
6476 #[test]
6477 fn the_sse_flags_and_the_processor_levels_name_extensions() {
6478 // tamnd/rucc#2003. Every one of these was an unknown option before, and Postgres's
6479 // configure probe for the CRC-32C intrinsics is compiled with the first.
6480 assert!(has(&["-msse4.2"], "sse4.2") && has(&["-msse4.2"], "crc32"));
6481 assert!(has(&["-msse4.2"], "ssse3") && has(&["-msse4.2"], "popcnt"));
6482 assert!(!has(&[], "sse3") && !has(&[], "popcnt"));
6483 assert!(has(&["-mssse3"], "sse3") && !has(&["-mssse3"], "sse4.1"));
6484 assert!(has(&["-msse4"], "sse4.2") && !has(&["-msse4", "-mno-sse4"], "sse4.1"));
6485 assert!(has(&["-mpopcnt"], "popcnt") && !has(&["-mpopcnt"], "sse3"));
6486 assert!(has(&["-mcrc32"], "crc32"));
6487 assert!(has(&["-mxsave"], "xsave") && !has(&["-mxsave", "-mno-xsave"], "xsave"));
6488 assert!(!has(&["-msse4.2", "-mno-popcnt"], "popcnt"));
6489 // A processor supplies what no flag spoke for, whichever order they came in.
6490 assert!(has(&["-march=x86-64-v2"], "sse4.2"));
6491 assert!(!has(&["-march=x86-64-v2", "-mno-sse4.2"], "sse4.2"));
6492 assert!(!has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.2"));
6493 assert!(has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.1"));
6494 assert!(!has(&["-march=x86-64-v2", "-march=x86-64"], "sse3"));
6495 // One it has no list for is the baseline, as it was when all of them were.
6496 assert!(!has(&["-march=pentium-m"], "sse3"));
6497 assert!(has(&["-march=x86-64-v3"], "avx2"));
6498 // Turning off what is never on is nothing, and the flag is still gcc's.
6499 assert!(!has(&["-mno-avx512f"], "avx512f"));
6500 }
6501
6502 #[test]
6503 fn an_extension_this_compiler_cannot_provide_for_a_whole_unit_is_refused() {
6504 let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6505 let said = refused(&[&x86[..], &["-mavx2"]].concat());
6506 assert!(said.contains("no intrinsics for avx2"), "{said}");
6507 let said = refused(&[&x86[..], &["-mno-sse2"]].concat());
6508 assert!(said.contains("baseline"), "{said}");
6509 assert!(refused(&[&x86[..], &["-msse5"]].concat()).contains("unknown option"));
6510 // No other target has these, whichever side of the target the flag was written on.
6511 let said = refused(&["-msse4.2", "--target=aarch64-linux-gnu", "-c", "a.c"]);
6512 assert!(said.contains("unknown option `-msse4.2`"), "{said}");
6513 let (opts, _) = compile(&["--target=aarch64-linux-gnu", "-march=armv8-a+crc", "-c", "a.c"]);
6514 assert_eq!(opts.isa, rucc_target::Isa::NONE);
6515 }
6516
6517 #[test]
6518 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
6519 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
6520 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
6521 // After the input, because a static link takes what it needs from a library when it
6522 // reaches it and not afterwards.
6523 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
6524 assert_eq!(names, vec!["a.c"]);
6525 }
6526
6527 #[test]
6528 fn the_version_banner_keeps_our_first_line_and_takes_meson_down_the_gnu_path() {
6529 let text = banner();
6530 let mut lines = text.lines();
6531 // Every harness we have reads the first line and nothing else.
6532 assert_eq!(lines.next(), Some(format!("rucc {VERSION}").as_str()));
6533 // The words meson looks for, in `mesonbuild/compilers/detect.py`.
6534 assert!(text.contains("Free Software Foundation"), "{text}");
6535 // GCC's own banner has three lines and so does this one, and the claim is the dialect.
6536 assert!(lines.next().is_some_and(|l| l.contains("GCC 16")), "{text}");
6537 assert!(lines.next().is_some() && lines.next().is_none(), "{text}");
6538 }
6539
6540 #[test]
6541 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
6542 let target = "--target=x86_64-unknown-linux-gnu";
6543 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
6544 assert_eq!(printed(&[target, "-dumpversion"]), "16");
6545 assert_eq!(printed(&[target, "-dumpfullversion"]), "16.0.0");
6546 // They follow the release claimed, since that is the one `__GNUC__` says.
6547 assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpversion"]), "15");
6548 assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpfullversion"]), "15.2.0");
6549 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
6550 // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
6551 // answer safe to paste into a link line whether or not the file is there.
6552 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
6553 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
6554 let dirs = printed(&[target, "-print-search-dirs"]);
6555 assert!(dirs.starts_with("install: "), "{dirs}");
6556 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
6557 }
6558
6559 #[test]
6560 fn the_sysroot_in_effect_is_the_one_the_command_line_named_or_the_one_for_the_target() {
6561 // A tree the user named is the answer whatever the target is, because it is the answer to
6562 // every other question too.
6563 assert_eq!(printed(&["--sysroot=/opt/cross", "-print-sysroot"]), "/opt/cross");
6564
6565 // A target that is no machine this suite runs on is read under the cache, and the answer is
6566 // the root rather than one of the directories under it, since what asks is looking for a
6567 // file of its own.
6568 let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
6569 assert_eq!(
6570 printed(&["--target=riscv64-linux-musl", "-print-sysroot"]),
6571 root.display().to_string()
6572 );
6573
6574 // And a compile for this machine has no sysroot, which is the empty line GCC prints when it
6575 // was configured without one rather than a `/` that would be a claim about the filesystem.
6576 let host = Triple::host().expect("a host this compiler knows");
6577 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot"]), "");
6578 }
6579
6580 #[test]
6581 fn the_provenance_of_a_sysroot_is_the_manifest_it_carries() {
6582 // Section 13.5 wants seven things per input and wants them machine readable, and the manifest
6583 // is the record that already has them, so the flag prints that rather than a second format.
6584 let manifest = "rucc sysroot manifest 3\n\
6585 target\tx86_64-linux-musl\n\
6586 kernel\t6.12\n\
6587 include/generic/stdio.h\tmusl-1.2.5\t\
6588 https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6589 0000000000000000000000000000000000000000000000000000000000000000\tmit\t\
6590 bundled\n\
6591 lib/libc.so\tmusl-1.2.5\t\
6592 https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6593 1111111111111111111111111111111111111111111111111111111111111111\tmit\t\
6594 generated\n";
6595 let tree = TempTree::new("provenance", &[("manifest", manifest)]);
6596 let sysroot = format!("--sysroot={}", tree.0.display());
6597 // The kernel line of tamnd/rucc#934 is in the answer without anything here naming it, because
6598 // the flag parses the record and renders it again rather than picking fields out of it. That
6599 // is the reason it prints a manifest and not a format of its own.
6600 //
6601 // The answer is the file without its last newline, because whatever prints it adds one. The
6602 // file is what somebody diffs the output against, so the two have to be the same bytes.
6603 assert_eq!(printed(&[&sysroot, "-print-sysroot-provenance"]) + "\n", manifest);
6604
6605 // A tree with no manifest in it is a tree somebody assembled themselves, and nothing here
6606 // knows where any of it came from. Saying nothing is the only honest answer, and a reader can
6607 // tell it from a manifest with no inputs because that one still has its two header lines.
6608 let bare = TempTree::new("provenance-bare", &[]);
6609 assert_eq!(
6610 printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-provenance"]),
6611 ""
6612 );
6613
6614 // And a compile for this machine has no sysroot at all, which is the same empty answer
6615 // `-print-sysroot` gives for it.
6616 let host = Triple::host().expect("a host this compiler knows");
6617 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-provenance"]), "");
6618
6619 // And the other spelling, which section 13.5 is the document that writes.
6620 assert_eq!(printed(&[&sysroot, "--print-sysroot-provenance"]) + "\n", manifest);
6621
6622 // tamnd/rucc#1021. The digest of the same tree is the sha256 of that record, so it is one
6623 // line where the provenance is a few hundred, and it is checkable with `sha256sum` because
6624 // the bytes it is over are the bytes of the file. The number here is that hash of the
6625 // fixture above, computed by `sha256sum` rather than by this compiler.
6626 assert_eq!(
6627 printed(&[&sysroot, "-print-sysroot-digest"]),
6628 "d705ae6ebeafeb7fda4bd57cecc7882bf49784b17015664a09cfae25a1b2000a"
6629 );
6630 assert_eq!(
6631 printed(&[&sysroot, "--print-sysroot-digest"]),
6632 printed(&[&sysroot, "-print-sysroot-digest"])
6633 );
6634
6635 // And the two empty answers are empty here too, because a digest of nothing would read as a
6636 // claim about a sysroot rather than as the absence of one.
6637 assert_eq!(
6638 printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-digest"]),
6639 ""
6640 );
6641 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-digest"]), "");
6642 }
6643
6644 #[test]
6645 fn a_manifest_this_build_cannot_read_is_refused_rather_than_printed() {
6646 // Passing a file we could not parse to whoever asked would make their parser the one that
6647 // finds the problem, and the three uses section 13.5 gives for this are all somebody else
6648 // parsing it.
6649 let tree = TempTree::new(
6650 "provenance-bad",
6651 &[("manifest", "rucc sysroot manifest 3\ntarget\tx86_64-linux-musl\nlib/libc.a\n")],
6652 );
6653 let message =
6654 refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-provenance"]);
6655 assert!(message.contains("manifest"), "{message}");
6656 assert!(message.contains("1 fields where an input has six"), "{message}");
6657
6658 // The digest is refused for the same file and for a stronger reason: a hash of bytes this
6659 // build cannot read would be a number that names a record nobody can act on.
6660 let digest =
6661 refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-digest"]);
6662 assert_eq!(digest, message);
6663 }
6664
6665 #[test]
6666 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
6667 let (opts, _) = compile(&["-M", "a.c"]);
6668 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
6669 assert!(opts.deps.system_headers, "plain -M lists them");
6670 assert_eq!(opts.emit, EmitKind::Preprocessed);
6671
6672 // Even where a later flag asked for something else, because the family is a mode and
6673 // the mode is what the run is for.
6674 let (opts, _) = compile(&["-M", "-c", "a.c"]);
6675 assert_eq!(opts.emit, EmitKind::Preprocessed);
6676
6677 let (opts, _) = compile(&["-MM", "a.c"]);
6678 assert!(!opts.deps.system_headers);
6679 }
6680
6681 #[test]
6682 fn the_two_that_end_in_d_leave_the_compilation_alone() {
6683 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
6684 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6685 assert!(opts.deps.system_headers);
6686 assert_eq!(opts.emit, EmitKind::Object);
6687
6688 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
6689 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6690 assert!(!opts.deps.system_headers);
6691 }
6692
6693 #[test]
6694 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
6695 // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
6696 // the answer, because the other one never asked the question.
6697 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
6698 assert!(!opts.deps.system_headers);
6699 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
6700 assert!(!opts.deps.system_headers);
6701 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
6702 assert!(!opts.deps.system_headers);
6703 }
6704
6705 #[test]
6706 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
6707 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
6708 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
6709 }
6710
6711 #[test]
6712 fn the_rest_of_the_family_is_a_file_and_a_switch() {
6713 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
6714 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
6715 assert!(opts.deps.phony);
6716
6717 for flag in ["-MF", "-MT", "-MQ"] {
6718 let e = parse_args(&args(&[flag])).unwrap_err();
6719 assert!(e.message.contains("requires an argument"), "{}", e.message);
6720 }
6721 }
6722
6723 /// Kbuild's spelling, which is how busybox and the kernel ask for every dependency file.
6724 #[test]
6725 fn a_dependency_file_asked_for_through_the_preprocessor_is_written_where_it_said() {
6726 let (opts, _) = compile(&["-Wp,-MD,applets/.applets.o.d", "-c", "a.c"]);
6727 assert!(opts.deps.emit);
6728 assert!(opts.deps.system_headers);
6729 assert_eq!(opts.deps.file.as_deref(), Some("applets/.applets.o.d"));
6730
6731 let (opts, _) = compile(&["-Wp,-MMD,x.d,-MP,-MT,x.o", "-c", "a.c"]);
6732 assert!(!opts.deps.system_headers);
6733 assert!(opts.deps.phony);
6734 assert_eq!(opts.deps.file.as_deref(), Some("x.d"));
6735 assert_eq!(opts.deps.targets, vec!["x.o".to_owned()]);
6736 }
6737
6738 #[test]
6739 fn a_preprocessor_flag_this_compiler_does_not_read_is_still_refused_whole() {
6740 assert!(refused(&["-Wp,-MD", "-c", "a.c"]).contains("separate assembler"));
6741 assert!(refused(&["-Wp,-MD,x.d,-C", "-c", "a.c"]).contains("-Wp,-MD,x.d,-C"));
6742 }
6743
6744 /// A directory of sources for one test, removed when the test is done with it.
6745 struct TempTree(PathBuf);
6746
6747 impl Drop for TempTree {
6748 fn drop(&mut self) {
6749 let _ = std::fs::remove_dir_all(&self.0);
6750 }
6751 }
6752
6753 impl TempTree {
6754 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
6755 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
6756 let _ = std::fs::remove_dir_all(&dir);
6757 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
6758 for (path, text) in files {
6759 let at = dir.join(path);
6760 if let Some(parent) = at.parent() {
6761 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
6762 }
6763 std::fs::write(&at, text).expect("writing a temporary file should work");
6764 }
6765 TempTree(dir)
6766 }
6767
6768 fn path(&self, name: &str) -> String {
6769 self.0.join(name).to_string_lossy().into_owned()
6770 }
6771 }
6772
6773 #[test]
6774 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
6775 // End to end, because the list comes from the preprocessor and the format comes from
6776 // somewhere else, and a test of either half on its own would pass with the two of them
6777 // wired up backwards.
6778 let tree = TempTree::new(
6779 "found",
6780 &[
6781 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
6782 ("one.h", "#define X 0\n"),
6783 ("two.h", "#include \"one.h\"\n"),
6784 ],
6785 );
6786 let out = tree.path("dep.d");
6787 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6788 assert_eq!(code, 0);
6789
6790 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6791 let names: Vec<&str> = text.split_whitespace().collect();
6792 // The target, the source, and each header once however many times it was reached.
6793 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
6794 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
6795 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
6796 // And the `-o` went to the file the rule replaced, which is left empty rather than
6797 // absent because a makefile that named it as a target will look for it.
6798 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
6799 }
6800
6801 #[test]
6802 fn syntax_only_checks_the_file_and_writes_nothing() {
6803 // What meson's `has_header_symbol` probe does: compile with `-fsyntax-only` and read the
6804 // exit status. A good file passes and leaves no output behind, a bad one fails.
6805 let tree = TempTree::new(
6806 "syntax-only",
6807 &[
6808 ("good.c", "int f(int x) { return x + 1; }\n"),
6809 ("bad.c", "int f(void) { return y; }\n"),
6810 ],
6811 );
6812 let (opts, _) = compile(&["-fsyntax-only", "a.c"]);
6813 assert_eq!(opts.emit, EmitKind::SyntaxOnly);
6814
6815 let out = tree.path("good.o");
6816 assert_eq!(run(&args(&["-fsyntax-only", "-o", &out, &tree.path("good.c")])), 0);
6817 assert!(!std::path::Path::new(&out).exists(), "-fsyntax-only wrote {out}");
6818 assert!(!std::path::Path::new(&tree.path("good.s")).exists());
6819 assert_ne!(run(&args(&["-fsyntax-only", &tree.path("bad.c")])), 0);
6820 }
6821
6822 /// Where `-fstack-usage` puts each job's report, one entry per job, for a command line.
6823 fn stack_usage_files(line: &[&str]) -> Vec<Option<String>> {
6824 let mut words = vec![LINUX, "-fstack-usage"];
6825 words.extend_from_slice(line);
6826 let (_, plan) = compile(&words);
6827 plan.jobs.iter().map(|job| job.stack_usage.clone()).collect()
6828 }
6829
6830 #[test]
6831 fn a_stack_usage_file_is_named_the_way_gcc_names_it() {
6832 // Every row was run through gcc 16 with the same command line, and the name is the one it
6833 // wrote. `rpg frames` finds gcc's file and this compiler's by the same rule, so a name that
6834 // differs is a function that goes missing from the comparison.
6835 let cases: &[(&[&str], &[Option<&str>])] = &[
6836 (&["-c", "sub/a.c"], &[Some("a.su")]),
6837 (&["-c", "sub/a.c", "-o", "out/x.o"], &[Some("out/x.su")]),
6838 (&["-c", "sub/a.c", "b.c"], &[Some("a.su"), Some("b.su")]),
6839 (&["-S", "sub/a.c", "-o", "out/y.s"], &[Some("out/y.su")]),
6840 (&["-S", "sub/a.c", "-o", "-"], &[Some("a.su")]),
6841 (&["-E", "sub/a.c", "-o", "out/z.i"], &[None]),
6842 (&["-fsyntax-only", "sub/a.c"], &[Some("a.su")]),
6843 (&["-fsyntax-only", "sub/a.c", "-o", "out/x.o"], &[Some("out/x.o-a.su")]),
6844 (&["sub/a.c"], &[Some("a.su")]),
6845 (&["sub/a.c", "-lm"], &[Some("a.su")]),
6846 (&["sub/a.c", "b.c"], &[Some("a-a.su"), Some("a-b.su")]),
6847 (&["sub/a.c", "b.o"], &[Some("a-a.su"), None]),
6848 (&["sub/a.c", "-o", "out/prog"], &[Some("out/prog-a.su")]),
6849 (&["sub/a.c", "-o", "out/lib.so"], &[Some("out/lib.so-a.su")]),
6850 (&["sub/a.c", "-o", "out/prog.exe"], &[Some("out/prog-a.su")]),
6851 (&["sub/a.c", "-o", "out/prog", "-dumpbase", "zz"], &[Some("out/zz-a.su")]),
6852 (&["sub/a.c", "-o", "out/prog", "-dumpdir", "dd-"], &[Some("dd-a.su")]),
6853 (
6854 &["sub/a.c", "b.c", "-dumpdir", "dd/", "-dumpbase", "zz"],
6855 &[Some("dd/zz-a.su"), Some("dd/zz-b.su")],
6856 ),
6857 (&["-c", "sub/a.c", "-dumpbase", "foo", "-o", "out/w.o"], &[Some("out/foo.su")]),
6858 (&["-c", "sub/a.c", "-dumpdir", "dd/", "-dumpbase", "sub/zz"], &[Some("sub/zz.su")]),
6859 (&["-c", "sub/a.c", "-dumpbase", "zz.c", "-dumpbase-ext", ".c"], &[Some("zz.su")]),
6860 (&["-c", "sub/a.c", "-dumpdir", "pre", "-o", "out/x.o"], &[Some("prex.su")]),
6861 (&["-c", "sub/a.c", "-save-temps=cwd", "-o", "out/x.o"], &[Some("x.su")]),
6862 ];
6863 for (line, want) in cases {
6864 let want: Vec<Option<String>> = want.iter().map(|w| w.map(str::to_owned)).collect();
6865 assert_eq!(stack_usage_files(line), want, "{line:?}");
6866 }
6867 // Nothing at all without the flag.
6868 let (_, plan) = compile(&[LINUX, "-c", "sub/a.c"]);
6869 assert_eq!(plan.jobs[0].stack_usage, None);
6870 }
6871
6872 #[test]
6873 fn a_stack_usage_file_has_a_line_per_function_where_gcc_would_put_it() {
6874 let tree = TempTree::new(
6875 "stack-usage",
6876 &[
6877 ("inc/h.h", "static inline int twice(int x) { return x * 2; }\n"),
6878 (
6879 "a.c",
6880 "#include \"inc/h.h\"\n\
6881 static int helper(int);\n\
6882 int grows(int n) { char v[n]; v[0] = (char)n; return v[n - 1] + twice(n); }\n\
6883 static int\n\
6884 helper(int x)\n\
6885 {\n\
6886 return x + 1;\n\
6887 }\n\
6888 int calls(int x) { return helper(x) + grows(x); }\n",
6889 ),
6890 ],
6891 );
6892 let (source, object) = (tree.path("a.c"), tree.path("a.o"));
6893 assert_eq!(run(&args(&["-O0", "-fstack-usage", "-c", &source, "-o", &object])), 0);
6894 let text = std::fs::read_to_string(tree.path("a.su")).expect("a.su should be written");
6895
6896 let line = |function: &str| {
6897 let suffix = format!(":{function}");
6898 let line =
6899 text.lines().find(|line| line.split('\t').next().unwrap().ends_with(&suffix));
6900 line.unwrap_or_else(|| panic!("no line for {function} in\n{text}"))
6901 };
6902 let expect = |function: &str, at: String, qualifier: &str| {
6903 let fields: Vec<&str> = line(function).split('\t').collect();
6904 assert_eq!(fields.len(), 3, "{text}");
6905 assert_eq!(fields[0], format!("{at}:{function}"), "{text}");
6906 let bytes: u32 = fields[1].parse().expect("the bytes should be a number");
6907 assert!(bytes >= 8 && bytes % 8 == 0, "{function} takes {bytes} bytes");
6908 assert_eq!(fields[2], qualifier, "{text}");
6909 };
6910 // A variable length array makes the frame grow while the function runs.
6911 expect("grows", format!("{source}:3:5"), "dynamic");
6912 // The definition rather than the declaration above it, and the line the name is on
6913 // rather than the one the type is on.
6914 expect("helper", format!("{source}:5:1"), "static");
6915 expect("calls", format!("{source}:9:5"), "static");
6916 // A function from a header is reported against the header.
6917 expect("twice", format!("{}:1:19", tree.path("inc/h.h")), "static");
6918 assert_eq!(text.lines().count(), 4, "{text}");
6919 }
6920
6921 #[test]
6922 fn a_stack_usage_file_is_empty_when_there_is_nothing_to_report_and_absent_under_dash_e() {
6923 let tree = TempTree::new(
6924 "stack-usage-empty",
6925 &[
6926 ("good.c", "int f(int x) { return x + 1; }\n"),
6927 ("bad.c", "int f(void) { return y; }\n"),
6928 ],
6929 );
6930 let good = tree.path("good.c");
6931 // gcc writes an empty file for a check that compiles nothing and for a file that failed,
6932 // and a build that looks for one beside every object finds one.
6933 assert_eq!(
6934 run(&args(&["-fstack-usage", "-fsyntax-only", &good, "-o", &tree.path("x")])),
6935 0
6936 );
6937 assert_eq!(std::fs::read_to_string(tree.path("x-good.su")).unwrap(), "");
6938 let bad = tree.path("bad.c");
6939 assert_ne!(run(&args(&["-fstack-usage", "-c", &bad, "-o", &tree.path("bad.o")])), 0);
6940 assert_eq!(std::fs::read_to_string(tree.path("bad.su")).unwrap(), "");
6941 // And none under `-E`, which never reaches a function.
6942 assert_eq!(run(&args(&["-fstack-usage", "-E", &good, "-o", &tree.path("e.i")])), 0);
6943 assert!(!std::path::Path::new(&tree.path("e.su")).exists());
6944 }
6945
6946 #[test]
6947 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
6948 // The multiple-include optimization means the second reach never opens the file. It is
6949 // still a file this translation unit was built from, so it is still in the rule.
6950 let tree = TempTree::new(
6951 "guarded",
6952 &[
6953 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
6954 ("g.h", "#ifndef G\n#define G\n#endif\n"),
6955 ],
6956 );
6957 let out = tree.path("dep.d");
6958 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6959 assert_eq!(code, 0);
6960 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6961 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
6962 }
6963
6964 #[test]
6965 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
6966 // Measured against GCC rather than read: the two flags the other way round produce the
6967 // same output byte for byte, so the command line order between the two families does not
6968 // decide anything and the order within one does. The `-include` file here can only see
6969 // the definition if the `-imacros` file that was written after it ran first.
6970 let tree = TempTree::new(
6971 "preinclude",
6972 &[
6973 ("a.c", "int main(void) { return 0; }\n"),
6974 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
6975 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
6976 ],
6977 );
6978 let out = tree.path("a.i");
6979 let code = run(&args(&[
6980 "-E",
6981 "-include",
6982 &tree.path("i.h"),
6983 "-imacros",
6984 &tree.path("m.h"),
6985 "-o",
6986 &out,
6987 &tree.path("a.c"),
6988 ]));
6989 assert_eq!(code, 0);
6990 let text = std::fs::read_to_string(&out).expect("the output should have been written");
6991 assert!(text.contains("saw_it"), "{text}");
6992 // And the text of the `-imacros` file is thrown away, which is the whole difference
6993 // between the two flags.
6994 assert!(!text.contains("macros_text"), "{text}");
6995 }
6996
6997 #[test]
6998 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
6999 let tree = TempTree::new(
7000 "preinclude-deps",
7001 &[
7002 ("a.c", "int main(void) { return 0; }\n"),
7003 ("i.h", "int from_include;\n"),
7004 ("m.h", "#define M 1\n"),
7005 ],
7006 );
7007 let out = tree.path("dep.d");
7008 let code = run(&args(&[
7009 "-MM",
7010 "-MF",
7011 &out,
7012 "-include",
7013 &tree.path("i.h"),
7014 "-imacros",
7015 &tree.path("m.h"),
7016 "-o",
7017 &tree.path("a.i"),
7018 &tree.path("a.c"),
7019 ]));
7020 assert_eq!(code, 0);
7021 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
7022 assert!(text.contains("i.h"), "{text}");
7023 assert!(text.contains("m.h"), "{text}");
7024 }
7025
7026 #[test]
7027 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
7028 // Including the directory of the source file, which is not on the path for these: the
7029 // command line was not written there, so a name in it is relative to where the compiler
7030 // was run rather than to where the source sits.
7031 let tree = TempTree::new(
7032 "preinclude-missing",
7033 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
7034 );
7035 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
7036 assert_eq!(code, 1);
7037 }
7038
7039 #[test]
7040 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
7041 // The object a link goes through is in a temporary directory and is gone before `make`
7042 // reads any of this, so the rule that named it would be a rule for a file that is never
7043 // there. The target and the file are both the `-o`, which is the executable.
7044 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
7045 assert_eq!(plan.output.as_deref(), Some("prog"));
7046 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
7047 assert_eq!(
7048 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
7049 Some("prog.d")
7050 );
7051 }
7052
7053 #[test]
7054 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
7055 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
7056 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
7057 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
7058 assert_eq!(plan.output, None);
7059 }
7060
7061 #[test]
7062 fn usage_fits_on_a_screen() {
7063 // Not a style preference. A help text that scrolls is one nobody reads, and this is
7064 // the cheapest way to keep it honest as flags accumulate. The number goes up only when
7065 // a family of flags arrives that has nowhere to share a line, which the two pass gates
7066 // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
7067 // the lines that family took. The four it went up by last are the flags a build system
7068 // passes without being asked to: how much to say, what machine to generate for, threads,
7069 // and the questions `configure` asks before it compiles anything. The one it went up by
7070 // last is the second line of `--emit`, whose kinds are a family that has now outgrown
7071 // one line and has nowhere else to go. The two it went up by last are the dependency
7072 // family, which is eight flags that share nothing with anything above them. The one it
7073 // went up by last is the four spellings of position independent code, which every
7074 // configure script writes and which could only have shared the link line, and that line
7075 // is already four characters short of the limit. The two it went up by last are the rest
7076 // of the include family, which is six more flags that change where a header is looked for
7077 // and two that name a header outright. The one it went up by last is the pair that keeps
7078 // the intermediate files and times the steps, which belong next to the two flags above
7079 // them that are also about watching a compilation rather than changing one. The two it
7080 // went up by last are the section flags and the visibility flag, which are what a build
7081 // that cares about the size of what it ships and about which names it exports writes, and
7082 // the second of them was already taken and only missing from here. The one it went up by
7083 // last is the stack protector, which is four spellings of one question and which every
7084 // distribution puts on every command line it issues, so a build that reads this list
7085 // looking for it and does not find it has to go and read the specification instead. The one
7086 // it went up by last is the profiler, which is two spellings of the request and two of
7087 // where the call goes, and which is about watching a program run rather than about what is
7088 // generated, so it shares its subject with nothing above it. The one it went up by last is
7089 // the room a function opens with for something to be written over it later, which takes an
7090 // argument of its own shape and is what a kernel build asks for, so it fits beside the
7091 // profiler and nothing else. The one it went up by last is what overflows rather than being
7092 // undefined, which is three spellings of two questions and which a kernel build and a great
7093 // deal of code written before the standard settled both pass. The one it went up by last is
7094 // the other answer to the first of those questions, which could not share the line because
7095 // what it asks for is the opposite of what the flags on that line ask for. The one it went
7096 // up by last is the split of the line that lists what this compiler does anyway into that
7097 // and what it assumes anyway, which are two different claims that were sharing a line until
7098 // the second of them got a second flag and the line stopped fitting. The one it went up by
7099 // last is the three flags that change the ABI rather than the code, which have to be given
7100 // to every file in a program or none of them and which therefore belong somewhere a person
7101 // reading this list will see them. The one it went up by last is the floating point group,
7102 // which is two lines rather than one because the first of them is a choice this compiler
7103 // records and the rest are claims about what it does anyway, and putting a real setting on
7104 // the same line as three flags that change nothing would be misleading about both. The one
7105 // it went up by last is the flag that says a write has to stay inside the member it names,
7106 // which is a setting rather than a claim and so cannot share the line above it, that being
7107 // the one that picks a tier. The two it went up by last are the prefix mapping family,
7108 // which is four flags whose whole job is to keep a build's output the same from two
7109 // different directories, and which a person chasing a reproducible build comes here
7110 // looking for by name. The one it went up by last is how the debug sections are compressed
7111 // and whether they go in a file of their own, which are two questions about the shape of
7112 // the debug output, where the line above them is about how much of it there is. The one it
7113 // went up by last is the `restrict` contract, which is a setting for the same reason the
7114 // flag that keeps a write inside its member is and which is the check a person who has been
7115 // bitten by a vectorizer comes here looking for. The one it went up by last is link time
7116 // optimization, which is a whole optimization rather than a flag and which says so on its
7117 // own line, because a build that passes it and reads this looking for what it got is
7118 // asking a question no other line here answers. The one it went up by last is the sysroot,
7119 // which is the question somebody asks when a cross build read a file nobody expected, and
7120 // which has no room on the line above it because the answers there are a path each and this
7121 // one is the root all of them are under. The one it went up by last is what is inside that
7122 // root and where each of it came from, which is a question about a whole tree rather than
7123 // about a path and which is long enough on its own that it could not have shared a line with
7124 // anything. The one it went up by last is the profile family, which splits down the middle
7125 // where no other family here does, so the line has to name the half that is taken and the
7126 // half that is refused or it would be read as taking both. The one it went up by last is
7127 // the sanitizers, which are what somebody reaching for a checked build writes first and
7128 // which belong beside the tier that is the nearest thing here to what they asked for. The
7129 // one it went up by last is the digest of that record, which is the same tree as one number
7130 // and could not share the line above it because that line prints a few hundred lines and
7131 // this one prints sixty four characters, and a reader who wants the short answer is looking
7132 // for it by name rather than reading the long one. The one it went up by last is the
7133 // sysroot fetch, which is the only command here that gets something from somewhere else and
7134 // is therefore the one a person wants to have read before they run it rather than after.
7135 // And the flag beside it that forbids every download, which earns its line by being what a
7136 // build in a sealed environment passes and by meaning something even though an ordinary
7137 // compile downloads nothing either way. The one it went up by last is the other fetch, the
7138 // one behind Microsoft's licence wall, which is a line rather than a paragraph because what
7139 // a person needs from here is that the command exists and that it will not do anything
7140 // until they have read a licence it prints for them.
7141 assert!(USAGE.lines().count() < 73, "usage text has grown past one screen");
7142 }
7143}