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