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::build_helper::up_to_date;
20 use crate::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};
28 build_llvm_config: PathBuf,
33 // Linker flags to pass to LLVM's CMake invocation.
34 #[derive(Debug, Clone, Default)]
36 // CMAKE_EXE_LINKER_FLAGS
38 // CMAKE_SHARED_LINKER_FLAGS
40 // CMAKE_MODULE_LINKER_FLAGS
45 fn push_all(&mut self, s: impl AsRef<OsStr>) {
49 self.shared.push(" ");
51 self.module.push(" ");
56 // This returns whether we've already previously built LLVM.
58 // It's used to avoid busting caches during x.py check -- if we've already built
59 // LLVM, it's fine for us to not try to avoid doing so.
61 // This will return the llvm-config if it can get it (but it will not build it
63 pub fn prebuilt_llvm_config(
64 builder: &Builder<'_>,
65 target: TargetSelection,
66 ) -> Result<PathBuf, Meta> {
67 // If we're using a custom LLVM bail out here, but we can only use a
68 // custom LLVM for the build triple.
69 if let Some(config) = builder.config.target_config.get(&target) {
70 if let Some(ref s) = config.llvm_config {
71 check_llvm_version(builder, s);
72 return Ok(s.to_path_buf());
76 let root = "src/llvm-project/llvm";
77 let out_dir = builder.llvm_out(target);
79 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
80 if !builder.config.build.contains("msvc") || builder.ninja() {
81 llvm_config_ret_dir.push("build");
83 llvm_config_ret_dir.push("bin");
85 let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
87 let stamp = out_dir.join("llvm-finished-building");
88 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
90 if builder.config.llvm_skip_rebuild && stamp.path.exists() {
93 Using a potentially stale build of LLVM; \
94 This may not behave well.",
96 return Ok(build_llvm_config);
100 if stamp.hash.is_none() {
102 "Could not determine the LLVM submodule commit hash. \
103 Assuming that an LLVM rebuild is not necessary.",
105 builder.info(&format!(
106 "To force LLVM to rebuild, remove the file `{}`",
110 return Ok(build_llvm_config);
113 Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
116 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
118 pub target: TargetSelection,
122 type Output = PathBuf; // path to llvm-config
124 const ONLY_HOSTS: bool = true;
126 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
127 run.path("src/llvm-project").path("src/llvm-project/llvm").path("src/llvm")
130 fn make_run(run: RunConfig<'_>) {
131 run.builder.ensure(Llvm { target: run.target });
134 /// Compile LLVM for `target`.
135 fn run(self, builder: &Builder<'_>) -> PathBuf {
136 let target = self.target;
137 let target_native = if self.target.starts_with("riscv") {
138 // RISC-V target triples in Rust is not named the same as C compiler target triples.
139 // This converts Rust RISC-V target triples to C compiler triples.
140 let idx = target.triple.find('-').unwrap();
142 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
143 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
144 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
145 // Set the version suffix to 13.0 so the correct target details are used.
146 format!("{}{}", self.target, "13.0")
151 let Meta { stamp, build_llvm_config, out_dir, root } =
152 match prebuilt_llvm_config(builder, target) {
157 builder.update_submodule(&Path::new("src").join("llvm-project"));
158 if builder.config.llvm_link_shared
159 && (target.contains("windows") || target.contains("apple-darwin"))
161 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
164 builder.info(&format!("Building LLVM for {}", target));
166 let _time = util::timeit(&builder);
167 t!(fs::create_dir_all(&out_dir));
169 // https://llvm.org/docs/CMake.html
170 let mut cfg = cmake::Config::new(builder.src.join(root));
171 let mut ldflags = LdFlags::default();
173 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
174 (false, _) => "Debug",
175 (true, false) => "Release",
176 (true, true) => "RelWithDebInfo",
179 // NOTE: remember to also update `config.toml.example` when changing the
181 let llvm_targets = match &builder.config.llvm_targets {
184 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
185 Sparc;SystemZ;WebAssembly;X86"
189 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
194 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
195 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
196 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
198 cfg.out_dir(&out_dir)
200 .define("LLVM_ENABLE_ASSERTIONS", assertions)
201 .define("LLVM_ENABLE_PLUGINS", plugins)
202 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
203 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
204 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
205 .define("LLVM_INCLUDE_DOCS", "OFF")
206 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
207 .define("LLVM_INCLUDE_TESTS", enable_tests)
208 .define("LLVM_ENABLE_TERMINFO", "OFF")
209 .define("LLVM_ENABLE_LIBEDIT", "OFF")
210 .define("LLVM_ENABLE_BINDINGS", "OFF")
211 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
212 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
213 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
214 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
216 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
217 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
218 // This flag makes sure `FileCheck` is copied in the final binaries directory.
219 cfg.define("LLVM_INSTALL_UTILS", "ON");
221 if builder.config.llvm_profile_generate {
222 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
223 cfg.define("LLVM_BUILD_RUNTIME", "No");
225 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
226 cfg.define("LLVM_PROFDATA_FILE", &path);
229 if target != "aarch64-apple-darwin" && !target.contains("windows") {
230 cfg.define("LLVM_ENABLE_ZLIB", "ON");
232 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
235 // Are we compiling for iOS/tvOS?
236 if target.contains("apple-ios") || target.contains("apple-tvos") {
237 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
238 cfg.define("CMAKE_OSX_SYSROOT", "/");
239 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
240 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
241 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
242 // Zlib fails to link properly, leading to a compiler error.
243 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
246 if builder.config.llvm_thin_lto {
247 cfg.define("LLVM_ENABLE_LTO", "Thin");
248 if !target.contains("apple") {
249 cfg.define("LLVM_ENABLE_LLD", "ON");
253 // This setting makes the LLVM tools link to the dynamic LLVM library,
254 // which saves both memory during parallel links and overall disk space
255 // for the tools. We don't do this on every platform as it doesn't work
256 // equally well everywhere.
258 // If we're not linking rustc to a dynamic LLVM, though, then don't link
260 if builder.llvm_link_tools_dynamically(target) && builder.config.llvm_link_shared {
261 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
264 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
265 // We also do this if the user explicitly requested static libstdc++.
266 if builder.config.llvm_tools_enabled || builder.config.llvm_static_stdcpp {
267 if !target.contains("msvc") && !target.contains("netbsd") {
268 if target.contains("apple") {
269 ldflags.push_all("-static-libstdc++");
271 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
276 if target.starts_with("riscv") && !target.contains("freebsd") {
277 // RISC-V GCC erroneously requires linking against
278 // `libatomic` when using 1-byte and 2-byte C++
279 // atomics but the LLVM build system check cannot
280 // detect this. Therefore it is set manually here.
281 // FreeBSD uses Clang as its system compiler and
282 // provides no libatomic in its base system so does
284 ldflags.exe.push(" -latomic");
285 ldflags.shared.push(" -latomic");
288 if target.contains("msvc") {
289 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
290 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
291 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
292 cfg.static_crt(true);
295 if target.starts_with("i686") {
296 cfg.define("LLVM_BUILD_32_BITS", "ON");
299 let mut enabled_llvm_projects = Vec::new();
301 if util::forcing_clang_based_tests() {
302 enabled_llvm_projects.push("clang");
303 enabled_llvm_projects.push("compiler-rt");
306 if builder.config.llvm_polly {
307 enabled_llvm_projects.push("polly");
310 if builder.config.llvm_clang {
311 enabled_llvm_projects.push("clang");
314 // We want libxml to be disabled.
315 // See https://github.com/rust-lang/rust/pull/50104
316 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
318 if !enabled_llvm_projects.is_empty() {
319 enabled_llvm_projects.sort();
320 enabled_llvm_projects.dedup();
321 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
324 if let Some(num_linkers) = builder.config.llvm_link_jobs {
326 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
330 // Workaround for ppc32 lld limitation
331 if target == "powerpc-unknown-freebsd" {
332 ldflags.exe.push(" -fuse-ld=bfd");
335 // https://llvm.org/docs/HowToCrossCompileLLVM.html
336 if target != builder.config.build {
337 builder.ensure(Llvm { target: builder.config.build });
338 // FIXME: if the llvm root for the build triple is overridden then we
339 // should use llvm-tblgen from there, also should verify that it
340 // actually exists most of the time in normal installs of LLVM.
341 let host_bin = builder.llvm_out(builder.config.build).join("bin");
342 cfg.define("CMAKE_CROSSCOMPILING", "True");
343 cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
344 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
347 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
351 if let Some(ref suffix) = builder.config.llvm_version_suffix {
352 // Allow version-suffix="" to not define a version suffix at all.
353 if !suffix.is_empty() {
354 cfg.define("LLVM_VERSION_SUFFIX", suffix);
356 } else if builder.config.channel == "dev" {
357 // Changes to a version suffix require a complete rebuild of the LLVM.
358 // To avoid rebuilds during a time of version bump, don't include rustc
359 // release number on the dev channel.
360 cfg.define("LLVM_VERSION_SUFFIX", "-rust-dev");
362 let suffix = format!("-rust-{}-{}", builder.version, builder.config.channel);
363 cfg.define("LLVM_VERSION_SUFFIX", suffix);
366 if let Some(ref linker) = builder.config.llvm_use_linker {
367 cfg.define("LLVM_USE_LINKER", linker);
370 if builder.config.llvm_allow_old_toolchain {
371 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
374 configure_cmake(builder, target, &mut cfg, true, ldflags);
376 for (key, val) in &builder.config.llvm_build_config {
377 cfg.define(key, val);
380 // FIXME: we don't actually need to build all LLVM tools and all LLVM
381 // libraries here, e.g., we just want a few components and a few
382 // tools. Figure out how to filter them down and only build the right
383 // tools and libs on all platforms.
385 if builder.config.dry_run {
386 return build_llvm_config;
397 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
398 if !builder.config.llvm_version_check {
402 if builder.config.dry_run {
406 let mut cmd = Command::new(llvm_config);
407 let version = output(cmd.arg("--version"));
408 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
409 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
414 panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
418 builder: &Builder<'_>,
419 target: TargetSelection,
420 cfg: &mut cmake::Config,
421 use_compiler_launcher: bool,
422 mut ldflags: LdFlags,
424 // Do not print installation messages for up-to-date files.
425 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
426 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
428 // Do not allow the user's value of DESTDIR to influence where
429 // LLVM will install itself. LLVM must always be installed in our
430 // own build directories.
431 cfg.env("DESTDIR", "");
434 cfg.generator("Ninja");
436 cfg.target(&target.triple).host(&builder.config.build.triple);
438 if target != builder.config.build {
439 if target.contains("netbsd") {
440 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
441 } else if target.contains("freebsd") {
442 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
443 } else if target.contains("windows") {
444 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
445 } else if target.contains("haiku") {
446 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
447 } else if target.contains("solaris") || target.contains("illumos") {
448 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
450 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
451 // that case like CMake we cannot easily determine system version either.
453 // Since, the LLVM itself makes rather limited use of version checks in
454 // CMakeFiles (and then only in tests), and so far no issues have been
455 // reported, the system version is currently left unset.
458 let sanitize_cc = |cc: &Path| {
459 if target.contains("msvc") {
460 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
462 cc.as_os_str().to_owned()
466 // MSVC with CMake uses msbuild by default which doesn't respect these
467 // vars that we'd otherwise configure. In that case we just skip this
469 if target.contains("msvc") && !builder.ninja() {
473 let (cc, cxx) = match builder.config.llvm_clang_cl {
474 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
475 None => (builder.cc(target), builder.cxx(target).unwrap()),
478 // Handle msvc + ninja + ccache specially (this is what the bots use)
479 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
480 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
481 wrap_cc.set_file_name("sccache-plus-cl.exe");
483 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
484 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
485 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
486 .env("SCCACHE_TARGET", target.triple)
487 .env("SCCACHE_CC", &cc)
488 .env("SCCACHE_CXX", &cxx);
490 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
491 // off the beaten path here that I'm not really sure this is even half
492 // supported any more. Here we're trying to:
494 // * Build LLVM on MSVC
495 // * Build LLVM with `clang-cl` instead of `cl.exe`
496 // * Build a project with `sccache`
497 // * Build for 32-bit as well
498 // * Build with Ninja
500 // For `cl.exe` there are different binaries to compile 32/64 bit which
501 // we use but for `clang-cl` there's only one which internally
502 // multiplexes via flags. As a result it appears that CMake's detection
503 // of a compiler's architecture and such on MSVC **doesn't** pass any
504 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
505 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
506 // definitely causes problems since all the env vars are pointing to
509 // To hack around this... again... we pass an argument that's
510 // unconditionally passed in the sccache shim. This'll get CMake to
511 // correctly diagnose it's doing a 32-bit compilation and LLVM will
512 // internally configure itself appropriately.
513 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
514 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
517 // If ccache is configured we inform the build a little differently how
518 // to invoke ccache while also invoking our compilers.
519 if use_compiler_launcher {
520 if let Some(ref ccache) = builder.config.ccache {
521 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
522 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
525 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
526 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
527 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
530 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
531 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
532 if let Some(ref s) = builder.config.llvm_cflags {
536 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
537 if target.contains("apple-ios") {
538 if target.contains("86-") {
539 cflags.push(" -miphonesimulator-version-min=10.0");
541 cflags.push(" -miphoneos-version-min=10.0");
544 if builder.config.llvm_clang_cl.is_some() {
545 cflags.push(&format!(" --target={}", target));
547 cfg.define("CMAKE_C_FLAGS", cflags);
548 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
549 if let Some(ref s) = builder.config.llvm_cxxflags {
553 if builder.config.llvm_clang_cl.is_some() {
554 cxxflags.push(&format!(" --target={}", target));
556 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
557 if let Some(ar) = builder.ar(target) {
558 if ar.is_absolute() {
559 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
560 // tries to resolve this path in the LLVM build directory.
561 cfg.define("CMAKE_AR", sanitize_cc(ar));
565 if let Some(ranlib) = builder.ranlib(target) {
566 if ranlib.is_absolute() {
567 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
568 // tries to resolve this path in the LLVM build directory.
569 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
573 if let Some(ref flags) = builder.config.llvm_ldflags {
574 ldflags.push_all(flags);
577 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
578 ldflags.push_all(&flags);
581 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
582 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
583 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
585 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
586 cfg.env("RUSTC_LOG", "sccache=warn");
590 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
591 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
592 let kind = if host == target { "HOST" } else { "TARGET" };
593 let target_u = target.replace("-", "_");
594 env::var_os(&format!("{}_{}", var_base, target))
595 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
596 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
597 .or_else(|| env::var_os(var_base))
600 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
602 pub target: TargetSelection,
606 type Output = PathBuf;
607 const ONLY_HOSTS: bool = true;
609 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
610 run.path("src/llvm-project/lld").path("src/tools/lld")
613 fn make_run(run: RunConfig<'_>) {
614 run.builder.ensure(Lld { target: run.target });
617 /// Compile LLD for `target`.
618 fn run(self, builder: &Builder<'_>) -> PathBuf {
619 if builder.config.dry_run {
620 return PathBuf::from("lld-out-dir-test-gen");
622 let target = self.target;
624 let llvm_config = builder.ensure(Llvm { target: self.target });
626 let out_dir = builder.lld_out(target);
627 let done_stamp = out_dir.join("lld-finished-building");
628 if done_stamp.exists() {
632 builder.info(&format!("Building LLD for {}", target));
633 let _time = util::timeit(&builder);
634 t!(fs::create_dir_all(&out_dir));
636 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
637 configure_cmake(builder, target, &mut cfg, true, LdFlags::default());
639 // This is an awful, awful hack. Discovered when we migrated to using
640 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
641 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
642 // that directory for later processing. Unfortunately if this path has
643 // forward slashes in it (which it basically always does on Windows)
644 // then CMake will hit a syntax error later on as... something isn't
647 // Instead of attempting to fix this problem in upstream CMake and/or
648 // LLVM/LLD we just hack around it here. This thin wrapper will take the
649 // output from llvm-config and replace all instances of `\` with `/` to
650 // ensure we don't hit the same bugs with escaping. It means that you
651 // can't build on a system where your paths require `\` on Windows, but
652 // there's probably a lot of reasons you can't do that other than this.
653 let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
655 cfg.out_dir(&out_dir)
657 .env("LLVM_CONFIG_REAL", &llvm_config)
658 .define("LLVM_CONFIG_PATH", llvm_config_shim)
659 .define("LLVM_INCLUDE_TESTS", "OFF");
661 // While we're using this horrible workaround to shim the execution of
662 // llvm-config, let's just pile on more. I can't seem to figure out how
663 // to build LLD as a standalone project and also cross-compile it at the
664 // same time. It wants a natively executable `llvm-config` to learn
665 // about LLVM, but then it learns about all the host configuration of
666 // LLVM and tries to link to host LLVM libraries.
668 // To work around that we tell our shim to replace anything with the
669 // build target with the actual target instead. This'll break parts of
670 // LLD though which try to execute host tools, such as llvm-tblgen, so
671 // we specifically tell it where to find those. This is likely super
672 // brittle and will break over time. If anyone knows better how to
673 // cross-compile LLD it would be much appreciated to fix this!
674 if target != builder.config.build {
675 cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
676 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
679 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
683 // Explicitly set C++ standard, because upstream doesn't do so
684 // for standalone builds.
685 cfg.define("CMAKE_CXX_STANDARD", "14");
689 t!(File::create(&done_stamp));
694 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
695 pub struct TestHelpers {
696 pub target: TargetSelection,
699 impl Step for TestHelpers {
702 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
703 run.path("src/test/auxiliary/rust_test_helpers.c")
706 fn make_run(run: RunConfig<'_>) {
707 run.builder.ensure(TestHelpers { target: run.target })
710 /// Compiles the `rust_test_helpers.c` library which we used in various
711 /// `run-pass` tests for ABI testing.
712 fn run(self, builder: &Builder<'_>) {
713 if builder.config.dry_run {
716 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
717 // toolchain. However, some x86_64 ELF objects can be linked
718 // without issues. Use this hack to compile the test helpers.
719 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
720 TargetSelection::from_user("x86_64-unknown-linux-gnu")
724 let dst = builder.test_helpers_out(target);
725 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
726 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
730 builder.info("Building test helpers");
731 t!(fs::create_dir_all(&dst));
732 let mut cfg = cc::Build::new();
733 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
734 if target.contains("emscripten") {
738 // We may have found various cross-compilers a little differently due to our
739 // extra configuration, so inform cc of these compilers. Note, though, that
740 // on MSVC we still need cc's detection of env vars (ugh).
741 if !target.contains("msvc") {
742 if let Some(ar) = builder.ar(target) {
745 cfg.compiler(builder.cc(target));
747 cfg.cargo_metadata(false)
749 .target(&target.triple)
750 .host(&builder.config.build.triple)
754 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
755 .compile("rust_test_helpers");
759 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
760 pub struct Sanitizers {
761 pub target: TargetSelection,
764 impl Step for Sanitizers {
765 type Output = Vec<SanitizerRuntime>;
767 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
768 run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
771 fn make_run(run: RunConfig<'_>) {
772 run.builder.ensure(Sanitizers { target: run.target });
775 /// Builds sanitizer runtime libraries.
776 fn run(self, builder: &Builder<'_>) -> Self::Output {
777 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
778 if !compiler_rt_dir.exists() {
782 let out_dir = builder.native_dir(self.target).join("sanitizers");
783 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
784 if runtimes.is_empty() {
788 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
789 if builder.config.dry_run {
793 let stamp = out_dir.join("sanitizers-finished-building");
794 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
797 if stamp.hash.is_none() {
798 builder.info(&format!(
799 "Rebuild sanitizers by removing the file `{}`",
806 builder.info(&format!("Building sanitizers for {}", self.target));
808 let _time = util::timeit(&builder);
810 let mut cfg = cmake::Config::new(&compiler_rt_dir);
811 cfg.profile("Release");
812 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
813 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
814 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
815 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
816 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
817 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
818 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
819 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
820 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
821 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
823 // On Darwin targets the sanitizer runtimes are build as universal binaries.
824 // Unfortunately sccache currently lacks support to build them successfully.
825 // Disable compiler launcher on Darwin targets to avoid potential issues.
826 let use_compiler_launcher = !self.target.contains("apple-darwin");
827 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
829 t!(fs::create_dir_all(&out_dir));
830 cfg.out_dir(out_dir);
832 for runtime in &runtimes {
833 cfg.build_target(&runtime.cmake_target);
842 #[derive(Clone, Debug)]
843 pub struct SanitizerRuntime {
844 /// CMake target used to build the runtime.
845 pub cmake_target: String,
846 /// Path to the built runtime library.
848 /// Library filename that will be used rustc.
852 /// Returns sanitizers available on a given target.
853 fn supported_sanitizers(
855 target: TargetSelection,
857 ) -> Vec<SanitizerRuntime> {
858 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
861 .map(move |c| SanitizerRuntime {
862 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
864 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
865 name: format!("librustc-{}_rt.{}.dylib", channel, c),
870 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
873 .map(move |c| SanitizerRuntime {
874 cmake_target: format!("clang_rt.{}-{}", c, arch),
875 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
876 name: format!("librustc-{}_rt.{}.a", channel, c),
881 match &*target.triple {
882 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
883 "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
884 "aarch64-unknown-linux-gnu" => {
885 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
887 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
888 "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
889 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
890 "x86_64-unknown-netbsd" => {
891 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
893 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
894 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
895 "x86_64-unknown-linux-gnu" => {
896 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
898 "x86_64-unknown-linux-musl" => {
899 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
907 hash: Option<Vec<u8>>,
911 fn new(path: PathBuf, hash: Option<&str>) -> Self {
912 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
915 fn is_done(&self) -> bool {
916 match fs::read(&self.path) {
917 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
918 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
920 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
925 fn remove(&self) -> io::Result<()> {
926 match fs::remove_file(&self.path) {
929 if e.kind() == io::ErrorKind::NotFound {
938 fn write(&self) -> io::Result<()> {
939 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
943 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
944 pub struct CrtBeginEnd {
945 pub target: TargetSelection,
948 impl Step for CrtBeginEnd {
949 type Output = PathBuf;
951 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
952 run.path("src/llvm-project/compiler-rt/lib/crt")
955 fn make_run(run: RunConfig<'_>) {
956 run.builder.ensure(CrtBeginEnd { target: run.target });
959 /// Build crtbegin.o/crtend.o for musl target.
960 fn run(self, builder: &Builder<'_>) -> Self::Output {
961 let out_dir = builder.native_dir(self.target).join("crt");
963 if builder.config.dry_run {
967 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
968 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
969 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
970 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
975 builder.info("Building crtbegin.o and crtend.o");
976 t!(fs::create_dir_all(&out_dir));
978 let mut cfg = cc::Build::new();
980 if let Some(ar) = builder.ar(self.target) {
983 cfg.compiler(builder.cc(self.target));
984 cfg.cargo_metadata(false)
986 .target(&self.target.triple)
987 .host(&builder.config.build.triple)
994 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
995 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
996 // instead of .ctors/.dtors
998 .define("CRT_HAS_INITFINI_ARRAY", None)
999 .define("EH_USE_FRAME_REGISTRY", None);
1003 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1004 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1009 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1010 pub struct Libunwind {
1011 pub target: TargetSelection,
1014 impl Step for Libunwind {
1015 type Output = PathBuf;
1017 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1018 run.path("src/llvm-project/libunwind")
1021 fn make_run(run: RunConfig<'_>) {
1022 run.builder.ensure(Libunwind { target: run.target });
1025 /// Build linunwind.a
1026 fn run(self, builder: &Builder<'_>) -> Self::Output {
1027 if builder.config.dry_run {
1028 return PathBuf::new();
1031 let out_dir = builder.native_dir(self.target).join("libunwind");
1032 let root = builder.src.join("src/llvm-project/libunwind");
1034 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1038 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1039 t!(fs::create_dir_all(&out_dir));
1041 let mut cc_cfg = cc::Build::new();
1042 let mut cpp_cfg = cc::Build::new();
1045 cpp_cfg.cpp_set_stdlib(None);
1046 cpp_cfg.flag("-nostdinc++");
1047 cpp_cfg.flag("-fno-exceptions");
1048 cpp_cfg.flag("-fno-rtti");
1049 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1051 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1052 if let Some(ar) = builder.ar(self.target) {
1055 cfg.target(&self.target.triple);
1056 cfg.host(&builder.config.build.triple);
1057 cfg.warnings(false);
1059 // get_compiler() need set opt_level first.
1061 cfg.flag("-fstrict-aliasing");
1062 cfg.flag("-funwind-tables");
1063 cfg.flag("-fvisibility=hidden");
1064 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1065 cfg.include(root.join("include"));
1066 cfg.cargo_metadata(false);
1067 cfg.out_dir(&out_dir);
1069 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1070 cfg.static_flag(true);
1071 cfg.flag("-fno-stack-protector");
1072 cfg.flag("-ffreestanding");
1073 cfg.flag("-fexceptions");
1075 // easiest way to undefine since no API available in cc::Build to undefine
1076 cfg.flag("-U_FORTIFY_SOURCE");
1077 cfg.define("_FORTIFY_SOURCE", "0");
1078 cfg.define("RUST_SGX", "1");
1079 cfg.define("__NO_STRING_INLINES", None);
1080 cfg.define("__NO_MATH_INLINES", None);
1081 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1082 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1083 cfg.define("NDEBUG", None);
1087 cc_cfg.compiler(builder.cc(self.target));
1088 if let Ok(cxx) = builder.cxx(self.target) {
1089 cpp_cfg.compiler(cxx);
1091 cc_cfg.compiler(builder.cc(self.target));
1094 // Don't set this for clang
1095 // By default, Clang builds C code in GNU C17 mode.
1096 // By default, Clang builds C++ code according to the C++98 standard,
1097 // with many C++11 features accepted as extensions.
1098 if cc_cfg.get_compiler().is_like_gnu() {
1099 cc_cfg.flag("-std=c99");
1101 if cpp_cfg.get_compiler().is_like_gnu() {
1102 cpp_cfg.flag("-std=c++11");
1105 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1106 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1107 // C++ compiler env variables on the builders.
1108 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1109 if cpp_cfg.get_compiler().is_like_gnu() {
1111 cpp_cfg.compiler(builder.cc(self.target));
1115 let mut c_sources = vec![
1117 "UnwindLevel1-gcc-ext.c",
1119 "UnwindRegistersRestore.S",
1120 "UnwindRegistersSave.S",
1123 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1124 let cpp_len = cpp_sources.len();
1126 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1127 c_sources.push("UnwindRustSgx.c");
1130 for src in c_sources {
1131 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1134 for src in &cpp_sources {
1135 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1138 cpp_cfg.compile("unwind-cpp");
1140 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1142 for entry in fs::read_dir(&out_dir).unwrap() {
1143 let file = entry.unwrap().path().canonicalize().unwrap();
1144 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1145 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1146 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1147 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1148 cc_cfg.object(&file);
1153 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1155 cc_cfg.compile("unwind");