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        if link_shared {
561            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
562            // Keep the pre-LLVM23 behavior for now.
563            cfg.define("LLVM_VERSIONED_DYLIB_NAME_ON_DARWIN", "OFF");
564        }
565
566        if (target.starts_with("csky")
567            || target.starts_with("riscv")
568            || target.starts_with("sparc-"))
569            && !target.contains("freebsd")
570            && !target.contains("openbsd")
571            && !target.contains("netbsd")
572        {
573            // CSKY and RISC-V GCC erroneously requires linking against
574            // `libatomic` when using 1-byte and 2-byte C++
575            // atomics but the LLVM build system check cannot
576            // detect this. Therefore it is set manually here.
577            // Some BSD uses Clang as its system compiler and
578            // provides no libatomic in its base system so does
579            // not want this. 32-bit SPARC requires linking against
580            // libatomic as well.
581            ldflags.exe.push(" -latomic");
582            ldflags.shared.push(" -latomic");
583        }
584
585        if target.starts_with("mips") && target.contains("netbsd") {
586            // LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic
587            ldflags.exe.push(" -latomic");
588            ldflags.shared.push(" -latomic");
589        }
590
591        if target.starts_with("arm64ec") {
592            // MSVC linker requires the -machine:arm64ec flag to be passed to
593            // know it's linking as Arm64EC (vs Arm64X).
594            ldflags.exe.push(" -machine:arm64ec");
595            ldflags.shared.push(" -machine:arm64ec");
596        }
597
598        // cc-rs deprecated `static_flag`, which used to supply `-static` for musl
599        // targets, so pass it here instead.
600        if target.contains("musl") && builder.crt_static(target).unwrap_or(true) {
601            ldflags.exe.push(" -static");
602        }
603
604        if target.is_msvc() {
605            cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");
606            cfg.static_crt(true);
607        }
608
609        if target.starts_with("i686") {
610            cfg.define("LLVM_BUILD_32_BITS", "ON");
611        }
612
613        if target.starts_with("x86_64") && target.contains("ohos") {
614            cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");
615        }
616
617        let mut enabled_llvm_projects = Vec::new();
618
619        if helpers::forcing_clang_based_tests() {
620            enabled_llvm_projects.push("clang");
621        }
622
623        if builder.config.llvm_polly {
624            enabled_llvm_projects.push("polly");
625        }
626
627        if builder.config.llvm_clang {
628            enabled_llvm_projects.push("clang");
629        }
630
631        // We want libxml to be disabled.
632        // See https://github.com/rust-lang/rust/pull/50104
633        cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
634
635        let mut enabled_llvm_runtimes = Vec::new();
636
637        if helpers::forcing_clang_based_tests() {
638            enabled_llvm_runtimes.push("compiler-rt");
639        }
640
641        if !enabled_llvm_projects.is_empty() {
642            enabled_llvm_projects.sort();
643            enabled_llvm_projects.dedup();
644            cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
645        }
646
647        if !enabled_llvm_runtimes.is_empty() {
648            enabled_llvm_runtimes.sort();
649            enabled_llvm_runtimes.dedup();
650            cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";"));
651        }
652
653        if let Some(num_linkers) = builder.config.llvm_link_jobs
654            && num_linkers > 0
655        {
656            cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
657        }
658
659        // https://llvm.org/docs/HowToCrossCompileLLVM.html
660        if !builder.config.is_host_target(target) {
661            let llvm_host = builder.ensure(Llvm { target: builder.config.host_target });
662            if !builder.config.dry_run() {
663                let llvm_bindir = command(llvm_host.llvm_config())
664                    .arg("--bindir")
665                    .cached()
666                    .run_capture_stdout(builder)
667                    .stdout();
668                let host_bin = Path::new(llvm_bindir.trim());
669                cfg.define(
670                    "LLVM_TABLEGEN",
671                    host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
672                );
673                // LLVM_NM is required for cross compiling using MSVC
674                cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
675            }
676            cfg.define("LLVM_CONFIG_PATH", llvm_host.llvm_config());
677            if builder.config.llvm_clang {
678                let build_bin = llvm_host.root_dir().join("bin");
679                let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
680                if !builder.config.dry_run() && !clang_tblgen.exists() {
681                    panic!("unable to find {}", clang_tblgen.display());
682                }
683                cfg.define("CLANG_TABLEGEN", clang_tblgen);
684            }
685        }
686
687        let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
688            // Allow version-suffix="" to not define a version suffix at all.
689            if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
690        } else if builder.config.channel == "dev" {
691            // Changes to a version suffix require a complete rebuild of the LLVM.
692            // To avoid rebuilds during a time of version bump, don't include rustc
693            // release number on the dev channel.
694            Some("-rust-dev".to_string())
695        } else {
696            Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
697        };
698        if let Some(ref suffix) = llvm_version_suffix {
699            cfg.define("LLVM_VERSION_SUFFIX", suffix);
700        }
701
702        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
703        configure_llvm(builder, target, &mut cfg);
704
705        for (key, val) in &builder.config.llvm_build_config {
706            cfg.define(key, val);
707        }
708
709        if builder.config.dry_run() {
710            return output;
711        }
712
713        cfg.build();
714
715        // Helper to find the name of LLVM's shared library on darwin and linux.
716        let find_llvm_lib_name = |extension| {
717            let llvm_config = if target == builder.host_target {
718                output.llvm_config().to_path_buf()
719            } else {
720                builder.ensure(Llvm { target: builder.host_target }).llvm_config().to_path_buf()
721            };
722
723            let major = get_llvm_version_major(builder, &llvm_config);
724            match &llvm_version_suffix {
725                Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.{extension}"),
726                None => format!("libLLVM-{major}.{extension}"),
727            }
728        };
729
730        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
731        // libLLVM.dylib will be built. However, llvm-config will still look
732        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
733        // link to make llvm-config happy.
734        if link_shared && target.contains("apple-darwin") {
735            let lib_name = find_llvm_lib_name("dylib");
736            let lib_llvm = output.root_dir().join("build").join("lib").join(lib_name);
737            if !lib_llvm.exists() {
738                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
739            }
740        }
741
742        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
743        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
744        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
745        if link_shared && builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
746            // Find the name of the LLVM shared library that we just built.
747            let lib_name = find_llvm_lib_name("so");
748
749            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
750            // debuginfo.
751            crate::core::build_steps::compile::strip_debug(
752                builder,
753                target,
754                &output.root_dir().join("lib").join(&lib_name),
755            );
756            crate::core::build_steps::compile::strip_debug(
757                builder,
758                target,
759                &output.root_dir().join("build").join("lib").join(&lib_name),
760            );
761        }
762
763        t!(stamp.write());
764
765        output
766    }
767
768    fn metadata(&self) -> Option<StepMetadata> {
769        Some(StepMetadata::build("llvm", self.target))
770    }
771}
772
773/// This has to be called with the **host** llvm-config!
774pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
775    command(llvm_config)
776        .arg("--version")
777        .cached()
778        .run_capture_stdout(builder)
779        .stdout()
780        .trim()
781        .to_owned()
782}
783
784/// This has to be called with the **host** llvm-config!
785pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
786    let version = get_llvm_version(builder, llvm_config);
787    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
788    major_str.parse().unwrap()
789}
790
791fn get_llvm_profile(config: &Config) -> &'static str {
792    match (config.llvm_optimize, config.llvm_release_debuginfo) {
793        (false, _) => "Debug",
794        (true, false) => "Release",
795        (true, true) => "RelWithDebInfo",
796    }
797}
798
799fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
800    if builder.config.dry_run() {
801        return;
802    }
803
804    let version = get_llvm_version(builder, llvm_config);
805    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
806    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())
807        && major >= 21
808    {
809        return;
810    }
811    panic!("\n\nbad LLVM version: {version}, need >=21\n\n")
812}
813
814/// C/C++ debug info remap flags for LLVM build.
815///
816/// The remap is observable when LLVM is compiled with debug info,
817/// for example, with `llvm.release-debuginfo = true`.
818fn debuginfo_map_cflags(builder: &Builder<'_>, target: TargetSelection) -> Vec<String> {
819    if !builder.config.rust_remap_debuginfo {
820        return Vec::new();
821    }
822
823    let mut flags = Vec::new();
824    let map = format!("{}=/rustc/llvm", builder.src.display());
825    let cc = builder.cc_tool(target);
826    if cc.is_like_clang() || cc.is_like_gnu() {
827        flags.push(format!("-fdebug-prefix-map={map}"));
828    } else if cc.is_like_clang_cl() {
829        flags.push("-Xclang".into());
830        flags.push(format!("-fdebug-prefix-map={map}"));
831    }
832    flags
833}
834
835fn configure_cmake(
836    builder: &Builder<'_>,
837    target: TargetSelection,
838    cfg: &mut cmake::Config,
839    use_compiler_launcher: bool,
840    mut ldflags: LdFlags,
841    ccflags: CcFlags,
842    suppressed_compiler_flag_prefixes: &[&str],
843) {
844    // Do not print installation messages for up-to-date files.
845    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
846    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
847
848    if builder.config.quiet {
849        // Only log errors and warnings from `cmake`.
850        cfg.define("CMAKE_MESSAGE_LOG_LEVEL", "WARNING");
851
852        // If we're configuring llvm to build with `ninja`, we can suppress output from it with
853        // `--quiet`. Otherwise don't add anything since we don't know which build system is going
854        // to use.
855        if builder.ninja() {
856            cfg.build_arg("--quiet");
857        }
858    }
859
860    // Do not allow the user's value of DESTDIR to influence where
861    // LLVM will install itself. LLVM must always be installed in our
862    // own build directories.
863    cfg.env("DESTDIR", "");
864
865    if builder.ninja() {
866        cfg.generator("Ninja");
867    }
868    cfg.target(&target.triple).host(&builder.config.host_target.triple);
869
870    if !builder.config.is_host_target(target) {
871        cfg.define("CMAKE_CROSSCOMPILING", "True");
872
873        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
874        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
875        // which isn't set when compiling outside `build.rs` (like bootstrap is).
876        //
877        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
878        if target.contains("netbsd") {
879            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
880        } else if target.contains("dragonfly") {
881            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
882        } else if target.contains("openbsd") {
883            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
884        } else if target.contains("freebsd") {
885            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
886        } else if target.is_windows() {
887            cfg.define("CMAKE_SYSTEM_NAME", "Windows");
888        } else if target.contains("haiku") {
889            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
890        } else if target.contains("solaris") || target.contains("illumos") {
891            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
892        } else if target.contains("linux") {
893            cfg.define("CMAKE_SYSTEM_NAME", "Linux");
894        } else if target.contains("darwin") {
895            // macOS
896            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
897        } else if target.contains("ios") {
898            cfg.define("CMAKE_SYSTEM_NAME", "iOS");
899        } else if target.contains("tvos") {
900            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
901        } else if target.contains("visionos") {
902            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
903        } else if target.contains("watchos") {
904            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
905        } else if target.contains("none") {
906            // "none" should be the last branch
907            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
908        } else {
909            builder.info(&format!(
910                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
911            ));
912            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
913            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
914            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
915        }
916
917        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
918        // that case like CMake we cannot easily determine system version either.
919        //
920        // Since, the LLVM itself makes rather limited use of version checks in
921        // CMakeFiles (and then only in tests), and so far no issues have been
922        // reported, the system version is currently left unset.
923
924        if target.contains("apple") {
925            if !target.contains("darwin") {
926                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
927                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?
928                //
929                // So for now we set it to "Darwin" on all Apple platforms.
930                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
931
932                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
933                cfg.define("CMAKE_OSX_SYSROOT", "/");
934                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
935            }
936
937            // Make sure that CMake does not build universal binaries on macOS.
938            // Explicitly specify the one single target architecture.
939            if target.starts_with("aarch64") {
940                // macOS uses a different name for building arm64
941                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
942            } else if target.starts_with("i686") {
943                // macOS uses a different name for building i386
944                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
945            } else {
946                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
947            }
948        }
949    }
950
951    let sanitize_cc = |cc: &Path| {
952        if target.is_msvc() {
953            OsString::from(cc.to_str().unwrap().replace('\\', "/"))
954        } else {
955            cc.as_os_str().to_owned()
956        }
957    };
958
959    // MSVC with CMake uses msbuild by default which doesn't respect these
960    // vars that we'd otherwise configure. In that case we just skip this
961    // entirely.
962    if target.is_msvc() && !builder.ninja() {
963        return;
964    }
965
966    let (cc, cxx) = match builder.config.llvm_clang_cl {
967        Some(ref cl) => (cl.into(), cl.into()),
968        None => (builder.cc(target), builder.cxx(target).unwrap()),
969    };
970
971    // If ccache is configured we inform the build a little differently how
972    // to invoke ccache while also invoking our compilers.
973    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {
974        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
975            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
976    }
977    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
978        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
979        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
980
981    // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it
982    // overrides the jobserver settings and can lead to oversubscription.
983    let has_modern_jobserver = env::var("MAKEFLAGS")
984        .map(|flags| flags.contains("--jobserver-auth=fifo:"))
985        .unwrap_or(false);
986
987    if !has_modern_jobserver {
988        cfg.build_arg("-j").build_arg(builder.jobs().to_string());
989    }
990    let mut cflags = ccflags.cflags.clone();
991    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
992    // our flags via `.cflag`/`.cxxflag` instead.
993    //
994    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
995    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
996    for flag in builder
997        .cc_handled_cflags(target, CLang::C)
998        .into_iter()
999        .chain(builder.cc_unhandled_cflags(target, CLang::C))
1000        .chain(debuginfo_map_cflags(builder, target))
1001        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))
1002    {
1003        cflags.push(" ");
1004        cflags.push(flag);
1005    }
1006    if let Some(ref s) = builder.config.llvm_cflags {
1007        cflags.push(" ");
1008        cflags.push(s);
1009    }
1010    if target.contains("ohos") {
1011        cflags.push(" -D_LINUX_SYSINFO_H");
1012    }
1013    if builder.config.llvm_clang_cl.is_some() {
1014        cflags.push(format!(" --target={target}"));
1015    }
1016    cfg.define("CMAKE_C_FLAGS", cflags);
1017    let mut cxxflags = ccflags.cxxflags.clone();
1018    for flag in builder
1019        .cc_handled_cflags(target, CLang::Cxx)
1020        .into_iter()
1021        .chain(builder.cc_unhandled_cflags(target, CLang::Cxx))
1022        .chain(debuginfo_map_cflags(builder, target))
1023        .filter(|flag| {
1024            !suppressed_compiler_flag_prefixes
1025                .iter()
1026                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
1027        })
1028    {
1029        cxxflags.push(" ");
1030        cxxflags.push(flag);
1031    }
1032    if let Some(ref s) = builder.config.llvm_cxxflags {
1033        cxxflags.push(" ");
1034        cxxflags.push(s);
1035    }
1036    if target.contains("ohos") {
1037        cxxflags.push(" -D_LINUX_SYSINFO_H");
1038    }
1039    if builder.config.llvm_clang_cl.is_some() {
1040        cxxflags.push(format!(" --target={target}"));
1041    }
1042
1043    cfg.define("CMAKE_CXX_FLAGS", cxxflags);
1044    if let Some(ar) = builder.ar(target)
1045        && ar.is_absolute()
1046    {
1047        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
1048        // tries to resolve this path in the LLVM build directory.
1049        cfg.define("CMAKE_AR", sanitize_cc(&ar));
1050    }
1051
1052    if let Some(ranlib) = builder.ranlib(target)
1053        && ranlib.is_absolute()
1054    {
1055        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
1056        // tries to resolve this path in the LLVM build directory.
1057        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
1058    }
1059
1060    if let Some(ref flags) = builder.config.llvm_ldflags {
1061        ldflags.push_all(flags);
1062    }
1063
1064    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
1065        ldflags.push_all(&flags);
1066    }
1067
1068    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
1069    // We also do this if the user explicitly requested static libstdc++.
1070    if builder.config.llvm_static_stdcpp
1071        && !target.is_msvc()
1072        && !target.contains("netbsd")
1073        && !target.contains("solaris")
1074    {
1075        if target.contains("apple") || target.is_windows() {
1076            ldflags.push_all("-static-libstdc++");
1077        } else {
1078            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
1079        }
1080    }
1081
1082    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
1083    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
1084    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
1085
1086    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
1087        cfg.env("RUSTC_LOG", "sccache=warn");
1088    }
1089}
1090
1091fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
1092    // ThinLTO is only available when building with LLVM, enabling LLD is required.
1093    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1094    if builder.config.llvm_thin_lto {
1095        cfg.define("LLVM_ENABLE_LTO", "Thin");
1096        if !target.contains("apple") {
1097            cfg.define("LLVM_ENABLE_LLD", "ON");
1098        }
1099    }
1100
1101    // Libraries for ELF section compression.
1102    if builder.config.llvm_libzstd {
1103        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
1104        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
1105    } else {
1106        cfg.define("LLVM_ENABLE_ZSTD", "OFF");
1107    }
1108
1109    if let Some(ref linker) = builder.config.llvm_use_linker {
1110        cfg.define("LLVM_USE_LINKER", linker);
1111    }
1112
1113    if builder.config.llvm_allow_old_toolchain {
1114        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
1115    }
1116}
1117
1118// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
1119fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
1120    let kind = if host == target { "HOST" } else { "TARGET" };
1121    let target_u = target.replace('-', "_");
1122    env::var_os(format!("{var_base}_{target}"))
1123        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))
1124        .or_else(|| env::var_os(format!("{kind}_{var_base}")))
1125        .or_else(|| env::var_os(var_base))
1126}
1127
1128#[derive(Clone)]
1129pub struct BuiltRustOffload {
1130    /// Path to the rust offload dylib
1131    offload: PathBuf,
1132}
1133
1134impl BuiltRustOffload {
1135    pub fn rust_offload_path(&self) -> PathBuf {
1136        self.offload.clone()
1137    }
1138
1139    pub fn rust_offload_filename(&self) -> String {
1140        self.offload.file_name().unwrap().to_str().unwrap().to_owned()
1141    }
1142}
1143
1144#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1145pub struct RustOffload {
1146    pub target: TargetSelection,
1147}
1148
1149impl CommandLineStep for RustOffload {
1150    type Output = BuiltRustOffload;
1151    const IS_HOST: bool = true;
1152
1153    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1154        run.alias("rust-offload")
1155    }
1156
1157    fn make_run(run: RunConfig<'_>) {
1158        run.builder.ensure(RustOffload { target: run.target });
1159    }
1160
1161    fn run(self, builder: &Builder<'_>) -> Self::Output {
1162        if builder.config.dry_run() {
1163            return BuiltRustOffload {
1164                offload: builder.config.tempdir().join("rust-offload-dry-run"),
1165            };
1166        }
1167
1168        let target = self.target;
1169
1170        let llvm_output = builder.ensure(Llvm { target });
1171
1172        let out_dir = builder.out.join(self.target.triple).join("rust-offload");
1173
1174        let llvm_version_major = get_llvm_version_major(builder, &builder.host_llvm_config());
1175        let lib_ext = std::env::consts::DLL_EXTENSION;
1176        let lib_rust_offload = format!("libRustOffload-{llvm_version_major}");
1177        let build_dir = out_dir.join(libdir(target));
1178        let dylib = build_dir.join(&lib_rust_offload).with_extension(lib_ext);
1179
1180        let mut cfg =
1181            cmake::Config::new(builder.src.join("compiler/rustc_llvm/llvm-wrapper/offload/"));
1182
1183        // Logic copied from `configure_llvm`
1184        // ThinLTO is only available when building with LLVM, enabling LLD is required.
1185        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1186        let mut ldflags = LdFlags::default();
1187        if builder.config.llvm_thin_lto && !target.contains("apple") {
1188            ldflags.push_all("-fuse-ld=lld");
1189        }
1190
1191        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1192
1193        let profile = get_llvm_profile(&builder.config);
1194
1195        cfg.out_dir(&out_dir).profile(profile).define("LLVM_DIR", llvm_output.cmake_dir());
1196
1197        cfg.build();
1198
1199        if !dylib.exists() {
1200            eprintln!(
1201                "`{lib_rust_offload}` not found in `{}`. Either the build has failed or RustOffload was built with a wrong version of LLVM",
1202                build_dir.display()
1203            );
1204            helpers::exit_process(1);
1205        }
1206
1207        BuiltRustOffload { offload: dylib }
1208    }
1209}
1210
1211#[derive(Clone)]
1212pub struct BuiltOmpOffload {
1213    /// Path to the omp and offload dylibs.
1214    offload: Vec<PathBuf>,
1215    /// Directory the dylibs were installed into.
1216    lib_dir: PathBuf,
1217}
1218
1219impl BuiltOmpOffload {
1220    pub fn lib_dir(&self) -> &Path {
1221        &self.lib_dir
1222    }
1223
1224    pub fn artifact_paths_with_symlink_targets(&self) -> Vec<PathBuf> {
1225        let mut paths = self.offload.clone();
1226
1227        for path in &self.offload {
1228            let mut current = path.clone();
1229
1230            while t!(fs::symlink_metadata(&current)).file_type().is_symlink() {
1231                let target = t!(fs::read_link(&current));
1232                current = current.parent().unwrap().join(target);
1233
1234                if paths.contains(&current) {
1235                    break;
1236                }
1237
1238                paths.push(current.clone());
1239            }
1240        }
1241
1242        paths
1243    }
1244}
1245
1246// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
1247// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
1248// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
1249// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
1250// don't always build clang (due to compile times), but instead use a slightly older external clang.
1251// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the
1252// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
1253// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
1254// runtimes. This external clang will try to use it's own (older) include dirs when building our
1255// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
1256// explicitly set our include dirs.
1257#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1258pub struct OmpOffload {
1259    pub target: TargetSelection,
1260}
1261
1262impl CommandLineStep for OmpOffload {
1263    type Output = BuiltOmpOffload;
1264    const IS_HOST: bool = true;
1265
1266    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1267        run.path("src/llvm-project/offload")
1268    }
1269
1270    fn make_run(run: RunConfig<'_>) {
1271        run.builder.ensure(OmpOffload { target: run.target });
1272    }
1273
1274    /// Compile OpenMP offload runtimes for `target`.
1275    #[allow(unused)]
1276    fn run(self, builder: &Builder<'_>) -> Self::Output {
1277        if builder.config.dry_run() {
1278            let dry_run = builder.config.tempdir().join("llvm-offload-dry-run");
1279            return BuiltOmpOffload { offload: vec![dry_run.clone()], lib_dir: dry_run };
1280        }
1281        let target = self.target;
1282
1283        let llvm_output = builder.ensure(Llvm { target });
1284
1285        let out_dir = builder.out.join(self.target.triple).join("offload");
1286
1287        let lib_ext = std::env::consts::DLL_EXTENSION;
1288        let files = vec![
1289            out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext),
1290            out_dir.join("lib").join("libomp").with_extension(lib_ext),
1291            out_dir.join("lib").join("libomptarget").with_extension(lib_ext),
1292        ];
1293
1294        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.
1295        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1296        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1297            generate_smart_stamp_hash(
1298                builder,
1299                &builder.config.src.join("src/llvm-project/offload"),
1300                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1301            )
1302        });
1303        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);
1304
1305        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");
1306        if stamp.is_up_to_date() {
1307            trace!(?out_dir, "offload/openmp build artifacts are up to date");
1308            if stamp.stamp().is_empty() {
1309                builder.info(
1310                    "Could not determine the Offload submodule commit hash. \
1311                     Assuming that an Offload rebuild is not necessary.",
1312                );
1313                builder.info(&format!(
1314                    "To force Offload/OpenMP to rebuild, remove the file `{}`",
1315                    stamp.path().display()
1316                ));
1317            }
1318            return BuiltOmpOffload { offload: files, lib_dir: out_dir.join("lib") };
1319        }
1320
1321        trace!(?target, "(re)building offload/openmp artifacts");
1322        builder.info(&format!("Building OpenMP/Offload for {target}"));
1323        t!(stamp.remove());
1324        let _time = helpers::timeit(builder);
1325        t!(fs::create_dir_all(&out_dir));
1326
1327        builder.config.update_submodule("src/llvm-project");
1328
1329        let offload_clang_dir = if !builder.config.llvm_clang {
1330            // We must have an external clang to use.
1331            builder.sess.config.offload_clang_dir.clone()
1332        } else {
1333            // No need to specify it, since we use the in-tree clang
1334            None
1335        };
1336
1337        // We currently build libompdevice by accident. It includes bitcode for our amd/nvptx
1338        // targets, and only the latest clang compiler can build those. We could stop building those
1339        // to fix this requirement, but we plan on instead building libc-for-gpu very soon, which
1340        // will have the same clang requirement, so we wouldn't save much. There are two ways in
1341        // which we can find a suitable clang. Either a user enabled the llvm.clang, in which case
1342        // we built our own clang based on the llvm submodule first, this always works. The
1343        // alternative is that the user sets the offload_clang_dir path, in which case they hopefully point
1344        // to a suitable clang, otherwise the build will fail.
1345        let clang_bin_dir = if builder.config.llvm_clang {
1346            llvm_output.llvm_config().parent().map(Path::to_path_buf)
1347        } else {
1348            // We expect the following (default) structure of the offload_clang_dir:
1349            // <prefix>/lib/cmake/clang, with a ClangConfig.cmake inside.
1350            // The clang binary is located in <prefix>/bin, so we go up three levels to find it.
1351            // This hardcodes the ClangConfig.cmake logic, which isn't great, so we filter for the
1352            // binary and error if we can't find it (presumably because LLVM build layout changed?).
1353            offload_clang_dir
1354                .as_deref()
1355                .and_then(|dir| dir.ancestors().nth(3))
1356                .map(|prefix| prefix.join("bin"))
1357        }
1358        .filter(|dir| dir.join(exe("clang", target)).exists());
1359
1360        let Some(clang_bin_dir) = clang_bin_dir else {
1361            eprintln!(
1362                "Building Offload requires a clang binary. Please either set `llvm.offload-clang-dir` or enable `llvm.clang` to build it."
1363            );
1364            helpers::exit_process(1);
1365        };
1366        let clang = clang_bin_dir.join(exe("clang", target));
1367        let clangxx = clang_bin_dir.join(exe("clang++", target));
1368
1369        // This was encountered when using gcc 13 to build the llvm submodule on a server, where no
1370        // clang was available. We first built clang along with llvm, and then switched over to use
1371        // the newly built clang to build the offload runtimes. Since we switched compiler, we have
1372        // to make sure that we're still using the same libstdc++ we used before. Without this
1373        // change, clang picked up a system libstdc++ from a different gcc and failed.
1374        let cxx_lib_dir = builder.cxx(target).ok().and_then(|cxx| {
1375            let stdout = command(&cxx)
1376                .arg("-print-file-name=libstdc++.so")
1377                .cached()
1378                .run_capture_stdout(builder)
1379                .stdout();
1380            let libstdcxx = PathBuf::from(stdout.trim());
1381            if !libstdcxx.is_absolute() {
1382                return None;
1383            }
1384            libstdcxx.parent().map(Path::to_path_buf)
1385        });
1386
1387        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));
1388
1389        // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1390        // come with it's own set of default include directories, which are based on a potentially older
1391        // LLVM. This can cause issues, so we overwrite it to include headers based on our
1392        // `src/llvm-project` submodule instead.
1393        let mut cflags = CcFlags::default();
1394        if !builder.config.llvm_clang {
1395            let base = llvm_output.root_dir().join("include");
1396            let inc_dir = base.display();
1397            cflags.push_all(format!(" -I {inc_dir}"));
1398        }
1399
1400        // Logic copied from `configure_llvm`
1401        // ThinLTO is only available when building with LLVM, enabling LLD is required.
1402        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1403        let mut ldflags = LdFlags::default();
1404        if builder.config.llvm_thin_lto && !target.contains("apple") {
1405            ldflags.push_all("-fuse-ld=lld");
1406        }
1407
1408        if let Some(dir) = &cxx_lib_dir {
1409            ldflags.push_all(format!("-L{}", dir.display()));
1410        }
1411
1412        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1413
1414        cfg.define("CMAKE_C_COMPILER", &clang)
1415            .define("CMAKE_CXX_COMPILER", &clangxx)
1416            .define("CMAKE_ASM_COMPILER", &clang);
1417
1418        // Re-use the same flags as llvm to control the level of debug information
1419        // generated for offload.
1420        let profile = get_llvm_profile(&builder.config);
1421        trace!(?profile);
1422
1423        // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1424        // runtime to simplify our build. So far, these are still under development.
1425        cfg.out_dir(&out_dir)
1426            .profile(profile)
1427            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1428            .define("LLVM_INCLUDE_TESTS", "OFF")
1429            .define("OFFLOAD_INCLUDE_TESTS", "OFF")
1430            .define("LLVM_ROOT", llvm_output.root_dir().join("build"))
1431            .define("LLVM_DIR", llvm_output.cmake_dir())
1432            .define("LLVM_DEFAULT_TARGET_TRIPLE", &*target.triple);
1433        if let Some(p) = offload_clang_dir {
1434            cfg.define("Clang_DIR", p);
1435        }
1436
1437        // The offload library provides functionality which only makes sense on the host.
1438        cfg.define("LLVM_ENABLE_RUNTIMES", "openmp;offload");
1439
1440        cfg.build();
1441
1442        t!(stamp.write());
1443
1444        for p in &files {
1445            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>
1446            // files.
1447            if !p.exists() {
1448                eprintln!(
1449                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",
1450                    out_dir.display()
1451                );
1452                helpers::exit_process(1);
1453            }
1454        }
1455        BuiltOmpOffload { offload: files, lib_dir: out_dir.join("lib") }
1456    }
1457}
1458
1459#[derive(Clone)]
1460pub struct BuiltEnzyme {
1461    /// Path to the libEnzyme dylib.
1462    enzyme: PathBuf,
1463}
1464
1465impl BuiltEnzyme {
1466    pub fn enzyme_path(&self) -> PathBuf {
1467        self.enzyme.clone()
1468    }
1469    pub fn enzyme_filename(&self) -> String {
1470        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
1471    }
1472}
1473
1474#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1475pub struct Enzyme {
1476    pub target: TargetSelection,
1477}
1478
1479impl CommandLineStep for Enzyme {
1480    type Output = BuiltEnzyme;
1481    const IS_HOST: bool = true;
1482
1483    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1484        run.path("src/tools/enzyme/enzyme")
1485    }
1486
1487    fn make_run(run: RunConfig<'_>) {
1488        run.builder.ensure(Enzyme { target: run.target });
1489    }
1490
1491    /// Compile Enzyme for `target`.
1492    fn run(self, builder: &Builder<'_>) -> Self::Output {
1493        builder.require_submodule(
1494            "src/tools/enzyme",
1495            Some("The Enzyme sources are required for autodiff."),
1496        );
1497        let target = self.target;
1498
1499        if builder.config.dry_run() {
1500            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1501        }
1502
1503        let llvm_output = builder.ensure(Llvm { target });
1504
1505        // Enzyme links against LLVM. If we update the LLVM submodule libLLVM might get a new
1506        // version number, in which case Enzyme will now fail to find LLVM. By including the LLVM
1507        // hash into the Enzyme hash we force a rebuild of Enzyme when updating LLVM.
1508        let enzyme_hash_input = builder.in_tree_llvm_info.sha().unwrap_or_default().to_owned()
1509            + builder.enzyme_info.sha().unwrap_or_default();
1510
1511        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1512        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1513            generate_smart_stamp_hash(
1514                builder,
1515                &builder.config.src.join("src/tools/enzyme"),
1516                &enzyme_hash_input,
1517            )
1518        });
1519
1520        let out_dir = builder.out.join(self.target.triple).join("enzyme");
1521        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1522
1523        let llvm_version_major = llvm::get_llvm_version_major(builder, &builder.host_llvm_config());
1524        let lib_ext = std::env::consts::DLL_EXTENSION;
1525        let libenzyme = format!("libEnzyme-{llvm_version_major}");
1526        let build_dir = out_dir.join(libdir(target));
1527        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);
1528
1529        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
1530        if stamp.is_up_to_date() {
1531            trace!(?out_dir, "enzyme build artifacts are up to date");
1532            if stamp.stamp().is_empty() {
1533                builder.info(
1534                    "Could not determine the Enzyme submodule commit hash. \
1535                     Assuming that an Enzyme rebuild is not necessary.",
1536                );
1537                builder.info(&format!(
1538                    "To force Enzyme to rebuild, remove the file `{}`",
1539                    stamp.path().display()
1540                ));
1541            }
1542            return BuiltEnzyme { enzyme: dylib };
1543        }
1544
1545        let llvm_cmake_dir = llvm_output.cmake_dir();
1546        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {
1547            builder.info(&format!(
1548                "WARNING: {:?} does not exist, Enzyme build will likely fail",
1549                llvm_cmake_dir
1550            ));
1551        }
1552
1553        trace!(?target, "(re)building enzyme artifacts");
1554        builder.info(&format!("Building Enzyme for {target}"));
1555        t!(stamp.remove());
1556        let _time = helpers::timeit(builder);
1557        t!(fs::create_dir_all(&out_dir));
1558
1559        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
1560        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about
1561        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1562        // hard to spot more relevant issues.
1563        let mut cflags = CcFlags::default();
1564        cflags.push_all("-Wno-deprecated");
1565
1566        // Logic copied from `configure_llvm`
1567        // ThinLTO is only available when building with LLVM, enabling LLD is required.
1568        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1569        let mut ldflags = LdFlags::default();
1570        if builder.config.llvm_thin_lto && !target.contains("apple") {
1571            ldflags.push_all("-fuse-ld=lld");
1572        }
1573
1574        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1575
1576        // Re-use the same flags as llvm to control the level of debug information
1577        // generated by Enzyme.
1578        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
1579        let profile = get_llvm_profile(&builder.config);
1580        trace!(?profile);
1581
1582        cfg.out_dir(&out_dir)
1583            .profile(profile)
1584            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1585            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
1586            .define("ENZYME_BC_LOADER", "OFF")
1587            .define("LLVM_DIR", llvm_cmake_dir);
1588
1589        cfg.build();
1590
1591        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>
1592        // file.
1593        if !dylib.exists() {
1594            eprintln!(
1595                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",
1596                build_dir.display()
1597            );
1598            helpers::exit_process(1);
1599        }
1600
1601        t!(stamp.write());
1602        BuiltEnzyme { enzyme: dylib }
1603    }
1604}
1605
1606#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1607pub struct Lld {
1608    pub target: TargetSelection,
1609}
1610
1611impl CommandLineStep for Lld {
1612    type Output = PathBuf;
1613    const IS_HOST: bool = true;
1614
1615    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1616        run.path("src/llvm-project/lld")
1617    }
1618
1619    fn make_run(run: RunConfig<'_>) {
1620        run.builder.ensure(Lld { target: run.target });
1621    }
1622
1623    /// Compile LLD for `target`.
1624    fn run(self, builder: &Builder<'_>) -> PathBuf {
1625        if builder.config.dry_run() {
1626            return PathBuf::from("lld-out-dir-test-gen");
1627        }
1628        let target = self.target;
1629
1630        let llvm_output = builder.ensure(Llvm { target });
1631
1632        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1633        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
1634        // subfolder. We check if that's the case, and if LLD's binary already exists there next to
1635        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
1636        if matches!(llvm_output.kind, LlvmKind::DownloadedFromCi) {
1637            let bin_dir = llvm_output.root_dir().join("bin");
1638            let lld_path = bin_dir.join(exe("lld", target));
1639            if lld_path.exists() {
1640                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
1641                // `bin` subfolder of this step's out dir.
1642                return bin_dir.parent().unwrap().to_path_buf();
1643            }
1644        }
1645
1646        let out_dir = builder.out.join(target).join("lld");
1647
1648        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1649        if lld_stamp.path().exists() {
1650            return out_dir;
1651        }
1652
1653        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1654        let _time = helpers::timeit(builder);
1655        t!(fs::create_dir_all(&out_dir));
1656
1657        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1658        let mut ldflags = LdFlags::default();
1659
1660        // When building LLD as part of a build with instrumentation on windows, for example
1661        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1662        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1663        // linking errors, much like LLVM's cmake setup does in that situation.
1664        if builder.config.llvm_pgo.generate_profile.is_some()
1665            && target.is_msvc()
1666            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()
1667        {
1668            // Find clang's runtime library directory and push that as a search path to the
1669            // cmake linker flags.
1670            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1671            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));
1672        }
1673
1674        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,
1675        // which impacts where it expects to find LLVM's shared library. This causes #80703.
1676        //
1677        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it
1678        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1679        // lib path for LLVM tools, not the one for rust binaries.
1680        //
1681        // (The `llvm-tools` component copies the .so there for the other tools, and with that
1682        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1683        // `LD_LIBRARY_PATH` overrides)
1684        //
1685        if builder.config.rpath_enabled(target)
1686            && helpers::use_host_linker(target)
1687            && llvm_output.link_shared()
1688            && target.contains("linux")
1689        {
1690            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the
1691            // expected parent `lib` directory.
1692            //
1693            // Be careful when changing this path, we need to ensure it's quoted or escaped:
1694            // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1695            // cmake.
1696            ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");
1697        }
1698
1699        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1700        configure_llvm(builder, target, &mut cfg);
1701
1702        // Re-use the same flags as llvm to control the level of debug information
1703        // generated for lld.
1704        let profile = get_llvm_profile(&builder.config);
1705
1706        cfg.out_dir(&out_dir)
1707            .profile(profile)
1708            .define("LLVM_CMAKE_DIR", llvm_output.cmake_dir())
1709            .define("LLVM_INCLUDE_TESTS", "OFF");
1710
1711        if !builder.config.is_host_target(target) {
1712            // Use the host llvm-tblgen binary.
1713            cfg.define(
1714                "LLVM_TABLEGEN_EXE",
1715                builder
1716                    .host_llvm_config()
1717                    .with_file_name("llvm-tblgen")
1718                    .with_extension(EXE_EXTENSION),
1719            );
1720        }
1721
1722        cfg.build();
1723
1724        t!(lld_stamp.write());
1725        out_dir
1726    }
1727}
1728
1729#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1730pub struct Sanitizers {
1731    pub target: TargetSelection,
1732}
1733
1734impl CommandLineStep for Sanitizers {
1735    type Output = Vec<SanitizerRuntime>;
1736
1737    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1738        run.alias("sanitizers")
1739    }
1740
1741    fn make_run(run: RunConfig<'_>) {
1742        run.builder.ensure(Sanitizers { target: run.target });
1743    }
1744
1745    /// Builds sanitizer runtime libraries.
1746    fn run(self, builder: &Builder<'_>) -> Self::Output {
1747        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1748        if !compiler_rt_dir.exists() {
1749            return Vec::new();
1750        }
1751
1752        let out_dir = builder.native_dir(self.target).join("sanitizers");
1753        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1754
1755        if builder.config.dry_run() || runtimes.is_empty() {
1756            return runtimes;
1757        }
1758
1759        let llvm_host = builder.ensure(Llvm { target: builder.config.host_target });
1760
1761        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1762        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1763            generate_smart_stamp_hash(
1764                builder,
1765                &builder.config.src.join("src/llvm-project/compiler-rt"),
1766                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1767            )
1768        });
1769
1770        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1771
1772        if stamp.is_up_to_date() {
1773            if stamp.stamp().is_empty() {
1774                builder.info(&format!(
1775                    "Rebuild sanitizers by removing the file `{}`",
1776                    stamp.path().display()
1777                ));
1778            }
1779
1780            return runtimes;
1781        }
1782
1783        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1784        t!(stamp.remove());
1785        let _time = helpers::timeit(builder);
1786
1787        let mut cfg = cmake::Config::new(&compiler_rt_dir);
1788        cfg.profile("Release");
1789        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1790        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1791        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1792        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1793        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1794        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1795        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1796        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1797        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1798        cfg.define("LLVM_CONFIG_PATH", llvm_host.llvm_config());
1799
1800        if self.target.contains("ohos") {
1801            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1802        }
1803
1804        // On Darwin targets the sanitizer runtimes are build as universal binaries.
1805        // Unfortunately sccache currently lacks support to build them successfully.
1806        // Disable compiler launcher on Darwin targets to avoid potential issues.
1807        let use_compiler_launcher = !self.target.contains("apple-darwin");
1808        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default
1809        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1810        // causes architecture detection to be skipped when this flag is present,
1811        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1812        let suppressed_compiler_flag_prefixes: &[&str] =
1813            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };
1814        configure_cmake(
1815            builder,
1816            self.target,
1817            &mut cfg,
1818            use_compiler_launcher,
1819            LdFlags::default(),
1820            CcFlags::default(),
1821            suppressed_compiler_flag_prefixes,
1822        );
1823
1824        t!(fs::create_dir_all(&out_dir));
1825        cfg.out_dir(out_dir);
1826
1827        for runtime in &runtimes {
1828            cfg.build_target(&runtime.cmake_target);
1829            cfg.build();
1830        }
1831        t!(stamp.write());
1832
1833        runtimes
1834    }
1835}
1836
1837#[derive(Clone, Debug)]
1838pub struct SanitizerRuntime {
1839    /// CMake target used to build the runtime.
1840    pub cmake_target: String,
1841    /// Path to the built runtime library.
1842    pub path: PathBuf,
1843    /// Library filename that will be used rustc.
1844    pub name: String,
1845}
1846
1847/// Returns sanitizers available on a given target.
1848fn supported_sanitizers(
1849    out_dir: &Path,
1850    target: TargetSelection,
1851    channel: &str,
1852) -> Vec<SanitizerRuntime> {
1853    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1854        components
1855            .iter()
1856            .map(move |c| {
1857                let cmake_c = if *c == "ubsan" { "ubsan_standalone" } else { *c };
1858                SanitizerRuntime {
1859                    cmake_target: format!("clang_rt.{cmake_c}_{os}_dynamic"),
1860                    path: out_dir
1861                        .join(format!("build/lib/darwin/libclang_rt.{cmake_c}_{os}_dynamic.dylib")),
1862                    name: format!("librustc-{channel}_rt.{c}.dylib"),
1863                }
1864            })
1865            .collect()
1866    };
1867
1868    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1869        components
1870            .iter()
1871            .map(move |c| {
1872                let cmake_c = if *c == "ubsan" { "ubsan_standalone" } else { *c };
1873                SanitizerRuntime {
1874                    cmake_target: format!("clang_rt.{cmake_c}-{arch}"),
1875                    path: out_dir.join(format!("build/lib/{os}/libclang_rt.{cmake_c}-{arch}.a")),
1876                    name: format!("librustc-{channel}_rt.{c}.a"),
1877                }
1878            })
1879            .collect()
1880    };
1881
1882    match &*target.triple {
1883        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1884        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),
1885        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),
1886        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1887        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1888        "aarch64-unknown-linux-gnu" => common_libs(
1889            "linux",
1890            "aarch64",
1891            &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan", "ubsan"],
1892        ),
1893        "aarch64-unknown-linux-ohos" => {
1894            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1895        }
1896        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {
1897            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])
1898        }
1899        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1900        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1901        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),
1902        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1903        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1904        "x86_64-unknown-netbsd" => {
1905            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1906        }
1907        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1908        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1909        "x86_64-unknown-linux-gnu" => common_libs(
1910            "linux",
1911            "x86_64",
1912            &["asan", "dfsan", "lsan", "msan", "safestack", "tsan", "rtsan", "ubsan"],
1913        ),
1914        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),
1915        "x86_64-unknown-linux-gnumsan" => common_libs("linux", "x86_64", &["msan"]),
1916        "x86_64-unknown-linux-gnutsan" => common_libs("linux", "x86_64", &["tsan"]),
1917        "x86_64-unknown-linux-musl" => {
1918            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1919        }
1920        "s390x-unknown-linux-gnu" => {
1921            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1922        }
1923        "s390x-unknown-linux-musl" => {
1924            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1925        }
1926        "x86_64-unknown-linux-ohos" => {
1927            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1928        }
1929        _ => Vec::new(),
1930    }
1931}
1932
1933#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1934pub struct CrtBeginEnd {
1935    pub target: TargetSelection,
1936}
1937
1938impl CommandLineStep for CrtBeginEnd {
1939    type Output = PathBuf;
1940
1941    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1942        run.path("src/llvm-project/compiler-rt/lib/crt")
1943    }
1944
1945    fn make_run(run: RunConfig<'_>) {
1946        if run.target.needs_crt_begin_end() {
1947            run.builder.ensure(CrtBeginEnd { target: run.target });
1948        }
1949    }
1950
1951    /// Build crtbegin.o/crtend.o for musl target.
1952    fn run(self, builder: &Builder<'_>) -> Self::Output {
1953        builder.require_submodule(
1954            "src/llvm-project",
1955            Some("The LLVM sources are required for the CRT from `compiler-rt`."),
1956        );
1957
1958        let out_dir = builder.native_dir(self.target).join("crt");
1959
1960        if builder.config.dry_run() {
1961            return out_dir;
1962        }
1963
1964        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");
1965        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");
1966        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))
1967            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1968        {
1969            return out_dir;
1970        }
1971
1972        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
1973        t!(fs::create_dir_all(&out_dir));
1974
1975        let mut cfg = cc::Build::new();
1976
1977        if let Some(ar) = builder.ar(self.target) {
1978            cfg.archiver(ar);
1979        }
1980        cfg.compiler(builder.cc(self.target));
1981        cfg.cargo_metadata(false)
1982            .out_dir(&out_dir)
1983            .target(&self.target.triple)
1984            .host(&builder.config.host_target.triple)
1985            .warnings(false)
1986            .debug(false)
1987            .opt_level(3)
1988            .file(crtbegin_src)
1989            .file(crtend_src);
1990
1991        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
1992        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1993        // instead of .ctors/.dtors
1994        cfg.flag("-std=c11")
1995            .define("CRT_HAS_INITFINI_ARRAY", None)
1996            .define("EH_USE_FRAME_REGISTRY", None);
1997
1998        let objs = cfg.compile_intermediates();
1999        assert_eq!(objs.len(), 2);
2000        for obj in objs {
2001            let base_name = unhashed_basename(&obj);
2002            assert!(base_name == "crtbegin" || base_name == "crtend");
2003            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));
2004            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));
2005        }
2006
2007        out_dir
2008    }
2009}
2010
2011#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2012pub struct Libunwind {
2013    pub target: TargetSelection,
2014}
2015
2016impl CommandLineStep for Libunwind {
2017    type Output = PathBuf;
2018
2019    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2020        run.path("src/llvm-project/libunwind")
2021    }
2022
2023    fn make_run(run: RunConfig<'_>) {
2024        run.builder.ensure(Libunwind { target: run.target });
2025    }
2026
2027    /// Build libunwind.a
2028    fn run(self, builder: &Builder<'_>) -> Self::Output {
2029        builder.require_submodule(
2030            "src/llvm-project",
2031            Some("The LLVM sources are required for libunwind."),
2032        );
2033
2034        if builder.config.dry_run() {
2035            return PathBuf::new();
2036        }
2037
2038        let out_dir = builder.native_dir(self.target).join("libunwind");
2039        let root = builder.src.join("src/llvm-project/libunwind");
2040
2041        if up_to_date(&root, &out_dir.join("libunwind.a")) {
2042            return out_dir;
2043        }
2044
2045        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
2046        t!(fs::create_dir_all(&out_dir));
2047
2048        let mut cc_cfg = cc::Build::new();
2049        let mut cpp_cfg = cc::Build::new();
2050
2051        cpp_cfg.cpp(true);
2052        cpp_cfg.cpp_set_stdlib(None);
2053        cpp_cfg.flag("-nostdinc++");
2054        cpp_cfg.flag("-fno-exceptions");
2055        cpp_cfg.flag("-fno-rtti");
2056        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
2057
2058        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
2059            if let Some(ar) = builder.ar(self.target) {
2060                cfg.archiver(ar);
2061            }
2062            cfg.target(&self.target.triple);
2063            cfg.host(&builder.config.host_target.triple);
2064            cfg.warnings(false);
2065            cfg.debug(false);
2066            // get_compiler() need set opt_level first.
2067            cfg.opt_level(3);
2068            cfg.flag("-fstrict-aliasing");
2069            cfg.flag("-funwind-tables");
2070            cfg.flag("-fvisibility=hidden");
2071            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
2072            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
2073            cfg.include(root.join("include"));
2074            cfg.cargo_metadata(false);
2075            cfg.out_dir(&out_dir);
2076
2077            if self.target.contains("x86_64-fortanix-unknown-sgx") {
2078                cfg.flag("-fno-stack-protector");
2079                cfg.flag("-ffreestanding");
2080                cfg.flag("-fexceptions");
2081
2082                // easiest way to undefine since no API available in cc::Build to undefine
2083                cfg.flag("-U_FORTIFY_SOURCE");
2084                cfg.define("_FORTIFY_SOURCE", "0");
2085                cfg.define("RUST_SGX", "1");
2086                cfg.define("__NO_STRING_INLINES", None);
2087                cfg.define("__NO_MATH_INLINES", None);
2088                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
2089                cfg.define("NDEBUG", None);
2090            }
2091            if self.target.is_windows() {
2092                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
2093            }
2094        }
2095
2096        cc_cfg.compiler(builder.cc(self.target));
2097        if let Ok(cxx) = builder.cxx(self.target) {
2098            cpp_cfg.compiler(cxx);
2099        } else {
2100            cc_cfg.compiler(builder.cc(self.target));
2101        }
2102
2103        // Don't set this for clang
2104        // By default, Clang builds C code in GNU C17 mode.
2105        // By default, Clang builds C++ code according to the C++98 standard,
2106        // with many C++11 features accepted as extensions.
2107        if cc_cfg.get_compiler().is_like_gnu() {
2108            cc_cfg.flag("-std=c99");
2109        }
2110        if cpp_cfg.get_compiler().is_like_gnu() {
2111            cpp_cfg.flag("-std=c++11");
2112        }
2113
2114        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
2115            // use the same GCC C compiler command to compile C++ code so we do not need to setup the
2116            // C++ compiler env variables on the builders.
2117            // Don't set this for clang++, as clang++ is able to compile this without libc++.
2118            if cpp_cfg.get_compiler().is_like_gnu() {
2119                cpp_cfg.cpp(false);
2120                cpp_cfg.compiler(builder.cc(self.target));
2121            }
2122        }
2123
2124        let mut c_sources = vec![
2125            "Unwind-sjlj.c",
2126            "UnwindLevel1-gcc-ext.c",
2127            "UnwindLevel1.c",
2128            "UnwindRegistersRestore.S",
2129            "UnwindRegistersSave.S",
2130        ];
2131
2132        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
2133        let cpp_len = cpp_sources.len();
2134
2135        if self.target.contains("x86_64-fortanix-unknown-sgx") {
2136            c_sources.push("UnwindRustSgx.c");
2137        }
2138
2139        for src in c_sources {
2140            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
2141        }
2142
2143        for src in &cpp_sources {
2144            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
2145        }
2146
2147        cpp_cfg.compile("unwind-cpp");
2148
2149        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
2150        let mut count = 0;
2151        let mut files = fs::read_dir(&out_dir)
2152            .unwrap()
2153            .map(|entry| entry.unwrap().path().canonicalize().unwrap())
2154            .collect::<Vec<_>>();
2155        files.sort();
2156        for file in files {
2157            if file.is_file() && file.extension() == Some(OsStr::new("o")) {
2158                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".
2159                let base_name = unhashed_basename(&file);
2160                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
2161                    cc_cfg.object(&file);
2162                    count += 1;
2163                }
2164            }
2165        }
2166        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");
2167
2168        cc_cfg.compile("unwind");
2169        out_dir
2170    }
2171}
2172
2173/// Returns the path to `FileCheck` LLVM binary for the specified target.
2174#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2175pub struct FileCheck {
2176    pub target: TargetSelection,
2177}
2178
2179impl Step for FileCheck {
2180    type Output = PathBuf;
2181
2182    fn run(self, builder: &Builder<'_>) -> Self::Output {
2183        let target_config = builder.config.target_config.get(&self.target);
2184
2185        // The target configured filecheck, prefer it
2186        if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
2187            return s.clone();
2188        };
2189
2190        // There is a LLVM config set, take filecheck from it
2191        if let Some(llvm_config) = target_config.and_then(|c| c.llvm_config.as_ref()) {
2192            // We can only execute llvm-config if we're on the same host target
2193            return if builder.is_host_target(self.target) {
2194                let llvm_bindir =
2195                    command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
2196                let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", self.target));
2197
2198                if filecheck.exists() {
2199                    filecheck
2200                } else {
2201                    // On Fedora the system LLVM installs FileCheck in the
2202                    // llvm subdirectory of the libdir.
2203                    let llvm_libdir =
2204                        command(llvm_config).arg("--libdir").run_capture_stdout(builder).stdout();
2205                    let lib_filecheck = Path::new(llvm_libdir.trim())
2206                        .join("llvm")
2207                        .join(exe("FileCheck", self.target));
2208                    if lib_filecheck.exists() {
2209                        lib_filecheck
2210                    } else {
2211                        // Return the most normal file name, even though
2212                        // it doesn't exist, so that any error message
2213                        // refers to that.
2214                        filecheck
2215                    }
2216                }
2217            } else {
2218                // In other cases, just guess that Filecheck is available in the same directory
2219                // as the llvm-config
2220                llvm_config.parent().unwrap().join(exe("FileCheck", self.target))
2221            };
2222        }
2223        // Here we take the filecheck from LLVM directly
2224        let llvm_output = builder.ensure(Llvm { target: self.target });
2225        llvm_output.root_dir().join("bin").join(exe("FileCheck", self.target))
2226    }
2227}