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