1 //! Compilation of native dependencies like LLVM.
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).
8 //! LLVM and compiler-rt are essentially just wired up to everything else to
9 //! ensure that they're always in place if needed.
12 use std::env::consts::EXE_EXTENSION;
13 use std::ffi::{OsStr, OsString};
14 use std::fs::{self, File};
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
19 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
20 use crate::config::TargetSelection;
21 use crate::util::get_clang_cl_resource_dir;
22 use crate::util::{self, exe, output, program_out_of_date, t, up_to_date};
23 use crate::{CLang, GitRepo};
27 build_llvm_config: PathBuf,
32 // Linker flags to pass to LLVM's CMake invocation.
33 #[derive(Debug, Clone, Default)]
35 // CMAKE_EXE_LINKER_FLAGS
37 // CMAKE_SHARED_LINKER_FLAGS
39 // CMAKE_MODULE_LINKER_FLAGS
44 fn push_all(&mut self, s: impl AsRef<OsStr>) {
48 self.shared.push(" ");
50 self.module.push(" ");
55 // This returns whether we've already previously built LLVM.
57 // It's used to avoid busting caches during x.py check -- if we've already built
58 // LLVM, it's fine for us to not try to avoid doing so.
60 // This will return the llvm-config if it can get it (but it will not build it
62 pub fn prebuilt_llvm_config(
63 builder: &Builder<'_>,
64 target: TargetSelection,
65 ) -> Result<PathBuf, Meta> {
66 maybe_download_ci_llvm(builder);
68 // If we're using a custom LLVM bail out here, but we can only use a
69 // custom LLVM for the build triple.
70 if let Some(config) = builder.config.target_config.get(&target) {
71 if let Some(ref s) = config.llvm_config {
72 check_llvm_version(builder, s);
73 return Ok(s.to_path_buf());
77 let root = "src/llvm-project/llvm";
78 let out_dir = builder.llvm_out(target);
80 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
81 if !builder.config.build.contains("msvc") || builder.ninja() {
82 llvm_config_ret_dir.push("build");
84 llvm_config_ret_dir.push("bin");
86 let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
88 let stamp = out_dir.join("llvm-finished-building");
89 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
91 if builder.config.llvm_skip_rebuild && stamp.path.exists() {
94 Using a potentially stale build of LLVM; \
95 This may not behave well.",
97 return Ok(build_llvm_config);
101 if stamp.hash.is_none() {
103 "Could not determine the LLVM submodule commit hash. \
104 Assuming that an LLVM rebuild is not necessary.",
106 builder.info(&format!(
107 "To force LLVM to rebuild, remove the file `{}`",
111 return Ok(build_llvm_config);
114 Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
117 pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) {
118 let config = &builder.config;
119 if !config.llvm_from_ci {
122 let mut rev_list = config.git();
124 PathBuf::from("rev-list"),
125 format!("--author={}", builder.config.stage0_metadata.config.git_merge_commit_email).into(),
127 "--first-parent".into(),
130 builder.src.join("src/llvm-project"),
131 builder.src.join("src/bootstrap/download-ci-llvm-stamp"),
132 // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
133 builder.src.join("src/version"),
135 let llvm_sha = output(&mut rev_list);
136 let llvm_sha = llvm_sha.trim();
139 eprintln!("error: could not find commit hash for downloading LLVM");
140 eprintln!("help: maybe your repository history is too shallow?");
141 eprintln!("help: consider disabling `download-ci-llvm`");
142 eprintln!("help: or fetch enough history to include one upstream commit");
146 let llvm_root = config.ci_llvm_root();
147 let llvm_stamp = llvm_root.join(".llvm-stamp");
148 let key = format!("{}{}", llvm_sha, config.llvm_assertions);
149 if program_out_of_date(&llvm_stamp, &key) && !config.dry_run {
150 download_ci_llvm(builder, &llvm_sha);
151 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
152 builder.fix_bin_or_dylib(&t!(entry).path());
155 // Update the timestamp of llvm-config to force rustc_llvm to be
156 // rebuilt. This is a hacky workaround for a deficiency in Cargo where
157 // the rerun-if-changed directive doesn't handle changes very well.
158 // https://github.com/rust-lang/cargo/issues/10791
159 // Cargo only compares the timestamp of the file relative to the last
160 // time `rustc_llvm` build script ran. However, the timestamps of the
161 // files in the tarball are in the past, so it doesn't trigger a
163 let now = filetime::FileTime::from_system_time(std::time::SystemTime::now());
164 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", builder.config.build));
165 t!(filetime::set_file_times(&llvm_config, now, now));
167 let llvm_lib = llvm_root.join("lib");
168 for entry in t!(fs::read_dir(&llvm_lib)) {
169 let lib = t!(entry).path();
170 if lib.extension().map_or(false, |ext| ext == "so") {
171 builder.fix_bin_or_dylib(&lib);
174 t!(fs::write(llvm_stamp, key));
178 fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) {
179 let llvm_assertions = builder.config.llvm_assertions;
181 let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
182 let cache_dst = builder.out.join("cache");
183 let rustc_cache = cache_dst.join(cache_prefix);
184 if !rustc_cache.exists() {
185 t!(fs::create_dir_all(&rustc_cache));
187 let base = if llvm_assertions {
188 &builder.config.stage0_metadata.config.artifacts_with_llvm_assertions_server
190 &builder.config.stage0_metadata.config.artifacts_server
192 let filename = format!("rust-dev-nightly-{}.tar.xz", builder.build.build.triple);
193 let tarball = rustc_cache.join(&filename);
194 if !tarball.exists() {
195 let help_on_error = "error: failed to download llvm from ci
197 help: old builds get deleted after a certain time
198 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
201 download-ci-llvm = false
203 builder.download_component(
204 &format!("{base}/{llvm_sha}/{filename}"),
209 let llvm_root = builder.config.ci_llvm_root();
210 builder.unpack(&tarball, &llvm_root, "rust-dev");
213 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
215 pub target: TargetSelection,
219 type Output = PathBuf; // path to llvm-config
221 const ONLY_HOSTS: bool = true;
223 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
224 run.path("src/llvm-project").path("src/llvm-project/llvm")
227 fn make_run(run: RunConfig<'_>) {
228 run.builder.ensure(Llvm { target: run.target });
231 /// Compile LLVM for `target`.
232 fn run(self, builder: &Builder<'_>) -> PathBuf {
233 let target = self.target;
234 let target_native = if self.target.starts_with("riscv") {
235 // RISC-V target triples in Rust is not named the same as C compiler target triples.
236 // This converts Rust RISC-V target triples to C compiler triples.
237 let idx = target.triple.find('-').unwrap();
239 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
240 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
241 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
242 // Set the version suffix to 13.0 so the correct target details are used.
243 format!("{}{}", self.target, "13.0")
248 let Meta { stamp, build_llvm_config, out_dir, root } =
249 match prebuilt_llvm_config(builder, target) {
254 builder.update_submodule(&Path::new("src").join("llvm-project"));
255 if builder.llvm_link_shared() && target.contains("windows") {
256 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
259 builder.info(&format!("Building LLVM for {}", target));
261 let _time = util::timeit(&builder);
262 t!(fs::create_dir_all(&out_dir));
264 // https://llvm.org/docs/CMake.html
265 let mut cfg = cmake::Config::new(builder.src.join(root));
266 let mut ldflags = LdFlags::default();
268 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
269 (false, _) => "Debug",
270 (true, false) => "Release",
271 (true, true) => "RelWithDebInfo",
274 // NOTE: remember to also update `config.toml.example` when changing the
276 let llvm_targets = match &builder.config.llvm_targets {
279 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
280 Sparc;SystemZ;WebAssembly;X86"
284 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
289 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
290 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
291 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
293 cfg.out_dir(&out_dir)
295 .define("LLVM_ENABLE_ASSERTIONS", assertions)
296 .define("LLVM_ENABLE_PLUGINS", plugins)
297 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
298 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
299 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
300 .define("LLVM_INCLUDE_DOCS", "OFF")
301 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
302 .define("LLVM_INCLUDE_TESTS", enable_tests)
303 .define("LLVM_ENABLE_TERMINFO", "OFF")
304 .define("LLVM_ENABLE_LIBEDIT", "OFF")
305 .define("LLVM_ENABLE_BINDINGS", "OFF")
306 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
307 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
308 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
309 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
311 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
312 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
313 // This flag makes sure `FileCheck` is copied in the final binaries directory.
314 cfg.define("LLVM_INSTALL_UTILS", "ON");
316 if builder.config.llvm_profile_generate {
317 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
318 if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
319 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
321 cfg.define("LLVM_BUILD_RUNTIME", "No");
323 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
324 cfg.define("LLVM_PROFDATA_FILE", &path);
327 if target != "aarch64-apple-darwin" && !target.contains("windows") {
328 cfg.define("LLVM_ENABLE_ZLIB", "ON");
330 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
333 // Are we compiling for iOS/tvOS/watchOS?
334 if target.contains("apple-ios")
335 || target.contains("apple-tvos")
336 || target.contains("apple-watchos")
338 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
339 cfg.define("CMAKE_OSX_SYSROOT", "/");
340 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
341 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
342 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
343 // Zlib fails to link properly, leading to a compiler error.
344 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
347 if builder.config.llvm_thin_lto {
348 cfg.define("LLVM_ENABLE_LTO", "Thin");
349 if !target.contains("apple") {
350 cfg.define("LLVM_ENABLE_LLD", "ON");
354 // This setting makes the LLVM tools link to the dynamic LLVM library,
355 // which saves both memory during parallel links and overall disk space
356 // for the tools. We don't do this on every platform as it doesn't work
357 // equally well everywhere.
359 // If we're not linking rustc to a dynamic LLVM, though, then don't link
361 let llvm_link_shared =
362 builder.llvm_link_tools_dynamically(target) && builder.llvm_link_shared();
363 if llvm_link_shared {
364 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
367 if target.starts_with("riscv") && !target.contains("freebsd") {
368 // RISC-V GCC erroneously requires linking against
369 // `libatomic` when using 1-byte and 2-byte C++
370 // atomics but the LLVM build system check cannot
371 // detect this. Therefore it is set manually here.
372 // FreeBSD uses Clang as its system compiler and
373 // provides no libatomic in its base system so does
375 ldflags.exe.push(" -latomic");
376 ldflags.shared.push(" -latomic");
379 if target.contains("msvc") {
380 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
381 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
382 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
383 cfg.static_crt(true);
386 if target.starts_with("i686") {
387 cfg.define("LLVM_BUILD_32_BITS", "ON");
390 let mut enabled_llvm_projects = Vec::new();
392 if util::forcing_clang_based_tests() {
393 enabled_llvm_projects.push("clang");
394 enabled_llvm_projects.push("compiler-rt");
397 if builder.config.llvm_polly {
398 enabled_llvm_projects.push("polly");
401 if builder.config.llvm_clang {
402 enabled_llvm_projects.push("clang");
405 // We want libxml to be disabled.
406 // See https://github.com/rust-lang/rust/pull/50104
407 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
409 if !enabled_llvm_projects.is_empty() {
410 enabled_llvm_projects.sort();
411 enabled_llvm_projects.dedup();
412 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
415 if let Some(num_linkers) = builder.config.llvm_link_jobs {
417 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
421 // Workaround for ppc32 lld limitation
422 if target == "powerpc-unknown-freebsd" {
423 ldflags.exe.push(" -fuse-ld=bfd");
426 // https://llvm.org/docs/HowToCrossCompileLLVM.html
427 if target != builder.config.build {
428 builder.ensure(Llvm { target: builder.config.build });
429 // FIXME: if the llvm root for the build triple is overridden then we
430 // should use llvm-tblgen from there, also should verify that it
431 // actually exists most of the time in normal installs of LLVM.
432 let host_bin = builder.llvm_out(builder.config.build).join("bin");
433 cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
434 // LLVM_NM is required for cross compiling using MSVC
435 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
438 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
440 if builder.config.llvm_clang {
441 let build_bin = builder.llvm_out(builder.config.build).join("build").join("bin");
442 let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
443 if !builder.config.dry_run && !clang_tblgen.exists() {
444 panic!("unable to find {}", clang_tblgen.display());
446 cfg.define("CLANG_TABLEGEN", clang_tblgen);
450 let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
451 // Allow version-suffix="" to not define a version suffix at all.
452 if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
453 } else if builder.config.channel == "dev" {
454 // Changes to a version suffix require a complete rebuild of the LLVM.
455 // To avoid rebuilds during a time of version bump, don't include rustc
456 // release number on the dev channel.
457 Some("-rust-dev".to_string())
459 Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
461 if let Some(ref suffix) = llvm_version_suffix {
462 cfg.define("LLVM_VERSION_SUFFIX", suffix);
465 if let Some(ref linker) = builder.config.llvm_use_linker {
466 cfg.define("LLVM_USE_LINKER", linker);
469 if builder.config.llvm_allow_old_toolchain {
470 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
473 configure_cmake(builder, target, &mut cfg, true, ldflags);
475 for (key, val) in &builder.config.llvm_build_config {
476 cfg.define(key, val);
479 // FIXME: we don't actually need to build all LLVM tools and all LLVM
480 // libraries here, e.g., we just want a few components and a few
481 // tools. Figure out how to filter them down and only build the right
482 // tools and libs on all platforms.
484 if builder.config.dry_run {
485 return build_llvm_config;
490 // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
491 // libLLVM.dylib will be built. However, llvm-config will still look
492 // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
493 // link to make llvm-config happy.
494 if llvm_link_shared && target.contains("apple-darwin") {
495 let mut cmd = Command::new(&build_llvm_config);
496 let version = output(cmd.arg("--version"));
497 let major = version.split('.').next().unwrap();
498 let lib_name = match llvm_version_suffix {
499 Some(s) => format!("libLLVM-{}{}.dylib", major, s),
500 None => format!("libLLVM-{}.dylib", major),
503 let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
504 if !lib_llvm.exists() {
505 t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
515 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
516 if !builder.config.llvm_version_check {
520 if builder.config.dry_run {
524 let mut cmd = Command::new(llvm_config);
525 let version = output(cmd.arg("--version"));
526 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
527 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
532 panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
536 builder: &Builder<'_>,
537 target: TargetSelection,
538 cfg: &mut cmake::Config,
539 use_compiler_launcher: bool,
540 mut ldflags: LdFlags,
542 // Do not print installation messages for up-to-date files.
543 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
544 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
546 // Do not allow the user's value of DESTDIR to influence where
547 // LLVM will install itself. LLVM must always be installed in our
548 // own build directories.
549 cfg.env("DESTDIR", "");
552 cfg.generator("Ninja");
554 cfg.target(&target.triple).host(&builder.config.build.triple);
556 if target != builder.config.build {
557 cfg.define("CMAKE_CROSSCOMPILING", "True");
559 if target.contains("netbsd") {
560 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
561 } else if target.contains("freebsd") {
562 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
563 } else if target.contains("windows") {
564 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
565 } else if target.contains("haiku") {
566 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
567 } else if target.contains("solaris") || target.contains("illumos") {
568 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
570 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
571 // that case like CMake we cannot easily determine system version either.
573 // Since, the LLVM itself makes rather limited use of version checks in
574 // CMakeFiles (and then only in tests), and so far no issues have been
575 // reported, the system version is currently left unset.
577 if target.contains("darwin") {
578 // Make sure that CMake does not build universal binaries on macOS.
579 // Explicitly specifiy the one single target architecture.
580 if target.starts_with("aarch64") {
581 // macOS uses a different name for building arm64
582 cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
584 cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
589 let sanitize_cc = |cc: &Path| {
590 if target.contains("msvc") {
591 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
593 cc.as_os_str().to_owned()
597 // MSVC with CMake uses msbuild by default which doesn't respect these
598 // vars that we'd otherwise configure. In that case we just skip this
600 if target.contains("msvc") && !builder.ninja() {
604 let (cc, cxx) = match builder.config.llvm_clang_cl {
605 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
606 None => (builder.cc(target), builder.cxx(target).unwrap()),
609 // Handle msvc + ninja + ccache specially (this is what the bots use)
610 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
611 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
612 wrap_cc.set_file_name("sccache-plus-cl.exe");
614 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
615 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
616 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
617 .env("SCCACHE_TARGET", target.triple)
618 .env("SCCACHE_CC", &cc)
619 .env("SCCACHE_CXX", &cxx);
621 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
622 // off the beaten path here that I'm not really sure this is even half
623 // supported any more. Here we're trying to:
625 // * Build LLVM on MSVC
626 // * Build LLVM with `clang-cl` instead of `cl.exe`
627 // * Build a project with `sccache`
628 // * Build for 32-bit as well
629 // * Build with Ninja
631 // For `cl.exe` there are different binaries to compile 32/64 bit which
632 // we use but for `clang-cl` there's only one which internally
633 // multiplexes via flags. As a result it appears that CMake's detection
634 // of a compiler's architecture and such on MSVC **doesn't** pass any
635 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
636 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
637 // definitely causes problems since all the env vars are pointing to
640 // To hack around this... again... we pass an argument that's
641 // unconditionally passed in the sccache shim. This'll get CMake to
642 // correctly diagnose it's doing a 32-bit compilation and LLVM will
643 // internally configure itself appropriately.
644 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
645 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
648 // If ccache is configured we inform the build a little differently how
649 // to invoke ccache while also invoking our compilers.
650 if use_compiler_launcher {
651 if let Some(ref ccache) = builder.config.ccache {
652 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
653 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
656 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
657 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
658 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
661 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
662 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
663 if let Some(ref s) = builder.config.llvm_cflags {
667 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
668 if target.contains("apple-ios") {
669 if target.contains("86-") {
670 cflags.push(" -miphonesimulator-version-min=10.0");
672 cflags.push(" -miphoneos-version-min=10.0");
675 if builder.config.llvm_clang_cl.is_some() {
676 cflags.push(&format!(" --target={}", target));
678 cfg.define("CMAKE_C_FLAGS", cflags);
679 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
680 if let Some(ref s) = builder.config.llvm_cxxflags {
684 if builder.config.llvm_clang_cl.is_some() {
685 cxxflags.push(&format!(" --target={}", target));
687 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
688 if let Some(ar) = builder.ar(target) {
689 if ar.is_absolute() {
690 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
691 // tries to resolve this path in the LLVM build directory.
692 cfg.define("CMAKE_AR", sanitize_cc(ar));
696 if let Some(ranlib) = builder.ranlib(target) {
697 if ranlib.is_absolute() {
698 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
699 // tries to resolve this path in the LLVM build directory.
700 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
704 if let Some(ref flags) = builder.config.llvm_ldflags {
705 ldflags.push_all(flags);
708 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
709 ldflags.push_all(&flags);
712 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
713 // We also do this if the user explicitly requested static libstdc++.
714 if builder.config.llvm_static_stdcpp {
715 if !target.contains("msvc") && !target.contains("netbsd") && !target.contains("solaris") {
716 if target.contains("apple") || target.contains("windows") {
717 ldflags.push_all("-static-libstdc++");
719 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
724 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
725 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
726 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
728 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
729 cfg.env("RUSTC_LOG", "sccache=warn");
733 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
734 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
735 let kind = if host == target { "HOST" } else { "TARGET" };
736 let target_u = target.replace("-", "_");
737 env::var_os(&format!("{}_{}", var_base, target))
738 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
739 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
740 .or_else(|| env::var_os(var_base))
743 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
745 pub target: TargetSelection,
749 type Output = PathBuf;
750 const ONLY_HOSTS: bool = true;
752 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
753 run.path("src/llvm-project/lld")
756 fn make_run(run: RunConfig<'_>) {
757 run.builder.ensure(Lld { target: run.target });
760 /// Compile LLD for `target`.
761 fn run(self, builder: &Builder<'_>) -> PathBuf {
762 if builder.config.dry_run {
763 return PathBuf::from("lld-out-dir-test-gen");
765 let target = self.target;
767 let llvm_config = builder.ensure(Llvm { target: self.target });
769 let out_dir = builder.lld_out(target);
770 let done_stamp = out_dir.join("lld-finished-building");
771 if done_stamp.exists() {
775 builder.info(&format!("Building LLD for {}", target));
776 let _time = util::timeit(&builder);
777 t!(fs::create_dir_all(&out_dir));
779 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
780 let mut ldflags = LdFlags::default();
782 // When building LLD as part of a build with instrumentation on windows, for example
783 // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
784 // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
785 // linking errors, much like LLVM's cmake setup does in that situation.
786 if builder.config.llvm_profile_generate && target.contains("msvc") {
787 if let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref() {
788 // Find clang's runtime library directory and push that as a search path to the
789 // cmake linker flags.
790 let clang_rt_dir = get_clang_cl_resource_dir(clang_cl_path);
791 ldflags.push_all(&format!("/libpath:{}", clang_rt_dir.display()));
795 configure_cmake(builder, target, &mut cfg, true, ldflags);
797 // This is an awful, awful hack. Discovered when we migrated to using
798 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
799 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
800 // that directory for later processing. Unfortunately if this path has
801 // forward slashes in it (which it basically always does on Windows)
802 // then CMake will hit a syntax error later on as... something isn't
805 // Instead of attempting to fix this problem in upstream CMake and/or
806 // LLVM/LLD we just hack around it here. This thin wrapper will take the
807 // output from llvm-config and replace all instances of `\` with `/` to
808 // ensure we don't hit the same bugs with escaping. It means that you
809 // can't build on a system where your paths require `\` on Windows, but
810 // there's probably a lot of reasons you can't do that other than this.
811 let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
813 // Re-use the same flags as llvm to control the level of debug information
814 // generated for lld.
815 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
816 (false, _) => "Debug",
817 (true, false) => "Release",
818 (true, true) => "RelWithDebInfo",
821 cfg.out_dir(&out_dir)
823 .env("LLVM_CONFIG_REAL", &llvm_config)
824 .define("LLVM_CONFIG_PATH", llvm_config_shim)
825 .define("LLVM_INCLUDE_TESTS", "OFF");
827 if builder.config.llvm_allow_old_toolchain {
828 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
831 // While we're using this horrible workaround to shim the execution of
832 // llvm-config, let's just pile on more. I can't seem to figure out how
833 // to build LLD as a standalone project and also cross-compile it at the
834 // same time. It wants a natively executable `llvm-config` to learn
835 // about LLVM, but then it learns about all the host configuration of
836 // LLVM and tries to link to host LLVM libraries.
838 // To work around that we tell our shim to replace anything with the
839 // build target with the actual target instead. This'll break parts of
840 // LLD though which try to execute host tools, such as llvm-tblgen, so
841 // we specifically tell it where to find those. This is likely super
842 // brittle and will break over time. If anyone knows better how to
843 // cross-compile LLD it would be much appreciated to fix this!
844 if target != builder.config.build {
845 cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
846 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
849 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
853 // Explicitly set C++ standard, because upstream doesn't do so
854 // for standalone builds.
855 cfg.define("CMAKE_CXX_STANDARD", "14");
859 t!(File::create(&done_stamp));
864 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
865 pub struct TestHelpers {
866 pub target: TargetSelection,
869 impl Step for TestHelpers {
872 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
873 run.path("src/test/auxiliary/rust_test_helpers.c")
876 fn make_run(run: RunConfig<'_>) {
877 run.builder.ensure(TestHelpers { target: run.target })
880 /// Compiles the `rust_test_helpers.c` library which we used in various
881 /// `run-pass` tests for ABI testing.
882 fn run(self, builder: &Builder<'_>) {
883 if builder.config.dry_run {
886 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
887 // toolchain. However, some x86_64 ELF objects can be linked
888 // without issues. Use this hack to compile the test helpers.
889 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
890 TargetSelection::from_user("x86_64-unknown-linux-gnu")
894 let dst = builder.test_helpers_out(target);
895 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
896 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
900 builder.info("Building test helpers");
901 t!(fs::create_dir_all(&dst));
902 let mut cfg = cc::Build::new();
903 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
904 if target.contains("emscripten") {
908 // We may have found various cross-compilers a little differently due to our
909 // extra configuration, so inform cc of these compilers. Note, though, that
910 // on MSVC we still need cc's detection of env vars (ugh).
911 if !target.contains("msvc") {
912 if let Some(ar) = builder.ar(target) {
915 cfg.compiler(builder.cc(target));
917 cfg.cargo_metadata(false)
919 .target(&target.triple)
920 .host(&builder.config.build.triple)
924 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
925 .compile("rust_test_helpers");
929 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
930 pub struct Sanitizers {
931 pub target: TargetSelection,
934 impl Step for Sanitizers {
935 type Output = Vec<SanitizerRuntime>;
937 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
938 run.alias("sanitizers")
941 fn make_run(run: RunConfig<'_>) {
942 run.builder.ensure(Sanitizers { target: run.target });
945 /// Builds sanitizer runtime libraries.
946 fn run(self, builder: &Builder<'_>) -> Self::Output {
947 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
948 if !compiler_rt_dir.exists() {
952 let out_dir = builder.native_dir(self.target).join("sanitizers");
953 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
954 if runtimes.is_empty() {
958 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
959 if builder.config.dry_run {
963 let stamp = out_dir.join("sanitizers-finished-building");
964 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
967 if stamp.hash.is_none() {
968 builder.info(&format!(
969 "Rebuild sanitizers by removing the file `{}`",
976 builder.info(&format!("Building sanitizers for {}", self.target));
978 let _time = util::timeit(&builder);
980 let mut cfg = cmake::Config::new(&compiler_rt_dir);
981 cfg.profile("Release");
982 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
983 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
984 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
985 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
986 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
987 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
988 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
989 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
990 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
991 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
993 // On Darwin targets the sanitizer runtimes are build as universal binaries.
994 // Unfortunately sccache currently lacks support to build them successfully.
995 // Disable compiler launcher on Darwin targets to avoid potential issues.
996 let use_compiler_launcher = !self.target.contains("apple-darwin");
997 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
999 t!(fs::create_dir_all(&out_dir));
1000 cfg.out_dir(out_dir);
1002 for runtime in &runtimes {
1003 cfg.build_target(&runtime.cmake_target);
1012 #[derive(Clone, Debug)]
1013 pub struct SanitizerRuntime {
1014 /// CMake target used to build the runtime.
1015 pub cmake_target: String,
1016 /// Path to the built runtime library.
1018 /// Library filename that will be used rustc.
1022 /// Returns sanitizers available on a given target.
1023 fn supported_sanitizers(
1025 target: TargetSelection,
1027 ) -> Vec<SanitizerRuntime> {
1028 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1031 .map(move |c| SanitizerRuntime {
1032 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
1034 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
1035 name: format!("librustc-{}_rt.{}.dylib", channel, c),
1040 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1043 .map(move |c| SanitizerRuntime {
1044 cmake_target: format!("clang_rt.{}-{}", c, arch),
1045 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
1046 name: format!("librustc-{}_rt.{}.a", channel, c),
1051 match &*target.triple {
1052 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1053 "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1054 "aarch64-unknown-linux-gnu" => {
1055 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1057 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1058 "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1059 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1060 "x86_64-unknown-netbsd" => {
1061 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1063 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1064 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1065 "x86_64-unknown-linux-gnu" => {
1066 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1068 "x86_64-unknown-linux-musl" => {
1069 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1077 hash: Option<Vec<u8>>,
1081 fn new(path: PathBuf, hash: Option<&str>) -> Self {
1082 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1085 fn is_done(&self) -> bool {
1086 match fs::read(&self.path) {
1087 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1088 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1090 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1095 fn remove(&self) -> io::Result<()> {
1096 match fs::remove_file(&self.path) {
1099 if e.kind() == io::ErrorKind::NotFound {
1108 fn write(&self) -> io::Result<()> {
1109 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1113 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1114 pub struct CrtBeginEnd {
1115 pub target: TargetSelection,
1118 impl Step for CrtBeginEnd {
1119 type Output = PathBuf;
1121 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1122 run.path("src/llvm-project/compiler-rt/lib/crt")
1125 fn make_run(run: RunConfig<'_>) {
1126 run.builder.ensure(CrtBeginEnd { target: run.target });
1129 /// Build crtbegin.o/crtend.o for musl target.
1130 fn run(self, builder: &Builder<'_>) -> Self::Output {
1131 let out_dir = builder.native_dir(self.target).join("crt");
1133 if builder.config.dry_run {
1137 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1138 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1139 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1140 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1145 builder.info("Building crtbegin.o and crtend.o");
1146 t!(fs::create_dir_all(&out_dir));
1148 let mut cfg = cc::Build::new();
1150 if let Some(ar) = builder.ar(self.target) {
1153 cfg.compiler(builder.cc(self.target));
1154 cfg.cargo_metadata(false)
1156 .target(&self.target.triple)
1157 .host(&builder.config.build.triple)
1164 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1165 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1166 // instead of .ctors/.dtors
1167 cfg.flag("-std=c11")
1168 .define("CRT_HAS_INITFINI_ARRAY", None)
1169 .define("EH_USE_FRAME_REGISTRY", None);
1173 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1174 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1179 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1180 pub struct Libunwind {
1181 pub target: TargetSelection,
1184 impl Step for Libunwind {
1185 type Output = PathBuf;
1187 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1188 run.path("src/llvm-project/libunwind")
1191 fn make_run(run: RunConfig<'_>) {
1192 run.builder.ensure(Libunwind { target: run.target });
1195 /// Build linunwind.a
1196 fn run(self, builder: &Builder<'_>) -> Self::Output {
1197 if builder.config.dry_run {
1198 return PathBuf::new();
1201 let out_dir = builder.native_dir(self.target).join("libunwind");
1202 let root = builder.src.join("src/llvm-project/libunwind");
1204 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1208 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1209 t!(fs::create_dir_all(&out_dir));
1211 let mut cc_cfg = cc::Build::new();
1212 let mut cpp_cfg = cc::Build::new();
1215 cpp_cfg.cpp_set_stdlib(None);
1216 cpp_cfg.flag("-nostdinc++");
1217 cpp_cfg.flag("-fno-exceptions");
1218 cpp_cfg.flag("-fno-rtti");
1219 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1221 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1222 if let Some(ar) = builder.ar(self.target) {
1225 cfg.target(&self.target.triple);
1226 cfg.host(&builder.config.build.triple);
1227 cfg.warnings(false);
1229 // get_compiler() need set opt_level first.
1231 cfg.flag("-fstrict-aliasing");
1232 cfg.flag("-funwind-tables");
1233 cfg.flag("-fvisibility=hidden");
1234 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1235 cfg.include(root.join("include"));
1236 cfg.cargo_metadata(false);
1237 cfg.out_dir(&out_dir);
1239 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1240 cfg.static_flag(true);
1241 cfg.flag("-fno-stack-protector");
1242 cfg.flag("-ffreestanding");
1243 cfg.flag("-fexceptions");
1245 // easiest way to undefine since no API available in cc::Build to undefine
1246 cfg.flag("-U_FORTIFY_SOURCE");
1247 cfg.define("_FORTIFY_SOURCE", "0");
1248 cfg.define("RUST_SGX", "1");
1249 cfg.define("__NO_STRING_INLINES", None);
1250 cfg.define("__NO_MATH_INLINES", None);
1251 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1252 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1253 cfg.define("NDEBUG", None);
1255 if self.target.contains("windows") {
1256 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1257 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1261 cc_cfg.compiler(builder.cc(self.target));
1262 if let Ok(cxx) = builder.cxx(self.target) {
1263 cpp_cfg.compiler(cxx);
1265 cc_cfg.compiler(builder.cc(self.target));
1268 // Don't set this for clang
1269 // By default, Clang builds C code in GNU C17 mode.
1270 // By default, Clang builds C++ code according to the C++98 standard,
1271 // with many C++11 features accepted as extensions.
1272 if cc_cfg.get_compiler().is_like_gnu() {
1273 cc_cfg.flag("-std=c99");
1275 if cpp_cfg.get_compiler().is_like_gnu() {
1276 cpp_cfg.flag("-std=c++11");
1279 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1280 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1281 // C++ compiler env variables on the builders.
1282 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1283 if cpp_cfg.get_compiler().is_like_gnu() {
1285 cpp_cfg.compiler(builder.cc(self.target));
1289 let mut c_sources = vec![
1291 "UnwindLevel1-gcc-ext.c",
1293 "UnwindRegistersRestore.S",
1294 "UnwindRegistersSave.S",
1297 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1298 let cpp_len = cpp_sources.len();
1300 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1301 c_sources.push("UnwindRustSgx.c");
1304 for src in c_sources {
1305 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1308 for src in &cpp_sources {
1309 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1312 cpp_cfg.compile("unwind-cpp");
1314 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1316 for entry in fs::read_dir(&out_dir).unwrap() {
1317 let file = entry.unwrap().path().canonicalize().unwrap();
1318 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1319 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1320 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1321 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1322 cc_cfg.object(&file);
1327 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1329 cc_cfg.compile("unwind");