]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Rollup merge of #94831 - yaahc:lib-tracking-issue-template-update, r=JohnTitor
[rust.git] / src / bootstrap / native.rs
1 //! Compilation of native dependencies like LLVM.
2 //!
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).
7 //!
8 //! LLVM and compiler-rt are essentially just wired up to everything else to
9 //! ensure that they're always in place if needed.
10
11 use std::env;
12 use std::env::consts::EXE_EXTENSION;
13 use std::ffi::{OsStr, OsString};
14 use std::fs::{self, File};
15 use std::io;
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
18
19 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
20 use crate::config::TargetSelection;
21 use crate::util::{self, exe, output, program_out_of_date, t, up_to_date};
22 use crate::{CLang, GitRepo};
23
24 pub struct Meta {
25     stamp: HashStamp,
26     build_llvm_config: PathBuf,
27     out_dir: PathBuf,
28     root: String,
29 }
30
31 // Linker flags to pass to LLVM's CMake invocation.
32 #[derive(Debug, Clone, Default)]
33 struct LdFlags {
34     // CMAKE_EXE_LINKER_FLAGS
35     exe: OsString,
36     // CMAKE_SHARED_LINKER_FLAGS
37     shared: OsString,
38     // CMAKE_MODULE_LINKER_FLAGS
39     module: OsString,
40 }
41
42 impl LdFlags {
43     fn push_all(&mut self, s: impl AsRef<OsStr>) {
44         let s = s.as_ref();
45         self.exe.push(" ");
46         self.exe.push(s);
47         self.shared.push(" ");
48         self.shared.push(s);
49         self.module.push(" ");
50         self.module.push(s);
51     }
52 }
53
54 // This returns whether we've already previously built LLVM.
55 //
56 // It's used to avoid busting caches during x.py check -- if we've already built
57 // LLVM, it's fine for us to not try to avoid doing so.
58 //
59 // This will return the llvm-config if it can get it (but it will not build it
60 // if not).
61 pub fn prebuilt_llvm_config(
62     builder: &Builder<'_>,
63     target: TargetSelection,
64 ) -> Result<PathBuf, Meta> {
65     maybe_download_ci_llvm(builder);
66
67     // If we're using a custom LLVM bail out here, but we can only use a
68     // custom LLVM for the build triple.
69     if let Some(config) = builder.config.target_config.get(&target) {
70         if let Some(ref s) = config.llvm_config {
71             check_llvm_version(builder, s);
72             return Ok(s.to_path_buf());
73         }
74     }
75
76     let root = "src/llvm-project/llvm";
77     let out_dir = builder.llvm_out(target);
78
79     let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
80     if !builder.config.build.contains("msvc") || builder.ninja() {
81         llvm_config_ret_dir.push("build");
82     }
83     llvm_config_ret_dir.push("bin");
84
85     let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
86
87     let stamp = out_dir.join("llvm-finished-building");
88     let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
89
90     if builder.config.llvm_skip_rebuild && stamp.path.exists() {
91         builder.info(
92             "Warning: \
93                 Using a potentially stale build of LLVM; \
94                 This may not behave well.",
95         );
96         return Ok(build_llvm_config);
97     }
98
99     if stamp.is_done() {
100         if stamp.hash.is_none() {
101             builder.info(
102                 "Could not determine the LLVM submodule commit hash. \
103                      Assuming that an LLVM rebuild is not necessary.",
104             );
105             builder.info(&format!(
106                 "To force LLVM to rebuild, remove the file `{}`",
107                 stamp.path.display()
108             ));
109         }
110         return Ok(build_llvm_config);
111     }
112
113     Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
114 }
115
116 pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) {
117     let config = &builder.config;
118     if !config.llvm_from_ci {
119         return;
120     }
121     let mut rev_list = Command::new("git");
122     rev_list.args(&[
123         PathBuf::from("rev-list"),
124         format!("--author={}", builder.config.stage0_metadata.config.git_merge_commit_email).into(),
125         "-n1".into(),
126         "--first-parent".into(),
127         "HEAD".into(),
128         "--".into(),
129         builder.src.join("src/llvm-project"),
130         builder.src.join("src/bootstrap/download-ci-llvm-stamp"),
131         // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
132         builder.src.join("src/version"),
133     ]);
134     let llvm_sha = output(&mut rev_list);
135     let llvm_sha = llvm_sha.trim();
136
137     if llvm_sha == "" {
138         eprintln!("error: could not find commit hash for downloading LLVM");
139         eprintln!("help: maybe your repository history is too shallow?");
140         eprintln!("help: consider disabling `download-ci-llvm`");
141         eprintln!("help: or fetch enough history to include one upstream commit");
142         panic!();
143     }
144
145     let llvm_root = config.ci_llvm_root();
146     let llvm_stamp = llvm_root.join(".llvm-stamp");
147     let key = format!("{}{}", llvm_sha, config.llvm_assertions);
148     if program_out_of_date(&llvm_stamp, &key) && !config.dry_run {
149         download_ci_llvm(builder, &llvm_sha);
150         for binary in ["llvm-config", "FileCheck"] {
151             builder.fix_bin_or_dylib(&llvm_root.join("bin").join(binary));
152         }
153
154         // Update the timestamp of llvm-config to force rustc_llvm to be
155         // rebuilt. This is a hacky workaround for a deficiency in Cargo where
156         // the rerun-if-changed directive doesn't handle changes very well.
157         // https://github.com/rust-lang/cargo/issues/10791
158         // Cargo only compares the timestamp of the file relative to the last
159         // time `rustc_llvm` build script ran. However, the timestamps of the
160         // files in the tarball are in the past, so it doesn't trigger a
161         // rebuild.
162         let now = filetime::FileTime::from_system_time(std::time::SystemTime::now());
163         let llvm_config = llvm_root.join("bin").join(exe("llvm-config", builder.config.build));
164         t!(filetime::set_file_times(&llvm_config, now, now));
165
166         let llvm_lib = llvm_root.join("lib");
167         for entry in t!(fs::read_dir(&llvm_lib)) {
168             let lib = t!(entry).path();
169             if lib.extension().map_or(false, |ext| ext == "so") {
170                 builder.fix_bin_or_dylib(&lib);
171             }
172         }
173         t!(fs::write(llvm_stamp, key));
174     }
175 }
176
177 fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) {
178     let llvm_assertions = builder.config.llvm_assertions;
179
180     let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
181     let cache_dst = builder.out.join("cache");
182     let rustc_cache = cache_dst.join(cache_prefix);
183     if !rustc_cache.exists() {
184         t!(fs::create_dir_all(&rustc_cache));
185     }
186     let base = if llvm_assertions {
187         &builder.config.stage0_metadata.config.artifacts_with_llvm_assertions_server
188     } else {
189         &builder.config.stage0_metadata.config.artifacts_server
190     };
191     let filename = format!("rust-dev-nightly-{}.tar.xz", builder.build.build.triple);
192     let tarball = rustc_cache.join(&filename);
193     if !tarball.exists() {
194         let help_on_error = "error: failed to download llvm from ci
195
196 help: old builds get deleted after a certain time
197 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
198
199 [llvm]
200 download-ci-llvm = false
201 ";
202         builder.download_component(
203             &format!("{base}/{llvm_sha}/{filename}"),
204             &tarball,
205             help_on_error,
206         );
207     }
208     let llvm_root = builder.config.ci_llvm_root();
209     builder.unpack(&tarball, &llvm_root, "rust-dev");
210 }
211
212 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
213 pub struct Llvm {
214     pub target: TargetSelection,
215 }
216
217 impl Step for Llvm {
218     type Output = PathBuf; // path to llvm-config
219
220     const ONLY_HOSTS: bool = true;
221
222     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
223         run.path("src/llvm-project").path("src/llvm-project/llvm")
224     }
225
226     fn make_run(run: RunConfig<'_>) {
227         run.builder.ensure(Llvm { target: run.target });
228     }
229
230     /// Compile LLVM for `target`.
231     fn run(self, builder: &Builder<'_>) -> PathBuf {
232         let target = self.target;
233         let target_native = if self.target.starts_with("riscv") {
234             // RISC-V target triples in Rust is not named the same as C compiler target triples.
235             // This converts Rust RISC-V target triples to C compiler triples.
236             let idx = target.triple.find('-').unwrap();
237
238             format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
239         } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
240             // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
241             // Set the version suffix to 13.0 so the correct target details are used.
242             format!("{}{}", self.target, "13.0")
243         } else {
244             target.to_string()
245         };
246
247         let Meta { stamp, build_llvm_config, out_dir, root } =
248             match prebuilt_llvm_config(builder, target) {
249                 Ok(p) => return p,
250                 Err(m) => m,
251             };
252
253         builder.update_submodule(&Path::new("src").join("llvm-project"));
254         if builder.llvm_link_shared() && target.contains("windows") {
255             panic!("shared linking to LLVM is not currently supported on {}", target.triple);
256         }
257
258         builder.info(&format!("Building LLVM for {}", target));
259         t!(stamp.remove());
260         let _time = util::timeit(&builder);
261         t!(fs::create_dir_all(&out_dir));
262
263         // https://llvm.org/docs/CMake.html
264         let mut cfg = cmake::Config::new(builder.src.join(root));
265         let mut ldflags = LdFlags::default();
266
267         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
268             (false, _) => "Debug",
269             (true, false) => "Release",
270             (true, true) => "RelWithDebInfo",
271         };
272
273         // NOTE: remember to also update `config.toml.example` when changing the
274         // defaults!
275         let llvm_targets = match &builder.config.llvm_targets {
276             Some(s) => s,
277             None => {
278                 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
279                      Sparc;SystemZ;WebAssembly;X86"
280             }
281         };
282
283         let llvm_exp_targets = match builder.config.llvm_experimental_targets {
284             Some(ref s) => s,
285             None => "AVR;M68k",
286         };
287
288         let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
289         let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
290         let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
291
292         cfg.out_dir(&out_dir)
293             .profile(profile)
294             .define("LLVM_ENABLE_ASSERTIONS", assertions)
295             .define("LLVM_ENABLE_PLUGINS", plugins)
296             .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
297             .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
298             .define("LLVM_INCLUDE_EXAMPLES", "OFF")
299             .define("LLVM_INCLUDE_DOCS", "OFF")
300             .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
301             .define("LLVM_INCLUDE_TESTS", enable_tests)
302             .define("LLVM_ENABLE_TERMINFO", "OFF")
303             .define("LLVM_ENABLE_LIBEDIT", "OFF")
304             .define("LLVM_ENABLE_BINDINGS", "OFF")
305             .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
306             .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
307             .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
308             .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
309
310         // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
311         // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
312         // This flag makes sure `FileCheck` is copied in the final binaries directory.
313         cfg.define("LLVM_INSTALL_UTILS", "ON");
314
315         if builder.config.llvm_profile_generate {
316             cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
317             if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
318                 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
319             }
320             cfg.define("LLVM_BUILD_RUNTIME", "No");
321         }
322         if let Some(path) = builder.config.llvm_profile_use.as_ref() {
323             cfg.define("LLVM_PROFDATA_FILE", &path);
324         }
325
326         if target != "aarch64-apple-darwin" && !target.contains("windows") {
327             cfg.define("LLVM_ENABLE_ZLIB", "ON");
328         } else {
329             cfg.define("LLVM_ENABLE_ZLIB", "OFF");
330         }
331
332         // Are we compiling for iOS/tvOS/watchOS?
333         if target.contains("apple-ios")
334             || target.contains("apple-tvos")
335             || target.contains("apple-watchos")
336         {
337             // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
338             cfg.define("CMAKE_OSX_SYSROOT", "/");
339             cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
340             // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
341             cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
342             // Zlib fails to link properly, leading to a compiler error.
343             cfg.define("LLVM_ENABLE_ZLIB", "OFF");
344         }
345
346         if builder.config.llvm_thin_lto {
347             cfg.define("LLVM_ENABLE_LTO", "Thin");
348             if !target.contains("apple") {
349                 cfg.define("LLVM_ENABLE_LLD", "ON");
350             }
351         }
352
353         // This setting makes the LLVM tools link to the dynamic LLVM library,
354         // which saves both memory during parallel links and overall disk space
355         // for the tools. We don't do this on every platform as it doesn't work
356         // equally well everywhere.
357         //
358         // If we're not linking rustc to a dynamic LLVM, though, then don't link
359         // tools to it.
360         let llvm_link_shared =
361             builder.llvm_link_tools_dynamically(target) && builder.llvm_link_shared();
362         if llvm_link_shared {
363             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
364         }
365
366         if target.starts_with("riscv") && !target.contains("freebsd") {
367             // RISC-V GCC erroneously requires linking against
368             // `libatomic` when using 1-byte and 2-byte C++
369             // atomics but the LLVM build system check cannot
370             // detect this. Therefore it is set manually here.
371             // FreeBSD uses Clang as its system compiler and
372             // provides no libatomic in its base system so does
373             // not want this.
374             ldflags.exe.push(" -latomic");
375             ldflags.shared.push(" -latomic");
376         }
377
378         if target.contains("msvc") {
379             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
380             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
381             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
382             cfg.static_crt(true);
383         }
384
385         if target.starts_with("i686") {
386             cfg.define("LLVM_BUILD_32_BITS", "ON");
387         }
388
389         let mut enabled_llvm_projects = Vec::new();
390
391         if util::forcing_clang_based_tests() {
392             enabled_llvm_projects.push("clang");
393             enabled_llvm_projects.push("compiler-rt");
394         }
395
396         if builder.config.llvm_polly {
397             enabled_llvm_projects.push("polly");
398         }
399
400         if builder.config.llvm_clang {
401             enabled_llvm_projects.push("clang");
402         }
403
404         // We want libxml to be disabled.
405         // See https://github.com/rust-lang/rust/pull/50104
406         cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
407
408         if !enabled_llvm_projects.is_empty() {
409             enabled_llvm_projects.sort();
410             enabled_llvm_projects.dedup();
411             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
412         }
413
414         if let Some(num_linkers) = builder.config.llvm_link_jobs {
415             if num_linkers > 0 {
416                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
417             }
418         }
419
420         // Workaround for ppc32 lld limitation
421         if target == "powerpc-unknown-freebsd" {
422             ldflags.exe.push(" -fuse-ld=bfd");
423         }
424
425         // https://llvm.org/docs/HowToCrossCompileLLVM.html
426         if target != builder.config.build {
427             builder.ensure(Llvm { target: builder.config.build });
428             // FIXME: if the llvm root for the build triple is overridden then we
429             //        should use llvm-tblgen from there, also should verify that it
430             //        actually exists most of the time in normal installs of LLVM.
431             let host_bin = builder.llvm_out(builder.config.build).join("bin");
432             cfg.define("CMAKE_CROSSCOMPILING", "True");
433             cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
434             cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
435             cfg.define(
436                 "LLVM_CONFIG_PATH",
437                 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
438             );
439         }
440
441         let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
442             // Allow version-suffix="" to not define a version suffix at all.
443             if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
444         } else if builder.config.channel == "dev" {
445             // Changes to a version suffix require a complete rebuild of the LLVM.
446             // To avoid rebuilds during a time of version bump, don't include rustc
447             // release number on the dev channel.
448             Some("-rust-dev".to_string())
449         } else {
450             Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
451         };
452         if let Some(ref suffix) = llvm_version_suffix {
453             cfg.define("LLVM_VERSION_SUFFIX", suffix);
454         }
455
456         if let Some(ref linker) = builder.config.llvm_use_linker {
457             cfg.define("LLVM_USE_LINKER", linker);
458         }
459
460         if builder.config.llvm_allow_old_toolchain {
461             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
462         }
463
464         configure_cmake(builder, target, &mut cfg, true, ldflags);
465
466         for (key, val) in &builder.config.llvm_build_config {
467             cfg.define(key, val);
468         }
469
470         // FIXME: we don't actually need to build all LLVM tools and all LLVM
471         //        libraries here, e.g., we just want a few components and a few
472         //        tools. Figure out how to filter them down and only build the right
473         //        tools and libs on all platforms.
474
475         if builder.config.dry_run {
476             return build_llvm_config;
477         }
478
479         cfg.build();
480
481         // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
482         // libLLVM.dylib will be built. However, llvm-config will still look
483         // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
484         // link to make llvm-config happy.
485         if llvm_link_shared && target.contains("apple-darwin") {
486             let mut cmd = Command::new(&build_llvm_config);
487             let version = output(cmd.arg("--version"));
488             let major = version.split('.').next().unwrap();
489             let lib_name = match llvm_version_suffix {
490                 Some(s) => format!("lib/libLLVM-{}{}.dylib", major, s),
491                 None => format!("lib/libLLVM-{}.dylib", major),
492             };
493
494             // The reason why we build the library path from llvm-config is because
495             // the output of llvm-config depends on its location in the file system.
496             // Make sure we create the symlink exactly where it's needed.
497             let llvm_base = build_llvm_config.parent().unwrap().parent().unwrap();
498             let lib_llvm = llvm_base.join(lib_name);
499             t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
500         }
501
502         t!(stamp.write());
503
504         build_llvm_config
505     }
506 }
507
508 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
509     if !builder.config.llvm_version_check {
510         return;
511     }
512
513     if builder.config.dry_run {
514         return;
515     }
516
517     let mut cmd = Command::new(llvm_config);
518     let version = output(cmd.arg("--version"));
519     let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
520     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
521         if major >= 12 {
522             return;
523         }
524     }
525     panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
526 }
527
528 fn configure_cmake(
529     builder: &Builder<'_>,
530     target: TargetSelection,
531     cfg: &mut cmake::Config,
532     use_compiler_launcher: bool,
533     mut ldflags: LdFlags,
534 ) {
535     // Do not print installation messages for up-to-date files.
536     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
537     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
538
539     // Do not allow the user's value of DESTDIR to influence where
540     // LLVM will install itself. LLVM must always be installed in our
541     // own build directories.
542     cfg.env("DESTDIR", "");
543
544     if builder.ninja() {
545         cfg.generator("Ninja");
546     }
547     cfg.target(&target.triple).host(&builder.config.build.triple);
548
549     if target != builder.config.build {
550         if target.contains("netbsd") {
551             cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
552         } else if target.contains("freebsd") {
553             cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
554         } else if target.contains("windows") {
555             cfg.define("CMAKE_SYSTEM_NAME", "Windows");
556         } else if target.contains("haiku") {
557             cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
558         } else if target.contains("solaris") || target.contains("illumos") {
559             cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
560         }
561         // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
562         // that case like CMake we cannot easily determine system version either.
563         //
564         // Since, the LLVM itself makes rather limited use of version checks in
565         // CMakeFiles (and then only in tests), and so far no issues have been
566         // reported, the system version is currently left unset.
567     }
568
569     let sanitize_cc = |cc: &Path| {
570         if target.contains("msvc") {
571             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
572         } else {
573             cc.as_os_str().to_owned()
574         }
575     };
576
577     // MSVC with CMake uses msbuild by default which doesn't respect these
578     // vars that we'd otherwise configure. In that case we just skip this
579     // entirely.
580     if target.contains("msvc") && !builder.ninja() {
581         return;
582     }
583
584     let (cc, cxx) = match builder.config.llvm_clang_cl {
585         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
586         None => (builder.cc(target), builder.cxx(target).unwrap()),
587     };
588
589     // Handle msvc + ninja + ccache specially (this is what the bots use)
590     if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
591         let mut wrap_cc = env::current_exe().expect("failed to get cwd");
592         wrap_cc.set_file_name("sccache-plus-cl.exe");
593
594         cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
595             .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
596         cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
597             .env("SCCACHE_TARGET", target.triple)
598             .env("SCCACHE_CC", &cc)
599             .env("SCCACHE_CXX", &cxx);
600
601         // Building LLVM on MSVC can be a little ludicrous at times. We're so far
602         // off the beaten path here that I'm not really sure this is even half
603         // supported any more. Here we're trying to:
604         //
605         // * Build LLVM on MSVC
606         // * Build LLVM with `clang-cl` instead of `cl.exe`
607         // * Build a project with `sccache`
608         // * Build for 32-bit as well
609         // * Build with Ninja
610         //
611         // For `cl.exe` there are different binaries to compile 32/64 bit which
612         // we use but for `clang-cl` there's only one which internally
613         // multiplexes via flags. As a result it appears that CMake's detection
614         // of a compiler's architecture and such on MSVC **doesn't** pass any
615         // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
616         // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
617         // definitely causes problems since all the env vars are pointing to
618         // 32-bit libraries.
619         //
620         // To hack around this... again... we pass an argument that's
621         // unconditionally passed in the sccache shim. This'll get CMake to
622         // correctly diagnose it's doing a 32-bit compilation and LLVM will
623         // internally configure itself appropriately.
624         if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
625             cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
626         }
627     } else {
628         // If ccache is configured we inform the build a little differently how
629         // to invoke ccache while also invoking our compilers.
630         if use_compiler_launcher {
631             if let Some(ref ccache) = builder.config.ccache {
632                 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
633                     .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
634             }
635         }
636         cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
637             .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
638             .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
639     }
640
641     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
642     let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
643     if let Some(ref s) = builder.config.llvm_cflags {
644         cflags.push(" ");
645         cflags.push(s);
646     }
647     // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
648     if target.contains("apple-ios") {
649         if target.contains("86-") {
650             cflags.push(" -miphonesimulator-version-min=10.0");
651         } else {
652             cflags.push(" -miphoneos-version-min=10.0");
653         }
654     }
655     if builder.config.llvm_clang_cl.is_some() {
656         cflags.push(&format!(" --target={}", target));
657     }
658     cfg.define("CMAKE_C_FLAGS", cflags);
659     let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
660     if let Some(ref s) = builder.config.llvm_cxxflags {
661         cxxflags.push(" ");
662         cxxflags.push(s);
663     }
664     if builder.config.llvm_clang_cl.is_some() {
665         cxxflags.push(&format!(" --target={}", target));
666     }
667     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
668     if let Some(ar) = builder.ar(target) {
669         if ar.is_absolute() {
670             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
671             // tries to resolve this path in the LLVM build directory.
672             cfg.define("CMAKE_AR", sanitize_cc(ar));
673         }
674     }
675
676     if let Some(ranlib) = builder.ranlib(target) {
677         if ranlib.is_absolute() {
678             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
679             // tries to resolve this path in the LLVM build directory.
680             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
681         }
682     }
683
684     if let Some(ref flags) = builder.config.llvm_ldflags {
685         ldflags.push_all(flags);
686     }
687
688     if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
689         ldflags.push_all(&flags);
690     }
691
692     // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
693     // We also do this if the user explicitly requested static libstdc++.
694     if builder.config.llvm_static_stdcpp {
695         if !target.contains("msvc") && !target.contains("netbsd") && !target.contains("solaris") {
696             if target.contains("apple") || target.contains("windows") {
697                 ldflags.push_all("-static-libstdc++");
698             } else {
699                 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
700             }
701         }
702     }
703
704     cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
705     cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
706     cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
707
708     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
709         cfg.env("RUSTC_LOG", "sccache=warn");
710     }
711 }
712
713 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
714 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
715     let kind = if host == target { "HOST" } else { "TARGET" };
716     let target_u = target.replace("-", "_");
717     env::var_os(&format!("{}_{}", var_base, target))
718         .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
719         .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
720         .or_else(|| env::var_os(var_base))
721 }
722
723 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
724 pub struct Lld {
725     pub target: TargetSelection,
726 }
727
728 impl Step for Lld {
729     type Output = PathBuf;
730     const ONLY_HOSTS: bool = true;
731
732     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
733         run.path("src/llvm-project/lld")
734     }
735
736     fn make_run(run: RunConfig<'_>) {
737         run.builder.ensure(Lld { target: run.target });
738     }
739
740     /// Compile LLD for `target`.
741     fn run(self, builder: &Builder<'_>) -> PathBuf {
742         if builder.config.dry_run {
743             return PathBuf::from("lld-out-dir-test-gen");
744         }
745         let target = self.target;
746
747         let llvm_config = builder.ensure(Llvm { target: self.target });
748
749         let out_dir = builder.lld_out(target);
750         let done_stamp = out_dir.join("lld-finished-building");
751         if done_stamp.exists() {
752             return out_dir;
753         }
754
755         builder.info(&format!("Building LLD for {}", target));
756         let _time = util::timeit(&builder);
757         t!(fs::create_dir_all(&out_dir));
758
759         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
760         configure_cmake(builder, target, &mut cfg, true, LdFlags::default());
761
762         // This is an awful, awful hack. Discovered when we migrated to using
763         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
764         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
765         // that directory for later processing. Unfortunately if this path has
766         // forward slashes in it (which it basically always does on Windows)
767         // then CMake will hit a syntax error later on as... something isn't
768         // escaped it seems?
769         //
770         // Instead of attempting to fix this problem in upstream CMake and/or
771         // LLVM/LLD we just hack around it here. This thin wrapper will take the
772         // output from llvm-config and replace all instances of `\` with `/` to
773         // ensure we don't hit the same bugs with escaping. It means that you
774         // can't build on a system where your paths require `\` on Windows, but
775         // there's probably a lot of reasons you can't do that other than this.
776         let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
777
778         // Re-use the same flags as llvm to control the level of debug information
779         // generated for lld.
780         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
781             (false, _) => "Debug",
782             (true, false) => "Release",
783             (true, true) => "RelWithDebInfo",
784         };
785
786         cfg.out_dir(&out_dir)
787             .profile(profile)
788             .env("LLVM_CONFIG_REAL", &llvm_config)
789             .define("LLVM_CONFIG_PATH", llvm_config_shim)
790             .define("LLVM_INCLUDE_TESTS", "OFF");
791
792         if builder.config.llvm_allow_old_toolchain {
793             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
794         }
795
796         // While we're using this horrible workaround to shim the execution of
797         // llvm-config, let's just pile on more. I can't seem to figure out how
798         // to build LLD as a standalone project and also cross-compile it at the
799         // same time. It wants a natively executable `llvm-config` to learn
800         // about LLVM, but then it learns about all the host configuration of
801         // LLVM and tries to link to host LLVM libraries.
802         //
803         // To work around that we tell our shim to replace anything with the
804         // build target with the actual target instead. This'll break parts of
805         // LLD though which try to execute host tools, such as llvm-tblgen, so
806         // we specifically tell it where to find those. This is likely super
807         // brittle and will break over time. If anyone knows better how to
808         // cross-compile LLD it would be much appreciated to fix this!
809         if target != builder.config.build {
810             cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
811                 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
812                 .define(
813                     "LLVM_TABLEGEN_EXE",
814                     llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
815                 );
816         }
817
818         // Explicitly set C++ standard, because upstream doesn't do so
819         // for standalone builds.
820         cfg.define("CMAKE_CXX_STANDARD", "14");
821
822         cfg.build();
823
824         t!(File::create(&done_stamp));
825         out_dir
826     }
827 }
828
829 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
830 pub struct TestHelpers {
831     pub target: TargetSelection,
832 }
833
834 impl Step for TestHelpers {
835     type Output = ();
836
837     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
838         run.path("src/test/auxiliary/rust_test_helpers.c")
839     }
840
841     fn make_run(run: RunConfig<'_>) {
842         run.builder.ensure(TestHelpers { target: run.target })
843     }
844
845     /// Compiles the `rust_test_helpers.c` library which we used in various
846     /// `run-pass` tests for ABI testing.
847     fn run(self, builder: &Builder<'_>) {
848         if builder.config.dry_run {
849             return;
850         }
851         // The x86_64-fortanix-unknown-sgx target doesn't have a working C
852         // toolchain. However, some x86_64 ELF objects can be linked
853         // without issues. Use this hack to compile the test helpers.
854         let target = if self.target == "x86_64-fortanix-unknown-sgx" {
855             TargetSelection::from_user("x86_64-unknown-linux-gnu")
856         } else {
857             self.target
858         };
859         let dst = builder.test_helpers_out(target);
860         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
861         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
862             return;
863         }
864
865         builder.info("Building test helpers");
866         t!(fs::create_dir_all(&dst));
867         let mut cfg = cc::Build::new();
868         // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
869         if target.contains("emscripten") {
870             cfg.pic(false);
871         }
872
873         // We may have found various cross-compilers a little differently due to our
874         // extra configuration, so inform cc of these compilers. Note, though, that
875         // on MSVC we still need cc's detection of env vars (ugh).
876         if !target.contains("msvc") {
877             if let Some(ar) = builder.ar(target) {
878                 cfg.archiver(ar);
879             }
880             cfg.compiler(builder.cc(target));
881         }
882         cfg.cargo_metadata(false)
883             .out_dir(&dst)
884             .target(&target.triple)
885             .host(&builder.config.build.triple)
886             .opt_level(0)
887             .warnings(false)
888             .debug(false)
889             .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
890             .compile("rust_test_helpers");
891     }
892 }
893
894 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
895 pub struct Sanitizers {
896     pub target: TargetSelection,
897 }
898
899 impl Step for Sanitizers {
900     type Output = Vec<SanitizerRuntime>;
901
902     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
903         run.alias("sanitizers")
904     }
905
906     fn make_run(run: RunConfig<'_>) {
907         run.builder.ensure(Sanitizers { target: run.target });
908     }
909
910     /// Builds sanitizer runtime libraries.
911     fn run(self, builder: &Builder<'_>) -> Self::Output {
912         let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
913         if !compiler_rt_dir.exists() {
914             return Vec::new();
915         }
916
917         let out_dir = builder.native_dir(self.target).join("sanitizers");
918         let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
919         if runtimes.is_empty() {
920             return runtimes;
921         }
922
923         let llvm_config = builder.ensure(Llvm { target: builder.config.build });
924         if builder.config.dry_run {
925             return runtimes;
926         }
927
928         let stamp = out_dir.join("sanitizers-finished-building");
929         let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
930
931         if stamp.is_done() {
932             if stamp.hash.is_none() {
933                 builder.info(&format!(
934                     "Rebuild sanitizers by removing the file `{}`",
935                     stamp.path.display()
936                 ));
937             }
938             return runtimes;
939         }
940
941         builder.info(&format!("Building sanitizers for {}", self.target));
942         t!(stamp.remove());
943         let _time = util::timeit(&builder);
944
945         let mut cfg = cmake::Config::new(&compiler_rt_dir);
946         cfg.profile("Release");
947         cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
948         cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
949         cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
950         cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
951         cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
952         cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
953         cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
954         cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
955         cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
956         cfg.define("LLVM_CONFIG_PATH", &llvm_config);
957
958         // On Darwin targets the sanitizer runtimes are build as universal binaries.
959         // Unfortunately sccache currently lacks support to build them successfully.
960         // Disable compiler launcher on Darwin targets to avoid potential issues.
961         let use_compiler_launcher = !self.target.contains("apple-darwin");
962         configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
963
964         t!(fs::create_dir_all(&out_dir));
965         cfg.out_dir(out_dir);
966
967         for runtime in &runtimes {
968             cfg.build_target(&runtime.cmake_target);
969             cfg.build();
970         }
971         t!(stamp.write());
972
973         runtimes
974     }
975 }
976
977 #[derive(Clone, Debug)]
978 pub struct SanitizerRuntime {
979     /// CMake target used to build the runtime.
980     pub cmake_target: String,
981     /// Path to the built runtime library.
982     pub path: PathBuf,
983     /// Library filename that will be used rustc.
984     pub name: String,
985 }
986
987 /// Returns sanitizers available on a given target.
988 fn supported_sanitizers(
989     out_dir: &Path,
990     target: TargetSelection,
991     channel: &str,
992 ) -> Vec<SanitizerRuntime> {
993     let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
994         components
995             .iter()
996             .map(move |c| SanitizerRuntime {
997                 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
998                 path: out_dir
999                     .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
1000                 name: format!("librustc-{}_rt.{}.dylib", channel, c),
1001             })
1002             .collect()
1003     };
1004
1005     let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1006         components
1007             .iter()
1008             .map(move |c| SanitizerRuntime {
1009                 cmake_target: format!("clang_rt.{}-{}", c, arch),
1010                 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
1011                 name: format!("librustc-{}_rt.{}.a", channel, c),
1012             })
1013             .collect()
1014     };
1015
1016     match &*target.triple {
1017         "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1018         "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1019         "aarch64-unknown-linux-gnu" => {
1020             common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1021         }
1022         "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1023         "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1024         "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1025         "x86_64-unknown-netbsd" => {
1026             common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1027         }
1028         "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1029         "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1030         "x86_64-unknown-linux-gnu" => {
1031             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1032         }
1033         "x86_64-unknown-linux-musl" => {
1034             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1035         }
1036         _ => Vec::new(),
1037     }
1038 }
1039
1040 struct HashStamp {
1041     path: PathBuf,
1042     hash: Option<Vec<u8>>,
1043 }
1044
1045 impl HashStamp {
1046     fn new(path: PathBuf, hash: Option<&str>) -> Self {
1047         HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1048     }
1049
1050     fn is_done(&self) -> bool {
1051         match fs::read(&self.path) {
1052             Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1053             Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1054             Err(e) => {
1055                 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1056             }
1057         }
1058     }
1059
1060     fn remove(&self) -> io::Result<()> {
1061         match fs::remove_file(&self.path) {
1062             Ok(()) => Ok(()),
1063             Err(e) => {
1064                 if e.kind() == io::ErrorKind::NotFound {
1065                     Ok(())
1066                 } else {
1067                     Err(e)
1068                 }
1069             }
1070         }
1071     }
1072
1073     fn write(&self) -> io::Result<()> {
1074         fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1075     }
1076 }
1077
1078 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1079 pub struct CrtBeginEnd {
1080     pub target: TargetSelection,
1081 }
1082
1083 impl Step for CrtBeginEnd {
1084     type Output = PathBuf;
1085
1086     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1087         run.path("src/llvm-project/compiler-rt/lib/crt")
1088     }
1089
1090     fn make_run(run: RunConfig<'_>) {
1091         run.builder.ensure(CrtBeginEnd { target: run.target });
1092     }
1093
1094     /// Build crtbegin.o/crtend.o for musl target.
1095     fn run(self, builder: &Builder<'_>) -> Self::Output {
1096         let out_dir = builder.native_dir(self.target).join("crt");
1097
1098         if builder.config.dry_run {
1099             return out_dir;
1100         }
1101
1102         let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1103         let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1104         if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1105             && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1106         {
1107             return out_dir;
1108         }
1109
1110         builder.info("Building crtbegin.o and crtend.o");
1111         t!(fs::create_dir_all(&out_dir));
1112
1113         let mut cfg = cc::Build::new();
1114
1115         if let Some(ar) = builder.ar(self.target) {
1116             cfg.archiver(ar);
1117         }
1118         cfg.compiler(builder.cc(self.target));
1119         cfg.cargo_metadata(false)
1120             .out_dir(&out_dir)
1121             .target(&self.target.triple)
1122             .host(&builder.config.build.triple)
1123             .warnings(false)
1124             .debug(false)
1125             .opt_level(3)
1126             .file(crtbegin_src)
1127             .file(crtend_src);
1128
1129         // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1130         // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1131         // instead of .ctors/.dtors
1132         cfg.flag("-std=c11")
1133             .define("CRT_HAS_INITFINI_ARRAY", None)
1134             .define("EH_USE_FRAME_REGISTRY", None);
1135
1136         cfg.compile("crt");
1137
1138         t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1139         t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1140         out_dir
1141     }
1142 }
1143
1144 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1145 pub struct Libunwind {
1146     pub target: TargetSelection,
1147 }
1148
1149 impl Step for Libunwind {
1150     type Output = PathBuf;
1151
1152     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1153         run.path("src/llvm-project/libunwind")
1154     }
1155
1156     fn make_run(run: RunConfig<'_>) {
1157         run.builder.ensure(Libunwind { target: run.target });
1158     }
1159
1160     /// Build linunwind.a
1161     fn run(self, builder: &Builder<'_>) -> Self::Output {
1162         if builder.config.dry_run {
1163             return PathBuf::new();
1164         }
1165
1166         let out_dir = builder.native_dir(self.target).join("libunwind");
1167         let root = builder.src.join("src/llvm-project/libunwind");
1168
1169         if up_to_date(&root, &out_dir.join("libunwind.a")) {
1170             return out_dir;
1171         }
1172
1173         builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1174         t!(fs::create_dir_all(&out_dir));
1175
1176         let mut cc_cfg = cc::Build::new();
1177         let mut cpp_cfg = cc::Build::new();
1178
1179         cpp_cfg.cpp(true);
1180         cpp_cfg.cpp_set_stdlib(None);
1181         cpp_cfg.flag("-nostdinc++");
1182         cpp_cfg.flag("-fno-exceptions");
1183         cpp_cfg.flag("-fno-rtti");
1184         cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1185
1186         for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1187             if let Some(ar) = builder.ar(self.target) {
1188                 cfg.archiver(ar);
1189             }
1190             cfg.target(&self.target.triple);
1191             cfg.host(&builder.config.build.triple);
1192             cfg.warnings(false);
1193             cfg.debug(false);
1194             // get_compiler() need set opt_level first.
1195             cfg.opt_level(3);
1196             cfg.flag("-fstrict-aliasing");
1197             cfg.flag("-funwind-tables");
1198             cfg.flag("-fvisibility=hidden");
1199             cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1200             cfg.include(root.join("include"));
1201             cfg.cargo_metadata(false);
1202             cfg.out_dir(&out_dir);
1203
1204             if self.target.contains("x86_64-fortanix-unknown-sgx") {
1205                 cfg.static_flag(true);
1206                 cfg.flag("-fno-stack-protector");
1207                 cfg.flag("-ffreestanding");
1208                 cfg.flag("-fexceptions");
1209
1210                 // easiest way to undefine since no API available in cc::Build to undefine
1211                 cfg.flag("-U_FORTIFY_SOURCE");
1212                 cfg.define("_FORTIFY_SOURCE", "0");
1213                 cfg.define("RUST_SGX", "1");
1214                 cfg.define("__NO_STRING_INLINES", None);
1215                 cfg.define("__NO_MATH_INLINES", None);
1216                 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1217                 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1218                 cfg.define("NDEBUG", None);
1219             }
1220             if self.target.contains("windows") {
1221                 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1222                 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1223             }
1224         }
1225
1226         cc_cfg.compiler(builder.cc(self.target));
1227         if let Ok(cxx) = builder.cxx(self.target) {
1228             cpp_cfg.compiler(cxx);
1229         } else {
1230             cc_cfg.compiler(builder.cc(self.target));
1231         }
1232
1233         // Don't set this for clang
1234         // By default, Clang builds C code in GNU C17 mode.
1235         // By default, Clang builds C++ code according to the C++98 standard,
1236         // with many C++11 features accepted as extensions.
1237         if cc_cfg.get_compiler().is_like_gnu() {
1238             cc_cfg.flag("-std=c99");
1239         }
1240         if cpp_cfg.get_compiler().is_like_gnu() {
1241             cpp_cfg.flag("-std=c++11");
1242         }
1243
1244         if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1245             // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1246             // C++ compiler env variables on the builders.
1247             // Don't set this for clang++, as clang++ is able to compile this without libc++.
1248             if cpp_cfg.get_compiler().is_like_gnu() {
1249                 cpp_cfg.cpp(false);
1250                 cpp_cfg.compiler(builder.cc(self.target));
1251             }
1252         }
1253
1254         let mut c_sources = vec![
1255             "Unwind-sjlj.c",
1256             "UnwindLevel1-gcc-ext.c",
1257             "UnwindLevel1.c",
1258             "UnwindRegistersRestore.S",
1259             "UnwindRegistersSave.S",
1260         ];
1261
1262         let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1263         let cpp_len = cpp_sources.len();
1264
1265         if self.target.contains("x86_64-fortanix-unknown-sgx") {
1266             c_sources.push("UnwindRustSgx.c");
1267         }
1268
1269         for src in c_sources {
1270             cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1271         }
1272
1273         for src in &cpp_sources {
1274             cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1275         }
1276
1277         cpp_cfg.compile("unwind-cpp");
1278
1279         // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1280         let mut count = 0;
1281         for entry in fs::read_dir(&out_dir).unwrap() {
1282             let file = entry.unwrap().path().canonicalize().unwrap();
1283             if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1284                 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1285                 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1286                 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1287                     cc_cfg.object(&file);
1288                     count += 1;
1289                 }
1290             }
1291         }
1292         assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1293
1294         cc_cfg.compile("unwind");
1295         out_dir
1296     }
1297 }