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};
22 use crate::config::{Config, TargetSelection};
23 use crate::util::get_clang_cl_resource_dir;
24 use crate::util::{self, exe, output, t, up_to_date};
25 use crate::{CLang, GitRepo};
27 use build_helper::ci::CiEnv;
30 pub struct LlvmResult {
31 /// Path to llvm-config binary.
32 /// NB: This is always the host llvm-config!
33 pub llvm_config: PathBuf,
34 /// Path to LLVM cmake directory for the target.
35 pub llvm_cmake_dir: PathBuf,
45 // Linker flags to pass to LLVM's CMake invocation.
46 #[derive(Debug, Clone, Default)]
48 // CMAKE_EXE_LINKER_FLAGS
50 // CMAKE_SHARED_LINKER_FLAGS
52 // CMAKE_MODULE_LINKER_FLAGS
57 fn push_all(&mut self, s: impl AsRef<OsStr>) {
61 self.shared.push(" ");
63 self.module.push(" ");
68 /// This returns whether we've already previously built LLVM.
70 /// It's used to avoid busting caches during x.py check -- if we've already built
71 /// LLVM, it's fine for us to not try to avoid doing so.
73 /// This will return the llvm-config if it can get it (but it will not build it
75 pub fn prebuilt_llvm_config(
76 builder: &Builder<'_>,
77 target: TargetSelection,
78 ) -> Result<LlvmResult, Meta> {
79 builder.config.maybe_download_ci_llvm();
81 // If we're using a custom LLVM bail out here, but we can only use a
82 // custom LLVM for the build triple.
83 if let Some(config) = builder.config.target_config.get(&target) {
84 if let Some(ref s) = config.llvm_config {
85 check_llvm_version(builder, s);
86 let llvm_config = s.to_path_buf();
87 let mut llvm_cmake_dir = llvm_config.clone();
90 llvm_cmake_dir.push("lib");
91 llvm_cmake_dir.push("cmake");
92 llvm_cmake_dir.push("llvm");
93 return Ok(LlvmResult { llvm_config, llvm_cmake_dir });
97 let root = "src/llvm-project/llvm";
98 let out_dir = builder.llvm_out(target);
100 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
101 if !builder.config.build.contains("msvc") || builder.ninja() {
102 llvm_config_ret_dir.push("build");
104 llvm_config_ret_dir.push("bin");
105 let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
106 let llvm_cmake_dir = out_dir.join("lib/cmake/llvm");
107 let res = LlvmResult { llvm_config: build_llvm_config, llvm_cmake_dir };
109 let stamp = out_dir.join("llvm-finished-building");
110 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
112 if builder.config.llvm_skip_rebuild && stamp.path.exists() {
115 Using a potentially stale build of LLVM; \
116 This may not behave well.",
122 if stamp.hash.is_none() {
124 "Could not determine the LLVM submodule commit hash. \
125 Assuming that an LLVM rebuild is not necessary.",
127 builder.info(&format!(
128 "To force LLVM to rebuild, remove the file `{}`",
135 Err(Meta { stamp, res, out_dir, root: root.into() })
138 /// This retrieves the LLVM sha we *want* to use, according to git history.
139 pub(crate) fn detect_llvm_sha(config: &Config, is_git: bool) -> String {
140 let llvm_sha = if is_git {
141 let mut rev_list = config.git();
143 PathBuf::from("rev-list"),
144 format!("--author={}", config.stage0_metadata.config.git_merge_commit_email).into(),
146 "--first-parent".into(),
149 config.src.join("src/llvm-project"),
150 config.src.join("src/bootstrap/download-ci-llvm-stamp"),
151 // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
152 config.src.join("src/version"),
154 output(&mut rev_list).trim().to_owned()
155 } else if let Some(info) = channel::read_commit_info_file(&config.src) {
156 info.sha.trim().to_owned()
162 eprintln!("error: could not find commit hash for downloading LLVM");
163 eprintln!("help: maybe your repository history is too shallow?");
164 eprintln!("help: consider disabling `download-ci-llvm`");
165 eprintln!("help: or fetch enough history to include one upstream commit");
172 /// Returns whether the CI-found LLVM is currently usable.
174 /// This checks both the build triple platform to confirm we're usable at all,
175 /// and then verifies if the current HEAD matches the detected LLVM SHA head,
176 /// in which case LLVM is indicated as not available.
177 pub(crate) fn is_ci_llvm_available(config: &Config, asserts: bool) -> bool {
178 // This is currently all tier 1 targets and tier 2 targets with host tools
179 // (since others may not have CI artifacts)
180 // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
181 let supported_platforms = [
183 ("aarch64-unknown-linux-gnu", false),
184 ("i686-pc-windows-gnu", false),
185 ("i686-pc-windows-msvc", false),
186 ("i686-unknown-linux-gnu", false),
187 ("x86_64-unknown-linux-gnu", true),
188 ("x86_64-apple-darwin", true),
189 ("x86_64-pc-windows-gnu", true),
190 ("x86_64-pc-windows-msvc", true),
191 // tier 2 with host tools
192 ("aarch64-apple-darwin", false),
193 ("aarch64-pc-windows-msvc", false),
194 ("aarch64-unknown-linux-musl", false),
195 ("arm-unknown-linux-gnueabi", false),
196 ("arm-unknown-linux-gnueabihf", false),
197 ("armv7-unknown-linux-gnueabihf", false),
198 ("mips-unknown-linux-gnu", false),
199 ("mips64-unknown-linux-gnuabi64", false),
200 ("mips64el-unknown-linux-gnuabi64", false),
201 ("mipsel-unknown-linux-gnu", false),
202 ("powerpc-unknown-linux-gnu", false),
203 ("powerpc64-unknown-linux-gnu", false),
204 ("powerpc64le-unknown-linux-gnu", false),
205 ("riscv64gc-unknown-linux-gnu", false),
206 ("s390x-unknown-linux-gnu", false),
207 ("x86_64-unknown-freebsd", false),
208 ("x86_64-unknown-illumos", false),
209 ("x86_64-unknown-linux-musl", false),
210 ("x86_64-unknown-netbsd", false),
213 if !supported_platforms.contains(&(&*config.build.triple, asserts)) {
214 if asserts == true || !supported_platforms.contains(&(&*config.build.triple, true)) {
220 // We assume we have access to git, so it's okay to unconditionally pass
222 let llvm_sha = detect_llvm_sha(config, true);
223 let head_sha = output(config.git().arg("rev-parse").arg("HEAD"));
224 let head_sha = head_sha.trim();
225 if llvm_sha == head_sha {
227 "Detected LLVM as non-available: running in CI and modified LLVM in this change"
236 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
238 pub target: TargetSelection,
242 type Output = LlvmResult;
244 const ONLY_HOSTS: bool = true;
246 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
247 run.path("src/llvm-project").path("src/llvm-project/llvm")
250 fn make_run(run: RunConfig<'_>) {
251 run.builder.ensure(Llvm { target: run.target });
254 /// Compile LLVM for `target`.
255 fn run(self, builder: &Builder<'_>) -> LlvmResult {
256 let target = self.target;
257 let target_native = if self.target.starts_with("riscv") {
258 // RISC-V target triples in Rust is not named the same as C compiler target triples.
259 // This converts Rust RISC-V target triples to C compiler triples.
260 let idx = target.triple.find('-').unwrap();
262 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
263 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
264 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
265 // Set the version suffix to 13.0 so the correct target details are used.
266 format!("{}{}", self.target, "13.0")
271 let Meta { stamp, res, out_dir, root } = match prebuilt_llvm_config(builder, target) {
276 builder.update_submodule(&Path::new("src").join("llvm-project"));
277 if builder.llvm_link_shared() && target.contains("windows") {
278 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
281 builder.info(&format!("Building LLVM for {}", target));
283 let _time = util::timeit(&builder);
284 t!(fs::create_dir_all(&out_dir));
286 // https://llvm.org/docs/CMake.html
287 let mut cfg = cmake::Config::new(builder.src.join(root));
288 let mut ldflags = LdFlags::default();
290 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
291 (false, _) => "Debug",
292 (true, false) => "Release",
293 (true, true) => "RelWithDebInfo",
296 // NOTE: remember to also update `config.toml.example` when changing the
298 let llvm_targets = match &builder.config.llvm_targets {
301 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
302 Sparc;SystemZ;WebAssembly;X86"
306 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
311 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
312 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
313 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
315 cfg.out_dir(&out_dir)
317 .define("LLVM_ENABLE_ASSERTIONS", assertions)
318 .define("LLVM_ENABLE_PLUGINS", plugins)
319 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
320 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
321 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
322 .define("LLVM_INCLUDE_DOCS", "OFF")
323 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
324 .define("LLVM_INCLUDE_TESTS", enable_tests)
325 .define("LLVM_ENABLE_TERMINFO", "OFF")
326 .define("LLVM_ENABLE_LIBEDIT", "OFF")
327 .define("LLVM_ENABLE_BINDINGS", "OFF")
328 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
329 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
330 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
331 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
333 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
334 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
335 // This flag makes sure `FileCheck` is copied in the final binaries directory.
336 cfg.define("LLVM_INSTALL_UTILS", "ON");
338 if builder.config.llvm_profile_generate {
339 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
340 if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
341 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
343 cfg.define("LLVM_BUILD_RUNTIME", "No");
345 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
346 cfg.define("LLVM_PROFDATA_FILE", &path);
348 if builder.config.llvm_bolt_profile_generate
349 || builder.config.llvm_bolt_profile_use.is_some()
351 // Relocations are required for BOLT to work.
352 ldflags.push_all("-Wl,-q");
355 // Disable zstd to avoid a dependency on libzstd.so.
356 cfg.define("LLVM_ENABLE_ZSTD", "OFF");
358 if target != "aarch64-apple-darwin" && !target.contains("windows") {
359 cfg.define("LLVM_ENABLE_ZLIB", "ON");
361 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
364 // Are we compiling for iOS/tvOS/watchOS?
365 if target.contains("apple-ios")
366 || target.contains("apple-tvos")
367 || target.contains("apple-watchos")
369 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
370 cfg.define("CMAKE_OSX_SYSROOT", "/");
371 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
372 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
373 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
374 // Zlib fails to link properly, leading to a compiler error.
375 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
378 // This setting makes the LLVM tools link to the dynamic LLVM library,
379 // which saves both memory during parallel links and overall disk space
380 // for the tools. We don't do this on every platform as it doesn't work
381 // equally well everywhere.
382 if builder.llvm_link_shared() {
383 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
386 if target.starts_with("riscv") && !target.contains("freebsd") && !target.contains("openbsd")
388 // RISC-V GCC erroneously requires linking against
389 // `libatomic` when using 1-byte and 2-byte C++
390 // atomics but the LLVM build system check cannot
391 // detect this. Therefore it is set manually here.
392 // Some BSD uses Clang as its system compiler and
393 // provides no libatomic in its base system so does
395 ldflags.exe.push(" -latomic");
396 ldflags.shared.push(" -latomic");
399 if target.contains("msvc") {
400 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
401 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
402 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
403 cfg.static_crt(true);
406 if target.starts_with("i686") {
407 cfg.define("LLVM_BUILD_32_BITS", "ON");
410 let mut enabled_llvm_projects = Vec::new();
412 if util::forcing_clang_based_tests() {
413 enabled_llvm_projects.push("clang");
414 enabled_llvm_projects.push("compiler-rt");
417 if builder.config.llvm_polly {
418 enabled_llvm_projects.push("polly");
421 if builder.config.llvm_clang {
422 enabled_llvm_projects.push("clang");
425 // We want libxml to be disabled.
426 // See https://github.com/rust-lang/rust/pull/50104
427 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
429 if !enabled_llvm_projects.is_empty() {
430 enabled_llvm_projects.sort();
431 enabled_llvm_projects.dedup();
432 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
435 if let Some(num_linkers) = builder.config.llvm_link_jobs {
437 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
441 // Workaround for ppc32 lld limitation
442 if target == "powerpc-unknown-freebsd" {
443 ldflags.exe.push(" -fuse-ld=bfd");
446 // https://llvm.org/docs/HowToCrossCompileLLVM.html
447 if target != builder.config.build {
448 let LlvmResult { llvm_config, .. } =
449 builder.ensure(Llvm { target: builder.config.build });
450 if !builder.config.dry_run() {
451 let llvm_bindir = output(Command::new(&llvm_config).arg("--bindir"));
452 let host_bin = Path::new(llvm_bindir.trim());
455 host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
457 // LLVM_NM is required for cross compiling using MSVC
458 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
460 cfg.define("LLVM_CONFIG_PATH", llvm_config);
461 if builder.config.llvm_clang {
462 let build_bin = builder.llvm_out(builder.config.build).join("build").join("bin");
463 let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
464 if !builder.config.dry_run() && !clang_tblgen.exists() {
465 panic!("unable to find {}", clang_tblgen.display());
467 cfg.define("CLANG_TABLEGEN", clang_tblgen);
471 let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
472 // Allow version-suffix="" to not define a version suffix at all.
473 if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
474 } else if builder.config.channel == "dev" {
475 // Changes to a version suffix require a complete rebuild of the LLVM.
476 // To avoid rebuilds during a time of version bump, don't include rustc
477 // release number on the dev channel.
478 Some("-rust-dev".to_string())
480 Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
482 if let Some(ref suffix) = llvm_version_suffix {
483 cfg.define("LLVM_VERSION_SUFFIX", suffix);
486 configure_cmake(builder, target, &mut cfg, true, ldflags);
487 configure_llvm(builder, target, &mut cfg);
489 for (key, val) in &builder.config.llvm_build_config {
490 cfg.define(key, val);
493 // FIXME: we don't actually need to build all LLVM tools and all LLVM
494 // libraries here, e.g., we just want a few components and a few
495 // tools. Figure out how to filter them down and only build the right
496 // tools and libs on all platforms.
498 if builder.config.dry_run() {
504 // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
505 // libLLVM.dylib will be built. However, llvm-config will still look
506 // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
507 // link to make llvm-config happy.
508 if builder.llvm_link_shared() && target.contains("apple-darwin") {
509 let mut cmd = Command::new(&res.llvm_config);
510 let version = output(cmd.arg("--version"));
511 let major = version.split('.').next().unwrap();
512 let lib_name = match llvm_version_suffix {
513 Some(s) => format!("libLLVM-{}{}.dylib", major, s),
514 None => format!("libLLVM-{}.dylib", major),
517 let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
518 if !lib_llvm.exists() {
519 t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
523 // After LLVM is built, we modify (instrument or optimize) the libLLVM.so library file
524 // in place. This is fine, because currently we do not support incrementally rebuilding
525 // LLVM after a configuration change, so to rebuild it the build files have to be removed,
526 // which will also remove these modified files.
527 if builder.config.llvm_bolt_profile_generate {
528 instrument_with_bolt_inplace(&get_built_llvm_lib_path(&res.llvm_config));
530 if let Some(path) = &builder.config.llvm_bolt_profile_use {
531 optimize_library_with_bolt_inplace(
532 &get_built_llvm_lib_path(&res.llvm_config),
543 /// Returns path to a built LLVM library (libLLVM.so).
544 /// Assumes that we have built LLVM into a single library file.
545 fn get_built_llvm_lib_path(llvm_config_path: &Path) -> PathBuf {
546 let mut cmd = Command::new(llvm_config_path);
547 cmd.arg("--libfiles");
548 PathBuf::from(output(&mut cmd).trim())
551 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
552 if !builder.config.llvm_version_check {
556 if builder.config.dry_run() {
560 let mut cmd = Command::new(llvm_config);
561 let version = output(cmd.arg("--version"));
562 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
563 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
568 panic!("\n\nbad LLVM version: {}, need >=13.0\n\n", version)
572 builder: &Builder<'_>,
573 target: TargetSelection,
574 cfg: &mut cmake::Config,
575 use_compiler_launcher: bool,
576 mut ldflags: LdFlags,
578 // Do not print installation messages for up-to-date files.
579 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
580 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
582 // Do not allow the user's value of DESTDIR to influence where
583 // LLVM will install itself. LLVM must always be installed in our
584 // own build directories.
585 cfg.env("DESTDIR", "");
588 cfg.generator("Ninja");
590 cfg.target(&target.triple).host(&builder.config.build.triple);
592 if target != builder.config.build {
593 cfg.define("CMAKE_CROSSCOMPILING", "True");
595 if target.contains("netbsd") {
596 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
597 } else if target.contains("freebsd") {
598 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
599 } else if target.contains("windows") {
600 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
601 } else if target.contains("haiku") {
602 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
603 } else if target.contains("solaris") || target.contains("illumos") {
604 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
606 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
607 // that case like CMake we cannot easily determine system version either.
609 // Since, the LLVM itself makes rather limited use of version checks in
610 // CMakeFiles (and then only in tests), and so far no issues have been
611 // reported, the system version is currently left unset.
613 if target.contains("darwin") {
614 // Make sure that CMake does not build universal binaries on macOS.
615 // Explicitly specify the one single target architecture.
616 if target.starts_with("aarch64") {
617 // macOS uses a different name for building arm64
618 cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
619 } else if target.starts_with("i686") {
620 // macOS uses a different name for building i386
621 cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
623 cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
628 let sanitize_cc = |cc: &Path| {
629 if target.contains("msvc") {
630 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
632 cc.as_os_str().to_owned()
636 // MSVC with CMake uses msbuild by default which doesn't respect these
637 // vars that we'd otherwise configure. In that case we just skip this
639 if target.contains("msvc") && !builder.ninja() {
643 let (cc, cxx) = match builder.config.llvm_clang_cl {
644 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
645 None => (builder.cc(target), builder.cxx(target).unwrap()),
648 // Handle msvc + ninja + ccache specially (this is what the bots use)
649 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
650 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
651 wrap_cc.set_file_name("sccache-plus-cl.exe");
653 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
654 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
655 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
656 .env("SCCACHE_TARGET", target.triple)
657 .env("SCCACHE_CC", &cc)
658 .env("SCCACHE_CXX", &cxx);
660 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
661 // off the beaten path here that I'm not really sure this is even half
662 // supported any more. Here we're trying to:
664 // * Build LLVM on MSVC
665 // * Build LLVM with `clang-cl` instead of `cl.exe`
666 // * Build a project with `sccache`
667 // * Build for 32-bit as well
668 // * Build with Ninja
670 // For `cl.exe` there are different binaries to compile 32/64 bit which
671 // we use but for `clang-cl` there's only one which internally
672 // multiplexes via flags. As a result it appears that CMake's detection
673 // of a compiler's architecture and such on MSVC **doesn't** pass any
674 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
675 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
676 // definitely causes problems since all the env vars are pointing to
679 // To hack around this... again... we pass an argument that's
680 // unconditionally passed in the sccache shim. This'll get CMake to
681 // correctly diagnose it's doing a 32-bit compilation and LLVM will
682 // internally configure itself appropriately.
683 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
684 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
687 // If ccache is configured we inform the build a little differently how
688 // to invoke ccache while also invoking our compilers.
689 if use_compiler_launcher {
690 if let Some(ref ccache) = builder.config.ccache {
691 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
692 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
695 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
696 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
697 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
700 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
701 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
702 if let Some(ref s) = builder.config.llvm_cflags {
706 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
707 if target.contains("apple-ios") {
708 if target.contains("86-") {
709 cflags.push(" -miphonesimulator-version-min=10.0");
711 cflags.push(" -miphoneos-version-min=10.0");
714 if builder.config.llvm_clang_cl.is_some() {
715 cflags.push(&format!(" --target={}", target));
717 cfg.define("CMAKE_C_FLAGS", cflags);
718 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
719 if let Some(ref s) = builder.config.llvm_cxxflags {
723 if builder.config.llvm_clang_cl.is_some() {
724 cxxflags.push(&format!(" --target={}", target));
726 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
727 if let Some(ar) = builder.ar(target) {
728 if ar.is_absolute() {
729 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
730 // tries to resolve this path in the LLVM build directory.
731 cfg.define("CMAKE_AR", sanitize_cc(ar));
735 if let Some(ranlib) = builder.ranlib(target) {
736 if ranlib.is_absolute() {
737 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
738 // tries to resolve this path in the LLVM build directory.
739 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
743 if let Some(ref flags) = builder.config.llvm_ldflags {
744 ldflags.push_all(flags);
747 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
748 ldflags.push_all(&flags);
751 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
752 // We also do this if the user explicitly requested static libstdc++.
753 if builder.config.llvm_static_stdcpp {
754 if !target.contains("msvc") && !target.contains("netbsd") && !target.contains("solaris") {
755 if target.contains("apple") || target.contains("windows") {
756 ldflags.push_all("-static-libstdc++");
758 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
763 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
764 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
765 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
767 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
768 cfg.env("RUSTC_LOG", "sccache=warn");
772 fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
773 // ThinLTO is only available when building with LLVM, enabling LLD is required.
774 // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
775 if builder.config.llvm_thin_lto {
776 cfg.define("LLVM_ENABLE_LTO", "Thin");
777 if !target.contains("apple") {
778 cfg.define("LLVM_ENABLE_LLD", "ON");
782 if let Some(ref linker) = builder.config.llvm_use_linker {
783 cfg.define("LLVM_USE_LINKER", linker);
786 if builder.config.llvm_allow_old_toolchain {
787 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
791 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
792 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
793 let kind = if host == target { "HOST" } else { "TARGET" };
794 let target_u = target.replace("-", "_");
795 env::var_os(&format!("{}_{}", var_base, target))
796 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
797 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
798 .or_else(|| env::var_os(var_base))
801 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
803 pub target: TargetSelection,
807 type Output = PathBuf;
808 const ONLY_HOSTS: bool = true;
810 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
811 run.path("src/llvm-project/lld")
814 fn make_run(run: RunConfig<'_>) {
815 run.builder.ensure(Lld { target: run.target });
818 /// Compile LLD for `target`.
819 fn run(self, builder: &Builder<'_>) -> PathBuf {
820 if builder.config.dry_run() {
821 return PathBuf::from("lld-out-dir-test-gen");
823 let target = self.target;
825 let LlvmResult { llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
827 // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
828 // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
829 // subfolder. We check if that's the case, and if LLD's binary already exists there next to
830 // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
831 let ci_llvm_bin = llvm_config.parent().unwrap();
832 if ci_llvm_bin.is_dir() && ci_llvm_bin.file_name().unwrap() == "bin" {
833 let lld_path = ci_llvm_bin.join(exe("lld", target));
834 if lld_path.exists() {
835 // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
836 // `bin` subfolder of this step's out dir.
837 return ci_llvm_bin.parent().unwrap().to_path_buf();
841 let out_dir = builder.lld_out(target);
842 let done_stamp = out_dir.join("lld-finished-building");
843 if done_stamp.exists() {
847 builder.info(&format!("Building LLD for {}", target));
848 let _time = util::timeit(&builder);
849 t!(fs::create_dir_all(&out_dir));
851 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
852 let mut ldflags = LdFlags::default();
854 // When building LLD as part of a build with instrumentation on windows, for example
855 // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
856 // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
857 // linking errors, much like LLVM's cmake setup does in that situation.
858 if builder.config.llvm_profile_generate && target.contains("msvc") {
859 if let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref() {
860 // Find clang's runtime library directory and push that as a search path to the
861 // cmake linker flags.
862 let clang_rt_dir = get_clang_cl_resource_dir(clang_cl_path);
863 ldflags.push_all(&format!("/libpath:{}", clang_rt_dir.display()));
867 configure_cmake(builder, target, &mut cfg, true, ldflags);
868 configure_llvm(builder, target, &mut cfg);
870 // Re-use the same flags as llvm to control the level of debug information
871 // generated for lld.
872 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
873 (false, _) => "Debug",
874 (true, false) => "Release",
875 (true, true) => "RelWithDebInfo",
878 cfg.out_dir(&out_dir)
880 .define("LLVM_CMAKE_DIR", llvm_cmake_dir)
881 .define("LLVM_INCLUDE_TESTS", "OFF");
883 if target != builder.config.build {
884 // Use the host llvm-tblgen binary.
887 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
893 t!(File::create(&done_stamp));
898 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
899 pub struct TestHelpers {
900 pub target: TargetSelection,
903 impl Step for TestHelpers {
906 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
907 run.path("tests/auxiliary/rust_test_helpers.c")
910 fn make_run(run: RunConfig<'_>) {
911 run.builder.ensure(TestHelpers { target: run.target })
914 /// Compiles the `rust_test_helpers.c` library which we used in various
915 /// `run-pass` tests for ABI testing.
916 fn run(self, builder: &Builder<'_>) {
917 if builder.config.dry_run() {
920 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
921 // toolchain. However, some x86_64 ELF objects can be linked
922 // without issues. Use this hack to compile the test helpers.
923 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
924 TargetSelection::from_user("x86_64-unknown-linux-gnu")
928 let dst = builder.test_helpers_out(target);
929 let src = builder.src.join("tests/auxiliary/rust_test_helpers.c");
930 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
934 builder.info("Building test helpers");
935 t!(fs::create_dir_all(&dst));
936 let mut cfg = cc::Build::new();
937 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
938 if target.contains("emscripten") {
942 // We may have found various cross-compilers a little differently due to our
943 // extra configuration, so inform cc of these compilers. Note, though, that
944 // on MSVC we still need cc's detection of env vars (ugh).
945 if !target.contains("msvc") {
946 if let Some(ar) = builder.ar(target) {
949 cfg.compiler(builder.cc(target));
951 cfg.cargo_metadata(false)
953 .target(&target.triple)
954 .host(&builder.config.build.triple)
958 .file(builder.src.join("tests/auxiliary/rust_test_helpers.c"))
959 .compile("rust_test_helpers");
963 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
964 pub struct Sanitizers {
965 pub target: TargetSelection,
968 impl Step for Sanitizers {
969 type Output = Vec<SanitizerRuntime>;
971 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
972 run.alias("sanitizers")
975 fn make_run(run: RunConfig<'_>) {
976 run.builder.ensure(Sanitizers { target: run.target });
979 /// Builds sanitizer runtime libraries.
980 fn run(self, builder: &Builder<'_>) -> Self::Output {
981 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
982 if !compiler_rt_dir.exists() {
986 let out_dir = builder.native_dir(self.target).join("sanitizers");
987 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
988 if runtimes.is_empty() {
992 let LlvmResult { llvm_config, .. } = builder.ensure(Llvm { target: builder.config.build });
993 if builder.config.dry_run() {
997 let stamp = out_dir.join("sanitizers-finished-building");
998 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
1000 if stamp.is_done() {
1001 if stamp.hash.is_none() {
1002 builder.info(&format!(
1003 "Rebuild sanitizers by removing the file `{}`",
1004 stamp.path.display()
1010 builder.info(&format!("Building sanitizers for {}", self.target));
1012 let _time = util::timeit(&builder);
1014 let mut cfg = cmake::Config::new(&compiler_rt_dir);
1015 cfg.profile("Release");
1016 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1017 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1018 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1019 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1020 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1021 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1022 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1023 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1024 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1025 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
1027 // On Darwin targets the sanitizer runtimes are build as universal binaries.
1028 // Unfortunately sccache currently lacks support to build them successfully.
1029 // Disable compiler launcher on Darwin targets to avoid potential issues.
1030 let use_compiler_launcher = !self.target.contains("apple-darwin");
1031 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
1033 t!(fs::create_dir_all(&out_dir));
1034 cfg.out_dir(out_dir);
1036 for runtime in &runtimes {
1037 cfg.build_target(&runtime.cmake_target);
1046 #[derive(Clone, Debug)]
1047 pub struct SanitizerRuntime {
1048 /// CMake target used to build the runtime.
1049 pub cmake_target: String,
1050 /// Path to the built runtime library.
1052 /// Library filename that will be used rustc.
1056 /// Returns sanitizers available on a given target.
1057 fn supported_sanitizers(
1059 target: TargetSelection,
1061 ) -> Vec<SanitizerRuntime> {
1062 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1065 .map(move |c| SanitizerRuntime {
1066 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
1068 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
1069 name: format!("librustc-{}_rt.{}.dylib", channel, c),
1074 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1077 .map(move |c| SanitizerRuntime {
1078 cmake_target: format!("clang_rt.{}-{}", c, arch),
1079 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
1080 name: format!("librustc-{}_rt.{}.a", channel, c),
1085 match &*target.triple {
1086 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1087 "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1088 "aarch64-unknown-linux-gnu" => {
1089 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1091 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1092 "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1093 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1094 "x86_64-unknown-netbsd" => {
1095 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1097 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1098 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1099 "x86_64-unknown-linux-gnu" => {
1100 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1102 "x86_64-unknown-linux-musl" => {
1103 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1105 "s390x-unknown-linux-gnu" => {
1106 common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1108 "s390x-unknown-linux-musl" => {
1109 common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1117 hash: Option<Vec<u8>>,
1121 fn new(path: PathBuf, hash: Option<&str>) -> Self {
1122 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1125 fn is_done(&self) -> bool {
1126 match fs::read(&self.path) {
1127 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1128 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1130 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1135 fn remove(&self) -> io::Result<()> {
1136 match fs::remove_file(&self.path) {
1139 if e.kind() == io::ErrorKind::NotFound {
1148 fn write(&self) -> io::Result<()> {
1149 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1153 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1154 pub struct CrtBeginEnd {
1155 pub target: TargetSelection,
1158 impl Step for CrtBeginEnd {
1159 type Output = PathBuf;
1161 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1162 run.path("src/llvm-project/compiler-rt/lib/crt")
1165 fn make_run(run: RunConfig<'_>) {
1166 run.builder.ensure(CrtBeginEnd { target: run.target });
1169 /// Build crtbegin.o/crtend.o for musl target.
1170 fn run(self, builder: &Builder<'_>) -> Self::Output {
1171 let out_dir = builder.native_dir(self.target).join("crt");
1173 if builder.config.dry_run() {
1177 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1178 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1179 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1180 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1185 builder.info("Building crtbegin.o and crtend.o");
1186 t!(fs::create_dir_all(&out_dir));
1188 let mut cfg = cc::Build::new();
1190 if let Some(ar) = builder.ar(self.target) {
1193 cfg.compiler(builder.cc(self.target));
1194 cfg.cargo_metadata(false)
1196 .target(&self.target.triple)
1197 .host(&builder.config.build.triple)
1204 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1205 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1206 // instead of .ctors/.dtors
1207 cfg.flag("-std=c11")
1208 .define("CRT_HAS_INITFINI_ARRAY", None)
1209 .define("EH_USE_FRAME_REGISTRY", None);
1213 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1214 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1219 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1220 pub struct Libunwind {
1221 pub target: TargetSelection,
1224 impl Step for Libunwind {
1225 type Output = PathBuf;
1227 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1228 run.path("src/llvm-project/libunwind")
1231 fn make_run(run: RunConfig<'_>) {
1232 run.builder.ensure(Libunwind { target: run.target });
1235 /// Build linunwind.a
1236 fn run(self, builder: &Builder<'_>) -> Self::Output {
1237 if builder.config.dry_run() {
1238 return PathBuf::new();
1241 let out_dir = builder.native_dir(self.target).join("libunwind");
1242 let root = builder.src.join("src/llvm-project/libunwind");
1244 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1248 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1249 t!(fs::create_dir_all(&out_dir));
1251 let mut cc_cfg = cc::Build::new();
1252 let mut cpp_cfg = cc::Build::new();
1255 cpp_cfg.cpp_set_stdlib(None);
1256 cpp_cfg.flag("-nostdinc++");
1257 cpp_cfg.flag("-fno-exceptions");
1258 cpp_cfg.flag("-fno-rtti");
1259 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1261 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1262 if let Some(ar) = builder.ar(self.target) {
1265 cfg.target(&self.target.triple);
1266 cfg.host(&builder.config.build.triple);
1267 cfg.warnings(false);
1269 // get_compiler() need set opt_level first.
1271 cfg.flag("-fstrict-aliasing");
1272 cfg.flag("-funwind-tables");
1273 cfg.flag("-fvisibility=hidden");
1274 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1275 cfg.include(root.join("include"));
1276 cfg.cargo_metadata(false);
1277 cfg.out_dir(&out_dir);
1279 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1280 cfg.static_flag(true);
1281 cfg.flag("-fno-stack-protector");
1282 cfg.flag("-ffreestanding");
1283 cfg.flag("-fexceptions");
1285 // easiest way to undefine since no API available in cc::Build to undefine
1286 cfg.flag("-U_FORTIFY_SOURCE");
1287 cfg.define("_FORTIFY_SOURCE", "0");
1288 cfg.define("RUST_SGX", "1");
1289 cfg.define("__NO_STRING_INLINES", None);
1290 cfg.define("__NO_MATH_INLINES", None);
1291 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1292 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1293 cfg.define("NDEBUG", None);
1295 if self.target.contains("windows") {
1296 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1297 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1301 cc_cfg.compiler(builder.cc(self.target));
1302 if let Ok(cxx) = builder.cxx(self.target) {
1303 cpp_cfg.compiler(cxx);
1305 cc_cfg.compiler(builder.cc(self.target));
1308 // Don't set this for clang
1309 // By default, Clang builds C code in GNU C17 mode.
1310 // By default, Clang builds C++ code according to the C++98 standard,
1311 // with many C++11 features accepted as extensions.
1312 if cc_cfg.get_compiler().is_like_gnu() {
1313 cc_cfg.flag("-std=c99");
1315 if cpp_cfg.get_compiler().is_like_gnu() {
1316 cpp_cfg.flag("-std=c++11");
1319 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1320 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1321 // C++ compiler env variables on the builders.
1322 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1323 if cpp_cfg.get_compiler().is_like_gnu() {
1325 cpp_cfg.compiler(builder.cc(self.target));
1329 let mut c_sources = vec![
1331 "UnwindLevel1-gcc-ext.c",
1333 "UnwindRegistersRestore.S",
1334 "UnwindRegistersSave.S",
1337 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1338 let cpp_len = cpp_sources.len();
1340 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1341 c_sources.push("UnwindRustSgx.c");
1344 for src in c_sources {
1345 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1348 for src in &cpp_sources {
1349 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1352 cpp_cfg.compile("unwind-cpp");
1354 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1356 for entry in fs::read_dir(&out_dir).unwrap() {
1357 let file = entry.unwrap().path().canonicalize().unwrap();
1358 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1359 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1360 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1361 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1362 cc_cfg.object(&file);
1367 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1369 cc_cfg.compile("unwind");