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::git::PathFreshness;
18
19use crate::core::build_steps::llvm;
20use crate::core::builder::{
21    Builder, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
22};
23use crate::core::config::{Config, LlvmCiMode, LlvmPgoGenerationMode, TargetSelection};
24use crate::core::session::CLang;
25use crate::trace;
26use crate::utils::build_stamp::{BuildStamp, generate_smart_stamp_hash};
27use crate::utils::exec::command;
28use crate::utils::helpers::{
29    self, exe, get_clang_cl_resource_dir, libdir, t, unhashed_basename, up_to_date,
30};
31/// Path where a file containing the link type (dynamic or static) is stored in the LLVM CI tarball.
32pub const LLVM_CI_LINK_TYPE_PATH: &str = "link-type.txt";
33
34#[derive(Copy, Clone, PartialEq, Eq)]
35pub enum LlvmKind {
36    /// The LLVM was built from in-tree sources
37    BuiltLocally,
38    /// The LLVM was downloaded from the `rust-dev` CI artifact.
39    DownloadedFromCi,
40    /// The LLVM was provided externally through a `llvm-config` file.
41    External,
42}
43
44/// Result of building or downloading LLVM artifacts.
45#[derive(Clone)]
46pub struct LlvmOutput {
47    llvm_config: PathBuf,
48    link_shared: bool,
49    llvm_root_dir: PathBuf,
50    kind: LlvmKind,
51}
52
53impl LlvmOutput {
54    /// Directory containing the built LLVM artifacts.
55    /// Contains `bin`/`lib` directories.
56    pub fn root_dir(&self) -> &Path {
57        &self.llvm_root_dir
58    }
59
60    /// Path to LLVM cmake directory.
61    pub fn cmake_dir(&self) -> PathBuf {
62        self.llvm_root_dir.join("lib").join("cmake").join("llvm")
63    }
64
65    /// Should we link dynamically to the built LLVM?
66    pub fn link_shared(&self) -> bool {
67        self.link_shared
68    }
69
70    /// How was the LLVM produced?
71    pub fn kind(&self) -> LlvmKind {
72        self.kind
73    }
74
75    /// Path to the `llvm-config` binary.
76    ///
77    /// Note that this binary might not be executable on the current host, if LLVM was built for a
78    /// different target.
79    pub fn llvm_config(&self) -> &Path {
80        &self.llvm_config
81    }
82}
83
84pub struct LlvmBuildInfo {
85    stamp: BuildStamp,
86    output: LlvmOutput,
87}
88
89pub enum LlvmBuildStatus {
90    AlreadyBuilt(LlvmOutput),
91    ShouldBuild(LlvmBuildInfo),
92}
93
94impl LlvmBuildStatus {
95    pub fn llvm_output(&self) -> &LlvmOutput {
96        match self {
97            LlvmBuildStatus::AlreadyBuilt(res) => res,
98            LlvmBuildStatus::ShouldBuild(meta) => &meta.output,
99        }
100    }
101}
102
103/// Allows each step to add C/Cxx flags which are only used for a specific cmake invocation.
104#[derive(Debug, Clone, Default)]
105struct CcFlags {
106    /// Additional values for CMAKE_CC_FLAGS, to be added before all other values.
107    cflags: OsString,
108    /// Additional values for CMAKE_CXX_FLAGS, to be added before all other values.
109    cxxflags: OsString,
110}
111
112impl CcFlags {
113    fn push_all(&mut self, s: impl AsRef<OsStr>) {
114        let s = s.as_ref();
115        self.cflags.push(" ");
116        self.cflags.push(s);
117        self.cxxflags.push(" ");
118        self.cxxflags.push(s);
119    }
120}
121
122/// Linker flags to pass to LLVM's CMake invocation.
123#[derive(Debug, Clone, Default)]
124struct LdFlags {
125    /// CMAKE_EXE_LINKER_FLAGS
126    exe: OsString,
127    /// CMAKE_SHARED_LINKER_FLAGS
128    shared: OsString,
129    /// CMAKE_MODULE_LINKER_FLAGS
130    module: OsString,
131}
132
133impl LdFlags {
134    fn push_all(&mut self, s: impl AsRef<OsStr>) {
135        let s = s.as_ref();
136        self.exe.push(" ");
137        self.exe.push(s);
138        self.shared.push(" ");
139        self.shared.push(s);
140        self.module.push(" ");
141        self.module.push(s);
142    }
143}
144
145/// Attempt to return prebuilt LLVM output information, either downloaded from CI or through an
146/// externally provided LLVM.
147///
148/// It's used e.g. to avoid busting caches during x.py check -- if we've already built
149/// LLVM, it's fine for us to not try to avoid doing so.
150///
151/// Calling this function should never attempt to checkout the LLVM submodule.
152pub fn prebuilt_llvm_output(builder: &Builder<'_>, target: TargetSelection) -> Option<LlvmOutput> {
153    // Use an externally provided LLVM, if available
154    if let Some(config) = builder.config.target_config.get(&target)
155        && let Some(ref s) = config.llvm_config
156    {
157        // We execute the llvm-config, and we can only do that on the host target
158        if target == builder.host_target {
159            check_llvm_version(builder, s);
160        }
161        let llvm_config = s.to_path_buf();
162        let mut llvm_root_dir = llvm_config.clone();
163        llvm_root_dir.pop();
164        llvm_root_dir.pop();
165
166        return Some(LlvmOutput {
167            llvm_config,
168            link_shared: llvm_link_shared(&builder.config),
169            llvm_root_dir,
170            kind: LlvmKind::External,
171        });
172    }
173
174    // If external LLVM is not configured, try to download LLVM from CI, if possible
175    let llvm_ci = builder.ensure(LlvmFromCi { target });
176    if let Some(llvm) = llvm_ci {
177        return Some(llvm.output);
178    }
179
180    // If LLVM is not available from CI nor externally, it is still possible that it was already
181    // built locally before. In that case we still treat it as prebuilt config.
182    match get_locally_built_llvm_build_status(builder, target) {
183        LlvmBuildStatus::AlreadyBuilt(output) => Some(output),
184        LlvmBuildStatus::ShouldBuild(_) => None,
185    }
186}
187
188/// This returns whether we've already previously built LLVM.
189///
190/// This will return the llvm-config if it can get it (but it will not build it
191/// if not).
192///
193/// Note that calling this function *might* checkout the LLVM submodule!
194pub fn get_llvm_build_status(builder: &Builder<'_>, target: TargetSelection) -> LlvmBuildStatus {
195    if let Some(prebuilt_output) = prebuilt_llvm_output(builder, target) {
196        return LlvmBuildStatus::AlreadyBuilt(prebuilt_output);
197    }
198
199    // In remaining cases, build it locally
200    // If submodules are disabled, this does nothing.
201    builder.config.update_submodule("src/llvm-project");
202
203    get_locally_built_llvm_build_status(builder, target)
204}
205
206/// Return build status of LLVM, considering only the (possibly) locally built LLVM.
207///
208/// Calling this function should never attempt to checkout the LLVM submodule.
209fn get_locally_built_llvm_build_status(
210    builder: &Builder<'_>,
211    target: TargetSelection,
212) -> LlvmBuildStatus {
213    let out_dir = llvm_output_dir(builder, target);
214
215    let res = LlvmOutput {
216        llvm_config: out_dir.join("bin").join(exe("llvm-config", target)),
217        link_shared: llvm_link_shared(&builder.config),
218        llvm_root_dir: out_dir.clone(),
219        kind: LlvmKind::BuiltLocally,
220    };
221
222    static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
223    let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
224        generate_smart_stamp_hash(
225            builder,
226            &builder.config.src.join("src/llvm-project"),
227            builder.in_tree_llvm_info.sha().unwrap_or_default(),
228        )
229    });
230
231    let stamp = BuildStamp::new(&out_dir).with_prefix("llvm").add_stamp(smart_stamp_hash);
232
233    if stamp.is_up_to_date() {
234        if stamp.stamp().is_empty() {
235            builder.info(
236                "Could not determine the LLVM submodule commit hash. \
237                     Assuming that an LLVM rebuild is not necessary.",
238            );
239            builder.info(&format!(
240                "To force LLVM to rebuild, remove the file `{}`",
241                stamp.path().display()
242            ));
243        }
244        return LlvmBuildStatus::AlreadyBuilt(res);
245    }
246
247    LlvmBuildStatus::ShouldBuild(LlvmBuildInfo { stamp, output: res })
248}
249
250/// Output directory of *locally built* LLVM for the given `target`.
251/// Should only be used within this module, when building LLVM (or related tools).
252/// Otherwise, you should ensure the `Llvm` step and read its root directory.
253fn llvm_output_dir(builder: &Builder<'_>, target: TargetSelection) -> PathBuf {
254    builder.config.out.join(target).join("llvm")
255}
256
257fn try_download_ci_llvm(builder: &Builder<'_>, target: TargetSelection) -> Option<DownloadedLlvm> {
258    match builder.config.llvm_ci_mode {
259        LlvmCiMode::BuildLocally => return None,
260        LlvmCiMode::Download => {}
261        LlvmCiMode::DownloadIfUnchanged => {
262            builder.config.update_submodule("src/llvm-project");
263
264            // Check for untracked changes in `src/llvm-project` and other important places.
265            let has_changes = builder.config.has_changes_from_upstream(LLVM_INVALIDATION_PATHS);
266            if has_changes {
267                builder.info("Warning: LLVM will not be downloaded because of local changes");
268                return None;
269            }
270        }
271    }
272
273    if !is_ci_llvm_available_for_target(&target, builder.config.llvm_assertions) {
274        builder.info(&format!(
275            "Warning: LLVM not available on CI for target={target} and assertions={}",
276            builder.config.llvm_assertions
277        ));
278        return None;
279    }
280
281    let ci_llvm = builder.config.maybe_download_ci_llvm(target)?;
282    let link_shared = if !builder.config.dry_run() {
283        let link_type = t!(
284            std::fs::read_to_string(ci_llvm.join(LLVM_CI_LINK_TYPE_PATH)),
285            format!("LLVM downloaded from CI is missing the following file: {}", ci_llvm.display())
286        );
287        link_type == "dynamic"
288    } else {
289        false
290    };
291
292    Some(DownloadedLlvm {
293        output: LlvmOutput {
294            llvm_config: ci_llvm.join("bin").join(exe("llvm-config", target)),
295            link_shared,
296            llvm_root_dir: ci_llvm,
297            kind: LlvmKind::DownloadedFromCi,
298        },
299    })
300}
301
302/// Determine whether llvm should be linked dynamically.
303/// **NOTE**: This only contains the value from the config.
304/// If you need to figure out the correct value for a specific LLVM instance, use
305/// `prebuilt_llvm_config` instead.
306///
307/// This function is not a method on Config to discourage calling it from outside this module.
308fn llvm_link_shared(config: &Config) -> bool {
309    // unclear how thought-through this default is, but it maintains compatibility with
310    // previous behavior
311    config.llvm_link_shared.unwrap_or(false)
312}
313
314/// Paths whose changes invalidate LLVM downloads.
315pub const LLVM_INVALIDATION_PATHS: &[&str] = &[
316    "src/llvm-project",
317    "src/bootstrap/download-ci-llvm-stamp",
318    // the LLVM shared object file is named `LLVM-<LLVM-version>-rust-{version}-nightly`
319    "src/version",
320];
321
322/// Detect whether LLVM sources have been modified locally or not.
323pub(crate) fn detect_llvm_freshness(config: &Config, is_git: bool) -> PathFreshness {
324    assert!(cfg!(not(test)), "unit tests shouldn't care about LLVM freshness");
325
326    if is_git {
327        config.check_path_modifications(LLVM_INVALIDATION_PATHS)
328    } else if let Some(info) = crate::utils::channel::read_commit_info_file(&config.src) {
329        PathFreshness::LastModifiedUpstream { upstream: info.sha.trim().to_owned() }
330    } else {
331        PathFreshness::MissingUpstream
332    }
333}
334
335/// Returns whether the CI-found LLVM is currently usable.
336///
337/// This checks the build triple platform to confirm we're usable at all, and if LLVM
338/// with/without assertions is available.
339pub(crate) fn is_ci_llvm_available_for_target(
340    host_target: &TargetSelection,
341    asserts: bool,
342) -> bool {
343    // This is currently all tier 1 targets and tier 2 targets with host tools
344    // (since others may not have CI artifacts)
345    // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
346    let supported_platforms = [
347        // tier 1
348        ("aarch64-unknown-linux-gnu", false),
349        ("aarch64-apple-darwin", false),
350        ("aarch64-pc-windows-msvc", false),
351        ("i686-pc-windows-msvc", false),
352        ("i686-unknown-linux-gnu", false),
353        ("x86_64-unknown-linux-gnu", true),
354        ("x86_64-apple-darwin", true),
355        ("x86_64-pc-windows-gnu", false),
356        ("x86_64-pc-windows-msvc", true),
357        // tier 2 with host tools
358        ("aarch64-unknown-linux-musl", false),
359        ("aarch64-pc-windows-gnullvm", false),
360        ("arm-unknown-linux-gnueabi", false),
361        ("arm-unknown-linux-gnueabihf", false),
362        ("armv7-unknown-linux-gnueabihf", false),
363        ("i686-pc-windows-gnu", false),
364        ("loongarch64-unknown-linux-gnu", false),
365        ("loongarch64-unknown-linux-musl", false),
366        ("powerpc-unknown-linux-gnu", false),
367        ("powerpc64-unknown-linux-gnu", false),
368        ("powerpc64-unknown-linux-musl", false),
369        ("powerpc64le-unknown-linux-gnu", false),
370        ("powerpc64le-unknown-linux-musl", false),
371        ("riscv64gc-unknown-linux-gnu", false),
372        ("riscv64gc-unknown-linux-musl", false),
373        ("s390x-unknown-linux-gnu", false),
374        ("x86_64-pc-windows-gnullvm", false),
375        ("x86_64-unknown-freebsd", false),
376        ("x86_64-unknown-illumos", false),
377        ("x86_64-unknown-linux-musl", false),
378        ("x86_64-unknown-netbsd", false),
379    ];
380
381    // Check if the host target is available with the requested assertions (true/false),
382    supported_platforms.contains(&(&*host_target.triple, asserts))
383        // if it is not available for the given `asserts`, check if it is available with assertions (superset).
384        || supported_platforms.contains(&(&*host_target.triple, true))
385}
386
387#[derive(Clone)]
388pub struct DownloadedLlvm {
389    pub output: LlvmOutput,
390}
391
392/// This step explicitly represents the output of *downloaded* LLVM.
393/// The step will provide an output only if all the following is true:
394/// - `llvm.download-ci-llvm` is `true` or `if-unchanged`
395/// - If the previous value is `if-unchanged`, the local LLVM inputs are not modified
396/// - Artifacts for LLVM for the given target (and debug assertions) are available on CI
397///
398/// There are some places in bootstrap that explicitly want to do something special about the
399/// downloaded LLVM, this step serves for them to do it in an explicit way.
400/// For all other use-cases, the normal `Llvm` step should be used.
401#[derive(Debug, Clone, Hash, PartialEq, Eq)]
402pub struct LlvmFromCi {
403    pub target: TargetSelection,
404}
405
406impl Step for LlvmFromCi {
407    type Output = Option<DownloadedLlvm>;
408
409    fn run(self, builder: &Builder<'_>) -> Self::Output {
410        let llvm_ci = try_download_ci_llvm(builder, self.target)?;
411
412        // Sanity check (we execute the llvm-config, so we can only do it on the host target).
413        if builder.host_target == self.target {
414            check_llvm_version(builder, llvm_ci.output.llvm_config());
415        }
416
417        Some(llvm_ci)
418    }
419}
420
421#[derive(Debug, Clone, Hash, PartialEq, Eq)]
422pub struct Llvm {
423    pub target: TargetSelection,
424}
425
426impl CommandLineStep for Llvm {
427    type Output = LlvmOutput;
428
429    const IS_HOST: bool = true;
430
431    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
432        run.path("src/llvm-project").path("src/llvm-project/llvm")
433    }
434
435    fn make_run(run: RunConfig<'_>) {
436        run.builder.ensure(Llvm { target: run.target });
437    }
438
439    /// Compile LLVM for `target`.
440    fn run(self, builder: &Builder<'_>) -> LlvmOutput {
441        let target = self.target;
442        let target_native = if self.target.starts_with("riscv") {
443            // RISC-V target triples in Rust is not named the same as C compiler target triples.
444            // This converts Rust RISC-V target triples to C compiler triples.
445            let idx = target.triple.find('-').unwrap();
446
447            format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
448        } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
449            // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
450            // Set the version suffix to 13.0 so the correct target details are used.
451            format!("{}{}", self.target, "13.0")
452        } else {
453            target.to_string()
454        };
455
456        // If LLVM has already been built or been downloaded through download-ci-llvm, we avoid building it again.
457        let LlvmBuildInfo { stamp, output } = match get_llvm_build_status(builder, target) {
458            LlvmBuildStatus::AlreadyBuilt(p) => return p,
459            LlvmBuildStatus::ShouldBuild(m) => m,
460        };
461
462        let link_shared = llvm_link_shared(&builder.config);
463
464        if link_shared && target.is_windows() && !target.is_windows_gnullvm() {
465            panic!("shared linking to LLVM is not currently supported on {}", target.triple);
466        }
467
468        let _guard = builder.msg_unstaged(Kind::Build, "LLVM", target);
469        t!(stamp.remove());
470        let _time = helpers::timeit(builder);
471        t!(fs::create_dir_all(output.root_dir()));
472
473        // https://llvm.org/docs/CMake.html
474        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/llvm"));
475        let mut ldflags = LdFlags::default();
476
477        let profile = get_llvm_profile(&builder.config);
478
479        // NOTE: remember to also update `bootstrap.example.toml` when changing the
480        // defaults!
481        let llvm_targets = match &builder.config.llvm_targets {
482            Some(s) => s,
483            None => {
484                "AArch64;AMDGPU;ARM;BPF;Hexagon;LoongArch;MSP430;Mips;NVPTX;PowerPC;RISCV;\
485                     Sparc;SystemZ;WebAssembly;X86"
486            }
487        };
488
489        let llvm_exp_targets = match builder.config.llvm_experimental_targets {
490            Some(ref s) => s,
491            None => "AVR;M68k;CSKY;Xtensa",
492        };
493
494        let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
495        let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
496        let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
497        let enable_warnings = if builder.config.llvm_enable_warnings { "ON" } else { "OFF" };
498
499        cfg.out_dir(output.root_dir())
500            .profile(profile)
501            .define("LLVM_ENABLE_ASSERTIONS", assertions)
502            .define("LLVM_UNREACHABLE_OPTIMIZE", "OFF")
503            .define("LLVM_ENABLE_PLUGINS", plugins)
504            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
505            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
506            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
507            .define("LLVM_INCLUDE_DOCS", "OFF")
508            .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
509            .define("LLVM_INCLUDE_TESTS", enable_tests)
510            .define("LLVM_ENABLE_LIBEDIT", "OFF")
511            .define("LLVM_ENABLE_BINDINGS", "OFF")
512            .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
513            .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
514            .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
515            .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native)
516            .define("LLVM_ENABLE_WARNINGS", enable_warnings);
517
518        // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
519        // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
520        // This flag makes sure `FileCheck` is copied in the final binaries directory.
521        cfg.define("LLVM_INSTALL_UTILS", "ON");
522
523        if let Some(mode) = builder.config.llvm_pgo.generate_profile.as_ref() {
524            cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
525            match mode {
526                LlvmPgoGenerationMode::Implicit => {}
527                LlvmPgoGenerationMode::Directory(llvm_profile_dir) => {
528                    cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
529                }
530            }
531            cfg.define("LLVM_BUILD_RUNTIME", "No");
532        }
533        if let Some(path) = builder.config.llvm_pgo.use_profile.as_ref() {
534            cfg.define("LLVM_PROFDATA_FILE", path);
535        }
536
537        // Libraries for ELF section compression and profraw files merging.
538        if !target.is_msvc() {
539            cfg.define("LLVM_ENABLE_ZLIB", "ON");
540        } else {
541            cfg.define("LLVM_ENABLE_ZLIB", "OFF");
542        }
543
544        // Are we compiling for iOS/tvOS/watchOS/visionOS?
545        if target.contains("apple-ios")
546            || target.contains("apple-tvos")
547            || target.contains("apple-watchos")
548            || target.contains("apple-visionos")
549        {
550            // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
551            cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
552            // Zlib fails to link properly, leading to a compiler error.
553            cfg.define("LLVM_ENABLE_ZLIB", "OFF");
554        }
555
556        // This setting makes the LLVM tools link to the dynamic LLVM library,
557        // which saves both memory during parallel links and overall disk space
558        // for the tools. We don't do this on every platform as it doesn't work
559        // equally well everywhere.
560        //
561        // Under normal circumstances, the dylib LINK and BUILD vars below should
562        // be set to the same value. See #160597
563        let llvm_dylib = if link_shared { "ON" } else { "OFF" };
564        cfg.define("LLVM_LINK_LLVM_DYLIB", llvm_dylib);
565        cfg.define("LLVM_BUILD_LLVM_DYLIB", llvm_dylib);
566        // Keep the pre-LLVM23 behavior for now.
567        cfg.define("LLVM_VERSIONED_DYLIB_NAME_ON_DARWIN", "OFF");
568
569        if link_shared {
570            // We inform LLVM tools where they can find the LLVM library
571            // by adding an rpath entry to the expected parent `lib` directory,
572            // e.g. `rust-objcopy` is shipped in `lib/rustlib/<host>/bin`.
573            if let Some(rpath) = llvm_lib_rpath(builder, target) {
574                ldflags.exe.push(" ");
575                ldflags.exe.push(rpath);
576            }
577        }
578
579        if (target.starts_with("csky")
580            || target.starts_with("riscv")
581            || target.starts_with("sparc-"))
582            && !target.contains("freebsd")
583            && !target.contains("openbsd")
584            && !target.contains("netbsd")
585        {
586            // CSKY and RISC-V GCC erroneously requires linking against
587            // `libatomic` when using 1-byte and 2-byte C++
588            // atomics but the LLVM build system check cannot
589            // detect this. Therefore it is set manually here.
590            // Some BSD uses Clang as its system compiler and
591            // provides no libatomic in its base system so does
592            // not want this. 32-bit SPARC requires linking against
593            // libatomic as well.
594            ldflags.exe.push(" -latomic");
595            ldflags.shared.push(" -latomic");
596        }
597
598        if target.starts_with("mips") && target.contains("netbsd") {
599            // LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic
600            ldflags.exe.push(" -latomic");
601            ldflags.shared.push(" -latomic");
602        }
603
604        if target.starts_with("arm64ec") {
605            // MSVC linker requires the -machine:arm64ec flag to be passed to
606            // know it's linking as Arm64EC (vs Arm64X).
607            ldflags.exe.push(" -machine:arm64ec");
608            ldflags.shared.push(" -machine:arm64ec");
609        }
610
611        // cc-rs deprecated `static_flag`, which used to supply `-static` for musl
612        // targets, so pass it here instead.
613        if target.contains("musl") && builder.crt_static(target).unwrap_or(true) {
614            ldflags.exe.push(" -static");
615        }
616
617        if target.is_msvc() {
618            cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");
619            cfg.static_crt(true);
620        }
621
622        if target.starts_with("i686") {
623            cfg.define("LLVM_BUILD_32_BITS", "ON");
624        }
625
626        if target.starts_with("x86_64") && target.contains("ohos") {
627            cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");
628        }
629
630        let mut enabled_llvm_projects = Vec::new();
631
632        if helpers::forcing_clang_based_tests() {
633            enabled_llvm_projects.push("clang");
634        }
635
636        if builder.config.llvm_polly {
637            enabled_llvm_projects.push("polly");
638        }
639
640        if builder.config.llvm_clang {
641            enabled_llvm_projects.push("clang");
642        }
643
644        // We want libxml to be disabled.
645        // See https://github.com/rust-lang/rust/pull/50104
646        cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
647
648        let mut enabled_llvm_runtimes = Vec::new();
649
650        if helpers::forcing_clang_based_tests() {
651            enabled_llvm_runtimes.push("compiler-rt");
652        }
653
654        if !enabled_llvm_projects.is_empty() {
655            enabled_llvm_projects.sort();
656            enabled_llvm_projects.dedup();
657            cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
658        }
659
660        if !enabled_llvm_runtimes.is_empty() {
661            enabled_llvm_runtimes.sort();
662            enabled_llvm_runtimes.dedup();
663            cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";"));
664        }
665
666        if let Some(num_linkers) = builder.config.llvm_link_jobs
667            && num_linkers > 0
668        {
669            cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
670        }
671
672        // https://llvm.org/docs/HowToCrossCompileLLVM.html
673        if !builder.config.is_host_target(target) {
674            let llvm_host = builder.ensure(Llvm { target: builder.config.host_target });
675            if !builder.config.dry_run() {
676                let llvm_bindir = command(llvm_host.llvm_config())
677                    .arg("--bindir")
678                    .cached()
679                    .run_capture_stdout(builder)
680                    .stdout();
681                let host_bin = Path::new(llvm_bindir.trim());
682                cfg.define(
683                    "LLVM_TABLEGEN",
684                    host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
685                );
686                // LLVM_NM is required for cross compiling using MSVC
687                cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
688            }
689            cfg.define("LLVM_CONFIG_PATH", llvm_host.llvm_config());
690            if builder.config.llvm_clang {
691                let build_bin = llvm_host.root_dir().join("bin");
692                let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
693                if !builder.config.dry_run() && !clang_tblgen.exists() {
694                    panic!("unable to find {}", clang_tblgen.display());
695                }
696                cfg.define("CLANG_TABLEGEN", clang_tblgen);
697            }
698        }
699
700        let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
701            // Allow version-suffix="" to not define a version suffix at all.
702            if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
703        } else if builder.config.channel == "dev" {
704            // Changes to a version suffix require a complete rebuild of the LLVM.
705            // To avoid rebuilds during a time of version bump, don't include rustc
706            // release number on the dev channel.
707            Some("-rust-dev".to_string())
708        } else {
709            Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
710        };
711        if let Some(ref suffix) = llvm_version_suffix {
712            cfg.define("LLVM_VERSION_SUFFIX", suffix);
713        }
714
715        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
716        configure_llvm(builder, target, &mut cfg);
717
718        for (key, val) in &builder.config.llvm_build_config {
719            cfg.define(key, val);
720        }
721
722        if builder.config.dry_run() {
723            return output;
724        }
725
726        cfg.build();
727
728        // Helper to find the name of LLVM's shared library on darwin and linux.
729        let find_llvm_lib_name = |extension| {
730            let llvm_config = if target == builder.host_target {
731                output.llvm_config().to_path_buf()
732            } else {
733                builder.ensure(Llvm { target: builder.host_target }).llvm_config().to_path_buf()
734            };
735
736            let major = get_llvm_version_major(builder, &llvm_config);
737            match &llvm_version_suffix {
738                Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.{extension}"),
739                None => format!("libLLVM-{major}.{extension}"),
740            }
741        };
742
743        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
744        // libLLVM.dylib will be built. However, llvm-config will still look
745        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
746        // link to make llvm-config happy.
747        if link_shared && target.contains("apple-darwin") {
748            let lib_name = find_llvm_lib_name("dylib");
749            let lib_llvm = output.root_dir().join("build").join("lib").join(lib_name);
750            if !lib_llvm.exists() {
751                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
752            }
753        }
754
755        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
756        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
757        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
758        if link_shared && builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
759            // Find the name of the LLVM shared library that we just built.
760            let lib_name = find_llvm_lib_name("so");
761
762            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
763            // debuginfo.
764            crate::core::build_steps::compile::strip_debug(
765                builder,
766                target,
767                &output.root_dir().join("lib").join(&lib_name),
768            );
769            crate::core::build_steps::compile::strip_debug(
770                builder,
771                target,
772                &output.root_dir().join("build").join("lib").join(&lib_name),
773            );
774        }
775
776        t!(stamp.write());
777
778        output
779    }
780
781    fn metadata(&self) -> Option<StepMetadata> {
782        Some(StepMetadata::build("llvm", self.target))
783    }
784}
785
786/// This has to be called with the **host** llvm-config!
787pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
788    command(llvm_config)
789        .arg("--version")
790        .cached()
791        .run_capture_stdout(builder)
792        .stdout()
793        .trim()
794        .to_owned()
795}
796
797/// This has to be called with the **host** llvm-config!
798pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
799    let version = get_llvm_version(builder, llvm_config);
800    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
801    major_str.parse().unwrap()
802}
803
804fn get_llvm_profile(config: &Config) -> &'static str {
805    match (config.llvm_optimize, config.llvm_release_debuginfo) {
806        (false, _) => "Debug",
807        (true, false) => "Release",
808        (true, true) => "RelWithDebInfo",
809    }
810}
811
812fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
813    if builder.config.dry_run() {
814        return;
815    }
816
817    let version = get_llvm_version(builder, llvm_config);
818    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
819    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())
820        && major >= 22
821    {
822        return;
823    }
824    panic!("\n\nbad LLVM version: {version}, need >=22\n\n")
825}
826
827/// C/C++ debug info remap flags for LLVM build.
828///
829/// The remap is observable when LLVM is compiled with debug info,
830/// for example, with `llvm.release-debuginfo = true`.
831fn debuginfo_map_cflags(builder: &Builder<'_>, target: TargetSelection) -> Vec<String> {
832    if !builder.config.rust_remap_debuginfo {
833        return Vec::new();
834    }
835
836    let mut flags = Vec::new();
837    let map = format!("{}=/rustc/llvm", builder.src.display());
838    let cc = builder.cc_tool(target);
839    if cc.is_like_clang() || cc.is_like_gnu() {
840        flags.push(format!("-fdebug-prefix-map={map}"));
841    } else if cc.is_like_clang_cl() {
842        flags.push("-Xclang".into());
843        flags.push(format!("-fdebug-prefix-map={map}"));
844    }
845    flags
846}
847
848/// Tries to reuse a locally built LLD as a linker.
849/// If it is not available, uses a global LLD from PATH.
850fn try_link_with_in_tree_lld(
851    builder: &Builder<'_>,
852    target: TargetSelection,
853    llvm_output: &LlvmOutput,
854    cfg: &mut cmake::Config,
855    ldflags: &mut LdFlags,
856) {
857    // Apple has its own ld64 linker, so don't use LLD on Darwin.
858    if target.contains("apple") {
859        return;
860    }
861
862    if builder.config.llvm_use_linker.is_some() || !builder.config.lld_enabled || target.is_msvc() {
863        // Logic derived from `configure_llvm`
864        // ThinLTO is only available when building with LLVM, enabling LLD is required.
865        if builder.config.llvm_thin_lto {
866            ldflags.push_all("-fuse-ld=lld");
867        }
868        return;
869    }
870
871    let lld_bin = builder.ensure(Lld { target }).join("bin");
872    // Quote the path to LLD to prevent it from splitting if it contains a space
873    ldflags.push_all(format!("'-B{}' -fuse-ld=lld", lld_bin.display()));
874
875    if llvm_output.link_shared() {
876        // LLD in this case needs the LLVM lib, so tell where to look for it.
877        let mut dylib_path = helpers::dylib_path();
878        dylib_path.insert(0, llvm_output.root_dir().join("lib"));
879        cfg.env(helpers::dylib_path_var(), t!(env::join_paths(&dylib_path)));
880    }
881}
882
883fn configure_cmake(
884    builder: &Builder<'_>,
885    target: TargetSelection,
886    cfg: &mut cmake::Config,
887    use_compiler_launcher: bool,
888    mut ldflags: LdFlags,
889    ccflags: CcFlags,
890    suppressed_compiler_flag_prefixes: &[&str],
891) {
892    // Do not print installation messages for up-to-date files.
893    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
894    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
895
896    if builder.config.quiet {
897        // Only log errors and warnings from `cmake`.
898        cfg.define("CMAKE_MESSAGE_LOG_LEVEL", "WARNING");
899
900        // If we're configuring llvm to build with `ninja`, we can suppress output from it with
901        // `--quiet`. Otherwise don't add anything since we don't know which build system is going
902        // to use.
903        if builder.ninja() {
904            cfg.build_arg("--quiet");
905        }
906    }
907
908    // Do not allow the user's value of DESTDIR to influence where
909    // LLVM will install itself. LLVM must always be installed in our
910    // own build directories.
911    cfg.env("DESTDIR", "");
912
913    if builder.ninja() {
914        cfg.generator("Ninja");
915    }
916    cfg.target(&target.triple).host(&builder.config.host_target.triple);
917
918    if !builder.config.is_host_target(target) {
919        cfg.define("CMAKE_CROSSCOMPILING", "True");
920
921        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
922        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
923        // which isn't set when compiling outside `build.rs` (like bootstrap is).
924        //
925        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
926        if target.contains("netbsd") {
927            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
928        } else if target.contains("dragonfly") {
929            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
930        } else if target.contains("openbsd") {
931            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
932        } else if target.contains("freebsd") {
933            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
934        } else if target.is_windows() {
935            cfg.define("CMAKE_SYSTEM_NAME", "Windows");
936        } else if target.contains("haiku") {
937            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
938        } else if target.contains("solaris") || target.contains("illumos") {
939            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
940        } else if target.contains("linux") {
941            cfg.define("CMAKE_SYSTEM_NAME", "Linux");
942        } else if target.contains("darwin") {
943            // macOS
944            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
945        } else if target.contains("ios") {
946            cfg.define("CMAKE_SYSTEM_NAME", "iOS");
947        } else if target.contains("tvos") {
948            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
949        } else if target.contains("visionos") {
950            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
951        } else if target.contains("watchos") {
952            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
953        } else if target.contains("none") {
954            // "none" should be the last branch
955            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
956        } else {
957            builder.info(&format!(
958                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
959            ));
960            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
961            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
962            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
963        }
964
965        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
966        // that case like CMake we cannot easily determine system version either.
967        //
968        // Since, the LLVM itself makes rather limited use of version checks in
969        // CMakeFiles (and then only in tests), and so far no issues have been
970        // reported, the system version is currently left unset.
971
972        if target.contains("apple") {
973            if !target.contains("darwin") {
974                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
975                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?
976                //
977                // So for now we set it to "Darwin" on all Apple platforms.
978                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
979
980                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
981                cfg.define("CMAKE_OSX_SYSROOT", "/");
982                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
983            }
984
985            // Make sure that CMake does not build universal binaries on macOS.
986            // Explicitly specify the one single target architecture.
987            if target.starts_with("aarch64") {
988                // macOS uses a different name for building arm64
989                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
990            } else if target.starts_with("i686") {
991                // macOS uses a different name for building i386
992                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
993            } else {
994                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
995            }
996        }
997    }
998
999    let sanitize_cc = |cc: &Path| {
1000        if target.is_msvc() {
1001            OsString::from(cc.to_str().unwrap().replace('\\', "/"))
1002        } else {
1003            cc.as_os_str().to_owned()
1004        }
1005    };
1006
1007    // MSVC with CMake uses msbuild by default which doesn't respect these
1008    // vars that we'd otherwise configure. In that case we just skip this
1009    // entirely.
1010    if target.is_msvc() && !builder.ninja() {
1011        return;
1012    }
1013
1014    let (cc, cxx) = match builder.config.llvm_clang_cl {
1015        Some(ref cl) => (cl.into(), cl.into()),
1016        None => (builder.cc(target), builder.cxx(target).unwrap()),
1017    };
1018
1019    // If ccache is configured we inform the build a little differently how
1020    // to invoke ccache while also invoking our compilers.
1021    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {
1022        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
1023            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
1024    }
1025    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
1026        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
1027        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
1028
1029    // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it
1030    // overrides the jobserver settings and can lead to oversubscription.
1031    let has_modern_jobserver = env::var("MAKEFLAGS")
1032        .map(|flags| flags.contains("--jobserver-auth=fifo:"))
1033        .unwrap_or(false);
1034
1035    if !has_modern_jobserver {
1036        cfg.build_arg("-j").build_arg(builder.jobs().to_string());
1037    }
1038    let mut cflags = ccflags.cflags.clone();
1039    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
1040    // our flags via `.cflag`/`.cxxflag` instead.
1041    //
1042    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
1043    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
1044    for flag in builder
1045        .cc_handled_cflags(target, CLang::C)
1046        .into_iter()
1047        .chain(builder.cc_unhandled_cflags(target, CLang::C))
1048        .chain(debuginfo_map_cflags(builder, target))
1049        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))
1050    {
1051        cflags.push(" ");
1052        cflags.push(flag);
1053    }
1054    if let Some(ref s) = builder.config.llvm_cflags {
1055        cflags.push(" ");
1056        cflags.push(s);
1057    }
1058    if target.contains("ohos") {
1059        cflags.push(" -D_LINUX_SYSINFO_H");
1060    }
1061    if builder.config.llvm_clang_cl.is_some() {
1062        cflags.push(format!(" --target={target}"));
1063    }
1064    cfg.define("CMAKE_C_FLAGS", cflags);
1065    let mut cxxflags = ccflags.cxxflags.clone();
1066    for flag in builder
1067        .cc_handled_cflags(target, CLang::Cxx)
1068        .into_iter()
1069        .chain(builder.cc_unhandled_cflags(target, CLang::Cxx))
1070        .chain(debuginfo_map_cflags(builder, target))
1071        .filter(|flag| {
1072            !suppressed_compiler_flag_prefixes
1073                .iter()
1074                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
1075        })
1076    {
1077        cxxflags.push(" ");
1078        cxxflags.push(flag);
1079    }
1080    if let Some(ref s) = builder.config.llvm_cxxflags {
1081        cxxflags.push(" ");
1082        cxxflags.push(s);
1083    }
1084    if target.contains("ohos") {
1085        cxxflags.push(" -D_LINUX_SYSINFO_H");
1086    }
1087    if builder.config.llvm_clang_cl.is_some() {
1088        cxxflags.push(format!(" --target={target}"));
1089    }
1090
1091    cfg.define("CMAKE_CXX_FLAGS", cxxflags);
1092    if let Some(ar) = builder.ar(target)
1093        && ar.is_absolute()
1094    {
1095        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
1096        // tries to resolve this path in the LLVM build directory.
1097        cfg.define("CMAKE_AR", sanitize_cc(&ar));
1098    }
1099
1100    if let Some(ranlib) = builder.ranlib(target)
1101        && ranlib.is_absolute()
1102    {
1103        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
1104        // tries to resolve this path in the LLVM build directory.
1105        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
1106    }
1107
1108    if let Some(ref flags) = builder.config.llvm_ldflags {
1109        ldflags.push_all(flags);
1110    }
1111
1112    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
1113        ldflags.push_all(&flags);
1114    }
1115
1116    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
1117    // We also do this if the user explicitly requested static libstdc++.
1118    if builder.config.llvm_static_stdcpp
1119        && !target.is_msvc()
1120        && !target.contains("netbsd")
1121        && !target.contains("solaris")
1122    {
1123        if target.contains("apple") || target.is_windows() {
1124            ldflags.push_all("-static-libstdc++");
1125        } else {
1126            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
1127        }
1128    }
1129
1130    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
1131    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
1132    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
1133
1134    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
1135        cfg.env("RUSTC_LOG", "sccache=warn");
1136    }
1137}
1138
1139fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
1140    // ThinLTO is only available when building with LLVM, enabling LLD is required.
1141    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1142    if builder.config.llvm_thin_lto {
1143        cfg.define("LLVM_ENABLE_LTO", "Thin");
1144        if !target.contains("apple") {
1145            cfg.define("LLVM_ENABLE_LLD", "ON");
1146        }
1147    }
1148
1149    // Libraries for ELF section compression.
1150    if builder.config.llvm_libzstd {
1151        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
1152        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
1153    } else {
1154        cfg.define("LLVM_ENABLE_ZSTD", "OFF");
1155    }
1156
1157    if let Some(ref linker) = builder.config.llvm_use_linker {
1158        cfg.define("LLVM_USE_LINKER", linker);
1159    }
1160
1161    if builder.config.llvm_allow_old_toolchain {
1162        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
1163    }
1164}
1165
1166// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
1167fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
1168    let kind = if host == target { "HOST" } else { "TARGET" };
1169    let target_u = target.replace('-', "_");
1170    env::var_os(format!("{var_base}_{target}"))
1171        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))
1172        .or_else(|| env::var_os(format!("{kind}_{var_base}")))
1173        .or_else(|| env::var_os(var_base))
1174}
1175
1176/// Generate a RPATH entry for a binary that will link to LLVM (libLLVM.so) dynamically.
1177/// This will make it possible to execute the binary outside Rustup, so that it can still find the libLLVM.so file.
1178fn llvm_lib_rpath(builder: &Builder<'_>, target: TargetSelection) -> Option<&'static str> {
1179    if builder.config.rpath_enabled(target) && helpers::use_host_linker(target) {
1180        // Be careful when changing this path, we need to ensure it's quoted or escaped:
1181        // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1182        // cmake.
1183        if target.contains("linux") {
1184            return Some("-Wl,-rpath,'$ORIGIN/../../../'");
1185        }
1186        if target.contains("apple-darwin") {
1187            return Some("-Wl,-rpath,'@loader_path/../../../'");
1188        }
1189    }
1190    None
1191}
1192
1193#[derive(Clone)]
1194pub struct BuiltRustOffload {
1195    /// Path to the rust offload dylib
1196    offload: PathBuf,
1197}
1198
1199impl BuiltRustOffload {
1200    pub fn rust_offload_path(&self) -> PathBuf {
1201        self.offload.clone()
1202    }
1203
1204    pub fn rust_offload_filename(&self) -> String {
1205        self.offload.file_name().unwrap().to_str().unwrap().to_owned()
1206    }
1207}
1208
1209#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1210pub struct RustOffload {
1211    pub target: TargetSelection,
1212}
1213
1214impl CommandLineStep for RustOffload {
1215    type Output = BuiltRustOffload;
1216    const IS_HOST: bool = true;
1217
1218    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1219        run.alias("rust-offload")
1220    }
1221
1222    fn make_run(run: RunConfig<'_>) {
1223        run.builder.ensure(RustOffload { target: run.target });
1224    }
1225
1226    fn run(self, builder: &Builder<'_>) -> Self::Output {
1227        if builder.config.dry_run() {
1228            return BuiltRustOffload {
1229                offload: builder.config.tempdir().join("rust-offload-dry-run"),
1230            };
1231        }
1232
1233        let target = self.target;
1234
1235        let llvm_output = builder.ensure(Llvm { target });
1236
1237        let out_dir = builder.out.join(self.target.triple).join("rust-offload");
1238
1239        let llvm_version_major = get_llvm_version_major(builder, &builder.host_llvm_config());
1240        let lib_ext = std::env::consts::DLL_EXTENSION;
1241        let lib_rust_offload = format!("libRustOffload-{llvm_version_major}");
1242        let build_dir = out_dir.join(libdir(target));
1243        let dylib = build_dir.join(&lib_rust_offload).with_extension(lib_ext);
1244
1245        let mut cfg =
1246            cmake::Config::new(builder.src.join("compiler/rustc_llvm/llvm-wrapper/offload/"));
1247
1248        let mut ldflags = LdFlags::default();
1249        try_link_with_in_tree_lld(builder, target, &llvm_output, &mut cfg, &mut ldflags);
1250
1251        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1252
1253        let profile = get_llvm_profile(&builder.config);
1254
1255        cfg.out_dir(&out_dir).profile(profile).define("LLVM_DIR", llvm_output.cmake_dir());
1256
1257        cfg.build();
1258
1259        if !dylib.exists() {
1260            eprintln!(
1261                "`{lib_rust_offload}` not found in `{}`. Either the build has failed or RustOffload was built with a wrong version of LLVM",
1262                build_dir.display()
1263            );
1264            helpers::exit_process(1);
1265        }
1266
1267        BuiltRustOffload { offload: dylib }
1268    }
1269}
1270
1271#[derive(Clone)]
1272pub struct BuiltOmpOffload {
1273    /// Path to the omp and offload dylibs.
1274    offload: Vec<PathBuf>,
1275    /// Directory the dylibs were installed into.
1276    lib_dir: PathBuf,
1277}
1278
1279impl BuiltOmpOffload {
1280    pub fn lib_dir(&self) -> &Path {
1281        &self.lib_dir
1282    }
1283
1284    pub fn artifact_paths_with_symlink_targets(&self) -> Vec<PathBuf> {
1285        let mut paths = self.offload.clone();
1286
1287        for path in &self.offload {
1288            let mut current = path.clone();
1289
1290            while t!(fs::symlink_metadata(&current)).file_type().is_symlink() {
1291                let target = t!(fs::read_link(&current));
1292                current = current.parent().unwrap().join(target);
1293
1294                if paths.contains(&current) {
1295                    break;
1296                }
1297
1298                paths.push(current.clone());
1299            }
1300        }
1301
1302        paths
1303    }
1304}
1305
1306// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
1307// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
1308// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
1309// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
1310// don't always build clang (due to compile times), but instead use a slightly older external clang.
1311// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the
1312// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
1313// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
1314// runtimes. This external clang will try to use it's own (older) include dirs when building our
1315// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
1316// explicitly set our include dirs.
1317#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1318pub struct OmpOffload {
1319    pub target: TargetSelection,
1320}
1321
1322impl CommandLineStep for OmpOffload {
1323    type Output = BuiltOmpOffload;
1324    const IS_HOST: bool = true;
1325
1326    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1327        run.path("src/llvm-project/offload")
1328    }
1329
1330    fn make_run(run: RunConfig<'_>) {
1331        run.builder.ensure(OmpOffload { target: run.target });
1332    }
1333
1334    /// Compile OpenMP offload runtimes for `target`.
1335    #[allow(unused)]
1336    fn run(self, builder: &Builder<'_>) -> Self::Output {
1337        if builder.config.dry_run() {
1338            let dry_run = builder.config.tempdir().join("llvm-offload-dry-run");
1339            return BuiltOmpOffload { offload: vec![dry_run.clone()], lib_dir: dry_run };
1340        }
1341        let target = self.target;
1342
1343        let llvm_output = builder.ensure(Llvm { target });
1344
1345        let out_dir = builder.out.join(self.target.triple).join("offload");
1346
1347        let lib_ext = std::env::consts::DLL_EXTENSION;
1348        let files = vec![
1349            out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext),
1350            out_dir.join("lib").join("libomp").with_extension(lib_ext),
1351            out_dir.join("lib").join("libomptarget").with_extension(lib_ext),
1352        ];
1353
1354        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.
1355        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1356        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1357            generate_smart_stamp_hash(
1358                builder,
1359                &builder.config.src.join("src/llvm-project/offload"),
1360                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1361            )
1362        });
1363        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);
1364
1365        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");
1366        if stamp.is_up_to_date() {
1367            trace!(?out_dir, "offload/openmp build artifacts are up to date");
1368            if stamp.stamp().is_empty() {
1369                builder.info(
1370                    "Could not determine the Offload submodule commit hash. \
1371                     Assuming that an Offload rebuild is not necessary.",
1372                );
1373                builder.info(&format!(
1374                    "To force Offload/OpenMP to rebuild, remove the file `{}`",
1375                    stamp.path().display()
1376                ));
1377            }
1378            return BuiltOmpOffload { offload: files, lib_dir: out_dir.join("lib") };
1379        }
1380
1381        trace!(?target, "(re)building offload/openmp artifacts");
1382        builder.info(&format!("Building OpenMP/Offload for {target}"));
1383        t!(stamp.remove());
1384        let _time = helpers::timeit(builder);
1385        t!(fs::create_dir_all(&out_dir));
1386
1387        builder.config.update_submodule("src/llvm-project");
1388
1389        let offload_clang_dir = if !builder.config.llvm_clang {
1390            // We must have an external clang to use.
1391            builder.sess.config.offload_clang_dir.clone()
1392        } else {
1393            // No need to specify it, since we use the in-tree clang
1394            None
1395        };
1396
1397        // We currently build libompdevice by accident. It includes bitcode for our amd/nvptx
1398        // targets, and only the latest clang compiler can build those. We could stop building those
1399        // to fix this requirement, but we plan on instead building libc-for-gpu very soon, which
1400        // will have the same clang requirement, so we wouldn't save much. There are two ways in
1401        // which we can find a suitable clang. Either a user enabled the llvm.clang, in which case
1402        // we built our own clang based on the llvm submodule first, this always works. The
1403        // alternative is that the user sets the offload_clang_dir path, in which case they hopefully point
1404        // to a suitable clang, otherwise the build will fail.
1405        let clang_bin_dir = if builder.config.llvm_clang {
1406            llvm_output.llvm_config().parent().map(Path::to_path_buf)
1407        } else {
1408            // We expect the following (default) structure of the offload_clang_dir:
1409            // <prefix>/lib/cmake/clang, with a ClangConfig.cmake inside.
1410            // The clang binary is located in <prefix>/bin, so we go up three levels to find it.
1411            // This hardcodes the ClangConfig.cmake logic, which isn't great, so we filter for the
1412            // binary and error if we can't find it (presumably because LLVM build layout changed?).
1413            offload_clang_dir
1414                .as_deref()
1415                .and_then(|dir| dir.ancestors().nth(3))
1416                .map(|prefix| prefix.join("bin"))
1417        }
1418        .filter(|dir| dir.join(exe("clang", target)).exists());
1419
1420        let Some(clang_bin_dir) = clang_bin_dir else {
1421            eprintln!(
1422                "Building Offload requires a clang binary. Please either set `llvm.offload-clang-dir` or enable `llvm.clang` to build it."
1423            );
1424            helpers::exit_process(1);
1425        };
1426        let clang = clang_bin_dir.join(exe("clang", target));
1427        let clangxx = clang_bin_dir.join(exe("clang++", target));
1428
1429        // This was encountered when using gcc 13 to build the llvm submodule on a server, where no
1430        // clang was available. We first built clang along with llvm, and then switched over to use
1431        // the newly built clang to build the offload runtimes. Since we switched compiler, we have
1432        // to make sure that we're still using the same libstdc++ we used before. Without this
1433        // change, clang picked up a system libstdc++ from a different gcc and failed.
1434        let cxx_lib_dir = builder.cxx(target).ok().and_then(|cxx| {
1435            let stdout = command(&cxx)
1436                .arg("-print-file-name=libstdc++.so")
1437                .cached()
1438                .run_capture_stdout(builder)
1439                .stdout();
1440            let libstdcxx = PathBuf::from(stdout.trim());
1441            if !libstdcxx.is_absolute() {
1442                return None;
1443            }
1444            libstdcxx.parent().map(Path::to_path_buf)
1445        });
1446
1447        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));
1448
1449        // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1450        // come with it's own set of default include directories, which are based on a potentially older
1451        // LLVM. This can cause issues, so we overwrite it to include headers based on our
1452        // `src/llvm-project` submodule instead.
1453        let mut cflags = CcFlags::default();
1454        if !builder.config.llvm_clang {
1455            let base = llvm_output.root_dir().join("include");
1456            let inc_dir = base.display();
1457            cflags.push_all(format!(" -I {inc_dir}"));
1458        }
1459
1460        let mut ldflags = LdFlags::default();
1461        try_link_with_in_tree_lld(builder, target, &llvm_output, &mut cfg, &mut ldflags);
1462
1463        if let Some(dir) = &cxx_lib_dir {
1464            ldflags.push_all(format!("-L{}", dir.display()));
1465        }
1466
1467        if llvm_output.link_shared() {
1468            // We inform libomptarget.so where it can find LLVM's libraries
1469            // by adding an rpath entry to the expected parent `lib` directory.
1470            if let Some(rpath) = llvm_lib_rpath(builder, target) {
1471                ldflags.push_all(rpath);
1472            }
1473        }
1474
1475        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1476
1477        cfg.define("CMAKE_C_COMPILER", &clang)
1478            .define("CMAKE_CXX_COMPILER", &clangxx)
1479            .define("CMAKE_ASM_COMPILER", &clang);
1480
1481        // Re-use the same flags as llvm to control the level of debug information
1482        // generated for offload.
1483        let profile = get_llvm_profile(&builder.config);
1484        trace!(?profile);
1485
1486        // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1487        // runtime to simplify our build. So far, these are still under development.
1488        cfg.out_dir(&out_dir)
1489            .profile(profile)
1490            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1491            .define("LLVM_INCLUDE_TESTS", "OFF")
1492            .define("OFFLOAD_INCLUDE_TESTS", "OFF")
1493            .define("LLVM_ROOT", llvm_output.root_dir().join("build"))
1494            .define("LLVM_DIR", llvm_output.cmake_dir())
1495            .define("LLVM_DEFAULT_TARGET_TRIPLE", &*target.triple);
1496        if let Some(p) = offload_clang_dir {
1497            cfg.define("Clang_DIR", p);
1498        }
1499
1500        // The offload library provides functionality which only makes sense on the host.
1501        cfg.define("LLVM_ENABLE_RUNTIMES", "openmp;offload");
1502
1503        cfg.build();
1504
1505        t!(stamp.write());
1506
1507        for p in &files {
1508            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>
1509            // files.
1510            if !p.exists() {
1511                eprintln!(
1512                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",
1513                    out_dir.display()
1514                );
1515                helpers::exit_process(1);
1516            }
1517        }
1518        BuiltOmpOffload { offload: files, lib_dir: out_dir.join("lib") }
1519    }
1520}
1521
1522#[derive(Clone)]
1523pub struct BuiltEnzyme {
1524    /// Path to the libEnzyme dylib.
1525    enzyme: PathBuf,
1526}
1527
1528impl BuiltEnzyme {
1529    pub fn enzyme_path(&self) -> PathBuf {
1530        self.enzyme.clone()
1531    }
1532    pub fn enzyme_filename(&self) -> String {
1533        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
1534    }
1535}
1536
1537#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1538pub struct Enzyme {
1539    pub target: TargetSelection,
1540}
1541
1542impl CommandLineStep for Enzyme {
1543    type Output = BuiltEnzyme;
1544    const IS_HOST: bool = true;
1545
1546    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1547        run.path("src/tools/enzyme/enzyme")
1548    }
1549
1550    fn make_run(run: RunConfig<'_>) {
1551        run.builder.ensure(Enzyme { target: run.target });
1552    }
1553
1554    /// Compile Enzyme for `target`.
1555    fn run(self, builder: &Builder<'_>) -> Self::Output {
1556        builder.require_submodule(
1557            "src/tools/enzyme",
1558            Some("The Enzyme sources are required for autodiff."),
1559        );
1560        let target = self.target;
1561
1562        if builder.config.dry_run() {
1563            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1564        }
1565
1566        let llvm_output = builder.ensure(Llvm { target });
1567
1568        // Enzyme links against LLVM. If we update the LLVM submodule libLLVM might get a new
1569        // version number, in which case Enzyme will now fail to find LLVM. By including the LLVM
1570        // hash into the Enzyme hash we force a rebuild of Enzyme when updating LLVM.
1571        let enzyme_hash_input = builder.in_tree_llvm_info.sha().unwrap_or_default().to_owned()
1572            + builder.enzyme_info.sha().unwrap_or_default();
1573
1574        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1575        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1576            generate_smart_stamp_hash(
1577                builder,
1578                &builder.config.src.join("src/tools/enzyme"),
1579                &enzyme_hash_input,
1580            )
1581        });
1582
1583        let out_dir = builder.out.join(self.target.triple).join("enzyme");
1584        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1585
1586        let llvm_version_major = llvm::get_llvm_version_major(builder, &builder.host_llvm_config());
1587        let lib_ext = std::env::consts::DLL_EXTENSION;
1588        let libenzyme = format!("libEnzyme-{llvm_version_major}");
1589        let build_dir = out_dir.join(libdir(target));
1590        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);
1591
1592        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
1593        if stamp.is_up_to_date() {
1594            trace!(?out_dir, "enzyme build artifacts are up to date");
1595            if stamp.stamp().is_empty() {
1596                builder.info(
1597                    "Could not determine the Enzyme submodule commit hash. \
1598                     Assuming that an Enzyme rebuild is not necessary.",
1599                );
1600                builder.info(&format!(
1601                    "To force Enzyme to rebuild, remove the file `{}`",
1602                    stamp.path().display()
1603                ));
1604            }
1605            return BuiltEnzyme { enzyme: dylib };
1606        }
1607
1608        let llvm_cmake_dir = llvm_output.cmake_dir();
1609        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {
1610            builder.info(&format!(
1611                "WARNING: {:?} does not exist, Enzyme build will likely fail",
1612                llvm_cmake_dir
1613            ));
1614        }
1615
1616        trace!(?target, "(re)building enzyme artifacts");
1617        builder.info(&format!("Building Enzyme for {target}"));
1618        t!(stamp.remove());
1619        let _time = helpers::timeit(builder);
1620        t!(fs::create_dir_all(&out_dir));
1621
1622        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
1623        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about
1624        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1625        // hard to spot more relevant issues.
1626        let mut cflags = CcFlags::default();
1627        cflags.push_all("-Wno-deprecated");
1628
1629        // Logic copied from `configure_llvm`
1630        // ThinLTO is only available when building with LLVM, enabling LLD is required.
1631        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1632        let mut ldflags = LdFlags::default();
1633        if builder.config.llvm_thin_lto && !target.contains("apple") {
1634            ldflags.push_all("-fuse-ld=lld");
1635        }
1636
1637        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1638
1639        // Re-use the same flags as llvm to control the level of debug information
1640        // generated by Enzyme.
1641        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
1642        let profile = get_llvm_profile(&builder.config);
1643        trace!(?profile);
1644
1645        cfg.out_dir(&out_dir)
1646            .profile(profile)
1647            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1648            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
1649            .define("ENZYME_BC_LOADER", "OFF")
1650            .define("LLVM_DIR", llvm_cmake_dir);
1651
1652        cfg.build();
1653
1654        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>
1655        // file.
1656        if !dylib.exists() {
1657            eprintln!(
1658                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",
1659                build_dir.display()
1660            );
1661            helpers::exit_process(1);
1662        }
1663
1664        t!(stamp.write());
1665        BuiltEnzyme { enzyme: dylib }
1666    }
1667}
1668
1669#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1670pub struct Lld {
1671    pub target: TargetSelection,
1672}
1673
1674impl CommandLineStep for Lld {
1675    type Output = PathBuf;
1676    const IS_HOST: bool = true;
1677
1678    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1679        run.path("src/llvm-project/lld")
1680    }
1681
1682    fn make_run(run: RunConfig<'_>) {
1683        run.builder.ensure(Lld { target: run.target });
1684    }
1685
1686    /// Compile LLD for `target`.
1687    fn run(self, builder: &Builder<'_>) -> PathBuf {
1688        if builder.config.dry_run() {
1689            return PathBuf::from("lld-out-dir-test-gen");
1690        }
1691        let target = self.target;
1692
1693        let llvm_output = builder.ensure(Llvm { target });
1694
1695        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1696        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
1697        // subfolder. We check if that's the case, and if LLD's binary already exists there next to
1698        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
1699        if matches!(llvm_output.kind, LlvmKind::DownloadedFromCi) {
1700            let bin_dir = llvm_output.root_dir().join("bin");
1701            let lld_path = bin_dir.join(exe("lld", target));
1702            if lld_path.exists() {
1703                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
1704                // `bin` subfolder of this step's out dir.
1705                return bin_dir.parent().unwrap().to_path_buf();
1706            }
1707        }
1708
1709        let out_dir = builder.out.join(target).join("lld");
1710
1711        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1712        if lld_stamp.path().exists() {
1713            return out_dir;
1714        }
1715
1716        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1717        let _time = helpers::timeit(builder);
1718        t!(fs::create_dir_all(&out_dir));
1719
1720        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1721        let mut ldflags = LdFlags::default();
1722
1723        // When building LLD as part of a build with instrumentation on windows, for example
1724        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1725        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1726        // linking errors, much like LLVM's cmake setup does in that situation.
1727        if builder.config.llvm_pgo.generate_profile.is_some()
1728            && target.is_msvc()
1729            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()
1730        {
1731            // Find clang's runtime library directory and push that as a search path to the
1732            // cmake linker flags.
1733            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1734            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));
1735        }
1736
1737        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,
1738        // which impacts where it expects to find LLVM's shared library. This causes #80703.
1739        //
1740        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it
1741        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1742        // lib path for LLVM tools, not the one for rust binaries.
1743        //
1744        // (The `llvm-tools` component copies the .so there for the other tools, and with that
1745        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1746        // `LD_LIBRARY_PATH` overrides)
1747        //
1748        if llvm_output.link_shared() {
1749            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the
1750            // expected parent `lib` directory.
1751            if let Some(rpath) = llvm_lib_rpath(builder, target) {
1752                ldflags.push_all(rpath);
1753            }
1754        }
1755
1756        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1757        configure_llvm(builder, target, &mut cfg);
1758
1759        // Re-use the same flags as llvm to control the level of debug information
1760        // generated for lld.
1761        let profile = get_llvm_profile(&builder.config);
1762
1763        cfg.out_dir(&out_dir)
1764            .profile(profile)
1765            .define("LLVM_CMAKE_DIR", llvm_output.cmake_dir())
1766            .define("LLVM_INCLUDE_TESTS", "OFF");
1767
1768        if !builder.config.is_host_target(target) {
1769            // Use the host llvm-tblgen binary.
1770            cfg.define(
1771                "LLVM_TABLEGEN_EXE",
1772                builder
1773                    .host_llvm_config()
1774                    .with_file_name("llvm-tblgen")
1775                    .with_extension(EXE_EXTENSION),
1776            );
1777        }
1778
1779        cfg.build();
1780
1781        t!(lld_stamp.write());
1782        out_dir
1783    }
1784}
1785
1786#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1787pub struct Sanitizers {
1788    pub target: TargetSelection,
1789}
1790
1791impl CommandLineStep for Sanitizers {
1792    type Output = Vec<SanitizerRuntime>;
1793
1794    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1795        run.alias("sanitizers")
1796    }
1797
1798    fn make_run(run: RunConfig<'_>) {
1799        run.builder.ensure(Sanitizers { target: run.target });
1800    }
1801
1802    /// Builds sanitizer runtime libraries.
1803    fn run(self, builder: &Builder<'_>) -> Self::Output {
1804        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1805        if !compiler_rt_dir.exists() {
1806            return Vec::new();
1807        }
1808
1809        let out_dir = builder.native_dir(self.target).join("sanitizers");
1810        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1811
1812        if builder.config.dry_run() || runtimes.is_empty() {
1813            return runtimes;
1814        }
1815
1816        let llvm_host = builder.ensure(Llvm { target: builder.config.host_target });
1817
1818        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1819        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1820            generate_smart_stamp_hash(
1821                builder,
1822                &builder.config.src.join("src/llvm-project/compiler-rt"),
1823                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1824            )
1825        });
1826
1827        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1828
1829        if stamp.is_up_to_date() {
1830            if stamp.stamp().is_empty() {
1831                builder.info(&format!(
1832                    "Rebuild sanitizers by removing the file `{}`",
1833                    stamp.path().display()
1834                ));
1835            }
1836
1837            return runtimes;
1838        }
1839
1840        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1841        t!(stamp.remove());
1842        let _time = helpers::timeit(builder);
1843
1844        let mut cfg = cmake::Config::new(&compiler_rt_dir);
1845        cfg.profile("Release");
1846        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1847        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1848        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1849        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1850        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1851        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1852        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1853        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1854        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1855        cfg.define("LLVM_CONFIG_PATH", llvm_host.llvm_config());
1856
1857        if self.target.contains("ohos") {
1858            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1859        }
1860
1861        // On Darwin targets the sanitizer runtimes are build as universal binaries.
1862        // Unfortunately sccache currently lacks support to build them successfully.
1863        // Disable compiler launcher on Darwin targets to avoid potential issues.
1864        let use_compiler_launcher = !self.target.contains("apple-darwin");
1865        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default
1866        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1867        // causes architecture detection to be skipped when this flag is present,
1868        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1869        let suppressed_compiler_flag_prefixes: &[&str] =
1870            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };
1871        configure_cmake(
1872            builder,
1873            self.target,
1874            &mut cfg,
1875            use_compiler_launcher,
1876            LdFlags::default(),
1877            CcFlags::default(),
1878            suppressed_compiler_flag_prefixes,
1879        );
1880
1881        t!(fs::create_dir_all(&out_dir));
1882        cfg.out_dir(out_dir);
1883
1884        for runtime in &runtimes {
1885            cfg.build_target(&runtime.cmake_target);
1886            cfg.build();
1887        }
1888        t!(stamp.write());
1889
1890        runtimes
1891    }
1892}
1893
1894#[derive(Clone, Debug)]
1895pub struct SanitizerRuntime {
1896    /// CMake target used to build the runtime.
1897    pub cmake_target: String,
1898    /// Path to the built runtime library.
1899    pub path: PathBuf,
1900    /// Library filename that will be used rustc.
1901    pub name: String,
1902}
1903
1904/// Returns sanitizers available on a given target.
1905fn supported_sanitizers(
1906    out_dir: &Path,
1907    target: TargetSelection,
1908    channel: &str,
1909) -> Vec<SanitizerRuntime> {
1910    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1911        components
1912            .iter()
1913            .map(move |c| {
1914                let cmake_c = if *c == "ubsan" { "ubsan_standalone" } else { *c };
1915                SanitizerRuntime {
1916                    cmake_target: format!("clang_rt.{cmake_c}_{os}_dynamic"),
1917                    path: out_dir
1918                        .join(format!("build/lib/darwin/libclang_rt.{cmake_c}_{os}_dynamic.dylib")),
1919                    name: format!("librustc-{channel}_rt.{c}.dylib"),
1920                }
1921            })
1922            .collect()
1923    };
1924
1925    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1926        components
1927            .iter()
1928            .map(move |c| {
1929                let cmake_c = if *c == "ubsan" { "ubsan_standalone" } else { *c };
1930                SanitizerRuntime {
1931                    cmake_target: format!("clang_rt.{cmake_c}-{arch}"),
1932                    path: out_dir.join(format!("build/lib/{os}/libclang_rt.{cmake_c}-{arch}.a")),
1933                    name: format!("librustc-{channel}_rt.{c}.a"),
1934                }
1935            })
1936            .collect()
1937    };
1938
1939    match &*target.triple {
1940        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1941        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),
1942        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),
1943        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1944        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1945        "aarch64-unknown-linux-gnu" => common_libs(
1946            "linux",
1947            "aarch64",
1948            &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan", "ubsan", "ubsan_minimal"],
1949        ),
1950        "aarch64-unknown-linux-ohos" => {
1951            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1952        }
1953        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {
1954            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])
1955        }
1956        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1957        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1958        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),
1959        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1960        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1961        "x86_64-unknown-netbsd" => {
1962            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1963        }
1964        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1965        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1966        "x86_64-unknown-linux-gnu" => common_libs(
1967            "linux",
1968            "x86_64",
1969            &[
1970                "asan",
1971                "dfsan",
1972                "lsan",
1973                "msan",
1974                "safestack",
1975                "tsan",
1976                "rtsan",
1977                "ubsan",
1978                "ubsan_minimal",
1979            ],
1980        ),
1981        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),
1982        "x86_64-unknown-linux-gnumsan" => common_libs("linux", "x86_64", &["msan"]),
1983        "x86_64-unknown-linux-gnutsan" => common_libs("linux", "x86_64", &["tsan"]),
1984        "x86_64-unknown-linux-musl" => {
1985            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1986        }
1987        "s390x-unknown-linux-gnu" => {
1988            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1989        }
1990        "s390x-unknown-linux-musl" => {
1991            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1992        }
1993        "x86_64-unknown-linux-ohos" => {
1994            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1995        }
1996        _ => Vec::new(),
1997    }
1998}
1999
2000#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2001pub struct CrtBeginEnd {
2002    pub target: TargetSelection,
2003}
2004
2005impl CommandLineStep for CrtBeginEnd {
2006    type Output = PathBuf;
2007
2008    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2009        run.path("src/llvm-project/compiler-rt/lib/crt")
2010    }
2011
2012    fn make_run(run: RunConfig<'_>) {
2013        if run.target.needs_crt_begin_end() {
2014            run.builder.ensure(CrtBeginEnd { target: run.target });
2015        }
2016    }
2017
2018    /// Build crtbegin.o/crtend.o for musl target.
2019    fn run(self, builder: &Builder<'_>) -> Self::Output {
2020        builder.require_submodule(
2021            "src/llvm-project",
2022            Some("The LLVM sources are required for the CRT from `compiler-rt`."),
2023        );
2024
2025        let out_dir = builder.native_dir(self.target).join("crt");
2026
2027        if builder.config.dry_run() {
2028            return out_dir;
2029        }
2030
2031        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");
2032        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");
2033        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))
2034            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
2035        {
2036            return out_dir;
2037        }
2038
2039        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
2040        t!(fs::create_dir_all(&out_dir));
2041
2042        let mut cfg = cc::Build::new();
2043
2044        if let Some(ar) = builder.ar(self.target) {
2045            cfg.archiver(ar);
2046        }
2047        cfg.compiler(builder.cc(self.target));
2048        cfg.cargo_metadata(false)
2049            .out_dir(&out_dir)
2050            .target(&self.target.triple)
2051            .host(&builder.config.host_target.triple)
2052            .warnings(false)
2053            .debug(false)
2054            .opt_level(3)
2055            .file(crtbegin_src)
2056            .file(crtend_src);
2057
2058        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
2059        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
2060        // instead of .ctors/.dtors
2061        cfg.flag("-std=c11")
2062            .define("CRT_HAS_INITFINI_ARRAY", None)
2063            .define("EH_USE_FRAME_REGISTRY", None);
2064
2065        let objs = cfg.compile_intermediates();
2066        assert_eq!(objs.len(), 2);
2067        for obj in objs {
2068            let base_name = unhashed_basename(&obj);
2069            assert!(base_name == "crtbegin" || base_name == "crtend");
2070            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));
2071            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));
2072        }
2073
2074        out_dir
2075    }
2076}
2077
2078#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2079pub struct Libunwind {
2080    pub target: TargetSelection,
2081}
2082
2083impl CommandLineStep for Libunwind {
2084    type Output = PathBuf;
2085
2086    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2087        run.path("src/llvm-project/libunwind")
2088    }
2089
2090    fn make_run(run: RunConfig<'_>) {
2091        run.builder.ensure(Libunwind { target: run.target });
2092    }
2093
2094    /// Build libunwind.a
2095    fn run(self, builder: &Builder<'_>) -> Self::Output {
2096        builder.require_submodule(
2097            "src/llvm-project",
2098            Some("The LLVM sources are required for libunwind."),
2099        );
2100
2101        if builder.config.dry_run() {
2102            return PathBuf::new();
2103        }
2104
2105        let out_dir = builder.native_dir(self.target).join("libunwind");
2106        let root = builder.src.join("src/llvm-project/libunwind");
2107
2108        if up_to_date(&root, &out_dir.join("libunwind.a")) {
2109            return out_dir;
2110        }
2111
2112        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
2113        t!(fs::create_dir_all(&out_dir));
2114
2115        let mut cc_cfg = cc::Build::new();
2116        let mut cpp_cfg = cc::Build::new();
2117
2118        cpp_cfg.cpp(true);
2119        cpp_cfg.cpp_set_stdlib(None);
2120        cpp_cfg.flag("-nostdinc++");
2121        cpp_cfg.flag("-fno-exceptions");
2122        cpp_cfg.flag("-fno-rtti");
2123        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
2124
2125        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
2126            if let Some(ar) = builder.ar(self.target) {
2127                cfg.archiver(ar);
2128            }
2129            cfg.target(&self.target.triple);
2130            cfg.host(&builder.config.host_target.triple);
2131            cfg.warnings(false);
2132            cfg.debug(false);
2133            // get_compiler() need set opt_level first.
2134            cfg.opt_level(3);
2135            cfg.flag("-fstrict-aliasing");
2136            cfg.flag("-funwind-tables");
2137            cfg.flag("-fvisibility=hidden");
2138            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
2139            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
2140            cfg.include(root.join("include"));
2141            cfg.cargo_metadata(false);
2142            cfg.out_dir(&out_dir);
2143
2144            if self.target.contains("x86_64-fortanix-unknown-sgx") {
2145                cfg.flag("-fno-stack-protector");
2146                cfg.flag("-ffreestanding");
2147                cfg.flag("-fexceptions");
2148
2149                // easiest way to undefine since no API available in cc::Build to undefine
2150                cfg.flag("-U_FORTIFY_SOURCE");
2151                cfg.define("_FORTIFY_SOURCE", "0");
2152                cfg.define("RUST_SGX", "1");
2153                cfg.define("__NO_STRING_INLINES", None);
2154                cfg.define("__NO_MATH_INLINES", None);
2155                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
2156                cfg.define("NDEBUG", None);
2157            }
2158            if self.target.is_windows() {
2159                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
2160            }
2161        }
2162
2163        cc_cfg.compiler(builder.cc(self.target));
2164        if let Ok(cxx) = builder.cxx(self.target) {
2165            cpp_cfg.compiler(cxx);
2166        } else {
2167            cc_cfg.compiler(builder.cc(self.target));
2168        }
2169
2170        // Don't set this for clang
2171        // By default, Clang builds C code in GNU C17 mode.
2172        // By default, Clang builds C++ code according to the C++98 standard,
2173        // with many C++11 features accepted as extensions.
2174        if cc_cfg.get_compiler().is_like_gnu() {
2175            cc_cfg.flag("-std=c99");
2176        }
2177        if cpp_cfg.get_compiler().is_like_gnu() {
2178            cpp_cfg.flag("-std=c++11");
2179        }
2180
2181        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
2182            // use the same GCC C compiler command to compile C++ code so we do not need to setup the
2183            // C++ compiler env variables on the builders.
2184            // Don't set this for clang++, as clang++ is able to compile this without libc++.
2185            if cpp_cfg.get_compiler().is_like_gnu() {
2186                cpp_cfg.cpp(false);
2187                cpp_cfg.compiler(builder.cc(self.target));
2188            }
2189        }
2190
2191        let mut c_sources = vec![
2192            "Unwind-sjlj.c",
2193            "UnwindLevel1-gcc-ext.c",
2194            "UnwindLevel1.c",
2195            "UnwindRegistersRestore.S",
2196            "UnwindRegistersSave.S",
2197        ];
2198
2199        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
2200        let cpp_len = cpp_sources.len();
2201
2202        if self.target.contains("x86_64-fortanix-unknown-sgx") {
2203            c_sources.push("UnwindRustSgx.c");
2204        }
2205
2206        for src in c_sources {
2207            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
2208        }
2209
2210        for src in &cpp_sources {
2211            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
2212        }
2213
2214        cpp_cfg.compile("unwind-cpp");
2215
2216        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
2217        let mut count = 0;
2218        let mut files = fs::read_dir(&out_dir)
2219            .unwrap()
2220            .map(|entry| entry.unwrap().path().canonicalize().unwrap())
2221            .collect::<Vec<_>>();
2222        files.sort();
2223        for file in files {
2224            if file.is_file() && file.extension() == Some(OsStr::new("o")) {
2225                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".
2226                let base_name = unhashed_basename(&file);
2227                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
2228                    cc_cfg.object(&file);
2229                    count += 1;
2230                }
2231            }
2232        }
2233        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");
2234
2235        cc_cfg.compile("unwind");
2236        out_dir
2237    }
2238}
2239
2240/// Returns the path to `FileCheck` LLVM binary for the specified target.
2241#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2242pub struct FileCheck {
2243    pub target: TargetSelection,
2244}
2245
2246impl Step for FileCheck {
2247    type Output = PathBuf;
2248
2249    fn run(self, builder: &Builder<'_>) -> Self::Output {
2250        let target_config = builder.config.target_config.get(&self.target);
2251
2252        // The target configured filecheck, prefer it
2253        if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
2254            return s.clone();
2255        };
2256
2257        // There is a LLVM config set, take filecheck from it
2258        if let Some(llvm_config) = target_config.and_then(|c| c.llvm_config.as_ref()) {
2259            // We can only execute llvm-config if we're on the same host target
2260            return if builder.is_host_target(self.target) {
2261                let llvm_bindir =
2262                    command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
2263                let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", self.target));
2264
2265                if filecheck.exists() {
2266                    filecheck
2267                } else {
2268                    // On Fedora the system LLVM installs FileCheck in the
2269                    // llvm subdirectory of the libdir.
2270                    let llvm_libdir =
2271                        command(llvm_config).arg("--libdir").run_capture_stdout(builder).stdout();
2272                    let lib_filecheck = Path::new(llvm_libdir.trim())
2273                        .join("llvm")
2274                        .join(exe("FileCheck", self.target));
2275                    if lib_filecheck.exists() {
2276                        lib_filecheck
2277                    } else {
2278                        // Return the most normal file name, even though
2279                        // it doesn't exist, so that any error message
2280                        // refers to that.
2281                        filecheck
2282                    }
2283                }
2284            } else {
2285                // In other cases, just guess that Filecheck is available in the same directory
2286                // as the llvm-config
2287                llvm_config.parent().unwrap().join(exe("FileCheck", self.target))
2288            };
2289        }
2290        // Here we take the filecheck from LLVM directly
2291        let llvm_output = builder.ensure(Llvm { target: self.target });
2292        llvm_output.root_dir().join("bin").join(exe("FileCheck", self.target))
2293    }
2294}
2295
2296/// Result of building TPDE artifacts.
2297///
2298/// Currently only tpde-plugin.so is consumed elsewhere.
2299#[derive(Clone)]
2300pub struct TpdeOutput {
2301    tpde_root_dir: PathBuf,
2302    tpde_plugin_path: PathBuf,
2303}
2304
2305impl TpdeOutput {
2306    /// Path to tpde-plugin.so
2307    pub fn plugin_path(&self) -> &Path {
2308        &self.tpde_plugin_path
2309    }
2310}
2311
2312pub struct TpdeBuildInfo {
2313    stamp: BuildStamp,
2314    output: TpdeOutput,
2315}
2316
2317pub enum TpdeBuildStatus {
2318    AlreadyBuilt(TpdeOutput),
2319    ShouldBuild(TpdeBuildInfo),
2320}
2321
2322/// Return build status of TPDE, considering only the locally built TPDE.
2323///
2324/// Calling this function should never attempt to checkout the TPDE submodule.
2325fn get_locally_built_tpde_build_status(
2326    builder: &Builder<'_>,
2327    target: TargetSelection,
2328) -> TpdeBuildStatus {
2329    let out_dir = tpde_output_dir(builder, target);
2330
2331    let res = TpdeOutput {
2332        tpde_plugin_path: out_dir.join("build").join("tpde-llvm").join("tpde-plugin.so"),
2333        tpde_root_dir: out_dir,
2334    };
2335
2336    static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
2337    let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
2338        generate_smart_stamp_hash(
2339            builder,
2340            &builder.config.src.join("src/tpde"),
2341            builder.in_tree_tpde_info.sha().unwrap_or_default(),
2342        )
2343    });
2344
2345    // Rebuild if build options change
2346    let stamp = BuildStamp::new(&res.tpde_root_dir)
2347        .with_prefix("tpde")
2348        .add_stamp(smart_stamp_hash)
2349        .add_stamp(builder.config.llvm_assertions)
2350        .add_stamp(builder.config.llvm_optimize)
2351        .add_stamp(builder.config.llvm_release_debuginfo);
2352
2353    if stamp.is_up_to_date() {
2354        if smart_stamp_hash.is_empty() {
2355            builder.info(
2356                "Could not determine the TPDE submodule commit hash. \
2357                     Assuming that a TPDE rebuild is not necessary.",
2358            );
2359            builder.info(&format!(
2360                "To force TPDE to rebuild, remove the file `{}`",
2361                stamp.path().display()
2362            ));
2363        }
2364        return TpdeBuildStatus::AlreadyBuilt(res);
2365    }
2366
2367    TpdeBuildStatus::ShouldBuild(TpdeBuildInfo { stamp, output: res })
2368}
2369
2370/// Output directory of *locally built* TPDE for the given `target`.
2371/// Should only be used within this module, when building TPDE.
2372/// Otherwise, you should ensure the `Tpde` step and read its root directory.
2373fn tpde_output_dir(builder: &Builder<'_>, target: TargetSelection) -> PathBuf {
2374    builder.config.out.join(target).join("tpde")
2375}
2376
2377#[derive(Debug, Clone, Hash, PartialEq, Eq)]
2378pub struct Tpde {
2379    pub target: TargetSelection,
2380}
2381
2382impl CommandLineStep for Tpde {
2383    type Output = TpdeOutput;
2384
2385    const IS_HOST: bool = true;
2386
2387    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2388        run.path("src/tpde").alias("tpde")
2389    }
2390
2391    fn make_run(run: RunConfig<'_>) {
2392        run.builder.ensure(Tpde { target: run.target });
2393    }
2394
2395    /// Compile TPDE for `target`.
2396    fn run(self, builder: &Builder<'_>) -> TpdeOutput {
2397        let target = self.target;
2398        if !target.contains("linux") {
2399            builder.info(&format!("WARNING: host target {target} not supported by TPDE"));
2400        }
2401        let llvm = builder.ensure(Llvm { target });
2402        if llvm.kind() != LlvmKind::BuiltLocally || !llvm.link_shared() {
2403            // Due to current limitations with the way LLVM configures CMake exports, it is not possible to use CI LLVM.
2404            // FIXME: experiment with LLVM_OMIT_EXPORTS_FROM_CONFIG=OFF and changing library search paths as described in https://github.com/rust-lang/rust/pull/163731#discussion_r4286684608,
2405            // or (preferred) wait until upstream LLVM patches have landed to decouple static exports from dynamic exports in the CMake config
2406            panic!(
2407                "TPDE currently requires building with a locally built LLVM and `llvm.link-shared = true` in bootstrap"
2408            );
2409        }
2410        builder.config.update_submodule("src/tpde");
2411        // If TPDE has already been built, we avoid building it again.
2412        let TpdeBuildInfo { stamp, output } =
2413            match get_locally_built_tpde_build_status(builder, target) {
2414                TpdeBuildStatus::AlreadyBuilt(p) => return p,
2415                TpdeBuildStatus::ShouldBuild(m) => m,
2416            };
2417
2418        let _guard = builder.msg_unstaged(Kind::Build, "TPDE", target);
2419        t!(stamp.remove());
2420        let _time = helpers::timeit(builder);
2421        t!(fs::create_dir_all(&output.tpde_root_dir));
2422
2423        let mut cfg = cmake::Config::new(builder.src.join("src/tpde"));
2424
2425        let profile = get_llvm_profile(&builder.config);
2426        let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
2427
2428        cfg.out_dir(&output.tpde_root_dir)
2429            .profile(profile)
2430            .define("TPDE_ENABLE_ASSERTIONS", assertions)
2431            .define("TPDE_ENABLE_LLVM", "ON")
2432            .define("TPDE_ENABLE_ENCODEGEN", "ON")
2433            .define("TPDE_INCLUDE_TESTS", "OFF")
2434            .define("TPDE_ENABLE_ASAN", "OFF")
2435            .define("TPDE_LOGGING", "OFF")
2436            .define("TPDE_ENABLE_COVERAGE", "OFF")
2437            .define("TPDE_BUILD_DOCS", "OFF")
2438            .define("TPDE_ENABLE_EH", "OFF")
2439            .define("LLVM_DIR", llvm.cmake_dir());
2440
2441        let mut ldflags = LdFlags::default();
2442        try_link_with_in_tree_lld(builder, target, &llvm, &mut cfg, &mut ldflags);
2443        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
2444
2445        if builder.config.dry_run() {
2446            return output;
2447        }
2448
2449        cfg.build_target("tpde-plugin.so");
2450
2451        // When building TPDE as a shared library on linux, it can contain unexpected debuginfo:
2452        // some can come from the C++ standard library. Unless we're explicitly requesting TPDE to
2453        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
2454        if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
2455            // If the shared library exists in TPDE's `/build/tpde-llvm` folder, strip its
2456            // debuginfo.
2457            crate::core::build_steps::compile::strip_debug(builder, target, output.plugin_path());
2458        }
2459
2460        t!(stamp.write());
2461
2462        output
2463    }
2464
2465    fn metadata(&self) -> Option<StepMetadata> {
2466        Some(StepMetadata::build("tpde", self.target))
2467    }
2468}