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, libdir, 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        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
565        // libLLVM.dylib will be built. However, llvm-config will still look
566        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
567        // link to make llvm-config happy.
568        if builder.llvm_link_shared() && target.contains("apple-darwin") {
569            let lib_name = find_llvm_lib_name("dylib");
570            let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
571            if !lib_llvm.exists() {
572                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
573            }
574        }
575
576        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
577        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
578        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
579        if builder.llvm_link_shared()
580            && builder.config.llvm_optimize
581            && !builder.config.llvm_release_debuginfo
582        {
583            // Find the name of the LLVM shared library that we just built.
584            let lib_name = find_llvm_lib_name("so");
585
586            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
587            // debuginfo.
588            crate::core::build_steps::compile::strip_debug(
589                builder,
590                target,
591                &out_dir.join("lib").join(&lib_name),
592            );
593            crate::core::build_steps::compile::strip_debug(
594                builder,
595                target,
596                &out_dir.join("build").join("lib").join(&lib_name),
597            );
598        }
599
600        t!(stamp.write());
601
602        res
603    }
604
605    fn metadata(&self) -> Option<StepMetadata> {
606        Some(StepMetadata::build("llvm", self.target))
607    }
608}
609
610pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
611    command(llvm_config)
612        .arg("--version")
613        .cached()
614        .run_capture_stdout(builder)
615        .stdout()
616        .trim()
617        .to_owned()
618}
619
620pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
621    let version = get_llvm_version(builder, llvm_config);
622    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
623    major_str.parse().unwrap()
624}
625
626fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
627    if builder.config.dry_run() {
628        return;
629    }
630
631    let version = get_llvm_version(builder, llvm_config);
632    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
633    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())
634        && major >= 20
635    {
636        return;
637    }
638    panic!("\n\nbad LLVM version: {version}, need >=20\n\n")
639}
640
641fn configure_cmake(
642    builder: &Builder<'_>,
643    target: TargetSelection,
644    cfg: &mut cmake::Config,
645    use_compiler_launcher: bool,
646    mut ldflags: LdFlags,
647    ccflags: CcFlags,
648    suppressed_compiler_flag_prefixes: &[&str],
649) {
650    // Do not print installation messages for up-to-date files.
651    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
652    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
653
654    // Do not allow the user's value of DESTDIR to influence where
655    // LLVM will install itself. LLVM must always be installed in our
656    // own build directories.
657    cfg.env("DESTDIR", "");
658
659    if builder.ninja() {
660        cfg.generator("Ninja");
661    }
662    cfg.target(&target.triple).host(&builder.config.host_target.triple);
663
664    if !builder.config.is_host_target(target) {
665        cfg.define("CMAKE_CROSSCOMPILING", "True");
666
667        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
668        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
669        // which isn't set when compiling outside `build.rs` (like bootstrap is).
670        //
671        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
672        if target.contains("netbsd") {
673            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
674        } else if target.contains("dragonfly") {
675            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
676        } else if target.contains("openbsd") {
677            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
678        } else if target.contains("freebsd") {
679            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
680        } else if target.is_windows() {
681            cfg.define("CMAKE_SYSTEM_NAME", "Windows");
682        } else if target.contains("haiku") {
683            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
684        } else if target.contains("solaris") || target.contains("illumos") {
685            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
686        } else if target.contains("linux") {
687            cfg.define("CMAKE_SYSTEM_NAME", "Linux");
688        } else if target.contains("darwin") {
689            // macOS
690            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
691        } else if target.contains("ios") {
692            cfg.define("CMAKE_SYSTEM_NAME", "iOS");
693        } else if target.contains("tvos") {
694            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
695        } else if target.contains("visionos") {
696            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
697        } else if target.contains("watchos") {
698            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
699        } else if target.contains("none") {
700            // "none" should be the last branch
701            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
702        } else {
703            builder.info(&format!(
704                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
705            ));
706            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
707            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
708            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
709        }
710
711        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
712        // that case like CMake we cannot easily determine system version either.
713        //
714        // Since, the LLVM itself makes rather limited use of version checks in
715        // CMakeFiles (and then only in tests), and so far no issues have been
716        // reported, the system version is currently left unset.
717
718        if target.contains("apple") {
719            if !target.contains("darwin") {
720                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
721                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?
722                //
723                // So for now we set it to "Darwin" on all Apple platforms.
724                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
725
726                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
727                cfg.define("CMAKE_OSX_SYSROOT", "/");
728                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
729            }
730
731            // Make sure that CMake does not build universal binaries on macOS.
732            // Explicitly specify the one single target architecture.
733            if target.starts_with("aarch64") {
734                // macOS uses a different name for building arm64
735                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
736            } else if target.starts_with("i686") {
737                // macOS uses a different name for building i386
738                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
739            } else {
740                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
741            }
742        }
743    }
744
745    let sanitize_cc = |cc: &Path| {
746        if target.is_msvc() {
747            OsString::from(cc.to_str().unwrap().replace('\\', "/"))
748        } else {
749            cc.as_os_str().to_owned()
750        }
751    };
752
753    // MSVC with CMake uses msbuild by default which doesn't respect these
754    // vars that we'd otherwise configure. In that case we just skip this
755    // entirely.
756    if target.is_msvc() && !builder.ninja() {
757        return;
758    }
759
760    let (cc, cxx) = match builder.config.llvm_clang_cl {
761        Some(ref cl) => (cl.into(), cl.into()),
762        None => (builder.cc(target), builder.cxx(target).unwrap()),
763    };
764
765    // If ccache is configured we inform the build a little differently how
766    // to invoke ccache while also invoking our compilers.
767    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {
768        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
769            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
770    }
771    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
772        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
773        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
774
775    // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it
776    // overrides the jobserver settings and can lead to oversubscription.
777    let has_modern_jobserver = env::var("MAKEFLAGS")
778        .map(|flags| flags.contains("--jobserver-auth=fifo:"))
779        .unwrap_or(false);
780
781    if !has_modern_jobserver {
782        cfg.build_arg("-j").build_arg(builder.jobs().to_string());
783    }
784    let mut cflags = ccflags.cflags.clone();
785    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
786    // our flags via `.cflag`/`.cxxflag` instead.
787    //
788    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
789    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
790    for flag in builder
791        .cc_handled_clags(target, CLang::C)
792        .into_iter()
793        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::C))
794        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))
795    {
796        cflags.push(" ");
797        cflags.push(flag);
798    }
799    if let Some(ref s) = builder.config.llvm_cflags {
800        cflags.push(" ");
801        cflags.push(s);
802    }
803    if target.contains("ohos") {
804        cflags.push(" -D_LINUX_SYSINFO_H");
805    }
806    if builder.config.llvm_clang_cl.is_some() {
807        cflags.push(format!(" --target={target}"));
808    }
809    cfg.define("CMAKE_C_FLAGS", cflags);
810    let mut cxxflags = ccflags.cxxflags.clone();
811    for flag in builder
812        .cc_handled_clags(target, CLang::Cxx)
813        .into_iter()
814        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::Cxx))
815        .filter(|flag| {
816            !suppressed_compiler_flag_prefixes
817                .iter()
818                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
819        })
820    {
821        cxxflags.push(" ");
822        cxxflags.push(flag);
823    }
824    if let Some(ref s) = builder.config.llvm_cxxflags {
825        cxxflags.push(" ");
826        cxxflags.push(s);
827    }
828    if target.contains("ohos") {
829        cxxflags.push(" -D_LINUX_SYSINFO_H");
830    }
831    if builder.config.llvm_clang_cl.is_some() {
832        cxxflags.push(format!(" --target={target}"));
833    }
834
835    cfg.define("CMAKE_CXX_FLAGS", cxxflags);
836    if let Some(ar) = builder.ar(target)
837        && ar.is_absolute()
838    {
839        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
840        // tries to resolve this path in the LLVM build directory.
841        cfg.define("CMAKE_AR", sanitize_cc(&ar));
842    }
843
844    if let Some(ranlib) = builder.ranlib(target)
845        && ranlib.is_absolute()
846    {
847        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
848        // tries to resolve this path in the LLVM build directory.
849        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
850    }
851
852    if let Some(ref flags) = builder.config.llvm_ldflags {
853        ldflags.push_all(flags);
854    }
855
856    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
857        ldflags.push_all(&flags);
858    }
859
860    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
861    // We also do this if the user explicitly requested static libstdc++.
862    if builder.config.llvm_static_stdcpp
863        && !target.is_msvc()
864        && !target.contains("netbsd")
865        && !target.contains("solaris")
866    {
867        if target.contains("apple") || target.is_windows() {
868            ldflags.push_all("-static-libstdc++");
869        } else {
870            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
871        }
872    }
873
874    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
875    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
876    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
877
878    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
879        cfg.env("RUSTC_LOG", "sccache=warn");
880    }
881}
882
883fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
884    // ThinLTO is only available when building with LLVM, enabling LLD is required.
885    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
886    if builder.config.llvm_thin_lto {
887        cfg.define("LLVM_ENABLE_LTO", "Thin");
888        if !target.contains("apple") {
889            cfg.define("LLVM_ENABLE_LLD", "ON");
890        }
891    }
892
893    // Libraries for ELF section compression.
894    if builder.config.llvm_libzstd {
895        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
896        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
897    } else {
898        cfg.define("LLVM_ENABLE_ZSTD", "OFF");
899    }
900
901    if let Some(ref linker) = builder.config.llvm_use_linker {
902        cfg.define("LLVM_USE_LINKER", linker);
903    }
904
905    if builder.config.llvm_allow_old_toolchain {
906        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
907    }
908}
909
910// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
911fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
912    let kind = if host == target { "HOST" } else { "TARGET" };
913    let target_u = target.replace('-', "_");
914    env::var_os(format!("{var_base}_{target}"))
915        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))
916        .or_else(|| env::var_os(format!("{kind}_{var_base}")))
917        .or_else(|| env::var_os(var_base))
918}
919
920#[derive(Clone)]
921pub struct BuiltOmpOffload {
922    /// Path to the omp and offload dylibs.
923    offload: Vec<PathBuf>,
924}
925
926impl BuiltOmpOffload {
927    pub fn offload_paths(&self) -> Vec<PathBuf> {
928        self.offload.clone()
929    }
930}
931
932// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
933// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
934// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
935// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
936// don't always build clang (due to compile times), but instead use a slightly older external clang.
937// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the
938// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
939// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
940// runtimes. This external clang will try to use it's own (older) include dirs when building our
941// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
942// explicitly set our include dirs.
943#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
944pub struct OmpOffload {
945    pub target: TargetSelection,
946}
947
948impl Step for OmpOffload {
949    type Output = BuiltOmpOffload;
950    const IS_HOST: bool = true;
951
952    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
953        run.path("src/llvm-project/offload")
954    }
955
956    fn make_run(run: RunConfig<'_>) {
957        run.builder.ensure(OmpOffload { target: run.target });
958    }
959
960    /// Compile OpenMP offload runtimes for `target`.
961    #[allow(unused)]
962    fn run(self, builder: &Builder<'_>) -> Self::Output {
963        if builder.config.dry_run() {
964            return BuiltOmpOffload {
965                offload: vec![builder.config.tempdir().join("llvm-offload-dry-run")],
966            };
967        }
968        let target = self.target;
969
970        let LlvmResult { host_llvm_config, llvm_cmake_dir } =
971            builder.ensure(Llvm { target: self.target });
972
973        // Running cmake twice in the same folder is known to cause issues, like deleting existing
974        // binaries. We therefore write our offload artifacts into it's own folder, instead of
975        // using the llvm build dir.
976        let out_dir = builder.offload_out(target);
977
978        let mut files = vec![];
979        let lib_ext = std::env::consts::DLL_EXTENSION;
980        files.push(out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext));
981        files.push(out_dir.join("lib").join("libomp").with_extension(lib_ext));
982        files.push(out_dir.join("lib").join("libomptarget").with_extension(lib_ext));
983
984        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.
985        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
986        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
987            generate_smart_stamp_hash(
988                builder,
989                &builder.config.src.join("src/llvm-project/offload"),
990                builder.in_tree_llvm_info.sha().unwrap_or_default(),
991            )
992        });
993        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);
994
995        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");
996        if stamp.is_up_to_date() {
997            trace!(?out_dir, "offload/openmp build artifacts are up to date");
998            if stamp.stamp().is_empty() {
999                builder.info(
1000                    "Could not determine the Offload submodule commit hash. \
1001                     Assuming that an Offload rebuild is not necessary.",
1002                );
1003                builder.info(&format!(
1004                    "To force Offload/OpenMP to rebuild, remove the file `{}`",
1005                    stamp.path().display()
1006                ));
1007            }
1008            return BuiltOmpOffload { offload: files };
1009        }
1010
1011        trace!(?target, "(re)building offload/openmp artifacts");
1012        builder.info(&format!("Building OpenMP/Offload for {target}"));
1013        t!(stamp.remove());
1014        let _time = helpers::timeit(builder);
1015        t!(fs::create_dir_all(&out_dir));
1016
1017        builder.config.update_submodule("src/llvm-project");
1018
1019        // OpenMP/Offload builds currently (LLVM-22) still depend on Clang, although there are
1020        // intentions to loosen this requirement over time. FIXME(offload): re-evaluate on LLVM 23
1021        let clang_dir = if !builder.config.llvm_clang {
1022            // We must have an external clang to use.
1023            assert!(&builder.build.config.llvm_clang_dir.is_some());
1024            builder.build.config.llvm_clang_dir.clone()
1025        } else {
1026            // No need to specify it, since we use the in-tree clang
1027            None
1028        };
1029
1030        // In the context of OpenMP offload, some libraries must be compiled for the gpu target,
1031        // some for the host, and others for both. We do not perform a full cross-compilation, since
1032        // we don't want to run rustc on a GPU.
1033        let omp_targets = vec![target.triple.as_ref(), "amdgcn-amd-amdhsa", "nvptx64-nvidia-cuda"];
1034        for omp_target in omp_targets {
1035            let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));
1036
1037            // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1038            // come with it's own set of default include directories, which are based on a potentially older
1039            // LLVM. This can cause issues, so we overwrite it to include headers based on our
1040            // `src/llvm-project` submodule instead.
1041            // FIXME(offload): With LLVM-22 we hopefully won't need an external clang anymore.
1042            let mut cflags = CcFlags::default();
1043            if !builder.config.llvm_clang {
1044                let base = builder.llvm_out(target).join("include");
1045                let inc_dir = base.display();
1046                cflags.push_all(format!(" -I {inc_dir}"));
1047            }
1048
1049            configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), cflags, &[]);
1050
1051            // Re-use the same flags as llvm to control the level of debug information
1052            // generated for offload.
1053            let profile =
1054                match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1055                    (false, _) => "Debug",
1056                    (true, false) => "Release",
1057                    (true, true) => "RelWithDebInfo",
1058                };
1059            trace!(?profile);
1060
1061            // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1062            // runtime to simplify our build. So far, these are still under development.
1063            cfg.out_dir(&out_dir)
1064                .profile(profile)
1065                .env("LLVM_CONFIG_REAL", &host_llvm_config)
1066                .define("LLVM_ENABLE_ASSERTIONS", "ON")
1067                .define("LLVM_INCLUDE_TESTS", "OFF")
1068                .define("OFFLOAD_INCLUDE_TESTS", "OFF")
1069                .define("LLVM_ROOT", builder.llvm_out(target).join("build"))
1070                .define("LLVM_DIR", llvm_cmake_dir.clone())
1071                .define("LLVM_DEFAULT_TARGET_TRIPLE", omp_target);
1072            if let Some(p) = clang_dir.clone() {
1073                cfg.define("Clang_DIR", p);
1074            }
1075
1076            // We don't perform a full cross-compilation of rustc, therefore our target.triple
1077            // will still be a CPU target.
1078            if *omp_target == *target.triple {
1079                // The offload library provides functionality which only makes sense on the host.
1080                cfg.define("LLVM_ENABLE_RUNTIMES", "openmp;offload");
1081            } else {
1082                // OpenMP provides some device libraries, so we also compile it for all gpu targets.
1083                cfg.define("LLVM_USE_LINKER", "lld");
1084                cfg.define("LLVM_ENABLE_RUNTIMES", "openmp");
1085                cfg.define("CMAKE_C_COMPILER_TARGET", omp_target);
1086                cfg.define("CMAKE_CXX_COMPILER_TARGET", omp_target);
1087            }
1088            cfg.build();
1089        }
1090
1091        t!(stamp.write());
1092
1093        for p in &files {
1094            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>
1095            // files.
1096            if !p.exists() {
1097                eprintln!(
1098                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",
1099                    out_dir.display()
1100                );
1101                exit!(1);
1102            }
1103        }
1104        BuiltOmpOffload { offload: files }
1105    }
1106}
1107
1108#[derive(Clone)]
1109pub struct BuiltEnzyme {
1110    /// Path to the libEnzyme dylib.
1111    enzyme: PathBuf,
1112}
1113
1114impl BuiltEnzyme {
1115    pub fn enzyme_path(&self) -> PathBuf {
1116        self.enzyme.clone()
1117    }
1118    pub fn enzyme_filename(&self) -> String {
1119        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
1120    }
1121}
1122
1123#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1124pub struct Enzyme {
1125    pub target: TargetSelection,
1126}
1127
1128impl Step for Enzyme {
1129    type Output = BuiltEnzyme;
1130    const IS_HOST: bool = true;
1131
1132    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1133        run.path("src/tools/enzyme/enzyme")
1134    }
1135
1136    fn make_run(run: RunConfig<'_>) {
1137        run.builder.ensure(Enzyme { target: run.target });
1138    }
1139
1140    /// Compile Enzyme for `target`.
1141    fn run(self, builder: &Builder<'_>) -> Self::Output {
1142        builder.require_submodule(
1143            "src/tools/enzyme",
1144            Some("The Enzyme sources are required for autodiff."),
1145        );
1146        let target = self.target;
1147
1148        if builder.config.dry_run() {
1149            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1150        }
1151
1152        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1153
1154        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1155        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1156            generate_smart_stamp_hash(
1157                builder,
1158                &builder.config.src.join("src/tools/enzyme"),
1159                builder.enzyme_info.sha().unwrap_or_default(),
1160            )
1161        });
1162
1163        let out_dir = builder.enzyme_out(target);
1164        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1165
1166        let llvm_version_major = llvm::get_llvm_version_major(builder, &host_llvm_config);
1167        let lib_ext = std::env::consts::DLL_EXTENSION;
1168        let libenzyme = format!("libEnzyme-{llvm_version_major}");
1169        let build_dir = out_dir.join(libdir(target));
1170        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);
1171
1172        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
1173        if stamp.is_up_to_date() {
1174            trace!(?out_dir, "enzyme build artifacts are up to date");
1175            if stamp.stamp().is_empty() {
1176                builder.info(
1177                    "Could not determine the Enzyme submodule commit hash. \
1178                     Assuming that an Enzyme rebuild is not necessary.",
1179                );
1180                builder.info(&format!(
1181                    "To force Enzyme to rebuild, remove the file `{}`",
1182                    stamp.path().display()
1183                ));
1184            }
1185            return BuiltEnzyme { enzyme: dylib };
1186        }
1187
1188        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {
1189            builder.info(&format!(
1190                "WARNING: {} does not exist, Enzyme build will likely fail",
1191                llvm_cmake_dir.display()
1192            ));
1193        }
1194
1195        trace!(?target, "(re)building enzyme artifacts");
1196        builder.info(&format!("Building Enzyme for {target}"));
1197        t!(stamp.remove());
1198        let _time = helpers::timeit(builder);
1199        t!(fs::create_dir_all(&out_dir));
1200
1201        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
1202        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about
1203        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1204        // hard to spot more relevant issues.
1205        let mut cflags = CcFlags::default();
1206        cflags.push_all("-Wno-deprecated");
1207
1208        // Logic copied from `configure_llvm`
1209        // ThinLTO is only available when building with LLVM, enabling LLD is required.
1210        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1211        let mut ldflags = LdFlags::default();
1212        if builder.config.llvm_thin_lto && !target.contains("apple") {
1213            ldflags.push_all("-fuse-ld=lld");
1214        }
1215
1216        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1217
1218        // Re-use the same flags as llvm to control the level of debug information
1219        // generated by Enzyme.
1220        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
1221        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1222            (false, _) => "Debug",
1223            (true, false) => "Release",
1224            (true, true) => "RelWithDebInfo",
1225        };
1226        trace!(?profile);
1227
1228        cfg.out_dir(&out_dir)
1229            .profile(profile)
1230            .env("LLVM_CONFIG_REAL", &host_llvm_config)
1231            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1232            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
1233            .define("ENZYME_BC_LOADER", "OFF")
1234            .define("LLVM_DIR", llvm_cmake_dir);
1235
1236        cfg.build();
1237
1238        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>
1239        // file.
1240        if !dylib.exists() {
1241            eprintln!(
1242                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",
1243                build_dir.display()
1244            );
1245            exit!(1);
1246        }
1247
1248        t!(stamp.write());
1249        BuiltEnzyme { enzyme: dylib }
1250    }
1251}
1252
1253#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1254pub struct Lld {
1255    pub target: TargetSelection,
1256}
1257
1258impl Step for Lld {
1259    type Output = PathBuf;
1260    const IS_HOST: bool = true;
1261
1262    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1263        run.path("src/llvm-project/lld")
1264    }
1265
1266    fn make_run(run: RunConfig<'_>) {
1267        run.builder.ensure(Lld { target: run.target });
1268    }
1269
1270    /// Compile LLD for `target`.
1271    fn run(self, builder: &Builder<'_>) -> PathBuf {
1272        if builder.config.dry_run() {
1273            return PathBuf::from("lld-out-dir-test-gen");
1274        }
1275        let target = self.target;
1276
1277        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1278
1279        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1280        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
1281        // subfolder. We check if that's the case, and if LLD's binary already exists there next to
1282        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
1283        let ci_llvm_bin = host_llvm_config.parent().unwrap();
1284        if ci_llvm_bin.is_dir() && ci_llvm_bin.file_name().unwrap() == "bin" {
1285            let lld_path = ci_llvm_bin.join(exe("lld", target));
1286            if lld_path.exists() {
1287                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
1288                // `bin` subfolder of this step's out dir.
1289                return ci_llvm_bin.parent().unwrap().to_path_buf();
1290            }
1291        }
1292
1293        let out_dir = builder.lld_out(target);
1294
1295        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1296        if lld_stamp.path().exists() {
1297            return out_dir;
1298        }
1299
1300        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1301        let _time = helpers::timeit(builder);
1302        t!(fs::create_dir_all(&out_dir));
1303
1304        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1305        let mut ldflags = LdFlags::default();
1306
1307        // When building LLD as part of a build with instrumentation on windows, for example
1308        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1309        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1310        // linking errors, much like LLVM's cmake setup does in that situation.
1311        if builder.config.llvm_profile_generate
1312            && target.is_msvc()
1313            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()
1314        {
1315            // Find clang's runtime library directory and push that as a search path to the
1316            // cmake linker flags.
1317            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1318            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));
1319        }
1320
1321        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,
1322        // which impacts where it expects to find LLVM's shared library. This causes #80703.
1323        //
1324        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it
1325        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1326        // lib path for LLVM tools, not the one for rust binaries.
1327        //
1328        // (The `llvm-tools` component copies the .so there for the other tools, and with that
1329        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1330        // `LD_LIBRARY_PATH` overrides)
1331        //
1332        if builder.config.rpath_enabled(target)
1333            && helpers::use_host_linker(target)
1334            && builder.config.llvm_link_shared()
1335            && target.contains("linux")
1336        {
1337            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the
1338            // expected parent `lib` directory.
1339            //
1340            // Be careful when changing this path, we need to ensure it's quoted or escaped:
1341            // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1342            // cmake.
1343            ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");
1344        }
1345
1346        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1347        configure_llvm(builder, target, &mut cfg);
1348
1349        // Re-use the same flags as llvm to control the level of debug information
1350        // generated for lld.
1351        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1352            (false, _) => "Debug",
1353            (true, false) => "Release",
1354            (true, true) => "RelWithDebInfo",
1355        };
1356
1357        cfg.out_dir(&out_dir)
1358            .profile(profile)
1359            .define("LLVM_CMAKE_DIR", llvm_cmake_dir)
1360            .define("LLVM_INCLUDE_TESTS", "OFF");
1361
1362        if !builder.config.is_host_target(target) {
1363            // Use the host llvm-tblgen binary.
1364            cfg.define(
1365                "LLVM_TABLEGEN_EXE",
1366                host_llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
1367            );
1368        }
1369
1370        cfg.build();
1371
1372        t!(lld_stamp.write());
1373        out_dir
1374    }
1375}
1376
1377#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1378pub struct Sanitizers {
1379    pub target: TargetSelection,
1380}
1381
1382impl Step for Sanitizers {
1383    type Output = Vec<SanitizerRuntime>;
1384
1385    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1386        run.alias("sanitizers")
1387    }
1388
1389    fn make_run(run: RunConfig<'_>) {
1390        run.builder.ensure(Sanitizers { target: run.target });
1391    }
1392
1393    /// Builds sanitizer runtime libraries.
1394    fn run(self, builder: &Builder<'_>) -> Self::Output {
1395        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1396        if !compiler_rt_dir.exists() {
1397            return Vec::new();
1398        }
1399
1400        let out_dir = builder.native_dir(self.target).join("sanitizers");
1401        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1402
1403        if builder.config.dry_run() || runtimes.is_empty() {
1404            return runtimes;
1405        }
1406
1407        let LlvmResult { host_llvm_config, .. } =
1408            builder.ensure(Llvm { target: builder.config.host_target });
1409
1410        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1411        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1412            generate_smart_stamp_hash(
1413                builder,
1414                &builder.config.src.join("src/llvm-project/compiler-rt"),
1415                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1416            )
1417        });
1418
1419        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1420
1421        if stamp.is_up_to_date() {
1422            if stamp.stamp().is_empty() {
1423                builder.info(&format!(
1424                    "Rebuild sanitizers by removing the file `{}`",
1425                    stamp.path().display()
1426                ));
1427            }
1428
1429            return runtimes;
1430        }
1431
1432        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1433        t!(stamp.remove());
1434        let _time = helpers::timeit(builder);
1435
1436        let mut cfg = cmake::Config::new(&compiler_rt_dir);
1437        cfg.profile("Release");
1438        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1439        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1440        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1441        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1442        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1443        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1444        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1445        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1446        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1447        cfg.define("LLVM_CONFIG_PATH", &host_llvm_config);
1448
1449        if self.target.contains("ohos") {
1450            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1451        }
1452
1453        // On Darwin targets the sanitizer runtimes are build as universal binaries.
1454        // Unfortunately sccache currently lacks support to build them successfully.
1455        // Disable compiler launcher on Darwin targets to avoid potential issues.
1456        let use_compiler_launcher = !self.target.contains("apple-darwin");
1457        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default
1458        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1459        // causes architecture detection to be skipped when this flag is present,
1460        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1461        let suppressed_compiler_flag_prefixes: &[&str] =
1462            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };
1463        configure_cmake(
1464            builder,
1465            self.target,
1466            &mut cfg,
1467            use_compiler_launcher,
1468            LdFlags::default(),
1469            CcFlags::default(),
1470            suppressed_compiler_flag_prefixes,
1471        );
1472
1473        t!(fs::create_dir_all(&out_dir));
1474        cfg.out_dir(out_dir);
1475
1476        for runtime in &runtimes {
1477            cfg.build_target(&runtime.cmake_target);
1478            cfg.build();
1479        }
1480        t!(stamp.write());
1481
1482        runtimes
1483    }
1484}
1485
1486#[derive(Clone, Debug)]
1487pub struct SanitizerRuntime {
1488    /// CMake target used to build the runtime.
1489    pub cmake_target: String,
1490    /// Path to the built runtime library.
1491    pub path: PathBuf,
1492    /// Library filename that will be used rustc.
1493    pub name: String,
1494}
1495
1496/// Returns sanitizers available on a given target.
1497fn supported_sanitizers(
1498    out_dir: &Path,
1499    target: TargetSelection,
1500    channel: &str,
1501) -> Vec<SanitizerRuntime> {
1502    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1503        components
1504            .iter()
1505            .map(move |c| SanitizerRuntime {
1506                cmake_target: format!("clang_rt.{c}_{os}_dynamic"),
1507                path: out_dir.join(format!("build/lib/darwin/libclang_rt.{c}_{os}_dynamic.dylib")),
1508                name: format!("librustc-{channel}_rt.{c}.dylib"),
1509            })
1510            .collect()
1511    };
1512
1513    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1514        components
1515            .iter()
1516            .map(move |c| SanitizerRuntime {
1517                cmake_target: format!("clang_rt.{c}-{arch}"),
1518                path: out_dir.join(format!("build/lib/{os}/libclang_rt.{c}-{arch}.a")),
1519                name: format!("librustc-{channel}_rt.{c}.a"),
1520            })
1521            .collect()
1522    };
1523
1524    match &*target.triple {
1525        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1526        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),
1527        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),
1528        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1529        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1530        "aarch64-unknown-linux-gnu" => {
1531            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan"])
1532        }
1533        "aarch64-unknown-linux-ohos" => {
1534            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1535        }
1536        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {
1537            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])
1538        }
1539        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1540        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1541        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),
1542        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1543        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1544        "x86_64-unknown-netbsd" => {
1545            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1546        }
1547        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1548        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1549        "x86_64-unknown-linux-gnu" => common_libs(
1550            "linux",
1551            "x86_64",
1552            &["asan", "dfsan", "lsan", "msan", "safestack", "tsan", "rtsan"],
1553        ),
1554        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),
1555        "x86_64-unknown-linux-musl" => {
1556            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1557        }
1558        "s390x-unknown-linux-gnu" => {
1559            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1560        }
1561        "s390x-unknown-linux-musl" => {
1562            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1563        }
1564        "x86_64-unknown-linux-ohos" => {
1565            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1566        }
1567        _ => Vec::new(),
1568    }
1569}
1570
1571#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1572pub struct CrtBeginEnd {
1573    pub target: TargetSelection,
1574}
1575
1576impl Step for CrtBeginEnd {
1577    type Output = PathBuf;
1578
1579    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1580        run.path("src/llvm-project/compiler-rt/lib/crt")
1581    }
1582
1583    fn make_run(run: RunConfig<'_>) {
1584        if run.target.needs_crt_begin_end() {
1585            run.builder.ensure(CrtBeginEnd { target: run.target });
1586        }
1587    }
1588
1589    /// Build crtbegin.o/crtend.o for musl target.
1590    fn run(self, builder: &Builder<'_>) -> Self::Output {
1591        builder.require_submodule(
1592            "src/llvm-project",
1593            Some("The LLVM sources are required for the CRT from `compiler-rt`."),
1594        );
1595
1596        let out_dir = builder.native_dir(self.target).join("crt");
1597
1598        if builder.config.dry_run() {
1599            return out_dir;
1600        }
1601
1602        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");
1603        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");
1604        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))
1605            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1606        {
1607            return out_dir;
1608        }
1609
1610        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
1611        t!(fs::create_dir_all(&out_dir));
1612
1613        let mut cfg = cc::Build::new();
1614
1615        if let Some(ar) = builder.ar(self.target) {
1616            cfg.archiver(ar);
1617        }
1618        cfg.compiler(builder.cc(self.target));
1619        cfg.cargo_metadata(false)
1620            .out_dir(&out_dir)
1621            .target(&self.target.triple)
1622            .host(&builder.config.host_target.triple)
1623            .warnings(false)
1624            .debug(false)
1625            .opt_level(3)
1626            .file(crtbegin_src)
1627            .file(crtend_src);
1628
1629        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
1630        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1631        // instead of .ctors/.dtors
1632        cfg.flag("-std=c11")
1633            .define("CRT_HAS_INITFINI_ARRAY", None)
1634            .define("EH_USE_FRAME_REGISTRY", None);
1635
1636        let objs = cfg.compile_intermediates();
1637        assert_eq!(objs.len(), 2);
1638        for obj in objs {
1639            let base_name = unhashed_basename(&obj);
1640            assert!(base_name == "crtbegin" || base_name == "crtend");
1641            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));
1642            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));
1643        }
1644
1645        out_dir
1646    }
1647}
1648
1649#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1650pub struct Libunwind {
1651    pub target: TargetSelection,
1652}
1653
1654impl Step for Libunwind {
1655    type Output = PathBuf;
1656
1657    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1658        run.path("src/llvm-project/libunwind")
1659    }
1660
1661    fn make_run(run: RunConfig<'_>) {
1662        run.builder.ensure(Libunwind { target: run.target });
1663    }
1664
1665    /// Build libunwind.a
1666    fn run(self, builder: &Builder<'_>) -> Self::Output {
1667        builder.require_submodule(
1668            "src/llvm-project",
1669            Some("The LLVM sources are required for libunwind."),
1670        );
1671
1672        if builder.config.dry_run() {
1673            return PathBuf::new();
1674        }
1675
1676        let out_dir = builder.native_dir(self.target).join("libunwind");
1677        let root = builder.src.join("src/llvm-project/libunwind");
1678
1679        if up_to_date(&root, &out_dir.join("libunwind.a")) {
1680            return out_dir;
1681        }
1682
1683        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
1684        t!(fs::create_dir_all(&out_dir));
1685
1686        let mut cc_cfg = cc::Build::new();
1687        let mut cpp_cfg = cc::Build::new();
1688
1689        cpp_cfg.cpp(true);
1690        cpp_cfg.cpp_set_stdlib(None);
1691        cpp_cfg.flag("-nostdinc++");
1692        cpp_cfg.flag("-fno-exceptions");
1693        cpp_cfg.flag("-fno-rtti");
1694        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1695
1696        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1697            if let Some(ar) = builder.ar(self.target) {
1698                cfg.archiver(ar);
1699            }
1700            cfg.target(&self.target.triple);
1701            cfg.host(&builder.config.host_target.triple);
1702            cfg.warnings(false);
1703            cfg.debug(false);
1704            // get_compiler() need set opt_level first.
1705            cfg.opt_level(3);
1706            cfg.flag("-fstrict-aliasing");
1707            cfg.flag("-funwind-tables");
1708            cfg.flag("-fvisibility=hidden");
1709            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1710            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1711            cfg.include(root.join("include"));
1712            cfg.cargo_metadata(false);
1713            cfg.out_dir(&out_dir);
1714
1715            if self.target.contains("x86_64-fortanix-unknown-sgx") {
1716                cfg.static_flag(true);
1717                cfg.flag("-fno-stack-protector");
1718                cfg.flag("-ffreestanding");
1719                cfg.flag("-fexceptions");
1720
1721                // easiest way to undefine since no API available in cc::Build to undefine
1722                cfg.flag("-U_FORTIFY_SOURCE");
1723                cfg.define("_FORTIFY_SOURCE", "0");
1724                cfg.define("RUST_SGX", "1");
1725                cfg.define("__NO_STRING_INLINES", None);
1726                cfg.define("__NO_MATH_INLINES", None);
1727                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1728                cfg.define("NDEBUG", None);
1729            }
1730            if self.target.is_windows() {
1731                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1732            }
1733        }
1734
1735        cc_cfg.compiler(builder.cc(self.target));
1736        if let Ok(cxx) = builder.cxx(self.target) {
1737            cpp_cfg.compiler(cxx);
1738        } else {
1739            cc_cfg.compiler(builder.cc(self.target));
1740        }
1741
1742        // Don't set this for clang
1743        // By default, Clang builds C code in GNU C17 mode.
1744        // By default, Clang builds C++ code according to the C++98 standard,
1745        // with many C++11 features accepted as extensions.
1746        if cc_cfg.get_compiler().is_like_gnu() {
1747            cc_cfg.flag("-std=c99");
1748        }
1749        if cpp_cfg.get_compiler().is_like_gnu() {
1750            cpp_cfg.flag("-std=c++11");
1751        }
1752
1753        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1754            // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1755            // C++ compiler env variables on the builders.
1756            // Don't set this for clang++, as clang++ is able to compile this without libc++.
1757            if cpp_cfg.get_compiler().is_like_gnu() {
1758                cpp_cfg.cpp(false);
1759                cpp_cfg.compiler(builder.cc(self.target));
1760            }
1761        }
1762
1763        let mut c_sources = vec![
1764            "Unwind-sjlj.c",
1765            "UnwindLevel1-gcc-ext.c",
1766            "UnwindLevel1.c",
1767            "UnwindRegistersRestore.S",
1768            "UnwindRegistersSave.S",
1769        ];
1770
1771        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1772        let cpp_len = cpp_sources.len();
1773
1774        if self.target.contains("x86_64-fortanix-unknown-sgx") {
1775            c_sources.push("UnwindRustSgx.c");
1776        }
1777
1778        for src in c_sources {
1779            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1780        }
1781
1782        for src in &cpp_sources {
1783            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1784        }
1785
1786        cpp_cfg.compile("unwind-cpp");
1787
1788        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1789        let mut count = 0;
1790        let mut files = fs::read_dir(&out_dir)
1791            .unwrap()
1792            .map(|entry| entry.unwrap().path().canonicalize().unwrap())
1793            .collect::<Vec<_>>();
1794        files.sort();
1795        for file in files {
1796            if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1797                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".
1798                let base_name = unhashed_basename(&file);
1799                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
1800                    cc_cfg.object(&file);
1801                    count += 1;
1802                }
1803            }
1804        }
1805        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");
1806
1807        cc_cfg.compile("unwind");
1808        out_dir
1809    }
1810}