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