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