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