| @@ -104,46 +104,134 @@ fn runtime_dir(opts: &CcOptions) -> Result<PathBuf, BuildError> { |
| 104 | 104 | }) |
| 105 | 105 | } |
| 106 | 106 | |
| 107 | | −/// The first of `clang`, `cc`, `gcc` that supports `musttail` (clang 13+, |
| 108 | | −/// GCC 15+), found once per process. clang comes first: on generated C it |
| 109 | | −/// compiled 3 times faster than GCC 16 at `-O2`, and its code ran 0-25% |
| 110 | | −/// faster on `tests/bench` (issue #61). |
| 111 | | −fn default_cc() -> Result<String, BuildError> { |
| 112 | | − static FOUND: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new(); |
| 113 | | − FOUND |
| 114 | | − .get_or_init(|| { |
| 115 | | − // The probe goes through stdin to /dev/null: no files to clean |
| 116 | | − // up (a probe directory per process used to be left in /tmp |
| 117 | | − // when a build was interrupted). |
| 118 | | − const PROBE: &str = "static int g(int x) { return x; }\nint f(int x) { __attribute__((musttail)) return g(x); }\n"; |
| 119 | | − ["clang", "cc", "gcc"] |
| 120 | | − .into_iter() |
| 121 | | − .find(|cc| { |
| 122 | | − use std::io::Write; |
| 123 | | − let child = Command::new(cc) |
| 124 | | − .args(["-x", "c", "-c", "-o", "/dev/null", "-"]) |
| 125 | | − .stdin(std::process::Stdio::piped()) |
| 126 | | − .stdout(std::process::Stdio::null()) |
| 127 | | − .stderr(std::process::Stdio::null()) |
| 128 | | − .spawn(); |
| 129 | | − let Ok(mut child) = child else { |
| 130 | | − return false; |
| 131 | | − }; |
| 132 | | − let written = child |
| 133 | | − .stdin |
| 134 | | − .take() |
| 135 | | − .is_some_and(|mut stdin| stdin.write_all(PROBE.as_bytes()).is_ok()); |
| 136 | | − child.wait().is_ok_and(|s| s.success()) && written |
| 137 | | − }) |
| 138 | | − .map(str::to_owned) |
| 139 | | − }) |
| 140 | | − .clone() |
| 141 | | − .ok_or_else(|| { |
| 142 | | − BuildError::Cc( |
| 143 | | − "no C compiler supporting `musttail` was found (tried clang, cc, gcc): install clang 13+ or GCC 15+, or set LOUISE_CC" |
| 144 | | − .into(), |
| 145 | | − ) |
| 146 | | − }) |
| 107 | +/// The C compilers tried, in order, when `LOUISE_CC` is not set. clang |
| 108 | +/// comes first: on generated C it compiled 3 times faster than GCC 16 at |
| 109 | +/// `-O2`, and its code ran 0-25% faster on `tests/bench` (issue #61). |
| 110 | +const COMPILERS: [&str; 3] = ["clang", "cc", "gcc"]; |
| 111 | + |
| 112 | +/// The linkers tried, in order, when `LOUISE_LD` is not set: `mold`, then |
| 113 | +/// `lld`, then the compiler's default (GNU ld). Linking `liblouise_rt.a` |
| 114 | +/// dominates a warm build, and GNU ld takes about three times as long as |
| 115 | +/// either (issue #103). |
| 116 | +const LINKERS: [(&str, &str); 2] = [("mold", "mold"), ("lld", "ld.lld")]; |
| 117 | + |
| 118 | +/// Whether `cc`, given `args` and the C program `source` on stdin, |
| 119 | +/// succeeds. |
| 120 | +fn probe(cc: &str, args: &[&str], source: &str) -> bool { |
| 121 | + use std::io::Write; |
| 122 | + let child = Command::new(cc) |
| 123 | + .args(["-x", "c"]) |
| 124 | + .args(args) |
| 125 | + .arg("-") |
| 126 | + .stdin(std::process::Stdio::piped()) |
| 127 | + .stdout(std::process::Stdio::null()) |
| 128 | + .stderr(std::process::Stdio::null()) |
| 129 | + .spawn(); |
| 130 | + let Ok(mut child) = child else { |
| 131 | + return false; |
| 132 | + }; |
| 133 | + let written = child |
| 134 | + .stdin |
| 135 | + .take() |
| 136 | + .is_some_and(|mut stdin| stdin.write_all(source.as_bytes()).is_ok()); |
| 137 | + child.wait().is_ok_and(|s| s.success()) && written |
| 138 | +} |
| 139 | + |
| 140 | +/// The first of [`COMPILERS`] that supports `musttail` (clang 13+, GCC |
| 141 | +/// 15+). The probe goes through stdin to /dev/null: no files to clean up. |
| 142 | +fn find_cc() -> Option<String> { |
| 143 | + const PROBE: &str = "static int g(int x) { return x; }\nint f(int x) { __attribute__((musttail)) return g(x); }\n"; |
| 144 | + COMPILERS |
| 145 | + .into_iter() |
| 146 | + .find(|cc| probe(cc, &["-c", "-o", "/dev/null"], PROBE)) |
| 147 | + .map(str::to_owned) |
| 148 | +} |
| 149 | + |
| 150 | +/// The linker `$LOUISE_LD` asks for: `Some(None)` for the compiler's |
| 151 | +/// own (`bfd` or `default`), `Some(Some(name))` for `-fuse-ld=name`, and |
| 152 | +/// `None` when it is not set. |
| 153 | +fn chosen_ld() -> Option<Option<String>> { |
| 154 | + let ld = std::env::var("LOUISE_LD").ok()?; |
| 155 | + Some(match ld.as_str() { |
| 156 | + "" | "bfd" | "default" => None, |
| 157 | + _ => Some(ld), |
| 158 | + }) |
| 159 | +} |
| 160 | + |
| 161 | +/// The linker to ask the compiler for (`-fuse-ld=`): `$LOUISE_LD`'s |
| 162 | +/// choice if set, else the first of [`LINKERS`] on `PATH`. It is not |
| 163 | +/// tried first (a test link costs about 35 ms on every cold build): a |
| 164 | +/// link that fails with it is retried with the compiler's own, which is |
| 165 | +/// then remembered ([`link`]). |
| 166 | +fn find_ld() -> Option<String> { |
| 167 | + chosen_ld().unwrap_or_else(|| { |
| 168 | + LINKERS |
| 169 | + .into_iter() |
| 170 | + .find(|(_, program)| on_path(program).is_some()) |
| 171 | + .map(|(flag, _)| flag.to_owned()) |
| 172 | + }) |
| 173 | +} |
| 174 | + |
| 175 | +/// The full path of `program` in `$PATH`. |
| 176 | +fn on_path(program: &str) -> Option<PathBuf> { |
| 177 | + if program.contains('/') { |
| 178 | + return Some(PathBuf::from(program)).filter(|p| p.is_file()); |
| 179 | + } |
| 180 | + std::env::split_paths(&std::env::var_os("PATH")?) |
| 181 | + .map(|dir| dir.join(program)) |
| 182 | + .find(|p| p.is_file()) |
| 183 | +} |
| 184 | + |
| 185 | +/// The compiler and linker a build uses, and the flags it gives them. |
| 186 | +#[derive(Clone, Debug, PartialEq)] |
| 187 | +struct Toolchain { |
| 188 | + cc: String, |
| 189 | + /// The `-fuse-ld=` linker; none for the compiler's default. |
| 190 | + ld: Option<String>, |
| 191 | + flags: Vec<String>, |
| 192 | +} |
| 193 | + |
| 194 | +impl Toolchain { |
| 195 | + /// What the choice depends on: the settings, `PATH`, and each |
| 196 | + /// candidate program's location and modification time. A changed or |
| 197 | + /// newly installed compiler or linker changes it. |
| 198 | + fn key(cc: Option<&str>) -> String { |
| 199 | + let mut h = std::collections::hash_map::DefaultHasher::new(); |
| 200 | + cc.hash(&mut h); |
| 201 | + std::env::var("LOUISE_LD").ok().hash(&mut h); |
| 202 | + std::env::var_os("PATH").hash(&mut h); |
| 203 | + let candidates = cc |
| 204 | + .map_or(COMPILERS.to_vec(), |cc| vec![cc]) |
| 205 | + .into_iter() |
| 206 | + .chain(LINKERS.iter().map(|(_, program)| *program)); |
| 207 | + for program in candidates { |
| 208 | + let path = on_path(program); |
| 209 | + let mtime = path |
| 210 | + .as_ref() |
| 211 | + .and_then(|p| std::fs::metadata(p).ok()?.modified().ok()); |
| 212 | + (program, path, mtime).hash(&mut h); |
| 213 | + } |
| 214 | + format!("{:016x}", h.finish()) |
| 215 | + } |
| 216 | + |
| 217 | + /// Keep the choice in `file`, under `key`. Failing to is harmless: the |
| 218 | + /// next build finds it again. |
| 219 | + fn write(&self, file: &Path, key: &str) { |
| 220 | + let ld = self.ld.as_deref().unwrap_or(""); |
| 221 | + let _ = std::fs::write(file, format!("{key}\n{}\n{ld}\n", self.cc)); |
| 222 | + } |
| 223 | + |
| 224 | + /// The cached choice in `file`, if it was made with `key`. |
| 225 | + fn read(file: &Path, key: &str) -> Option<(String, Option<String>)> { |
| 226 | + let text = std::fs::read_to_string(file).ok()?; |
| 227 | + let mut lines = text.lines(); |
| 228 | + if lines.next()? != key { |
| 229 | + return None; |
| 230 | + } |
| 231 | + let cc = lines.next()?.to_owned(); |
| 232 | + let ld = lines.next().filter(|l| !l.is_empty()).map(str::to_owned); |
| 233 | + Some((cc, ld)) |
| 234 | + } |
| 147 | 235 | } |
| 148 | 236 | |
| 149 | 237 | /// Compile `c_source` into the executable `output`, with the build files |
| @@ -199,13 +287,15 @@ pub fn build_executable_timed( |
| 199 | 287 | std::fs::create_dir_all(dir)?; |
| 200 | 288 | } |
| 201 | 289 | write_if_changed(&build.join("louise_rt.h"), HEADER)?; |
| 202 | | − // Finding the compiler runs it once (`default_cc`). |
| 203 | | − let (cc, flags) = timings.time("C compile", || compiler(opts))?; |
| 204 | | − let mut link = Vec::new(); |
| 290 | + // Finding the compiler and linker runs them, unless the build |
| 291 | + // directory remembers them (`toolchain`). |
| 292 | + let tools = timings.time("C compile", || toolchain(opts, build))?; |
| 293 | + let (cc, flags) = (&tools.cc, &tools.flags); |
| 294 | + let mut natives = Vec::new(); |
| 205 | 295 | if !opts.natives.is_empty() { |
| 206 | 296 | timings.time("natives", || -> Result<(), BuildError> { |
| 207 | 297 | for dep in &opts.natives { |
| 208 | | − link.extend(build_native(dep, build, &cc, &flags)?); |
| 298 | + natives.extend(build_native(dep, build, cc, flags)?); |
| 209 | 299 | } |
| 210 | 300 | Ok(()) |
| 211 | 301 | })?; |
| @@ -222,7 +312,7 @@ pub fn build_executable_timed( |
| 222 | 312 | let c_file = build.join(format!("{stem}.c")); |
| 223 | 313 | let object = cache.join(format!("{stem}.o")); |
| 224 | 314 | std::fs::write(&c_file, unit)?; |
| 225 | | − let mut compile = Command::new(&cc); |
| 315 | + let mut compile = Command::new(cc); |
| 226 | 316 | compile |
| 227 | 317 | .arg("-std=gnu11") |
| 228 | 318 | .args(if opts.release { |
| @@ -233,7 +323,7 @@ pub fn build_executable_timed( |
| 233 | 323 | .arg("-w") |
| 234 | 324 | .arg("-I") |
| 235 | 325 | .arg(build) |
| 236 | | − .args(&flags) |
| 326 | + .args(flags) |
| 237 | 327 | .arg("-c") |
| 238 | 328 | .arg(&c_file) |
| 239 | 329 | .arg("-o") |
| @@ -247,15 +337,12 @@ pub fn build_executable_timed( |
| 247 | 337 | .into_iter() |
| 248 | 338 | .collect::<Result<Vec<_>, _>>() |
| 249 | 339 | })?; |
| 250 | | − let mut cmd = Command::new(&cc); |
| 251 | | − cmd.args(&flags) |
| 252 | | − .args(&objects) |
| 253 | | − .args(&link) |
| 254 | | − .arg(lib_dir.join("liblouise_rt.a")) |
| 255 | | − .args(SYSTEM_LIBS) |
| 256 | | − .arg("-o") |
| 257 | | − .arg(output); |
| 258 | | − timings.time("link", || run_cc(&mut cmd)) |
| 340 | + let mut args: Vec<std::ffi::OsString> = objects.into_iter().map(Into::into).collect(); |
| 341 | + args.extend(natives.into_iter().map(Into::into)); |
| 342 | + args.push(lib_dir.join("liblouise_rt.a").into()); |
| 343 | + args.extend(SYSTEM_LIBS.iter().map(Into::into)); |
| 344 | + args.extend(["-o".into(), output.into()]); |
| 345 | + timings.time("link", || link(&tools, &args, build, opts)) |
| 259 | 346 | } |
| 260 | 347 | |
| 261 | 348 | /// How many C translation units to split a program into |
| @@ -279,19 +366,74 @@ pub fn default_units(release: bool) -> usize { |
| 279 | 366 | std::thread::available_parallelism().map_or(1, |n| n.get().min(8)) |
| 280 | 367 | } |
| 281 | 368 | |
| 282 | | −/// The C compiler and the extra flags to give it. |
| 283 | | −fn compiler(opts: &CcOptions) -> Result<(String, Vec<String>), BuildError> { |
| 284 | | − let cc = match opts.cc.clone().or_else(|| std::env::var("LOUISE_CC").ok()) { |
| 285 | | − Some(cc) => cc, |
| 286 | | − None => default_cc()?, |
| 287 | | − }; |
| 369 | +/// The C compiler, the linker and the extra flags to give the compiler. |
| 370 | +/// |
| 371 | +/// Finding the compiler runs it (the `musttail` probe, about 15 ms), so |
| 372 | +/// the choice is kept in `cache/toolchain` in the build directory (ADR |
| 373 | +/// 0025) and made again only when what it depends on changes |
| 374 | +/// ([`Toolchain::key`]). |
| 375 | +fn toolchain(opts: &CcOptions, build: &Path) -> Result<Toolchain, BuildError> { |
| 288 | 376 | let mut flags = opts.flags.clone(); |
| 289 | 377 | if flags.is_empty() |
| 290 | 378 | && let Ok(env) = std::env::var("LOUISE_CFLAGS") |
| 291 | 379 | { |
| 292 | 380 | flags.extend(env.split_whitespace().map(str::to_owned)); |
| 293 | 381 | } |
| 294 | | − Ok((cc, flags)) |
| 382 | + let given = opts.cc.clone().or_else(|| std::env::var("LOUISE_CC").ok()); |
| 383 | + let file = build.join("cache").join("toolchain"); |
| 384 | + let key = Toolchain::key(given.as_deref()); |
| 385 | + if let Some((cc, ld)) = Toolchain::read(&file, &key) { |
| 386 | + return Ok(Toolchain { cc, ld, flags }); |
| 387 | + } |
| 388 | + let cc = match given { |
| 389 | + Some(cc) => cc, |
| 390 | + None => find_cc().ok_or_else(|| { |
| 391 | + BuildError::Cc( |
| 392 | + "no C compiler supporting `musttail` was found (tried clang, cc, gcc): install clang 13+ or GCC 15+, or set LOUISE_CC" |
| 393 | + .into(), |
| 394 | + ) |
| 395 | + })?, |
| 396 | + }; |
| 397 | + let found = Toolchain { |
| 398 | + cc, |
| 399 | + ld: find_ld(), |
| 400 | + flags, |
| 401 | + }; |
| 402 | + found.write(&file, &key); |
| 403 | + Ok(found) |
| 404 | +} |
| 405 | + |
| 406 | +/// Link with `tools`. If the link fails with a linker found on `PATH` |
| 407 | +/// (not one `$LOUISE_LD` asked for), it is tried again with the |
| 408 | +/// compiler's own, and if that works, the build directory remembers it. |
| 409 | +fn link( |
| 410 | + tools: &Toolchain, |
| 411 | + args: &[std::ffi::OsString], |
| 412 | + build: &Path, |
| 413 | + opts: &CcOptions, |
| 414 | +) -> Result<(), BuildError> { |
| 415 | + let command = |ld: Option<&str>| { |
| 416 | + let mut cmd = Command::new(&tools.cc); |
| 417 | + cmd.args(&tools.flags) |
| 418 | + .args(ld.map(|ld| format!("-fuse-ld={ld}"))) |
| 419 | + .args(args); |
| 420 | + cmd |
| 421 | + }; |
| 422 | + let first = run_cc(&mut command(tools.ld.as_deref())); |
| 423 | + if first.is_ok() || tools.ld.is_none() || chosen_ld().is_some() { |
| 424 | + return first; |
| 425 | + } |
| 426 | + run_cc(&mut command(None))?; |
| 427 | + let given = opts.cc.clone().or_else(|| std::env::var("LOUISE_CC").ok()); |
| 428 | + Toolchain { |
| 429 | + ld: None, |
| 430 | + ..tools.clone() |
| 431 | + } |
| 432 | + .write( |
| 433 | + &build.join("cache").join("toolchain"), |
| 434 | + &Toolchain::key(given.as_deref()), |
| 435 | + ); |
| 436 | + Ok(()) |
| 295 | 437 | } |
| 296 | 438 | |
| 297 | 439 | /// Run `compile`, which writes `object`, with `runner`, unless `object` |
| @@ -530,7 +672,7 @@ mod tests { |
| 530 | 672 | |
| 531 | 673 | #[test] |
| 532 | 674 | fn objects_are_rebuilt_only_when_an_input_changes() { |
| 533 | | − let (cc, _) = compiler(&CcOptions::default()).expect("a C compiler"); |
| 675 | + let cc = find_cc().expect("a C compiler"); |
| 534 | 676 | let dir = std::env::temp_dir().join(format!("louise-cache-test-{}", std::process::id())); |
| 535 | 677 | std::fs::create_dir_all(&dir).unwrap(); |
| 536 | 678 | std::fs::write( |
| @@ -557,4 +699,73 @@ mod tests { |
| 557 | 699 | assert_eq!(build("-O1"), 3, "the flags changed"); |
| 558 | 700 | let _ = std::fs::remove_dir_all(&dir); |
| 559 | 701 | } |
| 702 | + |
| 703 | + #[test] |
| 704 | + fn the_toolchain_is_found_once_per_build_directory() { |
| 705 | + let dir = |
| 706 | + std::env::temp_dir().join(format!("louise-toolchain-test-{}", std::process::id())); |
| 707 | + std::fs::create_dir_all(dir.join("cache")).unwrap(); |
| 708 | + let opts = CcOptions::default(); |
| 709 | + let found = toolchain(&opts, &dir).expect("a C compiler"); |
| 710 | + let file = dir.join("cache").join("toolchain"); |
| 711 | + assert!(file.is_file(), "the choice is kept"); |
| 712 | + // A kept choice is used as it is: only its key is checked. |
| 713 | + let given = std::env::var("LOUISE_CC").ok(); |
| 714 | + let key = Toolchain::key(given.as_deref()); |
| 715 | + std::fs::write(&file, format!("{key}\nkept-cc\nkept-ld\n")).unwrap(); |
| 716 | + let kept = toolchain(&opts, &dir).unwrap(); |
| 717 | + assert_eq!( |
| 718 | + (kept.cc.as_str(), kept.ld.as_deref()), |
| 719 | + ("kept-cc", Some("kept-ld")) |
| 720 | + ); |
| 721 | + // Another compiler changes the key: the choice is made again. |
| 722 | + let other = CcOptions { |
| 723 | + cc: Some(found.cc.clone()), |
| 724 | + ..CcOptions::default() |
| 725 | + }; |
| 726 | + let again = toolchain(&other, &dir).unwrap(); |
| 727 | + assert_eq!(again.cc, found.cc); |
| 728 | + assert_ne!(again.ld.as_deref(), Some("kept-ld")); |
| 729 | + let _ = std::fs::remove_dir_all(&dir); |
| 730 | + } |
| 731 | + |
| 732 | + #[test] |
| 733 | + fn a_link_that_fails_with_the_found_linker_uses_the_default() { |
| 734 | + if chosen_ld().is_some() { |
| 735 | + eprintln!("skipping: LOUISE_LD is set"); |
| 736 | + return; |
| 737 | + } |
| 738 | + let dir = std::env::temp_dir().join(format!("louise-link-test-{}", std::process::id())); |
| 739 | + std::fs::create_dir_all(dir.join("cache")).unwrap(); |
| 740 | + let cc = find_cc().expect("a C compiler"); |
| 741 | + let object = dir.join("main.o"); |
| 742 | + std::fs::write(dir.join("main.c"), "int main(void) { return 0; }\n").unwrap(); |
| 743 | + run_cc( |
| 744 | + Command::new(&cc) |
| 745 | + .arg("-c") |
| 746 | + .arg(dir.join("main.c")) |
| 747 | + .arg("-o") |
| 748 | + .arg(&object), |
| 749 | + ) |
| 750 | + .unwrap(); |
| 751 | + let tools = Toolchain { |
| 752 | + cc, |
| 753 | + ld: Some("no-such-linker".into()), |
| 754 | + flags: Vec::new(), |
| 755 | + }; |
| 756 | + let args = [ |
| 757 | + object.into_os_string(), |
| 758 | + "-o".into(), |
| 759 | + dir.join("main").into_os_string(), |
| 760 | + ]; |
| 761 | + link(&tools, &args, &dir, &CcOptions::default()).expect("linked with the default"); |
| 762 | + assert!(dir.join("main").is_file()); |
| 763 | + let kept = std::fs::read_to_string(dir.join("cache").join("toolchain")).unwrap(); |
| 764 | + assert_eq!( |
| 765 | + kept.lines().nth(2), |
| 766 | + Some(""), |
| 767 | + "the default is remembered: {kept}" |
| 768 | + ); |
| 769 | + let _ = std::fs::remove_dir_all(&dir); |
| 770 | + } |
| 560 | 771 | } |