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 build_helper::{output, t};
21 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
22 use crate::config::TargetSelection;
23 use crate::util::{self, exe};
24 use crate::{CLang, GitRepo};
25 use build_helper::up_to_date;
29 build_llvm_config: PathBuf,
34 // Linker flags to pass to LLVM's CMake invocation.
35 #[derive(Debug, Clone, Default)]
37 // CMAKE_EXE_LINKER_FLAGS
39 // CMAKE_SHARED_LINKER_FLAGS
41 // CMAKE_MODULE_LINKER_FLAGS
46 fn push_all(&mut self, s: impl AsRef<OsStr>) {
50 self.shared.push(" ");
52 self.module.push(" ");
57 // This returns whether we've already previously built LLVM.
59 // It's used to avoid busting caches during x.py check -- if we've already built
60 // LLVM, it's fine for us to not try to avoid doing so.
62 // This will return the llvm-config if it can get it (but it will not build it
64 pub fn prebuilt_llvm_config(
65 builder: &Builder<'_>,
66 target: TargetSelection,
67 ) -> Result<PathBuf, Meta> {
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 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
119 pub target: TargetSelection,
123 type Output = PathBuf; // path to llvm-config
125 const ONLY_HOSTS: bool = true;
127 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
128 run.path("src/llvm-project").path("src/llvm-project/llvm").path("src/llvm")
131 fn make_run(run: RunConfig<'_>) {
132 run.builder.ensure(Llvm { target: run.target });
135 /// Compile LLVM for `target`.
136 fn run(self, builder: &Builder<'_>) -> PathBuf {
137 let target = self.target;
138 let target_native = if self.target.starts_with("riscv") {
139 // RISC-V target triples in Rust is not named the same as C compiler target triples.
140 // This converts Rust RISC-V target triples to C compiler triples.
141 let idx = target.triple.find('-').unwrap();
143 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
144 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
145 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
146 // Set the version suffix to 13.0 so the correct target details are used.
147 format!("{}{}", self.target, "13.0")
152 let Meta { stamp, build_llvm_config, out_dir, root } =
153 match prebuilt_llvm_config(builder, target) {
158 builder.update_submodule(&Path::new("src").join("llvm-project"));
159 if builder.config.llvm_link_shared
160 && (target.contains("windows") || target.contains("apple-darwin"))
162 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
165 builder.info(&format!("Building LLVM for {}", target));
167 let _time = util::timeit(&builder);
168 t!(fs::create_dir_all(&out_dir));
170 // https://llvm.org/docs/CMake.html
171 let mut cfg = cmake::Config::new(builder.src.join(root));
172 let mut ldflags = LdFlags::default();
174 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
175 (false, _) => "Debug",
176 (true, false) => "Release",
177 (true, true) => "RelWithDebInfo",
180 // NOTE: remember to also update `config.toml.example` when changing the
182 let llvm_targets = match &builder.config.llvm_targets {
185 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
186 Sparc;SystemZ;WebAssembly;X86"
190 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
195 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
196 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
197 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
199 cfg.out_dir(&out_dir)
201 .define("LLVM_ENABLE_ASSERTIONS", assertions)
202 .define("LLVM_ENABLE_PLUGINS", plugins)
203 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
204 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
205 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
206 .define("LLVM_INCLUDE_DOCS", "OFF")
207 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
208 .define("LLVM_INCLUDE_TESTS", enable_tests)
209 .define("LLVM_ENABLE_TERMINFO", "OFF")
210 .define("LLVM_ENABLE_LIBEDIT", "OFF")
211 .define("LLVM_ENABLE_BINDINGS", "OFF")
212 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
213 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
214 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
215 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
217 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
218 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
219 // This flag makes sure `FileCheck` is copied in the final binaries directory.
220 cfg.define("LLVM_INSTALL_UTILS", "ON");
222 if builder.config.llvm_profile_generate {
223 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
224 cfg.define("LLVM_BUILD_RUNTIME", "No");
226 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
227 cfg.define("LLVM_PROFDATA_FILE", &path);
230 if target != "aarch64-apple-darwin" && !target.contains("windows") {
231 cfg.define("LLVM_ENABLE_ZLIB", "ON");
233 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
236 // Are we compiling for iOS/tvOS?
237 if target.contains("apple-ios") || target.contains("apple-tvos") {
238 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
239 cfg.define("CMAKE_OSX_SYSROOT", "/");
240 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
241 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
242 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
243 // Zlib fails to link properly, leading to a compiler error.
244 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
247 if builder.config.llvm_thin_lto {
248 cfg.define("LLVM_ENABLE_LTO", "Thin");
249 if !target.contains("apple") {
250 cfg.define("LLVM_ENABLE_LLD", "ON");
254 // This setting makes the LLVM tools link to the dynamic LLVM library,
255 // which saves both memory during parallel links and overall disk space
256 // for the tools. We don't do this on every platform as it doesn't work
257 // equally well everywhere.
259 // If we're not linking rustc to a dynamic LLVM, though, then don't link
261 if builder.llvm_link_tools_dynamically(target) && builder.config.llvm_link_shared {
262 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
265 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
266 // We also do this if the user explicitly requested static libstdc++.
267 if builder.config.llvm_tools_enabled || builder.config.llvm_static_stdcpp {
268 if !target.contains("msvc") && !target.contains("netbsd") {
269 if target.contains("apple") {
270 ldflags.push_all("-static-libstdc++");
272 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
277 if target.starts_with("riscv") && !target.contains("freebsd") {
278 // RISC-V GCC erroneously requires linking against
279 // `libatomic` when using 1-byte and 2-byte C++
280 // atomics but the LLVM build system check cannot
281 // detect this. Therefore it is set manually here.
282 // FreeBSD uses Clang as its system compiler and
283 // provides no libatomic in its base system so does
285 ldflags.exe.push(" -latomic");
286 ldflags.shared.push(" -latomic");
289 if target.contains("msvc") {
290 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
291 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
292 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
293 cfg.static_crt(true);
296 if target.starts_with("i686") {
297 cfg.define("LLVM_BUILD_32_BITS", "ON");
300 let mut enabled_llvm_projects = Vec::new();
302 if util::forcing_clang_based_tests() {
303 enabled_llvm_projects.push("clang");
304 enabled_llvm_projects.push("compiler-rt");
307 if builder.config.llvm_polly {
308 enabled_llvm_projects.push("polly");
311 if builder.config.llvm_clang {
312 enabled_llvm_projects.push("clang");
315 // We want libxml to be disabled.
316 // See https://github.com/rust-lang/rust/pull/50104
317 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
319 if !enabled_llvm_projects.is_empty() {
320 enabled_llvm_projects.sort();
321 enabled_llvm_projects.dedup();
322 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
325 if let Some(num_linkers) = builder.config.llvm_link_jobs {
327 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
331 // Workaround for ppc32 lld limitation
332 if target == "powerpc-unknown-freebsd" {
333 ldflags.exe.push(" -fuse-ld=bfd");
336 // https://llvm.org/docs/HowToCrossCompileLLVM.html
337 if target != builder.config.build {
338 builder.ensure(Llvm { target: builder.config.build });
339 // FIXME: if the llvm root for the build triple is overridden then we
340 // should use llvm-tblgen from there, also should verify that it
341 // actually exists most of the time in normal installs of LLVM.
342 let host_bin = builder.llvm_out(builder.config.build).join("bin");
343 cfg.define("CMAKE_CROSSCOMPILING", "True");
344 cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
345 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
348 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
352 if let Some(ref suffix) = builder.config.llvm_version_suffix {
353 // Allow version-suffix="" to not define a version suffix at all.
354 if !suffix.is_empty() {
355 cfg.define("LLVM_VERSION_SUFFIX", suffix);
357 } else if builder.config.channel == "dev" {
358 // Changes to a version suffix require a complete rebuild of the LLVM.
359 // To avoid rebuilds during a time of version bump, don't include rustc
360 // release number on the dev channel.
361 cfg.define("LLVM_VERSION_SUFFIX", "-rust-dev");
363 let suffix = format!("-rust-{}-{}", builder.version, builder.config.channel);
364 cfg.define("LLVM_VERSION_SUFFIX", suffix);
367 if let Some(ref linker) = builder.config.llvm_use_linker {
368 cfg.define("LLVM_USE_LINKER", linker);
371 if builder.config.llvm_allow_old_toolchain {
372 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
375 configure_cmake(builder, target, &mut cfg, true, ldflags);
377 for (key, val) in &builder.config.llvm_build_config {
378 cfg.define(key, val);
381 // FIXME: we don't actually need to build all LLVM tools and all LLVM
382 // libraries here, e.g., we just want a few components and a few
383 // tools. Figure out how to filter them down and only build the right
384 // tools and libs on all platforms.
386 if builder.config.dry_run {
387 return build_llvm_config;
398 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
399 if !builder.config.llvm_version_check {
403 if builder.config.dry_run {
407 let mut cmd = Command::new(llvm_config);
408 let version = output(cmd.arg("--version"));
409 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
410 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
415 panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
419 builder: &Builder<'_>,
420 target: TargetSelection,
421 cfg: &mut cmake::Config,
422 use_compiler_launcher: bool,
423 mut ldflags: LdFlags,
425 // Do not print installation messages for up-to-date files.
426 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
427 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
429 // Do not allow the user's value of DESTDIR to influence where
430 // LLVM will install itself. LLVM must always be installed in our
431 // own build directories.
432 cfg.env("DESTDIR", "");
435 cfg.generator("Ninja");
437 cfg.target(&target.triple).host(&builder.config.build.triple);
439 if target != builder.config.build {
440 if target.contains("netbsd") {
441 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
442 } else if target.contains("freebsd") {
443 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
444 } else if target.contains("windows") {
445 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
446 } else if target.contains("haiku") {
447 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
448 } else if target.contains("solaris") || target.contains("illumos") {
449 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
451 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
452 // that case like CMake we cannot easily determine system version either.
454 // Since, the LLVM itself makes rather limited use of version checks in
455 // CMakeFiles (and then only in tests), and so far no issues have been
456 // reported, the system version is currently left unset.
459 let sanitize_cc = |cc: &Path| {
460 if target.contains("msvc") {
461 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
463 cc.as_os_str().to_owned()
467 // MSVC with CMake uses msbuild by default which doesn't respect these
468 // vars that we'd otherwise configure. In that case we just skip this
470 if target.contains("msvc") && !builder.ninja() {
474 let (cc, cxx) = match builder.config.llvm_clang_cl {
475 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
476 None => (builder.cc(target), builder.cxx(target).unwrap()),
479 // Handle msvc + ninja + ccache specially (this is what the bots use)
480 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
481 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
482 wrap_cc.set_file_name("sccache-plus-cl.exe");
484 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
485 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
486 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
487 .env("SCCACHE_TARGET", target.triple)
488 .env("SCCACHE_CC", &cc)
489 .env("SCCACHE_CXX", &cxx);
491 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
492 // off the beaten path here that I'm not really sure this is even half
493 // supported any more. Here we're trying to:
495 // * Build LLVM on MSVC
496 // * Build LLVM with `clang-cl` instead of `cl.exe`
497 // * Build a project with `sccache`
498 // * Build for 32-bit as well
499 // * Build with Ninja
501 // For `cl.exe` there are different binaries to compile 32/64 bit which
502 // we use but for `clang-cl` there's only one which internally
503 // multiplexes via flags. As a result it appears that CMake's detection
504 // of a compiler's architecture and such on MSVC **doesn't** pass any
505 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
506 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
507 // definitely causes problems since all the env vars are pointing to
510 // To hack around this... again... we pass an argument that's
511 // unconditionally passed in the sccache shim. This'll get CMake to
512 // correctly diagnose it's doing a 32-bit compilation and LLVM will
513 // internally configure itself appropriately.
514 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
515 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
518 // If ccache is configured we inform the build a little differently how
519 // to invoke ccache while also invoking our compilers.
520 if use_compiler_launcher {
521 if let Some(ref ccache) = builder.config.ccache {
522 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
523 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
526 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
527 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
528 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
531 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
532 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
533 if let Some(ref s) = builder.config.llvm_cflags {
537 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
538 if target.contains("apple-ios") {
539 if target.contains("86-") {
540 cflags.push(" -miphonesimulator-version-min=10.0");
542 cflags.push(" -miphoneos-version-min=10.0");
545 if builder.config.llvm_clang_cl.is_some() {
546 cflags.push(&format!(" --target={}", target));
548 cfg.define("CMAKE_C_FLAGS", cflags);
549 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
550 if let Some(ref s) = builder.config.llvm_cxxflags {
554 if builder.config.llvm_clang_cl.is_some() {
555 cxxflags.push(&format!(" --target={}", target));
557 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
558 if let Some(ar) = builder.ar(target) {
559 if ar.is_absolute() {
560 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
561 // tries to resolve this path in the LLVM build directory.
562 cfg.define("CMAKE_AR", sanitize_cc(ar));
566 if let Some(ranlib) = builder.ranlib(target) {
567 if ranlib.is_absolute() {
568 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
569 // tries to resolve this path in the LLVM build directory.
570 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
574 if let Some(ref flags) = builder.config.llvm_ldflags {
575 ldflags.push_all(flags);
578 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
579 ldflags.push_all(&flags);
582 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
583 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
584 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
586 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
587 cfg.env("RUSTC_LOG", "sccache=warn");
591 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
592 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
593 let kind = if host == target { "HOST" } else { "TARGET" };
594 let target_u = target.replace("-", "_");
595 env::var_os(&format!("{}_{}", var_base, target))
596 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
597 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
598 .or_else(|| env::var_os(var_base))
601 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
603 pub target: TargetSelection,
607 type Output = PathBuf;
608 const ONLY_HOSTS: bool = true;
610 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
611 run.path("src/llvm-project/lld").path("src/tools/lld")
614 fn make_run(run: RunConfig<'_>) {
615 run.builder.ensure(Lld { target: run.target });
618 /// Compile LLD for `target`.
619 fn run(self, builder: &Builder<'_>) -> PathBuf {
620 if builder.config.dry_run {
621 return PathBuf::from("lld-out-dir-test-gen");
623 let target = self.target;
625 let llvm_config = builder.ensure(Llvm { target: self.target });
627 let out_dir = builder.lld_out(target);
628 let done_stamp = out_dir.join("lld-finished-building");
629 if done_stamp.exists() {
633 builder.info(&format!("Building LLD for {}", target));
634 let _time = util::timeit(&builder);
635 t!(fs::create_dir_all(&out_dir));
637 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
638 configure_cmake(builder, target, &mut cfg, true, LdFlags::default());
640 // This is an awful, awful hack. Discovered when we migrated to using
641 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
642 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
643 // that directory for later processing. Unfortunately if this path has
644 // forward slashes in it (which it basically always does on Windows)
645 // then CMake will hit a syntax error later on as... something isn't
648 // Instead of attempting to fix this problem in upstream CMake and/or
649 // LLVM/LLD we just hack around it here. This thin wrapper will take the
650 // output from llvm-config and replace all instances of `\` with `/` to
651 // ensure we don't hit the same bugs with escaping. It means that you
652 // can't build on a system where your paths require `\` on Windows, but
653 // there's probably a lot of reasons you can't do that other than this.
654 let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
656 cfg.out_dir(&out_dir)
658 .env("LLVM_CONFIG_REAL", &llvm_config)
659 .define("LLVM_CONFIG_PATH", llvm_config_shim)
660 .define("LLVM_INCLUDE_TESTS", "OFF");
662 // While we're using this horrible workaround to shim the execution of
663 // llvm-config, let's just pile on more. I can't seem to figure out how
664 // to build LLD as a standalone project and also cross-compile it at the
665 // same time. It wants a natively executable `llvm-config` to learn
666 // about LLVM, but then it learns about all the host configuration of
667 // LLVM and tries to link to host LLVM libraries.
669 // To work around that we tell our shim to replace anything with the
670 // build target with the actual target instead. This'll break parts of
671 // LLD though which try to execute host tools, such as llvm-tblgen, so
672 // we specifically tell it where to find those. This is likely super
673 // brittle and will break over time. If anyone knows better how to
674 // cross-compile LLD it would be much appreciated to fix this!
675 if target != builder.config.build {
676 cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
677 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
680 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
684 // Explicitly set C++ standard, because upstream doesn't do so
685 // for standalone builds.
686 cfg.define("CMAKE_CXX_STANDARD", "14");
690 t!(File::create(&done_stamp));
695 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
696 pub struct TestHelpers {
697 pub target: TargetSelection,
700 impl Step for TestHelpers {
703 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
704 run.path("src/test/auxiliary/rust_test_helpers.c")
707 fn make_run(run: RunConfig<'_>) {
708 run.builder.ensure(TestHelpers { target: run.target })
711 /// Compiles the `rust_test_helpers.c` library which we used in various
712 /// `run-pass` tests for ABI testing.
713 fn run(self, builder: &Builder<'_>) {
714 if builder.config.dry_run {
717 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
718 // toolchain. However, some x86_64 ELF objects can be linked
719 // without issues. Use this hack to compile the test helpers.
720 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
721 TargetSelection::from_user("x86_64-unknown-linux-gnu")
725 let dst = builder.test_helpers_out(target);
726 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
727 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
731 builder.info("Building test helpers");
732 t!(fs::create_dir_all(&dst));
733 let mut cfg = cc::Build::new();
734 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
735 if target.contains("emscripten") {
739 // We may have found various cross-compilers a little differently due to our
740 // extra configuration, so inform cc of these compilers. Note, though, that
741 // on MSVC we still need cc's detection of env vars (ugh).
742 if !target.contains("msvc") {
743 if let Some(ar) = builder.ar(target) {
746 cfg.compiler(builder.cc(target));
748 cfg.cargo_metadata(false)
750 .target(&target.triple)
751 .host(&builder.config.build.triple)
755 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
756 .compile("rust_test_helpers");
760 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
761 pub struct Sanitizers {
762 pub target: TargetSelection,
765 impl Step for Sanitizers {
766 type Output = Vec<SanitizerRuntime>;
768 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
769 run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
772 fn make_run(run: RunConfig<'_>) {
773 run.builder.ensure(Sanitizers { target: run.target });
776 /// Builds sanitizer runtime libraries.
777 fn run(self, builder: &Builder<'_>) -> Self::Output {
778 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
779 if !compiler_rt_dir.exists() {
783 let out_dir = builder.native_dir(self.target).join("sanitizers");
784 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
785 if runtimes.is_empty() {
789 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
790 if builder.config.dry_run {
794 let stamp = out_dir.join("sanitizers-finished-building");
795 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
798 if stamp.hash.is_none() {
799 builder.info(&format!(
800 "Rebuild sanitizers by removing the file `{}`",
807 builder.info(&format!("Building sanitizers for {}", self.target));
809 let _time = util::timeit(&builder);
811 let mut cfg = cmake::Config::new(&compiler_rt_dir);
812 cfg.profile("Release");
813 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
814 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
815 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
816 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
817 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
818 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
819 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
820 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
821 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
822 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
824 // On Darwin targets the sanitizer runtimes are build as universal binaries.
825 // Unfortunately sccache currently lacks support to build them successfully.
826 // Disable compiler launcher on Darwin targets to avoid potential issues.
827 let use_compiler_launcher = !self.target.contains("apple-darwin");
828 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
830 t!(fs::create_dir_all(&out_dir));
831 cfg.out_dir(out_dir);
833 for runtime in &runtimes {
834 cfg.build_target(&runtime.cmake_target);
843 #[derive(Clone, Debug)]
844 pub struct SanitizerRuntime {
845 /// CMake target used to build the runtime.
846 pub cmake_target: String,
847 /// Path to the built runtime library.
849 /// Library filename that will be used rustc.
853 /// Returns sanitizers available on a given target.
854 fn supported_sanitizers(
856 target: TargetSelection,
858 ) -> Vec<SanitizerRuntime> {
859 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
862 .map(move |c| SanitizerRuntime {
863 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
865 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
866 name: format!("librustc-{}_rt.{}.dylib", channel, c),
871 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
874 .map(move |c| SanitizerRuntime {
875 cmake_target: format!("clang_rt.{}-{}", c, arch),
876 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
877 name: format!("librustc-{}_rt.{}.a", channel, c),
882 match &*target.triple {
883 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
884 "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
885 "aarch64-unknown-linux-gnu" => {
886 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
888 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
889 "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
890 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
891 "x86_64-unknown-netbsd" => {
892 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
894 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
895 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
896 "x86_64-unknown-linux-gnu" => {
897 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
899 "x86_64-unknown-linux-musl" => {
900 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
908 hash: Option<Vec<u8>>,
912 fn new(path: PathBuf, hash: Option<&str>) -> Self {
913 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
916 fn is_done(&self) -> bool {
917 match fs::read(&self.path) {
918 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
919 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
921 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
926 fn remove(&self) -> io::Result<()> {
927 match fs::remove_file(&self.path) {
930 if e.kind() == io::ErrorKind::NotFound {
939 fn write(&self) -> io::Result<()> {
940 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
944 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
945 pub struct CrtBeginEnd {
946 pub target: TargetSelection,
949 impl Step for CrtBeginEnd {
950 type Output = PathBuf;
952 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
953 run.path("src/llvm-project/compiler-rt/lib/crt")
956 fn make_run(run: RunConfig<'_>) {
957 run.builder.ensure(CrtBeginEnd { target: run.target });
960 /// Build crtbegin.o/crtend.o for musl target.
961 fn run(self, builder: &Builder<'_>) -> Self::Output {
962 let out_dir = builder.native_dir(self.target).join("crt");
964 if builder.config.dry_run {
968 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
969 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
970 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
971 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
976 builder.info("Building crtbegin.o and crtend.o");
977 t!(fs::create_dir_all(&out_dir));
979 let mut cfg = cc::Build::new();
981 if let Some(ar) = builder.ar(self.target) {
984 cfg.compiler(builder.cc(self.target));
985 cfg.cargo_metadata(false)
987 .target(&self.target.triple)
988 .host(&builder.config.build.triple)
995 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
996 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
997 // instead of .ctors/.dtors
999 .define("CRT_HAS_INITFINI_ARRAY", None)
1000 .define("EH_USE_FRAME_REGISTRY", None);
1004 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1005 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1010 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1011 pub struct Libunwind {
1012 pub target: TargetSelection,
1015 impl Step for Libunwind {
1016 type Output = PathBuf;
1018 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1019 run.path("src/llvm-project/libunwind")
1022 fn make_run(run: RunConfig<'_>) {
1023 run.builder.ensure(Libunwind { target: run.target });
1026 /// Build linunwind.a
1027 fn run(self, builder: &Builder<'_>) -> Self::Output {
1028 if builder.config.dry_run {
1029 return PathBuf::new();
1032 let out_dir = builder.native_dir(self.target).join("libunwind");
1033 let root = builder.src.join("src/llvm-project/libunwind");
1035 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1039 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1040 t!(fs::create_dir_all(&out_dir));
1042 let mut cc_cfg = cc::Build::new();
1043 let mut cpp_cfg = cc::Build::new();
1046 cpp_cfg.cpp_set_stdlib(None);
1047 cpp_cfg.flag("-nostdinc++");
1048 cpp_cfg.flag("-fno-exceptions");
1049 cpp_cfg.flag("-fno-rtti");
1050 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1052 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1053 if let Some(ar) = builder.ar(self.target) {
1056 cfg.target(&self.target.triple);
1057 cfg.host(&builder.config.build.triple);
1058 cfg.warnings(false);
1060 // get_compiler() need set opt_level first.
1062 cfg.flag("-fstrict-aliasing");
1063 cfg.flag("-funwind-tables");
1064 cfg.flag("-fvisibility=hidden");
1065 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1066 cfg.include(root.join("include"));
1067 cfg.cargo_metadata(false);
1068 cfg.out_dir(&out_dir);
1070 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1071 cfg.static_flag(true);
1072 cfg.flag("-fno-stack-protector");
1073 cfg.flag("-ffreestanding");
1074 cfg.flag("-fexceptions");
1076 // easiest way to undefine since no API available in cc::Build to undefine
1077 cfg.flag("-U_FORTIFY_SOURCE");
1078 cfg.define("_FORTIFY_SOURCE", "0");
1079 cfg.define("RUST_SGX", "1");
1080 cfg.define("__NO_STRING_INLINES", None);
1081 cfg.define("__NO_MATH_INLINES", None);
1082 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1083 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1084 cfg.define("NDEBUG", None);
1088 cc_cfg.compiler(builder.cc(self.target));
1089 if let Ok(cxx) = builder.cxx(self.target) {
1090 cpp_cfg.compiler(cxx);
1092 cc_cfg.compiler(builder.cc(self.target));
1095 // Don't set this for clang
1096 // By default, Clang builds C code in GNU C17 mode.
1097 // By default, Clang builds C++ code according to the C++98 standard,
1098 // with many C++11 features accepted as extensions.
1099 if cc_cfg.get_compiler().is_like_gnu() {
1100 cc_cfg.flag("-std=c99");
1102 if cpp_cfg.get_compiler().is_like_gnu() {
1103 cpp_cfg.flag("-std=c++11");
1106 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1107 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1108 // C++ compiler env variables on the builders.
1109 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1110 if cpp_cfg.get_compiler().is_like_gnu() {
1112 cpp_cfg.compiler(builder.cc(self.target));
1116 let mut c_sources = vec![
1118 "UnwindLevel1-gcc-ext.c",
1120 "UnwindRegistersRestore.S",
1121 "UnwindRegistersSave.S",
1124 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1125 let cpp_len = cpp_sources.len();
1127 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1128 c_sources.push("UnwindRustSgx.c");
1131 for src in c_sources {
1132 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1135 for src in &cpp_sources {
1136 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1139 cpp_cfg.compile("unwind-cpp");
1141 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1143 for entry in fs::read_dir(&out_dir).unwrap() {
1144 let file = entry.unwrap().path().canonicalize().unwrap();
1145 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1146 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1147 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1148 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1149 cc_cfg.object(&file);
1154 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1156 cc_cfg.compile("unwind");