Skip to main content

bootstrap/core/build_steps/
llvm.rs

1//! Compilation of native dependencies like LLVM.
2//!
3//! Native projects like LLVM unfortunately aren't suited just yet for
4//! compilation in build scripts that Cargo has. This is because the
5//! compilation takes a *very* long time but also because we don't want to
6//! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
7//!
8//! LLVM and compiler-rt are essentially just wired up to everything else to
9//! ensure that they're always in place if needed.
10
11use std::env::consts::EXE_EXTENSION;
12use std::ffi::{OsStr, OsString};
13use std::path::{Path, PathBuf};
14use std::sync::OnceLock;
15use std::{env, fs};
16
17use build_helper::exit;
18use build_helper::git::PathFreshness;
19
20use crate::core::build_steps::llvm;
21use crate::core::builder::{Builder, RunConfig, ShouldRun, Step, StepMetadata};
22use crate::core::config::{Config, TargetSelection};
23use crate::utils::build_stamp::{BuildStamp, generate_smart_stamp_hash};
24use crate::utils::exec::command;
25use crate::utils::helpers::{
26    self, exe, get_clang_cl_resource_dir, t, unhashed_basename, up_to_date,
27};
28use crate::{CLang, GitRepo, Kind, trace};
29
30#[derive(Clone)]
31pub struct LlvmResult {
32    /// Path to llvm-config binary.
33    /// NB: This is always the host llvm-config!
34    pub host_llvm_config: PathBuf,
35    /// Path to LLVM cmake directory for the target.
36    pub llvm_cmake_dir: PathBuf,
37}
38
39pub struct Meta {
40    stamp: BuildStamp,
41    res: LlvmResult,
42    out_dir: PathBuf,
43    root: String,
44}
45
46pub enum LlvmBuildStatus {
47    AlreadyBuilt(LlvmResult),
48    ShouldBuild(Meta),
49}
50
51impl LlvmBuildStatus {
52    pub fn should_build(&self) -> bool {
53        match self {
54            LlvmBuildStatus::AlreadyBuilt(_) => false,
55            LlvmBuildStatus::ShouldBuild(_) => true,
56        }
57    }
58
59    #[cfg(test)]
60    pub fn llvm_result(&self) -> &LlvmResult {
61        match self {
62            LlvmBuildStatus::AlreadyBuilt(res) => res,
63            LlvmBuildStatus::ShouldBuild(meta) => &meta.res,
64        }
65    }
66}
67
68/// Allows each step to add C/Cxx flags which are only used for a specific cmake invocation.
69#[derive(Debug, Clone, Default)]
70struct CcFlags {
71    /// Additional values for CMAKE_CC_FLAGS, to be added before all other values.
72    cflags: OsString,
73    /// Additional values for CMAKE_CXX_FLAGS, to be added before all other values.
74    cxxflags: OsString,
75}
76
77impl CcFlags {
78    fn push_all(&mut self, s: impl AsRef<OsStr>) {
79        let s = s.as_ref();
80        self.cflags.push(" ");
81        self.cflags.push(s);
82        self.cxxflags.push(" ");
83        self.cxxflags.push(s);
84    }
85}
86
87/// Linker flags to pass to LLVM's CMake invocation.
88#[derive(Debug, Clone, Default)]
89struct LdFlags {
90    /// CMAKE_EXE_LINKER_FLAGS
91    exe: OsString,
92    /// CMAKE_SHARED_LINKER_FLAGS
93    shared: OsString,
94    /// CMAKE_MODULE_LINKER_FLAGS
95    module: OsString,
96}
97
98impl LdFlags {
99    fn push_all(&mut self, s: impl AsRef<OsStr>) {
100        let s = s.as_ref();
101        self.exe.push(" ");
102        self.exe.push(s);
103        self.shared.push(" ");
104        self.shared.push(s);
105        self.module.push(" ");
106        self.module.push(s);
107    }
108}
109
110/// This returns whether we've already previously built LLVM.
111///
112/// It's used to avoid busting caches during x.py check -- if we've already built
113/// LLVM, it's fine for us to not try to avoid doing so.
114///
115/// This will return the llvm-config if it can get it (but it will not build it
116/// if not).
117pub fn prebuilt_llvm_config(
118    builder: &Builder<'_>,
119    target: TargetSelection,
120    // Certain commands (like `x test mir-opt --bless`) may call this function with different targets,
121    // which could bypass the CI LLVM early-return even if `builder.config.llvm_from_ci` is true.
122    // This flag should be `true` only if the caller needs the LLVM sources (e.g., if it will build LLVM).
123    handle_submodule_when_needed: bool,
124) -> LlvmBuildStatus {
125    builder.config.maybe_download_ci_llvm();
126
127    // If we're using a custom LLVM bail out here, but we can only use a
128    // custom LLVM for the build triple.
129    if let Some(config) = builder.config.target_config.get(&target)
130        && let Some(ref s) = config.llvm_config
131    {
132        check_llvm_version(builder, s);
133        let host_llvm_config = s.to_path_buf();
134        let mut llvm_cmake_dir = host_llvm_config.clone();
135        llvm_cmake_dir.pop();
136        llvm_cmake_dir.pop();
137        llvm_cmake_dir.push("lib");
138        llvm_cmake_dir.push("cmake");
139        llvm_cmake_dir.push("llvm");
140        return LlvmBuildStatus::AlreadyBuilt(LlvmResult { host_llvm_config, llvm_cmake_dir });
141    }
142
143    if handle_submodule_when_needed {
144        // If submodules are disabled, this does nothing.
145        builder.config.update_submodule("src/llvm-project");
146    }
147
148    let root = "src/llvm-project/llvm";
149    let out_dir = builder.llvm_out(target);
150
151    let build_llvm_config = if let Some(build_llvm_config) = builder
152        .config
153        .target_config
154        .get(&builder.config.host_target)
155        .and_then(|config| config.llvm_config.clone())
156    {
157        build_llvm_config
158    } else {
159        let mut llvm_config_ret_dir = builder.llvm_out(builder.config.host_target);
160        llvm_config_ret_dir.push("bin");
161        llvm_config_ret_dir.join(exe("llvm-config", builder.config.host_target))
162    };
163
164    let llvm_cmake_dir = out_dir.join("lib/cmake/llvm");
165    let res = LlvmResult { host_llvm_config: build_llvm_config, llvm_cmake_dir };
166
167    static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
168    let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
169        generate_smart_stamp_hash(
170            builder,
171            &builder.config.src.join("src/llvm-project"),
172            builder.in_tree_llvm_info.sha().unwrap_or_default(),
173        )
174    });
175
176    let stamp = BuildStamp::new(&out_dir).with_prefix("llvm").add_stamp(smart_stamp_hash);
177
178    if stamp.is_up_to_date() {
179        if stamp.stamp().is_empty() {
180            builder.info(
181                "Could not determine the LLVM submodule commit hash. \
182                     Assuming that an LLVM rebuild is not necessary.",
183            );
184            builder.info(&format!(
185                "To force LLVM to rebuild, remove the file `{}`",
186                stamp.path().display()
187            ));
188        }
189        return LlvmBuildStatus::AlreadyBuilt(res);
190    }
191
192    LlvmBuildStatus::ShouldBuild(Meta { stamp, res, out_dir, root: root.into() })
193}
194
195/// Paths whose changes invalidate LLVM downloads.
196pub const LLVM_INVALIDATION_PATHS: &[&str] = &[
197    "src/llvm-project",
198    "src/bootstrap/download-ci-llvm-stamp",
199    // the LLVM shared object file is named `LLVM-<LLVM-version>-rust-{version}-nightly`
200    "src/version",
201];
202
203/// Detect whether LLVM sources have been modified locally or not.
204pub(crate) fn detect_llvm_freshness(config: &Config, is_git: bool) -> PathFreshness {
205    if is_git {
206        config.check_path_modifications(LLVM_INVALIDATION_PATHS)
207    } else if let Some(info) = crate::utils::channel::read_commit_info_file(&config.src) {
208        PathFreshness::LastModifiedUpstream { upstream: info.sha.trim().to_owned() }
209    } else {
210        PathFreshness::MissingUpstream
211    }
212}
213
214/// Returns whether the CI-found LLVM is currently usable.
215///
216/// This checks the build triple platform to confirm we're usable at all, and if LLVM
217/// with/without assertions is available.
218pub(crate) fn is_ci_llvm_available_for_target(
219    host_target: &TargetSelection,
220    asserts: bool,
221) -> bool {
222    // This is currently all tier 1 targets and tier 2 targets with host tools
223    // (since others may not have CI artifacts)
224    // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
225    let supported_platforms = [
226        // tier 1
227        ("aarch64-unknown-linux-gnu", false),
228        ("aarch64-apple-darwin", false),
229        ("aarch64-pc-windows-msvc", false),
230        ("i686-pc-windows-msvc", false),
231        ("i686-unknown-linux-gnu", false),
232        ("x86_64-unknown-linux-gnu", true),
233        ("x86_64-apple-darwin", true),
234        ("x86_64-pc-windows-gnu", false),
235        ("x86_64-pc-windows-msvc", true),
236        // tier 2 with host tools
237        ("aarch64-unknown-linux-musl", false),
238        ("aarch64-pc-windows-gnullvm", false),
239        ("arm-unknown-linux-gnueabi", false),
240        ("arm-unknown-linux-gnueabihf", false),
241        ("armv7-unknown-linux-gnueabihf", false),
242        ("i686-pc-windows-gnu", false),
243        ("loongarch64-unknown-linux-gnu", false),
244        ("loongarch64-unknown-linux-musl", false),
245        ("powerpc-unknown-linux-gnu", false),
246        ("powerpc64-unknown-linux-gnu", false),
247        ("powerpc64-unknown-linux-musl", false),
248        ("powerpc64le-unknown-linux-gnu", false),
249        ("powerpc64le-unknown-linux-musl", false),
250        ("riscv64gc-unknown-linux-gnu", false),
251        ("s390x-unknown-linux-gnu", false),
252        ("x86_64-pc-windows-gnullvm", false),
253        ("x86_64-unknown-freebsd", false),
254        ("x86_64-unknown-illumos", false),
255        ("x86_64-unknown-linux-musl", false),
256        ("x86_64-unknown-netbsd", false),
257    ];
258
259    if !supported_platforms.contains(&(&*host_target.triple, asserts))
260        && (asserts || !supported_platforms.contains(&(&*host_target.triple, true)))
261    {
262        return false;
263    }
264
265    true
266}
267
268#[derive(Debug, Clone, Hash, PartialEq, Eq)]
269pub struct Llvm {
270    pub target: TargetSelection,
271}
272
273impl Step for Llvm {
274    type Output = LlvmResult;
275
276    const IS_HOST: bool = true;
277
278    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
279        run.path("src/llvm-project").path("src/llvm-project/llvm")
280    }
281
282    fn make_run(run: RunConfig<'_>) {
283        run.builder.ensure(Llvm { target: run.target });
284    }
285
286    /// Compile LLVM for `target`.
287    fn run(self, builder: &Builder<'_>) -> LlvmResult {
288        let target = self.target;
289        let target_native = if self.target.starts_with("riscv") {
290            // RISC-V target triples in Rust is not named the same as C compiler target triples.
291            // This converts Rust RISC-V target triples to C compiler triples.
292            let idx = target.triple.find('-').unwrap();
293
294            format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
295        } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
296            // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
297            // Set the version suffix to 13.0 so the correct target details are used.
298            format!("{}{}", self.target, "13.0")
299        } else {
300            target.to_string()
301        };
302
303        // If LLVM has already been built or been downloaded through download-ci-llvm, we avoid building it again.
304        let Meta { stamp, res, out_dir, root } = match prebuilt_llvm_config(builder, target, true) {
305            LlvmBuildStatus::AlreadyBuilt(p) => return p,
306            LlvmBuildStatus::ShouldBuild(m) => m,
307        };
308
309        if builder.llvm_link_shared() && target.is_windows() && !target.is_windows_gnullvm() {
310            panic!("shared linking to LLVM is not currently supported on {}", target.triple);
311        }
312
313        let _guard = builder.msg_unstaged(Kind::Build, "LLVM", target);
314        t!(stamp.remove());
315        let _time = helpers::timeit(builder);
316        t!(fs::create_dir_all(&out_dir));
317
318        // https://llvm.org/docs/CMake.html
319        let mut cfg = cmake::Config::new(builder.src.join(root));
320        let mut ldflags = LdFlags::default();
321
322        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
323            (false, _) => "Debug",
324            (true, false) => "Release",
325            (true, true) => "RelWithDebInfo",
326        };
327
328        // NOTE: remember to also update `bootstrap.example.toml` when changing the
329        // defaults!
330        let llvm_targets = match &builder.config.llvm_targets {
331            Some(s) => s,
332            None => {
333                "AArch64;AMDGPU;ARM;BPF;Hexagon;LoongArch;MSP430;Mips;NVPTX;PowerPC;RISCV;\
334                     Sparc;SystemZ;WebAssembly;X86"
335            }
336        };
337
338        let llvm_exp_targets = match builder.config.llvm_experimental_targets {
339            Some(ref s) => s,
340            None => "AVR;M68k;CSKY;Xtensa",
341        };
342
343        let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
344        let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
345        let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
346        let enable_warnings = if builder.config.llvm_enable_warnings { "ON" } else { "OFF" };
347
348        cfg.out_dir(&out_dir)
349            .profile(profile)
350            .define("LLVM_ENABLE_ASSERTIONS", assertions)
351            .define("LLVM_UNREACHABLE_OPTIMIZE", "OFF")
352            .define("LLVM_ENABLE_PLUGINS", plugins)
353            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
354            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
355            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
356            .define("LLVM_INCLUDE_DOCS", "OFF")
357            .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
358            .define("LLVM_INCLUDE_TESTS", enable_tests)
359            .define("LLVM_ENABLE_LIBEDIT", "OFF")
360            .define("LLVM_ENABLE_BINDINGS", "OFF")
361            .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
362            .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
363            .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
364            .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native)
365            .define("LLVM_ENABLE_WARNINGS", enable_warnings);
366
367        // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
368        // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
369        // This flag makes sure `FileCheck` is copied in the final binaries directory.
370        cfg.define("LLVM_INSTALL_UTILS", "ON");
371
372        if builder.config.llvm_profile_generate {
373            cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
374            if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
375                cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
376            }
377            cfg.define("LLVM_BUILD_RUNTIME", "No");
378        }
379        if let Some(path) = builder.config.llvm_profile_use.as_ref() {
380            cfg.define("LLVM_PROFDATA_FILE", path);
381        }
382
383        // Libraries for ELF section compression and profraw files merging.
384        if !target.is_msvc() {
385            cfg.define("LLVM_ENABLE_ZLIB", "ON");
386        } else {
387            cfg.define("LLVM_ENABLE_ZLIB", "OFF");
388        }
389
390        // Are we compiling for iOS/tvOS/watchOS/visionOS?
391        if target.contains("apple-ios")
392            || target.contains("apple-tvos")
393            || target.contains("apple-watchos")
394            || target.contains("apple-visionos")
395        {
396            // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
397            cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
398            // Zlib fails to link properly, leading to a compiler error.
399            cfg.define("LLVM_ENABLE_ZLIB", "OFF");
400        }
401
402        // This setting makes the LLVM tools link to the dynamic LLVM library,
403        // which saves both memory during parallel links and overall disk space
404        // for the tools. We don't do this on every platform as it doesn't work
405        // equally well everywhere.
406        if builder.llvm_link_shared() {
407            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
408        }
409
410        if (target.starts_with("csky")
411            || target.starts_with("riscv")
412            || target.starts_with("sparc-"))
413            && !target.contains("freebsd")
414            && !target.contains("openbsd")
415            && !target.contains("netbsd")
416        {
417            // CSKY and RISC-V GCC erroneously requires linking against
418            // `libatomic` when using 1-byte and 2-byte C++
419            // atomics but the LLVM build system check cannot
420            // detect this. Therefore it is set manually here.
421            // Some BSD uses Clang as its system compiler and
422            // provides no libatomic in its base system so does
423            // not want this. 32-bit SPARC requires linking against
424            // libatomic as well.
425            ldflags.exe.push(" -latomic");
426            ldflags.shared.push(" -latomic");
427        }
428
429        if target.starts_with("mips") && target.contains("netbsd") {
430            // LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic
431            ldflags.exe.push(" -latomic");
432            ldflags.shared.push(" -latomic");
433        }
434
435        if target.starts_with("arm64ec") {
436            // MSVC linker requires the -machine:arm64ec flag to be passed to
437            // know it's linking as Arm64EC (vs Arm64X).
438            ldflags.exe.push(" -machine:arm64ec");
439            ldflags.shared.push(" -machine:arm64ec");
440        }
441
442        if target.is_msvc() {
443            cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");
444            cfg.static_crt(true);
445        }
446
447        if target.starts_with("i686") {
448            cfg.define("LLVM_BUILD_32_BITS", "ON");
449        }
450
451        if target.starts_with("x86_64") && target.contains("ohos") {
452            cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");
453        }
454
455        let mut enabled_llvm_projects = Vec::new();
456
457        if helpers::forcing_clang_based_tests() {
458            enabled_llvm_projects.push("clang");
459        }
460
461        if builder.config.llvm_polly {
462            enabled_llvm_projects.push("polly");
463        }
464
465        if builder.config.llvm_clang {
466            enabled_llvm_projects.push("clang");
467        }
468
469        // We want libxml to be disabled.
470        // See https://github.com/rust-lang/rust/pull/50104
471        cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
472
473        let mut enabled_llvm_runtimes = Vec::new();
474
475        if helpers::forcing_clang_based_tests() {
476            enabled_llvm_runtimes.push("compiler-rt");
477        }
478
479        if !enabled_llvm_projects.is_empty() {
480            enabled_llvm_projects.sort();
481            enabled_llvm_projects.dedup();
482            cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
483        }
484
485        if !enabled_llvm_runtimes.is_empty() {
486            enabled_llvm_runtimes.sort();
487            enabled_llvm_runtimes.dedup();
488            cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";"));
489        }
490
491        if let Some(num_linkers) = builder.config.llvm_link_jobs
492            && num_linkers > 0
493        {
494            cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
495        }
496
497        // https://llvm.org/docs/HowToCrossCompileLLVM.html
498        if !builder.config.is_host_target(target) {
499            let LlvmResult { host_llvm_config, .. } =
500                builder.ensure(Llvm { target: builder.config.host_target });
501            if !builder.config.dry_run() {
502                let llvm_bindir = command(&host_llvm_config)
503                    .arg("--bindir")
504                    .cached()
505                    .run_capture_stdout(builder)
506                    .stdout();
507                let host_bin = Path::new(llvm_bindir.trim());
508                cfg.define(
509                    "LLVM_TABLEGEN",
510                    host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
511                );
512                // LLVM_NM is required for cross compiling using MSVC
513                cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
514            }
515            cfg.define("LLVM_CONFIG_PATH", host_llvm_config);
516            if builder.config.llvm_clang {
517                let build_bin =
518                    builder.llvm_out(builder.config.host_target).join("build").join("bin");
519                let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
520                if !builder.config.dry_run() && !clang_tblgen.exists() {
521                    panic!("unable to find {}", clang_tblgen.display());
522                }
523                cfg.define("CLANG_TABLEGEN", clang_tblgen);
524            }
525        }
526
527        let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
528            // Allow version-suffix="" to not define a version suffix at all.
529            if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
530        } else if builder.config.channel == "dev" {
531            // Changes to a version suffix require a complete rebuild of the LLVM.
532            // To avoid rebuilds during a time of version bump, don't include rustc
533            // release number on the dev channel.
534            Some("-rust-dev".to_string())
535        } else {
536            Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
537        };
538        if let Some(ref suffix) = llvm_version_suffix {
539            cfg.define("LLVM_VERSION_SUFFIX", suffix);
540        }
541
542        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
543        configure_llvm(builder, target, &mut cfg);
544
545        for (key, val) in &builder.config.llvm_build_config {
546            cfg.define(key, val);
547        }
548
549        if builder.config.dry_run() {
550            return res;
551        }
552
553        cfg.build();
554
555        // Helper to find the name of LLVM's shared library on darwin and linux.
556        let find_llvm_lib_name = |extension| {
557            let major = get_llvm_version_major(builder, &res.host_llvm_config);
558            match &llvm_version_suffix {
559                Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.{extension}"),
560                None => format!("libLLVM-{major}.{extension}"),
561            }
562        };
563
564        // FIXME(ZuseZ4): Do we need that for Enzyme too?
565        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
566        // libLLVM.dylib will be built. However, llvm-config will still look
567        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
568        // link to make llvm-config happy.
569        if builder.llvm_link_shared() && target.contains("apple-darwin") {
570            let lib_name = find_llvm_lib_name("dylib");
571            let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
572            if !lib_llvm.exists() {
573                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
574            }
575        }
576
577        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
578        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
579        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
580        if builder.llvm_link_shared()
581            && builder.config.llvm_optimize
582            && !builder.config.llvm_release_debuginfo
583        {
584            // Find the name of the LLVM shared library that we just built.
585            let lib_name = find_llvm_lib_name("so");
586
587            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
588            // debuginfo.
589            crate::core::build_steps::compile::strip_debug(
590                builder,
591                target,
592                &out_dir.join("lib").join(&lib_name),
593            );
594            crate::core::build_steps::compile::strip_debug(
595                builder,
596                target,
597                &out_dir.join("build").join("lib").join(&lib_name),
598            );
599        }
600
601        t!(stamp.write());
602
603        res
604    }
605
606    fn metadata(&self) -> Option<StepMetadata> {
607        Some(StepMetadata::build("llvm", self.target))
608    }
609}
610
611pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
612    command(llvm_config)
613        .arg("--version")
614        .cached()
615        .run_capture_stdout(builder)
616        .stdout()
617        .trim()
618        .to_owned()
619}
620
621pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
622    let version = get_llvm_version(builder, llvm_config);
623    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
624    major_str.parse().unwrap()
625}
626
627fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
628    if builder.config.dry_run() {
629        return;
630    }
631
632    let version = get_llvm_version(builder, llvm_config);
633    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
634    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())
635        && major >= 20
636    {
637        return;
638    }
639    panic!("\n\nbad LLVM version: {version}, need >=20\n\n")
640}
641
642fn configure_cmake(
643    builder: &Builder<'_>,
644    target: TargetSelection,
645    cfg: &mut cmake::Config,
646    use_compiler_launcher: bool,
647    mut ldflags: LdFlags,
648    ccflags: CcFlags,
649    suppressed_compiler_flag_prefixes: &[&str],
650) {
651    // Do not print installation messages for up-to-date files.
652    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
653    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
654
655    // Do not allow the user's value of DESTDIR to influence where
656    // LLVM will install itself. LLVM must always be installed in our
657    // own build directories.
658    cfg.env("DESTDIR", "");
659
660    if builder.ninja() {
661        cfg.generator("Ninja");
662    }
663    cfg.target(&target.triple).host(&builder.config.host_target.triple);
664
665    if !builder.config.is_host_target(target) {
666        cfg.define("CMAKE_CROSSCOMPILING", "True");
667
668        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
669        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
670        // which isn't set when compiling outside `build.rs` (like bootstrap is).
671        //
672        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
673        if target.contains("netbsd") {
674            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
675        } else if target.contains("dragonfly") {
676            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
677        } else if target.contains("openbsd") {
678            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
679        } else if target.contains("freebsd") {
680            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
681        } else if target.is_windows() {
682            cfg.define("CMAKE_SYSTEM_NAME", "Windows");
683        } else if target.contains("haiku") {
684            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
685        } else if target.contains("solaris") || target.contains("illumos") {
686            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
687        } else if target.contains("linux") {
688            cfg.define("CMAKE_SYSTEM_NAME", "Linux");
689        } else if target.contains("darwin") {
690            // macOS
691            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
692        } else if target.contains("ios") {
693            cfg.define("CMAKE_SYSTEM_NAME", "iOS");
694        } else if target.contains("tvos") {
695            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
696        } else if target.contains("visionos") {
697            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
698        } else if target.contains("watchos") {
699            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
700        } else if target.contains("none") {
701            // "none" should be the last branch
702            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
703        } else {
704            builder.info(&format!(
705                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
706            ));
707            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
708            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
709            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
710        }
711
712        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
713        // that case like CMake we cannot easily determine system version either.
714        //
715        // Since, the LLVM itself makes rather limited use of version checks in
716        // CMakeFiles (and then only in tests), and so far no issues have been
717        // reported, the system version is currently left unset.
718
719        if target.contains("apple") {
720            if !target.contains("darwin") {
721                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
722                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?
723                //
724                // So for now we set it to "Darwin" on all Apple platforms.
725                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
726
727                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
728                cfg.define("CMAKE_OSX_SYSROOT", "/");
729                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
730            }
731
732            // Make sure that CMake does not build universal binaries on macOS.
733            // Explicitly specify the one single target architecture.
734            if target.starts_with("aarch64") {
735                // macOS uses a different name for building arm64
736                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
737            } else if target.starts_with("i686") {
738                // macOS uses a different name for building i386
739                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
740            } else {
741                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
742            }
743        }
744    }
745
746    let sanitize_cc = |cc: &Path| {
747        if target.is_msvc() {
748            OsString::from(cc.to_str().unwrap().replace('\\', "/"))
749        } else {
750            cc.as_os_str().to_owned()
751        }
752    };
753
754    // MSVC with CMake uses msbuild by default which doesn't respect these
755    // vars that we'd otherwise configure. In that case we just skip this
756    // entirely.
757    if target.is_msvc() && !builder.ninja() {
758        return;
759    }
760
761    let (cc, cxx) = match builder.config.llvm_clang_cl {
762        Some(ref cl) => (cl.into(), cl.into()),
763        None => (builder.cc(target), builder.cxx(target).unwrap()),
764    };
765
766    // If ccache is configured we inform the build a little differently how
767    // to invoke ccache while also invoking our compilers.
768    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {
769        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
770            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
771    }
772    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
773        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
774        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
775
776    cfg.build_arg("-j").build_arg(builder.jobs().to_string());
777    let mut cflags = ccflags.cflags.clone();
778    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
779    // our flags via `.cflag`/`.cxxflag` instead.
780    //
781    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
782    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
783    for flag in builder
784        .cc_handled_clags(target, CLang::C)
785        .into_iter()
786        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::C))
787        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))
788    {
789        cflags.push(" ");
790        cflags.push(flag);
791    }
792    if let Some(ref s) = builder.config.llvm_cflags {
793        cflags.push(" ");
794        cflags.push(s);
795    }
796    if target.contains("ohos") {
797        cflags.push(" -D_LINUX_SYSINFO_H");
798    }
799    if builder.config.llvm_clang_cl.is_some() {
800        cflags.push(format!(" --target={target}"));
801    }
802    cfg.define("CMAKE_C_FLAGS", cflags);
803    let mut cxxflags = ccflags.cxxflags.clone();
804    for flag in builder
805        .cc_handled_clags(target, CLang::Cxx)
806        .into_iter()
807        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::Cxx))
808        .filter(|flag| {
809            !suppressed_compiler_flag_prefixes
810                .iter()
811                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
812        })
813    {
814        cxxflags.push(" ");
815        cxxflags.push(flag);
816    }
817    if let Some(ref s) = builder.config.llvm_cxxflags {
818        cxxflags.push(" ");
819        cxxflags.push(s);
820    }
821    if target.contains("ohos") {
822        cxxflags.push(" -D_LINUX_SYSINFO_H");
823    }
824    if builder.config.llvm_clang_cl.is_some() {
825        cxxflags.push(format!(" --target={target}"));
826    }
827
828    cfg.define("CMAKE_CXX_FLAGS", cxxflags);
829    if let Some(ar) = builder.ar(target)
830        && ar.is_absolute()
831    {
832        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
833        // tries to resolve this path in the LLVM build directory.
834        cfg.define("CMAKE_AR", sanitize_cc(&ar));
835    }
836
837    if let Some(ranlib) = builder.ranlib(target)
838        && ranlib.is_absolute()
839    {
840        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
841        // tries to resolve this path in the LLVM build directory.
842        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
843    }
844
845    if let Some(ref flags) = builder.config.llvm_ldflags {
846        ldflags.push_all(flags);
847    }
848
849    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
850        ldflags.push_all(&flags);
851    }
852
853    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
854    // We also do this if the user explicitly requested static libstdc++.
855    if builder.config.llvm_static_stdcpp
856        && !target.is_msvc()
857        && !target.contains("netbsd")
858        && !target.contains("solaris")
859    {
860        if target.contains("apple") || target.is_windows() {
861            ldflags.push_all("-static-libstdc++");
862        } else {
863            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
864        }
865    }
866
867    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
868    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
869    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
870
871    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
872        cfg.env("RUSTC_LOG", "sccache=warn");
873    }
874}
875
876fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
877    // ThinLTO is only available when building with LLVM, enabling LLD is required.
878    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
879    if builder.config.llvm_thin_lto {
880        cfg.define("LLVM_ENABLE_LTO", "Thin");
881        if !target.contains("apple") {
882            cfg.define("LLVM_ENABLE_LLD", "ON");
883        }
884    }
885
886    // Libraries for ELF section compression.
887    if builder.config.llvm_libzstd {
888        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
889        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
890    } else {
891        cfg.define("LLVM_ENABLE_ZSTD", "OFF");
892    }
893
894    if let Some(ref linker) = builder.config.llvm_use_linker {
895        cfg.define("LLVM_USE_LINKER", linker);
896    }
897
898    if builder.config.llvm_allow_old_toolchain {
899        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
900    }
901}
902
903// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
904fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
905    let kind = if host == target { "HOST" } else { "TARGET" };
906    let target_u = target.replace('-', "_");
907    env::var_os(format!("{var_base}_{target}"))
908        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))
909        .or_else(|| env::var_os(format!("{kind}_{var_base}")))
910        .or_else(|| env::var_os(var_base))
911}
912
913#[derive(Clone)]
914pub struct BuiltOmpOffload {
915    /// Path to the omp and offload dylibs.
916    offload: Vec<PathBuf>,
917}
918
919impl BuiltOmpOffload {
920    pub fn offload_paths(&self) -> Vec<PathBuf> {
921        self.offload.clone()
922    }
923}
924
925// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
926// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
927// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
928// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
929// don't always build clang (due to compile times), but instead use a slightly older external clang.
930// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the
931// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
932// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
933// runtimes. This external clang will try to use it's own (older) include dirs when building our
934// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
935// explicitly set our include dirs.
936#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
937pub struct OmpOffload {
938    pub target: TargetSelection,
939}
940
941impl Step for OmpOffload {
942    type Output = BuiltOmpOffload;
943    const IS_HOST: bool = true;
944
945    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
946        run.path("src/llvm-project/offload")
947    }
948
949    fn make_run(run: RunConfig<'_>) {
950        run.builder.ensure(OmpOffload { target: run.target });
951    }
952
953    /// Compile OpenMP offload runtimes for `target`.
954    #[allow(unused)]
955    fn run(self, builder: &Builder<'_>) -> Self::Output {
956        if builder.config.dry_run() {
957            return BuiltOmpOffload {
958                offload: vec![builder.config.tempdir().join("llvm-offload-dry-run")],
959            };
960        }
961        let target = self.target;
962
963        let LlvmResult { host_llvm_config, llvm_cmake_dir } =
964            builder.ensure(Llvm { target: self.target });
965
966        // Running cmake twice in the same folder is known to cause issues, like deleting existing
967        // binaries. We therefore write our offload artifacts into it's own folder, instead of
968        // using the llvm build dir.
969        let out_dir = builder.offload_out(target);
970
971        let mut files = vec![];
972        let lib_ext = std::env::consts::DLL_EXTENSION;
973        files.push(out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext));
974        files.push(out_dir.join("lib").join("libomp").with_extension(lib_ext));
975        files.push(out_dir.join("lib").join("libomptarget").with_extension(lib_ext));
976
977        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.
978        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
979        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
980            generate_smart_stamp_hash(
981                builder,
982                &builder.config.src.join("src/llvm-project/offload"),
983                builder.in_tree_llvm_info.sha().unwrap_or_default(),
984            )
985        });
986        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);
987
988        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");
989        if stamp.is_up_to_date() {
990            trace!(?out_dir, "offload/openmp build artifacts are up to date");
991            if stamp.stamp().is_empty() {
992                builder.info(
993                    "Could not determine the Offload submodule commit hash. \
994                     Assuming that an Offload rebuild is not necessary.",
995                );
996                builder.info(&format!(
997                    "To force Offload/OpenMP to rebuild, remove the file `{}`",
998                    stamp.path().display()
999                ));
1000            }
1001            return BuiltOmpOffload { offload: files };
1002        }
1003
1004        trace!(?target, "(re)building offload/openmp artifacts");
1005        builder.info(&format!("Building OpenMP/Offload for {target}"));
1006        t!(stamp.remove());
1007        let _time = helpers::timeit(builder);
1008        t!(fs::create_dir_all(&out_dir));
1009
1010        builder.config.update_submodule("src/llvm-project");
1011        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));
1012
1013        // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1014        // come with it's own set of default include directories, which are based on a potentially older
1015        // LLVM. This can cause issues, so we overwrite it to include headers based on our
1016        // `src/llvm-project` submodule instead.
1017        // FIXME(offload): With LLVM-22 we hopefully won't need an external clang anymore.
1018        let mut cflags = CcFlags::default();
1019        if !builder.config.llvm_clang {
1020            let base = builder.llvm_out(target).join("include");
1021            let inc_dir = base.display();
1022            cflags.push_all(format!(" -I {inc_dir}"));
1023        }
1024
1025        configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), cflags, &[]);
1026
1027        // Re-use the same flags as llvm to control the level of debug information
1028        // generated for offload.
1029        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1030            (false, _) => "Debug",
1031            (true, false) => "Release",
1032            (true, true) => "RelWithDebInfo",
1033        };
1034        trace!(?profile);
1035
1036        // OpenMP/Offload builds currently (LLVM-21) still depend on Clang, although there are
1037        // intentions to loosen this requirement for LLVM-22. If we were to
1038        let clang_dir = if !builder.config.llvm_clang {
1039            // We must have an external clang to use.
1040            assert!(&builder.build.config.llvm_clang_dir.is_some());
1041            builder.build.config.llvm_clang_dir.clone()
1042        } else {
1043            // No need to specify it, since we use the in-tree clang
1044            None
1045        };
1046
1047        // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1048        // runtime to simplify our build. We should also re-evaluate the LLVM_Root and try to get
1049        // rid of the Clang_DIR, once we upgrade to LLVM-22.
1050        cfg.out_dir(&out_dir)
1051            .profile(profile)
1052            .env("LLVM_CONFIG_REAL", &host_llvm_config)
1053            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1054            .define("LLVM_ENABLE_RUNTIMES", "openmp;offload")
1055            .define("LLVM_INCLUDE_TESTS", "OFF")
1056            .define("OFFLOAD_INCLUDE_TESTS", "OFF")
1057            .define("OPENMP_STANDALONE_BUILD", "ON")
1058            .define("LLVM_ROOT", builder.llvm_out(target).join("build"))
1059            .define("LLVM_DIR", llvm_cmake_dir);
1060        if let Some(p) = clang_dir {
1061            cfg.define("Clang_DIR", p);
1062        }
1063        cfg.build();
1064
1065        t!(stamp.write());
1066
1067        for p in &files {
1068            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>
1069            // files.
1070            if !p.exists() {
1071                eprintln!(
1072                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",
1073                    out_dir.display()
1074                );
1075                exit!(1);
1076            }
1077        }
1078        BuiltOmpOffload { offload: files }
1079    }
1080}
1081
1082#[derive(Clone)]
1083pub struct BuiltEnzyme {
1084    /// Path to the libEnzyme dylib.
1085    enzyme: PathBuf,
1086}
1087
1088impl BuiltEnzyme {
1089    pub fn enzyme_path(&self) -> PathBuf {
1090        self.enzyme.clone()
1091    }
1092    pub fn enzyme_filename(&self) -> String {
1093        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
1094    }
1095}
1096
1097#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1098pub struct Enzyme {
1099    pub target: TargetSelection,
1100}
1101
1102impl Step for Enzyme {
1103    type Output = BuiltEnzyme;
1104    const IS_HOST: bool = true;
1105
1106    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1107        run.path("src/tools/enzyme/enzyme")
1108    }
1109
1110    fn make_run(run: RunConfig<'_>) {
1111        run.builder.ensure(Enzyme { target: run.target });
1112    }
1113
1114    /// Compile Enzyme for `target`.
1115    fn run(self, builder: &Builder<'_>) -> Self::Output {
1116        builder.require_submodule(
1117            "src/tools/enzyme",
1118            Some("The Enzyme sources are required for autodiff."),
1119        );
1120        let target = self.target;
1121
1122        if builder.config.dry_run() {
1123            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1124        }
1125
1126        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1127
1128        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1129        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1130            generate_smart_stamp_hash(
1131                builder,
1132                &builder.config.src.join("src/tools/enzyme"),
1133                builder.enzyme_info.sha().unwrap_or_default(),
1134            )
1135        });
1136
1137        let out_dir = builder.enzyme_out(target);
1138        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1139
1140        let llvm_version_major = llvm::get_llvm_version_major(builder, &host_llvm_config);
1141        let lib_ext = std::env::consts::DLL_EXTENSION;
1142        let libenzyme = format!("libEnzyme-{llvm_version_major}");
1143        let build_dir = out_dir.join("lib");
1144        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);
1145
1146        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
1147        if stamp.is_up_to_date() {
1148            trace!(?out_dir, "enzyme build artifacts are up to date");
1149            if stamp.stamp().is_empty() {
1150                builder.info(
1151                    "Could not determine the Enzyme submodule commit hash. \
1152                     Assuming that an Enzyme rebuild is not necessary.",
1153                );
1154                builder.info(&format!(
1155                    "To force Enzyme to rebuild, remove the file `{}`",
1156                    stamp.path().display()
1157                ));
1158            }
1159            return BuiltEnzyme { enzyme: dylib };
1160        }
1161
1162        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {
1163            builder.info(&format!(
1164                "WARNING: {} does not exist, Enzyme build will likely fail",
1165                llvm_cmake_dir.display()
1166            ));
1167        }
1168
1169        trace!(?target, "(re)building enzyme artifacts");
1170        builder.info(&format!("Building Enzyme for {target}"));
1171        t!(stamp.remove());
1172        let _time = helpers::timeit(builder);
1173        t!(fs::create_dir_all(&out_dir));
1174
1175        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
1176        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about
1177        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1178        // hard to spot more relevant issues.
1179        let mut cflags = CcFlags::default();
1180        cflags.push_all("-Wno-deprecated");
1181        configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), cflags, &[]);
1182
1183        // Re-use the same flags as llvm to control the level of debug information
1184        // generated by Enzyme.
1185        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
1186        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1187            (false, _) => "Debug",
1188            (true, false) => "Release",
1189            (true, true) => "RelWithDebInfo",
1190        };
1191        trace!(?profile);
1192
1193        cfg.out_dir(&out_dir)
1194            .profile(profile)
1195            .env("LLVM_CONFIG_REAL", &host_llvm_config)
1196            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1197            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
1198            .define("ENZYME_BC_LOADER", "OFF")
1199            .define("LLVM_DIR", llvm_cmake_dir);
1200
1201        cfg.build();
1202
1203        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>
1204        // file.
1205        if !dylib.exists() {
1206            eprintln!(
1207                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",
1208                build_dir.display()
1209            );
1210            exit!(1);
1211        }
1212
1213        t!(stamp.write());
1214        BuiltEnzyme { enzyme: dylib }
1215    }
1216}
1217
1218#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1219pub struct Lld {
1220    pub target: TargetSelection,
1221}
1222
1223impl Step for Lld {
1224    type Output = PathBuf;
1225    const IS_HOST: bool = true;
1226
1227    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1228        run.path("src/llvm-project/lld")
1229    }
1230
1231    fn make_run(run: RunConfig<'_>) {
1232        run.builder.ensure(Lld { target: run.target });
1233    }
1234
1235    /// Compile LLD for `target`.
1236    fn run(self, builder: &Builder<'_>) -> PathBuf {
1237        if builder.config.dry_run() {
1238            return PathBuf::from("lld-out-dir-test-gen");
1239        }
1240        let target = self.target;
1241
1242        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1243
1244        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1245        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
1246        // subfolder. We check if that's the case, and if LLD's binary already exists there next to
1247        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
1248        let ci_llvm_bin = host_llvm_config.parent().unwrap();
1249        if ci_llvm_bin.is_dir() && ci_llvm_bin.file_name().unwrap() == "bin" {
1250            let lld_path = ci_llvm_bin.join(exe("lld", target));
1251            if lld_path.exists() {
1252                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
1253                // `bin` subfolder of this step's out dir.
1254                return ci_llvm_bin.parent().unwrap().to_path_buf();
1255            }
1256        }
1257
1258        let out_dir = builder.lld_out(target);
1259
1260        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1261        if lld_stamp.path().exists() {
1262            return out_dir;
1263        }
1264
1265        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1266        let _time = helpers::timeit(builder);
1267        t!(fs::create_dir_all(&out_dir));
1268
1269        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1270        let mut ldflags = LdFlags::default();
1271
1272        // When building LLD as part of a build with instrumentation on windows, for example
1273        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1274        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1275        // linking errors, much like LLVM's cmake setup does in that situation.
1276        if builder.config.llvm_profile_generate
1277            && target.is_msvc()
1278            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()
1279        {
1280            // Find clang's runtime library directory and push that as a search path to the
1281            // cmake linker flags.
1282            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1283            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));
1284        }
1285
1286        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,
1287        // which impacts where it expects to find LLVM's shared library. This causes #80703.
1288        //
1289        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it
1290        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1291        // lib path for LLVM tools, not the one for rust binaries.
1292        //
1293        // (The `llvm-tools` component copies the .so there for the other tools, and with that
1294        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1295        // `LD_LIBRARY_PATH` overrides)
1296        //
1297        if builder.config.rpath_enabled(target)
1298            && helpers::use_host_linker(target)
1299            && builder.config.llvm_link_shared()
1300            && target.contains("linux")
1301        {
1302            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the
1303            // expected parent `lib` directory.
1304            //
1305            // Be careful when changing this path, we need to ensure it's quoted or escaped:
1306            // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1307            // cmake.
1308            ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");
1309        }
1310
1311        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1312        configure_llvm(builder, target, &mut cfg);
1313
1314        // Re-use the same flags as llvm to control the level of debug information
1315        // generated for lld.
1316        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1317            (false, _) => "Debug",
1318            (true, false) => "Release",
1319            (true, true) => "RelWithDebInfo",
1320        };
1321
1322        cfg.out_dir(&out_dir)
1323            .profile(profile)
1324            .define("LLVM_CMAKE_DIR", llvm_cmake_dir)
1325            .define("LLVM_INCLUDE_TESTS", "OFF");
1326
1327        if !builder.config.is_host_target(target) {
1328            // Use the host llvm-tblgen binary.
1329            cfg.define(
1330                "LLVM_TABLEGEN_EXE",
1331                host_llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
1332            );
1333        }
1334
1335        cfg.build();
1336
1337        t!(lld_stamp.write());
1338        out_dir
1339    }
1340}
1341
1342#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1343pub struct Sanitizers {
1344    pub target: TargetSelection,
1345}
1346
1347impl Step for Sanitizers {
1348    type Output = Vec<SanitizerRuntime>;
1349
1350    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1351        run.alias("sanitizers")
1352    }
1353
1354    fn make_run(run: RunConfig<'_>) {
1355        run.builder.ensure(Sanitizers { target: run.target });
1356    }
1357
1358    /// Builds sanitizer runtime libraries.
1359    fn run(self, builder: &Builder<'_>) -> Self::Output {
1360        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1361        if !compiler_rt_dir.exists() {
1362            return Vec::new();
1363        }
1364
1365        let out_dir = builder.native_dir(self.target).join("sanitizers");
1366        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1367
1368        if builder.config.dry_run() || runtimes.is_empty() {
1369            return runtimes;
1370        }
1371
1372        let LlvmResult { host_llvm_config, .. } =
1373            builder.ensure(Llvm { target: builder.config.host_target });
1374
1375        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1376        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1377            generate_smart_stamp_hash(
1378                builder,
1379                &builder.config.src.join("src/llvm-project/compiler-rt"),
1380                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1381            )
1382        });
1383
1384        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1385
1386        if stamp.is_up_to_date() {
1387            if stamp.stamp().is_empty() {
1388                builder.info(&format!(
1389                    "Rebuild sanitizers by removing the file `{}`",
1390                    stamp.path().display()
1391                ));
1392            }
1393
1394            return runtimes;
1395        }
1396
1397        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1398        t!(stamp.remove());
1399        let _time = helpers::timeit(builder);
1400
1401        let mut cfg = cmake::Config::new(&compiler_rt_dir);
1402        cfg.profile("Release");
1403        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1404        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1405        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1406        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1407        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1408        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1409        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1410        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1411        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1412        cfg.define("LLVM_CONFIG_PATH", &host_llvm_config);
1413
1414        if self.target.contains("ohos") {
1415            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1416        }
1417
1418        // On Darwin targets the sanitizer runtimes are build as universal binaries.
1419        // Unfortunately sccache currently lacks support to build them successfully.
1420        // Disable compiler launcher on Darwin targets to avoid potential issues.
1421        let use_compiler_launcher = !self.target.contains("apple-darwin");
1422        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default
1423        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1424        // causes architecture detection to be skipped when this flag is present,
1425        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1426        let suppressed_compiler_flag_prefixes: &[&str] =
1427            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };
1428        configure_cmake(
1429            builder,
1430            self.target,
1431            &mut cfg,
1432            use_compiler_launcher,
1433            LdFlags::default(),
1434            CcFlags::default(),
1435            suppressed_compiler_flag_prefixes,
1436        );
1437
1438        t!(fs::create_dir_all(&out_dir));
1439        cfg.out_dir(out_dir);
1440
1441        for runtime in &runtimes {
1442            cfg.build_target(&runtime.cmake_target);
1443            cfg.build();
1444        }
1445        t!(stamp.write());
1446
1447        runtimes
1448    }
1449}
1450
1451#[derive(Clone, Debug)]
1452pub struct SanitizerRuntime {
1453    /// CMake target used to build the runtime.
1454    pub cmake_target: String,
1455    /// Path to the built runtime library.
1456    pub path: PathBuf,
1457    /// Library filename that will be used rustc.
1458    pub name: String,
1459}
1460
1461/// Returns sanitizers available on a given target.
1462fn supported_sanitizers(
1463    out_dir: &Path,
1464    target: TargetSelection,
1465    channel: &str,
1466) -> Vec<SanitizerRuntime> {
1467    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1468        components
1469            .iter()
1470            .map(move |c| SanitizerRuntime {
1471                cmake_target: format!("clang_rt.{c}_{os}_dynamic"),
1472                path: out_dir.join(format!("build/lib/darwin/libclang_rt.{c}_{os}_dynamic.dylib")),
1473                name: format!("librustc-{channel}_rt.{c}.dylib"),
1474            })
1475            .collect()
1476    };
1477
1478    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1479        components
1480            .iter()
1481            .map(move |c| SanitizerRuntime {
1482                cmake_target: format!("clang_rt.{c}-{arch}"),
1483                path: out_dir.join(format!("build/lib/{os}/libclang_rt.{c}-{arch}.a")),
1484                name: format!("librustc-{channel}_rt.{c}.a"),
1485            })
1486            .collect()
1487    };
1488
1489    match &*target.triple {
1490        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1491        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),
1492        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),
1493        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1494        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1495        "aarch64-unknown-linux-gnu" => {
1496            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan"])
1497        }
1498        "aarch64-unknown-linux-ohos" => {
1499            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1500        }
1501        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {
1502            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])
1503        }
1504        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1505        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1506        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),
1507        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1508        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1509        "x86_64-unknown-netbsd" => {
1510            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1511        }
1512        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1513        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1514        "x86_64-unknown-linux-gnu" => common_libs(
1515            "linux",
1516            "x86_64",
1517            &["asan", "dfsan", "lsan", "msan", "safestack", "tsan", "rtsan"],
1518        ),
1519        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),
1520        "x86_64-unknown-linux-musl" => {
1521            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1522        }
1523        "s390x-unknown-linux-gnu" => {
1524            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1525        }
1526        "s390x-unknown-linux-musl" => {
1527            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1528        }
1529        "x86_64-unknown-linux-ohos" => {
1530            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1531        }
1532        _ => Vec::new(),
1533    }
1534}
1535
1536#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1537pub struct CrtBeginEnd {
1538    pub target: TargetSelection,
1539}
1540
1541impl Step for CrtBeginEnd {
1542    type Output = PathBuf;
1543
1544    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1545        run.path("src/llvm-project/compiler-rt/lib/crt")
1546    }
1547
1548    fn make_run(run: RunConfig<'_>) {
1549        if run.target.needs_crt_begin_end() {
1550            run.builder.ensure(CrtBeginEnd { target: run.target });
1551        }
1552    }
1553
1554    /// Build crtbegin.o/crtend.o for musl target.
1555    fn run(self, builder: &Builder<'_>) -> Self::Output {
1556        builder.require_submodule(
1557            "src/llvm-project",
1558            Some("The LLVM sources are required for the CRT from `compiler-rt`."),
1559        );
1560
1561        let out_dir = builder.native_dir(self.target).join("crt");
1562
1563        if builder.config.dry_run() {
1564            return out_dir;
1565        }
1566
1567        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");
1568        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");
1569        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))
1570            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1571        {
1572            return out_dir;
1573        }
1574
1575        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
1576        t!(fs::create_dir_all(&out_dir));
1577
1578        let mut cfg = cc::Build::new();
1579
1580        if let Some(ar) = builder.ar(self.target) {
1581            cfg.archiver(ar);
1582        }
1583        cfg.compiler(builder.cc(self.target));
1584        cfg.cargo_metadata(false)
1585            .out_dir(&out_dir)
1586            .target(&self.target.triple)
1587            .host(&builder.config.host_target.triple)
1588            .warnings(false)
1589            .debug(false)
1590            .opt_level(3)
1591            .file(crtbegin_src)
1592            .file(crtend_src);
1593
1594        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
1595        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1596        // instead of .ctors/.dtors
1597        cfg.flag("-std=c11")
1598            .define("CRT_HAS_INITFINI_ARRAY", None)
1599            .define("EH_USE_FRAME_REGISTRY", None);
1600
1601        let objs = cfg.compile_intermediates();
1602        assert_eq!(objs.len(), 2);
1603        for obj in objs {
1604            let base_name = unhashed_basename(&obj);
1605            assert!(base_name == "crtbegin" || base_name == "crtend");
1606            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));
1607            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));
1608        }
1609
1610        out_dir
1611    }
1612}
1613
1614#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1615pub struct Libunwind {
1616    pub target: TargetSelection,
1617}
1618
1619impl Step for Libunwind {
1620    type Output = PathBuf;
1621
1622    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1623        run.path("src/llvm-project/libunwind")
1624    }
1625
1626    fn make_run(run: RunConfig<'_>) {
1627        run.builder.ensure(Libunwind { target: run.target });
1628    }
1629
1630    /// Build libunwind.a
1631    fn run(self, builder: &Builder<'_>) -> Self::Output {
1632        builder.require_submodule(
1633            "src/llvm-project",
1634            Some("The LLVM sources are required for libunwind."),
1635        );
1636
1637        if builder.config.dry_run() {
1638            return PathBuf::new();
1639        }
1640
1641        let out_dir = builder.native_dir(self.target).join("libunwind");
1642        let root = builder.src.join("src/llvm-project/libunwind");
1643
1644        if up_to_date(&root, &out_dir.join("libunwind.a")) {
1645            return out_dir;
1646        }
1647
1648        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
1649        t!(fs::create_dir_all(&out_dir));
1650
1651        let mut cc_cfg = cc::Build::new();
1652        let mut cpp_cfg = cc::Build::new();
1653
1654        cpp_cfg.cpp(true);
1655        cpp_cfg.cpp_set_stdlib(None);
1656        cpp_cfg.flag("-nostdinc++");
1657        cpp_cfg.flag("-fno-exceptions");
1658        cpp_cfg.flag("-fno-rtti");
1659        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1660
1661        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1662            if let Some(ar) = builder.ar(self.target) {
1663                cfg.archiver(ar);
1664            }
1665            cfg.target(&self.target.triple);
1666            cfg.host(&builder.config.host_target.triple);
1667            cfg.warnings(false);
1668            cfg.debug(false);
1669            // get_compiler() need set opt_level first.
1670            cfg.opt_level(3);
1671            cfg.flag("-fstrict-aliasing");
1672            cfg.flag("-funwind-tables");
1673            cfg.flag("-fvisibility=hidden");
1674            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1675            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1676            cfg.include(root.join("include"));
1677            cfg.cargo_metadata(false);
1678            cfg.out_dir(&out_dir);
1679
1680            if self.target.contains("x86_64-fortanix-unknown-sgx") {
1681                cfg.static_flag(true);
1682                cfg.flag("-fno-stack-protector");
1683                cfg.flag("-ffreestanding");
1684                cfg.flag("-fexceptions");
1685
1686                // easiest way to undefine since no API available in cc::Build to undefine
1687                cfg.flag("-U_FORTIFY_SOURCE");
1688                cfg.define("_FORTIFY_SOURCE", "0");
1689                cfg.define("RUST_SGX", "1");
1690                cfg.define("__NO_STRING_INLINES", None);
1691                cfg.define("__NO_MATH_INLINES", None);
1692                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1693                cfg.define("NDEBUG", None);
1694            }
1695            if self.target.is_windows() {
1696                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1697            }
1698        }
1699
1700        cc_cfg.compiler(builder.cc(self.target));
1701        if let Ok(cxx) = builder.cxx(self.target) {
1702            cpp_cfg.compiler(cxx);
1703        } else {
1704            cc_cfg.compiler(builder.cc(self.target));
1705        }
1706
1707        // Don't set this for clang
1708        // By default, Clang builds C code in GNU C17 mode.
1709        // By default, Clang builds C++ code according to the C++98 standard,
1710        // with many C++11 features accepted as extensions.
1711        if cc_cfg.get_compiler().is_like_gnu() {
1712            cc_cfg.flag("-std=c99");
1713        }
1714        if cpp_cfg.get_compiler().is_like_gnu() {
1715            cpp_cfg.flag("-std=c++11");
1716        }
1717
1718        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1719            // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1720            // C++ compiler env variables on the builders.
1721            // Don't set this for clang++, as clang++ is able to compile this without libc++.
1722            if cpp_cfg.get_compiler().is_like_gnu() {
1723                cpp_cfg.cpp(false);
1724                cpp_cfg.compiler(builder.cc(self.target));
1725            }
1726        }
1727
1728        let mut c_sources = vec![
1729            "Unwind-sjlj.c",
1730            "UnwindLevel1-gcc-ext.c",
1731            "UnwindLevel1.c",
1732            "UnwindRegistersRestore.S",
1733            "UnwindRegistersSave.S",
1734        ];
1735
1736        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1737        let cpp_len = cpp_sources.len();
1738
1739        if self.target.contains("x86_64-fortanix-unknown-sgx") {
1740            c_sources.push("UnwindRustSgx.c");
1741        }
1742
1743        for src in c_sources {
1744            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1745        }
1746
1747        for src in &cpp_sources {
1748            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1749        }
1750
1751        cpp_cfg.compile("unwind-cpp");
1752
1753        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1754        let mut count = 0;
1755        let mut files = fs::read_dir(&out_dir)
1756            .unwrap()
1757            .map(|entry| entry.unwrap().path().canonicalize().unwrap())
1758            .collect::<Vec<_>>();
1759        files.sort();
1760        for file in files {
1761            if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1762                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".
1763                let base_name = unhashed_basename(&file);
1764                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
1765                    cc_cfg.object(&file);
1766                    count += 1;
1767                }
1768            }
1769        }
1770        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");
1771
1772        cc_cfg.compile("unwind");
1773        out_dir
1774    }
1775}