1 //! Compilation of native dependencies like LLVM.
3 //! Native projects like LLVM unfortunately aren't suited just yet for
4 //! compilation in build scripts that Cargo has. This is because the
5 //! compilation takes a *very* long time but also because we don't want to
6 //! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
8 //! LLVM and compiler-rt are essentially just wired up to everything else to
9 //! ensure that they're always in place if needed.
12 use std::env::consts::EXE_EXTENSION;
13 use std::ffi::{OsStr, OsString};
14 use std::fs::{self, File};
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
19 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
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, is_git: bool) -> String {
120 let llvm_sha = if is_git {
121 let mut rev_list = config.git();
123 PathBuf::from("rev-list"),
124 format!("--author={}", config.stage0_metadata.config.git_merge_commit_email).into(),
126 "--first-parent".into(),
129 config.src.join("src/llvm-project"),
130 config.src.join("src/bootstrap/download-ci-llvm-stamp"),
131 // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
132 config.src.join("src/version"),
134 output(&mut rev_list).trim().to_owned()
135 } else if let Some(info) = channel::read_commit_info_file(&config.src) {
136 info.sha.trim().to_owned()
142 eprintln!("error: could not find commit hash for downloading LLVM");
143 eprintln!("help: maybe your repository history is too shallow?");
144 eprintln!("help: consider disabling `download-ci-llvm`");
145 eprintln!("help: or fetch enough history to include one upstream commit");
152 /// Returns whether the CI-found LLVM is currently usable.
154 /// This checks both the build triple platform to confirm we're usable at all,
155 /// and then verifies if the current HEAD matches the detected LLVM SHA head,
156 /// in which case LLVM is indicated as not available.
157 pub(crate) fn is_ci_llvm_available(config: &crate::config::Config, asserts: bool) -> bool {
158 // This is currently all tier 1 targets and tier 2 targets with host tools
159 // (since others may not have CI artifacts)
160 // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
161 let supported_platforms = [
163 "aarch64-unknown-linux-gnu",
164 "i686-pc-windows-gnu",
165 "i686-pc-windows-msvc",
166 "i686-unknown-linux-gnu",
167 "x86_64-unknown-linux-gnu",
168 "x86_64-apple-darwin",
169 "x86_64-pc-windows-gnu",
170 "x86_64-pc-windows-msvc",
171 // tier 2 with host tools
172 "aarch64-apple-darwin",
173 "aarch64-pc-windows-msvc",
174 "aarch64-unknown-linux-musl",
175 "arm-unknown-linux-gnueabi",
176 "arm-unknown-linux-gnueabihf",
177 "armv7-unknown-linux-gnueabihf",
178 "mips-unknown-linux-gnu",
179 "mips64-unknown-linux-gnuabi64",
180 "mips64el-unknown-linux-gnuabi64",
181 "mipsel-unknown-linux-gnu",
182 "powerpc-unknown-linux-gnu",
183 "powerpc64-unknown-linux-gnu",
184 "powerpc64le-unknown-linux-gnu",
185 "riscv64gc-unknown-linux-gnu",
186 "s390x-unknown-linux-gnu",
187 "x86_64-unknown-freebsd",
188 "x86_64-unknown-illumos",
189 "x86_64-unknown-linux-musl",
190 "x86_64-unknown-netbsd",
192 if !supported_platforms.contains(&&*config.build.triple) {
196 let triple = &*config.build.triple;
197 if (triple == "aarch64-unknown-linux-gnu" || triple.contains("i686")) && asserts {
198 // No alt builder for aarch64-unknown-linux-gnu today.
202 if crate::util::CiEnv::is_ci() {
203 // We assume we have access to git, so it's okay to unconditionally pass
205 let llvm_sha = detect_llvm_sha(config, true);
206 let head_sha = output(config.git().arg("rev-parse").arg("HEAD"));
207 let head_sha = head_sha.trim();
208 if llvm_sha == head_sha {
210 "Detected LLVM as non-available: running in CI and modified LLVM in this change"
219 pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) {
220 let config = &builder.config;
221 if !config.llvm_from_ci {
224 let llvm_root = config.ci_llvm_root();
225 let llvm_stamp = llvm_root.join(".llvm-stamp");
226 let llvm_sha = detect_llvm_sha(&config, builder.rust_info.is_managed_git_subrepository());
227 let key = format!("{}{}", llvm_sha, config.llvm_assertions);
228 if program_out_of_date(&llvm_stamp, &key) && !config.dry_run {
229 download_ci_llvm(builder, &llvm_sha);
230 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
231 builder.fix_bin_or_dylib(&t!(entry).path());
234 // Update the timestamp of llvm-config to force rustc_llvm to be
235 // rebuilt. This is a hacky workaround for a deficiency in Cargo where
236 // the rerun-if-changed directive doesn't handle changes very well.
237 // https://github.com/rust-lang/cargo/issues/10791
238 // Cargo only compares the timestamp of the file relative to the last
239 // time `rustc_llvm` build script ran. However, the timestamps of the
240 // files in the tarball are in the past, so it doesn't trigger a
242 let now = filetime::FileTime::from_system_time(std::time::SystemTime::now());
243 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", builder.config.build));
244 t!(filetime::set_file_times(&llvm_config, now, now));
246 let llvm_lib = llvm_root.join("lib");
247 for entry in t!(fs::read_dir(&llvm_lib)) {
248 let lib = t!(entry).path();
249 if lib.extension().map_or(false, |ext| ext == "so") {
250 builder.fix_bin_or_dylib(&lib);
253 t!(fs::write(llvm_stamp, key));
257 fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) {
258 let llvm_assertions = builder.config.llvm_assertions;
260 let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
261 let cache_dst = builder.out.join("cache");
262 let rustc_cache = cache_dst.join(cache_prefix);
263 if !rustc_cache.exists() {
264 t!(fs::create_dir_all(&rustc_cache));
266 let base = if llvm_assertions {
267 &builder.config.stage0_metadata.config.artifacts_with_llvm_assertions_server
269 &builder.config.stage0_metadata.config.artifacts_server
271 let channel = builder.config.artifact_channel(builder, llvm_sha);
272 let filename = format!("rust-dev-{}-{}.tar.xz", channel, builder.build.build.triple);
273 let tarball = rustc_cache.join(&filename);
274 if !tarball.exists() {
275 let help_on_error = "error: failed to download llvm from ci
277 help: old builds get deleted after a certain time
278 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
281 download-ci-llvm = false
283 builder.download_component(
284 &format!("{base}/{llvm_sha}/{filename}"),
289 let llvm_root = builder.config.ci_llvm_root();
290 builder.unpack(&tarball, &llvm_root, "rust-dev");
293 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
295 pub target: TargetSelection,
299 type Output = PathBuf; // path to llvm-config
301 const ONLY_HOSTS: bool = true;
303 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
304 run.path("src/llvm-project").path("src/llvm-project/llvm")
307 fn make_run(run: RunConfig<'_>) {
308 run.builder.ensure(Llvm { target: run.target });
311 /// Compile LLVM for `target`.
312 fn run(self, builder: &Builder<'_>) -> PathBuf {
313 let target = self.target;
314 let target_native = if self.target.starts_with("riscv") {
315 // RISC-V target triples in Rust is not named the same as C compiler target triples.
316 // This converts Rust RISC-V target triples to C compiler triples.
317 let idx = target.triple.find('-').unwrap();
319 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
320 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
321 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
322 // Set the version suffix to 13.0 so the correct target details are used.
323 format!("{}{}", self.target, "13.0")
328 let Meta { stamp, build_llvm_config, out_dir, root } =
329 match prebuilt_llvm_config(builder, target) {
334 builder.update_submodule(&Path::new("src").join("llvm-project"));
335 if builder.llvm_link_shared() && target.contains("windows") {
336 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
339 builder.info(&format!("Building LLVM for {}", target));
341 let _time = util::timeit(&builder);
342 t!(fs::create_dir_all(&out_dir));
344 // https://llvm.org/docs/CMake.html
345 let mut cfg = cmake::Config::new(builder.src.join(root));
346 let mut ldflags = LdFlags::default();
348 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
349 (false, _) => "Debug",
350 (true, false) => "Release",
351 (true, true) => "RelWithDebInfo",
354 // NOTE: remember to also update `config.toml.example` when changing the
356 let llvm_targets = match &builder.config.llvm_targets {
359 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
360 Sparc;SystemZ;WebAssembly;X86"
364 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
369 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
370 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
371 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
373 cfg.out_dir(&out_dir)
375 .define("LLVM_ENABLE_ASSERTIONS", assertions)
376 .define("LLVM_ENABLE_PLUGINS", plugins)
377 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
378 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
379 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
380 .define("LLVM_INCLUDE_DOCS", "OFF")
381 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
382 .define("LLVM_INCLUDE_TESTS", enable_tests)
383 .define("LLVM_ENABLE_TERMINFO", "OFF")
384 .define("LLVM_ENABLE_LIBEDIT", "OFF")
385 .define("LLVM_ENABLE_BINDINGS", "OFF")
386 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
387 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
388 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
389 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
391 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
392 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
393 // This flag makes sure `FileCheck` is copied in the final binaries directory.
394 cfg.define("LLVM_INSTALL_UTILS", "ON");
396 if builder.config.llvm_profile_generate {
397 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
398 if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
399 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
401 cfg.define("LLVM_BUILD_RUNTIME", "No");
403 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
404 cfg.define("LLVM_PROFDATA_FILE", &path);
407 // Disable zstd to avoid a dependency on libzstd.so.
408 cfg.define("LLVM_ENABLE_ZSTD", "OFF");
410 if target != "aarch64-apple-darwin" && !target.contains("windows") {
411 cfg.define("LLVM_ENABLE_ZLIB", "ON");
413 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
416 // Are we compiling for iOS/tvOS/watchOS?
417 if target.contains("apple-ios")
418 || target.contains("apple-tvos")
419 || target.contains("apple-watchos")
421 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
422 cfg.define("CMAKE_OSX_SYSROOT", "/");
423 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
424 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
425 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
426 // Zlib fails to link properly, leading to a compiler error.
427 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
430 // This setting makes the LLVM tools link to the dynamic LLVM library,
431 // which saves both memory during parallel links and overall disk space
432 // for the tools. We don't do this on every platform as it doesn't work
433 // equally well everywhere.
434 if builder.llvm_link_shared() {
435 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
438 if target.starts_with("riscv") && !target.contains("freebsd") && !target.contains("openbsd")
440 // RISC-V GCC erroneously requires linking against
441 // `libatomic` when using 1-byte and 2-byte C++
442 // atomics but the LLVM build system check cannot
443 // detect this. Therefore it is set manually here.
444 // Some BSD uses Clang as its system compiler and
445 // provides no libatomic in its base system so does
447 ldflags.exe.push(" -latomic");
448 ldflags.shared.push(" -latomic");
451 if target.contains("msvc") {
452 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
453 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
454 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
455 cfg.static_crt(true);
458 if target.starts_with("i686") {
459 cfg.define("LLVM_BUILD_32_BITS", "ON");
462 let mut enabled_llvm_projects = Vec::new();
464 if util::forcing_clang_based_tests() {
465 enabled_llvm_projects.push("clang");
466 enabled_llvm_projects.push("compiler-rt");
469 if builder.config.llvm_polly {
470 enabled_llvm_projects.push("polly");
473 if builder.config.llvm_clang {
474 enabled_llvm_projects.push("clang");
477 // We want libxml to be disabled.
478 // See https://github.com/rust-lang/rust/pull/50104
479 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
481 if !enabled_llvm_projects.is_empty() {
482 enabled_llvm_projects.sort();
483 enabled_llvm_projects.dedup();
484 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
487 if let Some(num_linkers) = builder.config.llvm_link_jobs {
489 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
493 // Workaround for ppc32 lld limitation
494 if target == "powerpc-unknown-freebsd" {
495 ldflags.exe.push(" -fuse-ld=bfd");
498 // https://llvm.org/docs/HowToCrossCompileLLVM.html
499 if target != builder.config.build {
500 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
501 if !builder.config.dry_run {
502 let llvm_bindir = output(Command::new(&llvm_config).arg("--bindir"));
503 let host_bin = Path::new(llvm_bindir.trim());
506 host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
508 // LLVM_NM is required for cross compiling using MSVC
509 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
511 cfg.define("LLVM_CONFIG_PATH", llvm_config);
512 if builder.config.llvm_clang {
513 let build_bin = builder.llvm_out(builder.config.build).join("build").join("bin");
514 let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
515 if !builder.config.dry_run && !clang_tblgen.exists() {
516 panic!("unable to find {}", clang_tblgen.display());
518 cfg.define("CLANG_TABLEGEN", clang_tblgen);
522 let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
523 // Allow version-suffix="" to not define a version suffix at all.
524 if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
525 } else if builder.config.channel == "dev" {
526 // Changes to a version suffix require a complete rebuild of the LLVM.
527 // To avoid rebuilds during a time of version bump, don't include rustc
528 // release number on the dev channel.
529 Some("-rust-dev".to_string())
531 Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
533 if let Some(ref suffix) = llvm_version_suffix {
534 cfg.define("LLVM_VERSION_SUFFIX", suffix);
537 configure_cmake(builder, target, &mut cfg, true, ldflags);
538 configure_llvm(builder, target, &mut cfg);
540 for (key, val) in &builder.config.llvm_build_config {
541 cfg.define(key, val);
544 // FIXME: we don't actually need to build all LLVM tools and all LLVM
545 // libraries here, e.g., we just want a few components and a few
546 // tools. Figure out how to filter them down and only build the right
547 // tools and libs on all platforms.
549 if builder.config.dry_run {
550 return build_llvm_config;
555 // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
556 // libLLVM.dylib will be built. However, llvm-config will still look
557 // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
558 // link to make llvm-config happy.
559 if builder.llvm_link_shared() && target.contains("apple-darwin") {
560 let mut cmd = Command::new(&build_llvm_config);
561 let version = output(cmd.arg("--version"));
562 let major = version.split('.').next().unwrap();
563 let lib_name = match llvm_version_suffix {
564 Some(s) => format!("libLLVM-{}{}.dylib", major, s),
565 None => format!("libLLVM-{}.dylib", major),
568 let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
569 if !lib_llvm.exists() {
570 t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
580 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
581 if !builder.config.llvm_version_check {
585 if builder.config.dry_run {
589 let mut cmd = Command::new(llvm_config);
590 let version = output(cmd.arg("--version"));
591 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
592 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
597 panic!("\n\nbad LLVM version: {}, need >=13.0\n\n", version)
601 builder: &Builder<'_>,
602 target: TargetSelection,
603 cfg: &mut cmake::Config,
604 use_compiler_launcher: bool,
605 mut ldflags: LdFlags,
607 // Do not print installation messages for up-to-date files.
608 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
609 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
611 // Do not allow the user's value of DESTDIR to influence where
612 // LLVM will install itself. LLVM must always be installed in our
613 // own build directories.
614 cfg.env("DESTDIR", "");
617 cfg.generator("Ninja");
619 cfg.target(&target.triple).host(&builder.config.build.triple);
621 if target != builder.config.build {
622 cfg.define("CMAKE_CROSSCOMPILING", "True");
624 if target.contains("netbsd") {
625 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
626 } else if target.contains("freebsd") {
627 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
628 } else if target.contains("windows") {
629 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
630 } else if target.contains("haiku") {
631 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
632 } else if target.contains("solaris") || target.contains("illumos") {
633 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
635 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
636 // that case like CMake we cannot easily determine system version either.
638 // Since, the LLVM itself makes rather limited use of version checks in
639 // CMakeFiles (and then only in tests), and so far no issues have been
640 // reported, the system version is currently left unset.
642 if target.contains("darwin") {
643 // Make sure that CMake does not build universal binaries on macOS.
644 // Explicitly specify the one single target architecture.
645 if target.starts_with("aarch64") {
646 // macOS uses a different name for building arm64
647 cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
649 cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
654 let sanitize_cc = |cc: &Path| {
655 if target.contains("msvc") {
656 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
658 cc.as_os_str().to_owned()
662 // MSVC with CMake uses msbuild by default which doesn't respect these
663 // vars that we'd otherwise configure. In that case we just skip this
665 if target.contains("msvc") && !builder.ninja() {
669 let (cc, cxx) = match builder.config.llvm_clang_cl {
670 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
671 None => (builder.cc(target), builder.cxx(target).unwrap()),
674 // Handle msvc + ninja + ccache specially (this is what the bots use)
675 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
676 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
677 wrap_cc.set_file_name("sccache-plus-cl.exe");
679 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
680 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
681 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
682 .env("SCCACHE_TARGET", target.triple)
683 .env("SCCACHE_CC", &cc)
684 .env("SCCACHE_CXX", &cxx);
686 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
687 // off the beaten path here that I'm not really sure this is even half
688 // supported any more. Here we're trying to:
690 // * Build LLVM on MSVC
691 // * Build LLVM with `clang-cl` instead of `cl.exe`
692 // * Build a project with `sccache`
693 // * Build for 32-bit as well
694 // * Build with Ninja
696 // For `cl.exe` there are different binaries to compile 32/64 bit which
697 // we use but for `clang-cl` there's only one which internally
698 // multiplexes via flags. As a result it appears that CMake's detection
699 // of a compiler's architecture and such on MSVC **doesn't** pass any
700 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
701 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
702 // definitely causes problems since all the env vars are pointing to
705 // To hack around this... again... we pass an argument that's
706 // unconditionally passed in the sccache shim. This'll get CMake to
707 // correctly diagnose it's doing a 32-bit compilation and LLVM will
708 // internally configure itself appropriately.
709 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
710 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
713 // If ccache is configured we inform the build a little differently how
714 // to invoke ccache while also invoking our compilers.
715 if use_compiler_launcher {
716 if let Some(ref ccache) = builder.config.ccache {
717 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
718 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
721 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
722 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
723 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
726 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
727 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
728 if let Some(ref s) = builder.config.llvm_cflags {
732 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
733 if target.contains("apple-ios") {
734 if target.contains("86-") {
735 cflags.push(" -miphonesimulator-version-min=10.0");
737 cflags.push(" -miphoneos-version-min=10.0");
740 if builder.config.llvm_clang_cl.is_some() {
741 cflags.push(&format!(" --target={}", target));
743 cfg.define("CMAKE_C_FLAGS", cflags);
744 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
745 if let Some(ref s) = builder.config.llvm_cxxflags {
749 if builder.config.llvm_clang_cl.is_some() {
750 cxxflags.push(&format!(" --target={}", target));
752 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
753 if let Some(ar) = builder.ar(target) {
754 if ar.is_absolute() {
755 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
756 // tries to resolve this path in the LLVM build directory.
757 cfg.define("CMAKE_AR", sanitize_cc(ar));
761 if let Some(ranlib) = builder.ranlib(target) {
762 if ranlib.is_absolute() {
763 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
764 // tries to resolve this path in the LLVM build directory.
765 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
769 if let Some(ref flags) = builder.config.llvm_ldflags {
770 ldflags.push_all(flags);
773 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
774 ldflags.push_all(&flags);
777 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
778 // We also do this if the user explicitly requested static libstdc++.
779 if builder.config.llvm_static_stdcpp {
780 if !target.contains("msvc") && !target.contains("netbsd") && !target.contains("solaris") {
781 if target.contains("apple") || target.contains("windows") {
782 ldflags.push_all("-static-libstdc++");
784 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
789 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
790 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
791 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
793 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
794 cfg.env("RUSTC_LOG", "sccache=warn");
798 fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
799 // ThinLTO is only available when building with LLVM, enabling LLD is required.
800 // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
801 if builder.config.llvm_thin_lto {
802 cfg.define("LLVM_ENABLE_LTO", "Thin");
803 if !target.contains("apple") {
804 cfg.define("LLVM_ENABLE_LLD", "ON");
808 if let Some(ref linker) = builder.config.llvm_use_linker {
809 cfg.define("LLVM_USE_LINKER", linker);
812 if builder.config.llvm_allow_old_toolchain {
813 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
817 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
818 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
819 let kind = if host == target { "HOST" } else { "TARGET" };
820 let target_u = target.replace("-", "_");
821 env::var_os(&format!("{}_{}", var_base, target))
822 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
823 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
824 .or_else(|| env::var_os(var_base))
827 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
829 pub target: TargetSelection,
833 type Output = PathBuf;
834 const ONLY_HOSTS: bool = true;
836 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
837 run.path("src/llvm-project/lld")
840 fn make_run(run: RunConfig<'_>) {
841 run.builder.ensure(Lld { target: run.target });
844 /// Compile LLD for `target`.
845 fn run(self, builder: &Builder<'_>) -> PathBuf {
846 if builder.config.dry_run {
847 return PathBuf::from("lld-out-dir-test-gen");
849 let target = self.target;
851 let llvm_config = builder.ensure(Llvm { target: self.target });
853 let out_dir = builder.lld_out(target);
854 let done_stamp = out_dir.join("lld-finished-building");
855 if done_stamp.exists() {
859 builder.info(&format!("Building LLD for {}", target));
860 let _time = util::timeit(&builder);
861 t!(fs::create_dir_all(&out_dir));
863 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
864 let mut ldflags = LdFlags::default();
866 // When building LLD as part of a build with instrumentation on windows, for example
867 // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
868 // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
869 // linking errors, much like LLVM's cmake setup does in that situation.
870 if builder.config.llvm_profile_generate && target.contains("msvc") {
871 if let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref() {
872 // Find clang's runtime library directory and push that as a search path to the
873 // cmake linker flags.
874 let clang_rt_dir = get_clang_cl_resource_dir(clang_cl_path);
875 ldflags.push_all(&format!("/libpath:{}", clang_rt_dir.display()));
879 configure_cmake(builder, target, &mut cfg, true, ldflags);
880 configure_llvm(builder, target, &mut cfg);
882 // This is an awful, awful hack. Discovered when we migrated to using
883 // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
884 // tree, will execute `llvm-config --cmakedir` and then tell CMake about
885 // that directory for later processing. Unfortunately if this path has
886 // forward slashes in it (which it basically always does on Windows)
887 // then CMake will hit a syntax error later on as... something isn't
890 // Instead of attempting to fix this problem in upstream CMake and/or
891 // LLVM/LLD we just hack around it here. This thin wrapper will take the
892 // output from llvm-config and replace all instances of `\` with `/` to
893 // ensure we don't hit the same bugs with escaping. It means that you
894 // can't build on a system where your paths require `\` on Windows, but
895 // there's probably a lot of reasons you can't do that other than this.
896 let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
898 // Re-use the same flags as llvm to control the level of debug information
899 // generated for lld.
900 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
901 (false, _) => "Debug",
902 (true, false) => "Release",
903 (true, true) => "RelWithDebInfo",
906 cfg.out_dir(&out_dir)
908 .env("LLVM_CONFIG_REAL", &llvm_config)
909 .define("LLVM_CONFIG_PATH", llvm_config_shim)
910 .define("LLVM_INCLUDE_TESTS", "OFF");
912 // While we're using this horrible workaround to shim the execution of
913 // llvm-config, let's just pile on more. I can't seem to figure out how
914 // to build LLD as a standalone project and also cross-compile it at the
915 // same time. It wants a natively executable `llvm-config` to learn
916 // about LLVM, but then it learns about all the host configuration of
917 // LLVM and tries to link to host LLVM libraries.
919 // To work around that we tell our shim to replace anything with the
920 // build target with the actual target instead. This'll break parts of
921 // LLD though which try to execute host tools, such as llvm-tblgen, so
922 // we specifically tell it where to find those. This is likely super
923 // brittle and will break over time. If anyone knows better how to
924 // cross-compile LLD it would be much appreciated to fix this!
925 if target != builder.config.build {
926 cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
927 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
930 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
934 // Explicitly set C++ standard, because upstream doesn't do so
935 // for standalone builds.
936 cfg.define("CMAKE_CXX_STANDARD", "14");
940 t!(File::create(&done_stamp));
945 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
946 pub struct TestHelpers {
947 pub target: TargetSelection,
950 impl Step for TestHelpers {
953 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
954 run.path("src/test/auxiliary/rust_test_helpers.c")
957 fn make_run(run: RunConfig<'_>) {
958 run.builder.ensure(TestHelpers { target: run.target })
961 /// Compiles the `rust_test_helpers.c` library which we used in various
962 /// `run-pass` tests for ABI testing.
963 fn run(self, builder: &Builder<'_>) {
964 if builder.config.dry_run {
967 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
968 // toolchain. However, some x86_64 ELF objects can be linked
969 // without issues. Use this hack to compile the test helpers.
970 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
971 TargetSelection::from_user("x86_64-unknown-linux-gnu")
975 let dst = builder.test_helpers_out(target);
976 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
977 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
981 builder.info("Building test helpers");
982 t!(fs::create_dir_all(&dst));
983 let mut cfg = cc::Build::new();
984 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
985 if target.contains("emscripten") {
989 // We may have found various cross-compilers a little differently due to our
990 // extra configuration, so inform cc of these compilers. Note, though, that
991 // on MSVC we still need cc's detection of env vars (ugh).
992 if !target.contains("msvc") {
993 if let Some(ar) = builder.ar(target) {
996 cfg.compiler(builder.cc(target));
998 cfg.cargo_metadata(false)
1000 .target(&target.triple)
1001 .host(&builder.config.build.triple)
1005 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
1006 .compile("rust_test_helpers");
1010 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1011 pub struct Sanitizers {
1012 pub target: TargetSelection,
1015 impl Step for Sanitizers {
1016 type Output = Vec<SanitizerRuntime>;
1018 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1019 run.alias("sanitizers")
1022 fn make_run(run: RunConfig<'_>) {
1023 run.builder.ensure(Sanitizers { target: run.target });
1026 /// Builds sanitizer runtime libraries.
1027 fn run(self, builder: &Builder<'_>) -> Self::Output {
1028 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1029 if !compiler_rt_dir.exists() {
1033 let out_dir = builder.native_dir(self.target).join("sanitizers");
1034 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1035 if runtimes.is_empty() {
1039 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
1040 if builder.config.dry_run {
1044 let stamp = out_dir.join("sanitizers-finished-building");
1045 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
1047 if stamp.is_done() {
1048 if stamp.hash.is_none() {
1049 builder.info(&format!(
1050 "Rebuild sanitizers by removing the file `{}`",
1051 stamp.path.display()
1057 builder.info(&format!("Building sanitizers for {}", self.target));
1059 let _time = util::timeit(&builder);
1061 let mut cfg = cmake::Config::new(&compiler_rt_dir);
1062 cfg.profile("Release");
1063 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1064 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1065 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1066 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1067 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1068 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1069 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1070 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1071 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1072 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
1074 // On Darwin targets the sanitizer runtimes are build as universal binaries.
1075 // Unfortunately sccache currently lacks support to build them successfully.
1076 // Disable compiler launcher on Darwin targets to avoid potential issues.
1077 let use_compiler_launcher = !self.target.contains("apple-darwin");
1078 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
1080 t!(fs::create_dir_all(&out_dir));
1081 cfg.out_dir(out_dir);
1083 for runtime in &runtimes {
1084 cfg.build_target(&runtime.cmake_target);
1093 #[derive(Clone, Debug)]
1094 pub struct SanitizerRuntime {
1095 /// CMake target used to build the runtime.
1096 pub cmake_target: String,
1097 /// Path to the built runtime library.
1099 /// Library filename that will be used rustc.
1103 /// Returns sanitizers available on a given target.
1104 fn supported_sanitizers(
1106 target: TargetSelection,
1108 ) -> Vec<SanitizerRuntime> {
1109 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1112 .map(move |c| SanitizerRuntime {
1113 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
1115 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
1116 name: format!("librustc-{}_rt.{}.dylib", channel, c),
1121 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1124 .map(move |c| SanitizerRuntime {
1125 cmake_target: format!("clang_rt.{}-{}", c, arch),
1126 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
1127 name: format!("librustc-{}_rt.{}.a", channel, c),
1132 match &*target.triple {
1133 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1134 "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1135 "aarch64-unknown-linux-gnu" => {
1136 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1138 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1139 "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1140 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1141 "x86_64-unknown-netbsd" => {
1142 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1144 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1145 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1146 "x86_64-unknown-linux-gnu" => {
1147 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1149 "x86_64-unknown-linux-musl" => {
1150 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1158 hash: Option<Vec<u8>>,
1162 fn new(path: PathBuf, hash: Option<&str>) -> Self {
1163 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1166 fn is_done(&self) -> bool {
1167 match fs::read(&self.path) {
1168 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1169 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1171 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1176 fn remove(&self) -> io::Result<()> {
1177 match fs::remove_file(&self.path) {
1180 if e.kind() == io::ErrorKind::NotFound {
1189 fn write(&self) -> io::Result<()> {
1190 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1194 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1195 pub struct CrtBeginEnd {
1196 pub target: TargetSelection,
1199 impl Step for CrtBeginEnd {
1200 type Output = PathBuf;
1202 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1203 run.path("src/llvm-project/compiler-rt/lib/crt")
1206 fn make_run(run: RunConfig<'_>) {
1207 run.builder.ensure(CrtBeginEnd { target: run.target });
1210 /// Build crtbegin.o/crtend.o for musl target.
1211 fn run(self, builder: &Builder<'_>) -> Self::Output {
1212 let out_dir = builder.native_dir(self.target).join("crt");
1214 if builder.config.dry_run {
1218 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1219 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1220 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1221 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1226 builder.info("Building crtbegin.o and crtend.o");
1227 t!(fs::create_dir_all(&out_dir));
1229 let mut cfg = cc::Build::new();
1231 if let Some(ar) = builder.ar(self.target) {
1234 cfg.compiler(builder.cc(self.target));
1235 cfg.cargo_metadata(false)
1237 .target(&self.target.triple)
1238 .host(&builder.config.build.triple)
1245 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1246 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1247 // instead of .ctors/.dtors
1248 cfg.flag("-std=c11")
1249 .define("CRT_HAS_INITFINI_ARRAY", None)
1250 .define("EH_USE_FRAME_REGISTRY", None);
1254 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1255 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1260 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1261 pub struct Libunwind {
1262 pub target: TargetSelection,
1265 impl Step for Libunwind {
1266 type Output = PathBuf;
1268 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1269 run.path("src/llvm-project/libunwind")
1272 fn make_run(run: RunConfig<'_>) {
1273 run.builder.ensure(Libunwind { target: run.target });
1276 /// Build linunwind.a
1277 fn run(self, builder: &Builder<'_>) -> Self::Output {
1278 if builder.config.dry_run {
1279 return PathBuf::new();
1282 let out_dir = builder.native_dir(self.target).join("libunwind");
1283 let root = builder.src.join("src/llvm-project/libunwind");
1285 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1289 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1290 t!(fs::create_dir_all(&out_dir));
1292 let mut cc_cfg = cc::Build::new();
1293 let mut cpp_cfg = cc::Build::new();
1296 cpp_cfg.cpp_set_stdlib(None);
1297 cpp_cfg.flag("-nostdinc++");
1298 cpp_cfg.flag("-fno-exceptions");
1299 cpp_cfg.flag("-fno-rtti");
1300 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1302 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1303 if let Some(ar) = builder.ar(self.target) {
1306 cfg.target(&self.target.triple);
1307 cfg.host(&builder.config.build.triple);
1308 cfg.warnings(false);
1310 // get_compiler() need set opt_level first.
1312 cfg.flag("-fstrict-aliasing");
1313 cfg.flag("-funwind-tables");
1314 cfg.flag("-fvisibility=hidden");
1315 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1316 cfg.include(root.join("include"));
1317 cfg.cargo_metadata(false);
1318 cfg.out_dir(&out_dir);
1320 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1321 cfg.static_flag(true);
1322 cfg.flag("-fno-stack-protector");
1323 cfg.flag("-ffreestanding");
1324 cfg.flag("-fexceptions");
1326 // easiest way to undefine since no API available in cc::Build to undefine
1327 cfg.flag("-U_FORTIFY_SOURCE");
1328 cfg.define("_FORTIFY_SOURCE", "0");
1329 cfg.define("RUST_SGX", "1");
1330 cfg.define("__NO_STRING_INLINES", None);
1331 cfg.define("__NO_MATH_INLINES", None);
1332 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1333 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1334 cfg.define("NDEBUG", None);
1336 if self.target.contains("windows") {
1337 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1338 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1342 cc_cfg.compiler(builder.cc(self.target));
1343 if let Ok(cxx) = builder.cxx(self.target) {
1344 cpp_cfg.compiler(cxx);
1346 cc_cfg.compiler(builder.cc(self.target));
1349 // Don't set this for clang
1350 // By default, Clang builds C code in GNU C17 mode.
1351 // By default, Clang builds C++ code according to the C++98 standard,
1352 // with many C++11 features accepted as extensions.
1353 if cc_cfg.get_compiler().is_like_gnu() {
1354 cc_cfg.flag("-std=c99");
1356 if cpp_cfg.get_compiler().is_like_gnu() {
1357 cpp_cfg.flag("-std=c++11");
1360 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1361 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1362 // C++ compiler env variables on the builders.
1363 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1364 if cpp_cfg.get_compiler().is_like_gnu() {
1366 cpp_cfg.compiler(builder.cc(self.target));
1370 let mut c_sources = vec![
1372 "UnwindLevel1-gcc-ext.c",
1374 "UnwindRegistersRestore.S",
1375 "UnwindRegistersSave.S",
1378 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1379 let cpp_len = cpp_sources.len();
1381 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1382 c_sources.push("UnwindRustSgx.c");
1385 for src in c_sources {
1386 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1389 for src in &cpp_sources {
1390 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1393 cpp_cfg.compile("unwind-cpp");
1395 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1397 for entry in fs::read_dir(&out_dir).unwrap() {
1398 let file = entry.unwrap().path().canonicalize().unwrap();
1399 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1400 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1401 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1402 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1403 cc_cfg.object(&file);
1408 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1410 cc_cfg.compile("unwind");