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::bolt::{instrument_with_bolt_inplace, optimize_library_with_bolt_inplace};
20 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
21 use crate::config::TargetSelection;
22 use crate::util::get_clang_cl_resource_dir;
23 use crate::util::{self, exe, output, program_out_of_date, t, up_to_date};
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 maybe_download_ci_llvm(builder);
69 // If we're using a custom LLVM bail out here, but we can only use a
70 // custom LLVM for the build triple.
71 if let Some(config) = builder.config.target_config.get(&target) {
72 if let Some(ref s) = config.llvm_config {
73 check_llvm_version(builder, s);
74 return Ok(s.to_path_buf());
78 let root = "src/llvm-project/llvm";
79 let out_dir = builder.llvm_out(target);
81 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
82 if !builder.config.build.contains("msvc") || builder.ninja() {
83 llvm_config_ret_dir.push("build");
85 llvm_config_ret_dir.push("bin");
87 let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
89 let stamp = out_dir.join("llvm-finished-building");
90 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
92 if builder.config.llvm_skip_rebuild && stamp.path.exists() {
95 Using a potentially stale build of LLVM; \
96 This may not behave well.",
98 return Ok(build_llvm_config);
102 if stamp.hash.is_none() {
104 "Could not determine the LLVM submodule commit hash. \
105 Assuming that an LLVM rebuild is not necessary.",
107 builder.info(&format!(
108 "To force LLVM to rebuild, remove the file `{}`",
112 return Ok(build_llvm_config);
115 Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
118 /// This retrieves the LLVM sha we *want* to use, according to git history.
119 pub(crate) fn detect_llvm_sha(config: &crate::config::Config) -> String {
120 let mut rev_list = config.git();
122 PathBuf::from("rev-list"),
123 format!("--author={}", config.stage0_metadata.config.git_merge_commit_email).into(),
125 "--first-parent".into(),
128 config.src.join("src/llvm-project"),
129 config.src.join("src/bootstrap/download-ci-llvm-stamp"),
130 // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
131 config.src.join("src/version"),
133 let llvm_sha = output(&mut rev_list);
134 let llvm_sha = llvm_sha.trim();
137 eprintln!("error: could not find commit hash for downloading LLVM");
138 eprintln!("help: maybe your repository history is too shallow?");
139 eprintln!("help: consider disabling `download-ci-llvm`");
140 eprintln!("help: or fetch enough history to include one upstream commit");
147 /// Returns whether the CI-found LLVM is currently usable.
149 /// This checks both the build triple platform to confirm we're usable at all,
150 /// and then verifies if the current HEAD matches the detected LLVM SHA head,
151 /// in which case LLVM is indicated as not available.
152 pub(crate) fn is_ci_llvm_available(config: &crate::config::Config, asserts: bool) -> bool {
153 // This is currently all tier 1 targets and tier 2 targets with host tools
154 // (since others may not have CI artifacts)
155 // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
156 let supported_platforms = [
158 "aarch64-unknown-linux-gnu",
159 "i686-pc-windows-gnu",
160 "i686-pc-windows-msvc",
161 "i686-unknown-linux-gnu",
162 "x86_64-unknown-linux-gnu",
163 "x86_64-apple-darwin",
164 "x86_64-pc-windows-gnu",
165 "x86_64-pc-windows-msvc",
166 // tier 2 with host tools
167 "aarch64-apple-darwin",
168 "aarch64-pc-windows-msvc",
169 "aarch64-unknown-linux-musl",
170 "arm-unknown-linux-gnueabi",
171 "arm-unknown-linux-gnueabihf",
172 "armv7-unknown-linux-gnueabihf",
173 "mips-unknown-linux-gnu",
174 "mips64-unknown-linux-gnuabi64",
175 "mips64el-unknown-linux-gnuabi64",
176 "mipsel-unknown-linux-gnu",
177 "powerpc-unknown-linux-gnu",
178 "powerpc64-unknown-linux-gnu",
179 "powerpc64le-unknown-linux-gnu",
180 "riscv64gc-unknown-linux-gnu",
181 "s390x-unknown-linux-gnu",
182 "x86_64-unknown-freebsd",
183 "x86_64-unknown-illumos",
184 "x86_64-unknown-linux-musl",
185 "x86_64-unknown-netbsd",
187 if !supported_platforms.contains(&&*config.build.triple) {
191 let triple = &*config.build.triple;
192 if (triple == "aarch64-unknown-linux-gnu" || triple.contains("i686")) && asserts {
193 // No alt builder for aarch64-unknown-linux-gnu today.
197 if crate::util::CiEnv::is_ci() {
198 let llvm_sha = detect_llvm_sha(config);
199 let head_sha = output(config.git().arg("rev-parse").arg("HEAD"));
200 let head_sha = head_sha.trim();
201 if llvm_sha == head_sha {
203 "Detected LLVM as non-available: running in CI and modified LLVM in this change"
212 pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) {
213 let config = &builder.config;
214 if !config.llvm_from_ci {
217 let llvm_root = config.ci_llvm_root();
218 let llvm_stamp = llvm_root.join(".llvm-stamp");
219 let llvm_sha = detect_llvm_sha(&config);
220 let key = format!("{}{}", llvm_sha, config.llvm_assertions);
221 if program_out_of_date(&llvm_stamp, &key) && !config.dry_run {
222 download_ci_llvm(builder, &llvm_sha);
223 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
224 builder.fix_bin_or_dylib(&t!(entry).path());
227 // Update the timestamp of llvm-config to force rustc_llvm to be
228 // rebuilt. This is a hacky workaround for a deficiency in Cargo where
229 // the rerun-if-changed directive doesn't handle changes very well.
230 // https://github.com/rust-lang/cargo/issues/10791
231 // Cargo only compares the timestamp of the file relative to the last
232 // time `rustc_llvm` build script ran. However, the timestamps of the
233 // files in the tarball are in the past, so it doesn't trigger a
235 let now = filetime::FileTime::from_system_time(std::time::SystemTime::now());
236 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", builder.config.build));
237 t!(filetime::set_file_times(&llvm_config, now, now));
239 let llvm_lib = llvm_root.join("lib");
240 for entry in t!(fs::read_dir(&llvm_lib)) {
241 let lib = t!(entry).path();
242 if lib.extension().map_or(false, |ext| ext == "so") {
243 builder.fix_bin_or_dylib(&lib);
246 t!(fs::write(llvm_stamp, key));
250 fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) {
251 let llvm_assertions = builder.config.llvm_assertions;
253 let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
254 let cache_dst = builder.out.join("cache");
255 let rustc_cache = cache_dst.join(cache_prefix);
256 if !rustc_cache.exists() {
257 t!(fs::create_dir_all(&rustc_cache));
259 let base = if llvm_assertions {
260 &builder.config.stage0_metadata.config.artifacts_with_llvm_assertions_server
262 &builder.config.stage0_metadata.config.artifacts_server
264 let channel = builder.config.artifact_channel(llvm_sha);
265 let filename = format!("rust-dev-{}-{}.tar.xz", channel, builder.build.build.triple);
266 let tarball = rustc_cache.join(&filename);
267 if !tarball.exists() {
268 let help_on_error = "error: failed to download llvm from ci
270 help: old builds get deleted after a certain time
271 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
274 download-ci-llvm = false
276 builder.download_component(
277 &format!("{base}/{llvm_sha}/{filename}"),
282 let llvm_root = builder.config.ci_llvm_root();
283 builder.unpack(&tarball, &llvm_root, "rust-dev");
286 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
288 pub target: TargetSelection,
292 type Output = PathBuf; // path to llvm-config
294 const ONLY_HOSTS: bool = true;
296 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
297 run.path("src/llvm-project").path("src/llvm-project/llvm")
300 fn make_run(run: RunConfig<'_>) {
301 run.builder.ensure(Llvm { target: run.target });
304 /// Compile LLVM for `target`.
305 fn run(self, builder: &Builder<'_>) -> PathBuf {
306 let target = self.target;
307 let target_native = if self.target.starts_with("riscv") {
308 // RISC-V target triples in Rust is not named the same as C compiler target triples.
309 // This converts Rust RISC-V target triples to C compiler triples.
310 let idx = target.triple.find('-').unwrap();
312 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
313 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
314 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
315 // Set the version suffix to 13.0 so the correct target details are used.
316 format!("{}{}", self.target, "13.0")
321 let Meta { stamp, build_llvm_config, out_dir, root } =
322 match prebuilt_llvm_config(builder, target) {
327 builder.update_submodule(&Path::new("src").join("llvm-project"));
328 if builder.llvm_link_shared() && target.contains("windows") {
329 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
332 builder.info(&format!("Building LLVM for {}", target));
334 let _time = util::timeit(&builder);
335 t!(fs::create_dir_all(&out_dir));
337 // https://llvm.org/docs/CMake.html
338 let mut cfg = cmake::Config::new(builder.src.join(root));
339 let mut ldflags = LdFlags::default();
341 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
342 (false, _) => "Debug",
343 (true, false) => "Release",
344 (true, true) => "RelWithDebInfo",
347 // NOTE: remember to also update `config.toml.example` when changing the
349 let llvm_targets = match &builder.config.llvm_targets {
352 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
353 Sparc;SystemZ;WebAssembly;X86"
357 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
362 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
363 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
364 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
366 cfg.out_dir(&out_dir)
368 .define("LLVM_ENABLE_ASSERTIONS", assertions)
369 .define("LLVM_ENABLE_PLUGINS", plugins)
370 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
371 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
372 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
373 .define("LLVM_INCLUDE_DOCS", "OFF")
374 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
375 .define("LLVM_INCLUDE_TESTS", enable_tests)
376 .define("LLVM_ENABLE_TERMINFO", "OFF")
377 .define("LLVM_ENABLE_LIBEDIT", "OFF")
378 .define("LLVM_ENABLE_BINDINGS", "OFF")
379 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
380 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
381 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
382 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
384 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
385 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
386 // This flag makes sure `FileCheck` is copied in the final binaries directory.
387 cfg.define("LLVM_INSTALL_UTILS", "ON");
389 if builder.config.llvm_profile_generate {
390 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
391 if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
392 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
394 cfg.define("LLVM_BUILD_RUNTIME", "No");
396 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
397 cfg.define("LLVM_PROFDATA_FILE", &path);
399 if builder.config.llvm_bolt_profile_generate
400 || builder.config.llvm_bolt_profile_use.is_some()
402 // Relocations are required for BOLT to work.
403 ldflags.push_all("-Wl,-q");
406 // Disable zstd to avoid a dependency on libzstd.so.
407 cfg.define("LLVM_ENABLE_ZSTD", "OFF");
409 if target != "aarch64-apple-darwin" && !target.contains("windows") {
410 cfg.define("LLVM_ENABLE_ZLIB", "ON");
412 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
415 // Are we compiling for iOS/tvOS/watchOS?
416 if target.contains("apple-ios")
417 || target.contains("apple-tvos")
418 || target.contains("apple-watchos")
420 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
421 cfg.define("CMAKE_OSX_SYSROOT", "/");
422 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
423 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
424 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
425 // Zlib fails to link properly, leading to a compiler error.
426 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
429 // This setting makes the LLVM tools link to the dynamic LLVM library,
430 // which saves both memory during parallel links and overall disk space
431 // for the tools. We don't do this on every platform as it doesn't work
432 // equally well everywhere.
433 if builder.llvm_link_shared() {
434 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
437 if target.starts_with("riscv") && !target.contains("freebsd") && !target.contains("openbsd")
439 // RISC-V GCC erroneously requires linking against
440 // `libatomic` when using 1-byte and 2-byte C++
441 // atomics but the LLVM build system check cannot
442 // detect this. Therefore it is set manually here.
443 // Some BSD uses Clang as its system compiler and
444 // provides no libatomic in its base system so does
446 ldflags.exe.push(" -latomic");
447 ldflags.shared.push(" -latomic");
450 if target.contains("msvc") {
451 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
452 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
453 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
454 cfg.static_crt(true);
457 if target.starts_with("i686") {
458 cfg.define("LLVM_BUILD_32_BITS", "ON");
461 let mut enabled_llvm_projects = Vec::new();
463 if util::forcing_clang_based_tests() {
464 enabled_llvm_projects.push("clang");
465 enabled_llvm_projects.push("compiler-rt");
468 if builder.config.llvm_polly {
469 enabled_llvm_projects.push("polly");
472 if builder.config.llvm_clang {
473 enabled_llvm_projects.push("clang");
476 // We want libxml to be disabled.
477 // See https://github.com/rust-lang/rust/pull/50104
478 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
480 if !enabled_llvm_projects.is_empty() {
481 enabled_llvm_projects.sort();
482 enabled_llvm_projects.dedup();
483 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
486 if let Some(num_linkers) = builder.config.llvm_link_jobs {
488 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
492 // Workaround for ppc32 lld limitation
493 if target == "powerpc-unknown-freebsd" {
494 ldflags.exe.push(" -fuse-ld=bfd");
497 // https://llvm.org/docs/HowToCrossCompileLLVM.html
498 if target != builder.config.build {
499 builder.ensure(Llvm { target: builder.config.build });
500 // FIXME: if the llvm root for the build triple is overridden then we
501 // should use llvm-tblgen from there, also should verify that it
502 // actually exists most of the time in normal installs of LLVM.
503 let host_bin = builder.llvm_out(builder.config.build).join("bin");
504 cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
505 // LLVM_NM is required for cross compiling using MSVC
506 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
509 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
511 if builder.config.llvm_clang {
512 let build_bin = builder.llvm_out(builder.config.build).join("build").join("bin");
513 let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
514 if !builder.config.dry_run && !clang_tblgen.exists() {
515 panic!("unable to find {}", clang_tblgen.display());
517 cfg.define("CLANG_TABLEGEN", clang_tblgen);
521 let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
522 // Allow version-suffix="" to not define a version suffix at all.
523 if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
524 } else if builder.config.channel == "dev" {
525 // Changes to a version suffix require a complete rebuild of the LLVM.
526 // To avoid rebuilds during a time of version bump, don't include rustc
527 // release number on the dev channel.
528 Some("-rust-dev".to_string())
530 Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
532 if let Some(ref suffix) = llvm_version_suffix {
533 cfg.define("LLVM_VERSION_SUFFIX", suffix);
536 configure_cmake(builder, target, &mut cfg, true, ldflags);
537 configure_llvm(builder, target, &mut cfg);
539 for (key, val) in &builder.config.llvm_build_config {
540 cfg.define(key, val);
543 // FIXME: we don't actually need to build all LLVM tools and all LLVM
544 // libraries here, e.g., we just want a few components and a few
545 // tools. Figure out how to filter them down and only build the right
546 // tools and libs on all platforms.
548 if builder.config.dry_run {
549 return build_llvm_config;
554 // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
555 // libLLVM.dylib will be built. However, llvm-config will still look
556 // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
557 // link to make llvm-config happy.
558 if builder.llvm_link_shared() && target.contains("apple-darwin") {
559 let mut cmd = Command::new(&build_llvm_config);
560 let version = output(cmd.arg("--version"));
561 let major = version.split('.').next().unwrap();
562 let lib_name = match llvm_version_suffix {
563 Some(s) => format!("libLLVM-{}{}.dylib", major, s),
564 None => format!("libLLVM-{}.dylib", major),
567 let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
568 if !lib_llvm.exists() {
569 t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
573 // After LLVM is built, we modify (instrument or optimize) the libLLVM.so library file
574 // in place. This is fine, because currently we do not support incrementally rebuilding
575 // LLVM after a configuration change, so to rebuild it the build files have to be removed,
576 // which will also remove these modified files.
577 if builder.config.llvm_bolt_profile_generate {
578 instrument_with_bolt_inplace(&get_built_llvm_lib_path(&build_llvm_config));
580 if let Some(path) = &builder.config.llvm_bolt_profile_use {
581 optimize_library_with_bolt_inplace(
582 &get_built_llvm_lib_path(&build_llvm_config),
593 /// Returns path to a built LLVM library (libLLVM.so).
594 /// Assumes that we have built LLVM into a single library file.
595 fn get_built_llvm_lib_path(llvm_config_path: &Path) -> PathBuf {
596 let mut cmd = Command::new(llvm_config_path);
597 cmd.arg("--libfiles");
598 PathBuf::from(output(&mut cmd).trim())
601 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
602 if !builder.config.llvm_version_check {
606 if builder.config.dry_run {
610 let mut cmd = Command::new(llvm_config);
611 let version = output(cmd.arg("--version"));
612 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
613 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
618 panic!("\n\nbad LLVM version: {}, need >=13.0\n\n", version)
622 builder: &Builder<'_>,
623 target: TargetSelection,
624 cfg: &mut cmake::Config,
625 use_compiler_launcher: bool,
626 mut ldflags: LdFlags,
628 // Do not print installation messages for up-to-date files.
629 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
630 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
632 // Do not allow the user's value of DESTDIR to influence where
633 // LLVM will install itself. LLVM must always be installed in our
634 // own build directories.
635 cfg.env("DESTDIR", "");
638 cfg.generator("Ninja");
640 cfg.target(&target.triple).host(&builder.config.build.triple);
642 if target != builder.config.build {
643 cfg.define("CMAKE_CROSSCOMPILING", "True");
645 if target.contains("netbsd") {
646 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
647 } else if target.contains("freebsd") {
648 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
649 } else if target.contains("windows") {
650 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
651 } else if target.contains("haiku") {
652 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
653 } else if target.contains("solaris") || target.contains("illumos") {
654 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
656 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
657 // that case like CMake we cannot easily determine system version either.
659 // Since, the LLVM itself makes rather limited use of version checks in
660 // CMakeFiles (and then only in tests), and so far no issues have been
661 // reported, the system version is currently left unset.
663 if target.contains("darwin") {
664 // Make sure that CMake does not build universal binaries on macOS.
665 // Explicitly specify the one single target architecture.
666 if target.starts_with("aarch64") {
667 // macOS uses a different name for building arm64
668 cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
670 cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
675 let sanitize_cc = |cc: &Path| {
676 if target.contains("msvc") {
677 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
679 cc.as_os_str().to_owned()
683 // MSVC with CMake uses msbuild by default which doesn't respect these
684 // vars that we'd otherwise configure. In that case we just skip this
686 if target.contains("msvc") && !builder.ninja() {
690 let (cc, cxx) = match builder.config.llvm_clang_cl {
691 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
692 None => (builder.cc(target), builder.cxx(target).unwrap()),
695 // Handle msvc + ninja + ccache specially (this is what the bots use)
696 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
697 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
698 wrap_cc.set_file_name("sccache-plus-cl.exe");
700 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
701 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
702 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
703 .env("SCCACHE_TARGET", target.triple)
704 .env("SCCACHE_CC", &cc)
705 .env("SCCACHE_CXX", &cxx);
707 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
708 // off the beaten path here that I'm not really sure this is even half
709 // supported any more. Here we're trying to:
711 // * Build LLVM on MSVC
712 // * Build LLVM with `clang-cl` instead of `cl.exe`
713 // * Build a project with `sccache`
714 // * Build for 32-bit as well
715 // * Build with Ninja
717 // For `cl.exe` there are different binaries to compile 32/64 bit which
718 // we use but for `clang-cl` there's only one which internally
719 // multiplexes via flags. As a result it appears that CMake's detection
720 // of a compiler's architecture and such on MSVC **doesn't** pass any
721 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
722 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
723 // definitely causes problems since all the env vars are pointing to
726 // To hack around this... again... we pass an argument that's
727 // unconditionally passed in the sccache shim. This'll get CMake to
728 // correctly diagnose it's doing a 32-bit compilation and LLVM will
729 // internally configure itself appropriately.
730 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
731 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
734 // If ccache is configured we inform the build a little differently how
735 // to invoke ccache while also invoking our compilers.
736 if use_compiler_launcher {
737 if let Some(ref ccache) = builder.config.ccache {
738 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
739 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
742 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
743 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
744 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
747 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
748 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
749 if let Some(ref s) = builder.config.llvm_cflags {
753 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
754 if target.contains("apple-ios") {
755 if target.contains("86-") {
756 cflags.push(" -miphonesimulator-version-min=10.0");
758 cflags.push(" -miphoneos-version-min=10.0");
761 if builder.config.llvm_clang_cl.is_some() {
762 cflags.push(&format!(" --target={}", target));
764 cfg.define("CMAKE_C_FLAGS", cflags);
765 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
766 if let Some(ref s) = builder.config.llvm_cxxflags {
770 if builder.config.llvm_clang_cl.is_some() {
771 cxxflags.push(&format!(" --target={}", target));
773 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
774 if let Some(ar) = builder.ar(target) {
775 if ar.is_absolute() {
776 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
777 // tries to resolve this path in the LLVM build directory.
778 cfg.define("CMAKE_AR", sanitize_cc(ar));
782 if let Some(ranlib) = builder.ranlib(target) {
783 if ranlib.is_absolute() {
784 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
785 // tries to resolve this path in the LLVM build directory.
786 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
790 if let Some(ref flags) = builder.config.llvm_ldflags {
791 ldflags.push_all(flags);
794 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
795 ldflags.push_all(&flags);
798 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
799 // We also do this if the user explicitly requested static libstdc++.
800 if builder.config.llvm_static_stdcpp {
801 if !target.contains("msvc") && !target.contains("netbsd") && !target.contains("solaris") {
802 if target.contains("apple") || target.contains("windows") {
803 ldflags.push_all("-static-libstdc++");
805 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
810 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
811 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
812 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
814 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
815 cfg.env("RUSTC_LOG", "sccache=warn");
819 fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
820 // ThinLTO is only available when building with LLVM, enabling LLD is required.
821 // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
822 if builder.config.llvm_thin_lto {
823 cfg.define("LLVM_ENABLE_LTO", "Thin");
824 if !target.contains("apple") {
825 cfg.define("LLVM_ENABLE_LLD", "ON");
829 if let Some(ref linker) = builder.config.llvm_use_linker {
830 cfg.define("LLVM_USE_LINKER", linker);
833 if builder.config.llvm_allow_old_toolchain {
834 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
838 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
839 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
840 let kind = if host == target { "HOST" } else { "TARGET" };
841 let target_u = target.replace("-", "_");
842 env::var_os(&format!("{}_{}", var_base, target))
843 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
844 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
845 .or_else(|| env::var_os(var_base))
848 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
850 pub target: TargetSelection,
854 type Output = PathBuf;
855 const ONLY_HOSTS: bool = true;
857 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
858 run.path("src/llvm-project/lld")
861 fn make_run(run: RunConfig<'_>) {
862 run.builder.ensure(Lld { target: run.target });
865 /// Compile LLD for `target`.
866 fn run(self, builder: &Builder<'_>) -> PathBuf {
867 if builder.config.dry_run {
868 return PathBuf::from("lld-out-dir-test-gen");
870 let target = self.target;
872 let llvm_config = builder.ensure(Llvm { target: self.target });
874 let out_dir = builder.lld_out(target);
875 let done_stamp = out_dir.join("lld-finished-building");
876 if done_stamp.exists() {
880 builder.info(&format!("Building LLD for {}", target));
881 let _time = util::timeit(&builder);
882 t!(fs::create_dir_all(&out_dir));
884 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
885 let mut ldflags = LdFlags::default();
887 // When building LLD as part of a build with instrumentation on windows, for example
888 // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
889 // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
890 // linking errors, much like LLVM's cmake setup does in that situation.
891 if builder.config.llvm_profile_generate && target.contains("msvc") {
892 if let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref() {
893 // Find clang's runtime library directory and push that as a search path to the
894 // cmake linker flags.
895 let clang_rt_dir = get_clang_cl_resource_dir(clang_cl_path);
896 ldflags.push_all(&format!("/libpath:{}", clang_rt_dir.display()));
900 configure_cmake(builder, target, &mut cfg, true, ldflags);
901 configure_llvm(builder, target, &mut cfg);
903 // This is an awful, awful hack. Discovered when we migrated to using
904 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
905 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
906 // that directory for later processing. Unfortunately if this path has
907 // forward slashes in it (which it basically always does on Windows)
908 // then CMake will hit a syntax error later on as... something isn't
911 // Instead of attempting to fix this problem in upstream CMake and/or
912 // LLVM/LLD we just hack around it here. This thin wrapper will take the
913 // output from llvm-config and replace all instances of `\` with `/` to
914 // ensure we don't hit the same bugs with escaping. It means that you
915 // can't build on a system where your paths require `\` on Windows, but
916 // there's probably a lot of reasons you can't do that other than this.
917 let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
919 // Re-use the same flags as llvm to control the level of debug information
920 // generated for lld.
921 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
922 (false, _) => "Debug",
923 (true, false) => "Release",
924 (true, true) => "RelWithDebInfo",
927 cfg.out_dir(&out_dir)
929 .env("LLVM_CONFIG_REAL", &llvm_config)
930 .define("LLVM_CONFIG_PATH", llvm_config_shim)
931 .define("LLVM_INCLUDE_TESTS", "OFF");
933 // While we're using this horrible workaround to shim the execution of
934 // llvm-config, let's just pile on more. I can't seem to figure out how
935 // to build LLD as a standalone project and also cross-compile it at the
936 // same time. It wants a natively executable `llvm-config` to learn
937 // about LLVM, but then it learns about all the host configuration of
938 // LLVM and tries to link to host LLVM libraries.
940 // To work around that we tell our shim to replace anything with the
941 // build target with the actual target instead. This'll break parts of
942 // LLD though which try to execute host tools, such as llvm-tblgen, so
943 // we specifically tell it where to find those. This is likely super
944 // brittle and will break over time. If anyone knows better how to
945 // cross-compile LLD it would be much appreciated to fix this!
946 if target != builder.config.build {
947 cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
948 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
951 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
955 // Explicitly set C++ standard, because upstream doesn't do so
956 // for standalone builds.
957 cfg.define("CMAKE_CXX_STANDARD", "14");
961 t!(File::create(&done_stamp));
966 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
967 pub struct TestHelpers {
968 pub target: TargetSelection,
971 impl Step for TestHelpers {
974 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
975 run.path("src/test/auxiliary/rust_test_helpers.c")
978 fn make_run(run: RunConfig<'_>) {
979 run.builder.ensure(TestHelpers { target: run.target })
982 /// Compiles the `rust_test_helpers.c` library which we used in various
983 /// `run-pass` tests for ABI testing.
984 fn run(self, builder: &Builder<'_>) {
985 if builder.config.dry_run {
988 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
989 // toolchain. However, some x86_64 ELF objects can be linked
990 // without issues. Use this hack to compile the test helpers.
991 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
992 TargetSelection::from_user("x86_64-unknown-linux-gnu")
996 let dst = builder.test_helpers_out(target);
997 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
998 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
1002 builder.info("Building test helpers");
1003 t!(fs::create_dir_all(&dst));
1004 let mut cfg = cc::Build::new();
1005 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
1006 if target.contains("emscripten") {
1010 // We may have found various cross-compilers a little differently due to our
1011 // extra configuration, so inform cc of these compilers. Note, though, that
1012 // on MSVC we still need cc's detection of env vars (ugh).
1013 if !target.contains("msvc") {
1014 if let Some(ar) = builder.ar(target) {
1017 cfg.compiler(builder.cc(target));
1019 cfg.cargo_metadata(false)
1021 .target(&target.triple)
1022 .host(&builder.config.build.triple)
1026 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
1027 .compile("rust_test_helpers");
1031 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1032 pub struct Sanitizers {
1033 pub target: TargetSelection,
1036 impl Step for Sanitizers {
1037 type Output = Vec<SanitizerRuntime>;
1039 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1040 run.alias("sanitizers")
1043 fn make_run(run: RunConfig<'_>) {
1044 run.builder.ensure(Sanitizers { target: run.target });
1047 /// Builds sanitizer runtime libraries.
1048 fn run(self, builder: &Builder<'_>) -> Self::Output {
1049 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1050 if !compiler_rt_dir.exists() {
1054 let out_dir = builder.native_dir(self.target).join("sanitizers");
1055 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1056 if runtimes.is_empty() {
1060 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
1061 if builder.config.dry_run {
1065 let stamp = out_dir.join("sanitizers-finished-building");
1066 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
1068 if stamp.is_done() {
1069 if stamp.hash.is_none() {
1070 builder.info(&format!(
1071 "Rebuild sanitizers by removing the file `{}`",
1072 stamp.path.display()
1078 builder.info(&format!("Building sanitizers for {}", self.target));
1080 let _time = util::timeit(&builder);
1082 let mut cfg = cmake::Config::new(&compiler_rt_dir);
1083 cfg.profile("Release");
1084 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1085 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1086 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1087 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1088 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1089 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1090 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1091 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1092 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1093 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
1095 // On Darwin targets the sanitizer runtimes are build as universal binaries.
1096 // Unfortunately sccache currently lacks support to build them successfully.
1097 // Disable compiler launcher on Darwin targets to avoid potential issues.
1098 let use_compiler_launcher = !self.target.contains("apple-darwin");
1099 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
1101 t!(fs::create_dir_all(&out_dir));
1102 cfg.out_dir(out_dir);
1104 for runtime in &runtimes {
1105 cfg.build_target(&runtime.cmake_target);
1114 #[derive(Clone, Debug)]
1115 pub struct SanitizerRuntime {
1116 /// CMake target used to build the runtime.
1117 pub cmake_target: String,
1118 /// Path to the built runtime library.
1120 /// Library filename that will be used rustc.
1124 /// Returns sanitizers available on a given target.
1125 fn supported_sanitizers(
1127 target: TargetSelection,
1129 ) -> Vec<SanitizerRuntime> {
1130 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1133 .map(move |c| SanitizerRuntime {
1134 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
1136 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
1137 name: format!("librustc-{}_rt.{}.dylib", channel, c),
1142 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1145 .map(move |c| SanitizerRuntime {
1146 cmake_target: format!("clang_rt.{}-{}", c, arch),
1147 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
1148 name: format!("librustc-{}_rt.{}.a", channel, c),
1153 match &*target.triple {
1154 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1155 "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1156 "aarch64-unknown-linux-gnu" => {
1157 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1159 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1160 "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1161 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1162 "x86_64-unknown-netbsd" => {
1163 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1165 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1166 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1167 "x86_64-unknown-linux-gnu" => {
1168 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1170 "x86_64-unknown-linux-musl" => {
1171 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1179 hash: Option<Vec<u8>>,
1183 fn new(path: PathBuf, hash: Option<&str>) -> Self {
1184 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1187 fn is_done(&self) -> bool {
1188 match fs::read(&self.path) {
1189 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1190 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1192 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1197 fn remove(&self) -> io::Result<()> {
1198 match fs::remove_file(&self.path) {
1201 if e.kind() == io::ErrorKind::NotFound {
1210 fn write(&self) -> io::Result<()> {
1211 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1215 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1216 pub struct CrtBeginEnd {
1217 pub target: TargetSelection,
1220 impl Step for CrtBeginEnd {
1221 type Output = PathBuf;
1223 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1224 run.path("src/llvm-project/compiler-rt/lib/crt")
1227 fn make_run(run: RunConfig<'_>) {
1228 run.builder.ensure(CrtBeginEnd { target: run.target });
1231 /// Build crtbegin.o/crtend.o for musl target.
1232 fn run(self, builder: &Builder<'_>) -> Self::Output {
1233 let out_dir = builder.native_dir(self.target).join("crt");
1235 if builder.config.dry_run {
1239 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1240 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1241 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1242 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1247 builder.info("Building crtbegin.o and crtend.o");
1248 t!(fs::create_dir_all(&out_dir));
1250 let mut cfg = cc::Build::new();
1252 if let Some(ar) = builder.ar(self.target) {
1255 cfg.compiler(builder.cc(self.target));
1256 cfg.cargo_metadata(false)
1258 .target(&self.target.triple)
1259 .host(&builder.config.build.triple)
1266 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1267 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1268 // instead of .ctors/.dtors
1269 cfg.flag("-std=c11")
1270 .define("CRT_HAS_INITFINI_ARRAY", None)
1271 .define("EH_USE_FRAME_REGISTRY", None);
1275 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1276 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1281 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1282 pub struct Libunwind {
1283 pub target: TargetSelection,
1286 impl Step for Libunwind {
1287 type Output = PathBuf;
1289 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1290 run.path("src/llvm-project/libunwind")
1293 fn make_run(run: RunConfig<'_>) {
1294 run.builder.ensure(Libunwind { target: run.target });
1297 /// Build linunwind.a
1298 fn run(self, builder: &Builder<'_>) -> Self::Output {
1299 if builder.config.dry_run {
1300 return PathBuf::new();
1303 let out_dir = builder.native_dir(self.target).join("libunwind");
1304 let root = builder.src.join("src/llvm-project/libunwind");
1306 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1310 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1311 t!(fs::create_dir_all(&out_dir));
1313 let mut cc_cfg = cc::Build::new();
1314 let mut cpp_cfg = cc::Build::new();
1317 cpp_cfg.cpp_set_stdlib(None);
1318 cpp_cfg.flag("-nostdinc++");
1319 cpp_cfg.flag("-fno-exceptions");
1320 cpp_cfg.flag("-fno-rtti");
1321 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1323 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1324 if let Some(ar) = builder.ar(self.target) {
1327 cfg.target(&self.target.triple);
1328 cfg.host(&builder.config.build.triple);
1329 cfg.warnings(false);
1331 // get_compiler() need set opt_level first.
1333 cfg.flag("-fstrict-aliasing");
1334 cfg.flag("-funwind-tables");
1335 cfg.flag("-fvisibility=hidden");
1336 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1337 cfg.include(root.join("include"));
1338 cfg.cargo_metadata(false);
1339 cfg.out_dir(&out_dir);
1341 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1342 cfg.static_flag(true);
1343 cfg.flag("-fno-stack-protector");
1344 cfg.flag("-ffreestanding");
1345 cfg.flag("-fexceptions");
1347 // easiest way to undefine since no API available in cc::Build to undefine
1348 cfg.flag("-U_FORTIFY_SOURCE");
1349 cfg.define("_FORTIFY_SOURCE", "0");
1350 cfg.define("RUST_SGX", "1");
1351 cfg.define("__NO_STRING_INLINES", None);
1352 cfg.define("__NO_MATH_INLINES", None);
1353 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1354 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1355 cfg.define("NDEBUG", None);
1357 if self.target.contains("windows") {
1358 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1359 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1363 cc_cfg.compiler(builder.cc(self.target));
1364 if let Ok(cxx) = builder.cxx(self.target) {
1365 cpp_cfg.compiler(cxx);
1367 cc_cfg.compiler(builder.cc(self.target));
1370 // Don't set this for clang
1371 // By default, Clang builds C code in GNU C17 mode.
1372 // By default, Clang builds C++ code according to the C++98 standard,
1373 // with many C++11 features accepted as extensions.
1374 if cc_cfg.get_compiler().is_like_gnu() {
1375 cc_cfg.flag("-std=c99");
1377 if cpp_cfg.get_compiler().is_like_gnu() {
1378 cpp_cfg.flag("-std=c++11");
1381 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1382 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1383 // C++ compiler env variables on the builders.
1384 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1385 if cpp_cfg.get_compiler().is_like_gnu() {
1387 cpp_cfg.compiler(builder.cc(self.target));
1391 let mut c_sources = vec![
1393 "UnwindLevel1-gcc-ext.c",
1395 "UnwindRegistersRestore.S",
1396 "UnwindRegistersSave.S",
1399 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1400 let cpp_len = cpp_sources.len();
1402 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1403 c_sources.push("UnwindRustSgx.c");
1406 for src in c_sources {
1407 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1410 for src in &cpp_sources {
1411 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1414 cpp_cfg.compile("unwind-cpp");
1416 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1418 for entry in fs::read_dir(&out_dir).unwrap() {
1419 let file = entry.unwrap().path().canonicalize().unwrap();
1420 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1421 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1422 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1423 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1424 cc_cfg.object(&file);
1429 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1431 cc_cfg.compile("unwind");