]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Auto merge of #86416 - Amanieu:asm_clobber_only, r=nagisa
[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::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 build_helper::{output, t};
20
21 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
22 use crate::config::TargetSelection;
23 use crate::util::{self, exe};
24 use crate::{Build, GitRepo};
25 use build_helper::up_to_date;
26
27 pub struct Meta {
28     stamp: HashStamp,
29     build_llvm_config: PathBuf,
30     out_dir: PathBuf,
31     root: String,
32 }
33
34 // This returns whether we've already previously built LLVM.
35 //
36 // It's used to avoid busting caches during x.py check -- if we've already built
37 // LLVM, it's fine for us to not try to avoid doing so.
38 //
39 // This will return the llvm-config if it can get it (but it will not build it
40 // if not).
41 pub fn prebuilt_llvm_config(
42     builder: &Builder<'_>,
43     target: TargetSelection,
44 ) -> Result<PathBuf, Meta> {
45     // If we're using a custom LLVM bail out here, but we can only use a
46     // custom LLVM for the build triple.
47     if let Some(config) = builder.config.target_config.get(&target) {
48         if let Some(ref s) = config.llvm_config {
49             check_llvm_version(builder, s);
50             return Ok(s.to_path_buf());
51         }
52     }
53
54     let root = "src/llvm-project/llvm";
55     let out_dir = builder.llvm_out(target);
56
57     let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
58     if !builder.config.build.contains("msvc") || builder.ninja() {
59         llvm_config_ret_dir.push("build");
60     }
61     llvm_config_ret_dir.push("bin");
62
63     let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
64
65     let stamp = out_dir.join("llvm-finished-building");
66     let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
67
68     if builder.config.llvm_skip_rebuild && stamp.path.exists() {
69         builder.info(
70             "Warning: \
71                 Using a potentially stale build of LLVM; \
72                 This may not behave well.",
73         );
74         return Ok(build_llvm_config);
75     }
76
77     if stamp.is_done() {
78         if stamp.hash.is_none() {
79             builder.info(
80                 "Could not determine the LLVM submodule commit hash. \
81                      Assuming that an LLVM rebuild is not necessary.",
82             );
83             builder.info(&format!(
84                 "To force LLVM to rebuild, remove the file `{}`",
85                 stamp.path.display()
86             ));
87         }
88         return Ok(build_llvm_config);
89     }
90
91     Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
92 }
93
94 // modified from `check_submodule` and `update_submodule` in bootstrap.py
95 pub(crate) fn update_llvm_submodule(build: &Build) {
96     let llvm_project = &Path::new("src").join("llvm-project");
97
98     fn dir_is_empty(dir: &Path) -> bool {
99         t!(std::fs::read_dir(dir)).next().is_none()
100     }
101
102     // NOTE: The check for the empty directory is here because when running x.py
103     // the first time, the llvm submodule won't be checked out. Check it out
104     // now so we can build it.
105     if !build.in_tree_llvm_info.is_git() && !dir_is_empty(&build.config.src.join(llvm_project)) {
106         return;
107     }
108
109     // check_submodule
110     if build.config.fast_submodules {
111         let checked_out_hash = output(
112             Command::new("git")
113                 .args(&["rev-parse", "HEAD"])
114                 .current_dir(build.config.src.join(llvm_project)),
115         );
116         // update_submodules
117         let recorded = output(
118             Command::new("git")
119                 .args(&["ls-tree", "HEAD"])
120                 .arg(llvm_project)
121                 .current_dir(&build.config.src),
122         );
123         let actual_hash = recorded
124             .split_whitespace()
125             .nth(2)
126             .unwrap_or_else(|| panic!("unexpected output `{}`", recorded));
127
128         // update_submodule
129         if actual_hash == checked_out_hash.trim_end() {
130             // already checked out
131             return;
132         }
133     }
134
135     println!("Updating submodule {}", llvm_project.display());
136     build.run(
137         Command::new("git")
138             .args(&["submodule", "-q", "sync"])
139             .arg(llvm_project)
140             .current_dir(&build.config.src),
141     );
142
143     // Try passing `--progress` to start, then run git again without if that fails.
144     let update = |progress: bool| {
145         let mut git = Command::new("git");
146         git.args(&["submodule", "update", "--init", "--recursive"]);
147         if progress {
148             git.arg("--progress");
149         }
150         git.arg(llvm_project).current_dir(&build.config.src);
151         git
152     };
153     // NOTE: doesn't use `try_run` because this shouldn't print an error if it fails.
154     if !update(true).status().map_or(false, |status| status.success()) {
155         build.run(&mut update(false));
156     }
157
158     build.run(
159         Command::new("git")
160             .args(&["reset", "-q", "--hard"])
161             .current_dir(build.config.src.join(llvm_project)),
162     );
163     build.run(
164         Command::new("git")
165             .args(&["clean", "-qdfx"])
166             .current_dir(build.config.src.join(llvm_project)),
167     );
168 }
169
170 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
171 pub struct Llvm {
172     pub target: TargetSelection,
173 }
174
175 impl Step for Llvm {
176     type Output = PathBuf; // path to llvm-config
177
178     const ONLY_HOSTS: bool = true;
179
180     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
181         run.path("src/llvm-project").path("src/llvm-project/llvm").path("src/llvm")
182     }
183
184     fn make_run(run: RunConfig<'_>) {
185         run.builder.ensure(Llvm { target: run.target });
186     }
187
188     /// Compile LLVM for `target`.
189     fn run(self, builder: &Builder<'_>) -> PathBuf {
190         let target = self.target;
191         let target_native = if self.target.starts_with("riscv") {
192             // RISC-V target triples in Rust is not named the same as C compiler target triples.
193             // This converts Rust RISC-V target triples to C compiler triples.
194             let idx = target.triple.find('-').unwrap();
195
196             format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
197         } else {
198             target.to_string()
199         };
200
201         let Meta { stamp, build_llvm_config, out_dir, root } =
202             match prebuilt_llvm_config(builder, target) {
203                 Ok(p) => return p,
204                 Err(m) => m,
205             };
206
207         if !builder.config.dry_run {
208             update_llvm_submodule(builder);
209         }
210         if builder.config.llvm_link_shared
211             && (target.contains("windows") || target.contains("apple-darwin"))
212         {
213             panic!("shared linking to LLVM is not currently supported on {}", target.triple);
214         }
215
216         builder.info(&format!("Building LLVM for {}", target));
217         t!(stamp.remove());
218         let _time = util::timeit(&builder);
219         t!(fs::create_dir_all(&out_dir));
220
221         // https://llvm.org/docs/CMake.html
222         let mut cfg = cmake::Config::new(builder.src.join(root));
223
224         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
225             (false, _) => "Debug",
226             (true, false) => "Release",
227             (true, true) => "RelWithDebInfo",
228         };
229
230         // NOTE: remember to also update `config.toml.example` when changing the
231         // defaults!
232         let llvm_targets = match &builder.config.llvm_targets {
233             Some(s) => s,
234             None => {
235                 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
236                      Sparc;SystemZ;WebAssembly;X86"
237             }
238         };
239
240         let llvm_exp_targets = match builder.config.llvm_experimental_targets {
241             Some(ref s) => s,
242             None => "AVR",
243         };
244
245         let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
246
247         cfg.out_dir(&out_dir)
248             .profile(profile)
249             .define("LLVM_ENABLE_ASSERTIONS", assertions)
250             .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
251             .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
252             .define("LLVM_INCLUDE_EXAMPLES", "OFF")
253             .define("LLVM_INCLUDE_DOCS", "OFF")
254             .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
255             .define("LLVM_ENABLE_TERMINFO", "OFF")
256             .define("LLVM_ENABLE_LIBEDIT", "OFF")
257             .define("LLVM_ENABLE_BINDINGS", "OFF")
258             .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
259             .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
260             .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
261             .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
262
263         if target != "aarch64-apple-darwin" && !target.contains("windows") {
264             cfg.define("LLVM_ENABLE_ZLIB", "ON");
265         } else {
266             cfg.define("LLVM_ENABLE_ZLIB", "OFF");
267         }
268
269         // Are we compiling for iOS/tvOS?
270         if target.contains("apple-ios") || target.contains("apple-tvos") {
271             // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
272             cfg.define("CMAKE_OSX_SYSROOT", "/");
273             cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
274             // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
275             cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
276             // Zlib fails to link properly, leading to a compiler error.
277             cfg.define("LLVM_ENABLE_ZLIB", "OFF");
278         }
279
280         if builder.config.llvm_thin_lto {
281             cfg.define("LLVM_ENABLE_LTO", "Thin");
282             if !target.contains("apple") {
283                 cfg.define("LLVM_ENABLE_LLD", "ON");
284             }
285         }
286
287         // This setting makes the LLVM tools link to the dynamic LLVM library,
288         // which saves both memory during parallel links and overall disk space
289         // for the tools. We don't do this on every platform as it doesn't work
290         // equally well everywhere.
291         //
292         // If we're not linking rustc to a dynamic LLVM, though, then don't link
293         // tools to it.
294         if builder.llvm_link_tools_dynamically(target) && builder.config.llvm_link_shared {
295             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
296         }
297
298         // For distribution we want the LLVM tools to be *statically* linked to libstdc++
299         if builder.config.llvm_tools_enabled {
300             if !target.contains("msvc") {
301                 if target.contains("apple") {
302                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
303                 } else {
304                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
305                 }
306             }
307         }
308
309         if target.starts_with("riscv") {
310             // In RISC-V, using C++ atomics require linking to `libatomic` but the LLVM build
311             // system check cannot detect this. Therefore it is set manually here.
312             if !builder.config.llvm_tools_enabled {
313                 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-latomic");
314             } else {
315                 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-latomic -static-libstdc++");
316             }
317             cfg.define("CMAKE_SHARED_LINKER_FLAGS", "-latomic");
318         }
319
320         if target.contains("msvc") {
321             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
322             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
323             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
324             cfg.static_crt(true);
325         }
326
327         if target.starts_with("i686") {
328             cfg.define("LLVM_BUILD_32_BITS", "ON");
329         }
330
331         let mut enabled_llvm_projects = Vec::new();
332
333         if util::forcing_clang_based_tests() {
334             enabled_llvm_projects.push("clang");
335             enabled_llvm_projects.push("compiler-rt");
336         }
337
338         if builder.config.llvm_polly {
339             enabled_llvm_projects.push("polly");
340         }
341
342         // We want libxml to be disabled.
343         // See https://github.com/rust-lang/rust/pull/50104
344         cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
345
346         if !enabled_llvm_projects.is_empty() {
347             enabled_llvm_projects.sort();
348             enabled_llvm_projects.dedup();
349             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
350         }
351
352         if let Some(num_linkers) = builder.config.llvm_link_jobs {
353             if num_linkers > 0 {
354                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
355             }
356         }
357
358         // https://llvm.org/docs/HowToCrossCompileLLVM.html
359         if target != builder.config.build {
360             builder.ensure(Llvm { target: builder.config.build });
361             // FIXME: if the llvm root for the build triple is overridden then we
362             //        should use llvm-tblgen from there, also should verify that it
363             //        actually exists most of the time in normal installs of LLVM.
364             let host_bin = builder.llvm_out(builder.config.build).join("bin");
365             cfg.define("CMAKE_CROSSCOMPILING", "True");
366             cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
367             cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
368             cfg.define(
369                 "LLVM_CONFIG_PATH",
370                 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
371             );
372         }
373
374         if let Some(ref suffix) = builder.config.llvm_version_suffix {
375             // Allow version-suffix="" to not define a version suffix at all.
376             if !suffix.is_empty() {
377                 cfg.define("LLVM_VERSION_SUFFIX", suffix);
378             }
379         } else if builder.config.channel == "dev" {
380             // Changes to a version suffix require a complete rebuild of the LLVM.
381             // To avoid rebuilds during a time of version bump, don't include rustc
382             // release number on the dev channel.
383             cfg.define("LLVM_VERSION_SUFFIX", "-rust-dev");
384         } else {
385             let suffix = format!("-rust-{}-{}", builder.version, builder.config.channel);
386             cfg.define("LLVM_VERSION_SUFFIX", suffix);
387         }
388
389         if let Some(ref linker) = builder.config.llvm_use_linker {
390             cfg.define("LLVM_USE_LINKER", linker);
391         }
392
393         if builder.config.llvm_allow_old_toolchain {
394             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
395         }
396
397         configure_cmake(builder, target, &mut cfg, true);
398
399         // FIXME: we don't actually need to build all LLVM tools and all LLVM
400         //        libraries here, e.g., we just want a few components and a few
401         //        tools. Figure out how to filter them down and only build the right
402         //        tools and libs on all platforms.
403
404         if builder.config.dry_run {
405             return build_llvm_config;
406         }
407
408         cfg.build();
409
410         t!(stamp.write());
411
412         build_llvm_config
413     }
414 }
415
416 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
417     if !builder.config.llvm_version_check {
418         return;
419     }
420
421     if builder.config.dry_run {
422         return;
423     }
424
425     let mut cmd = Command::new(llvm_config);
426     let version = output(cmd.arg("--version"));
427     let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
428     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
429         if major >= 10 {
430             return;
431         }
432     }
433     panic!("\n\nbad LLVM version: {}, need >=10.0\n\n", version)
434 }
435
436 fn configure_cmake(
437     builder: &Builder<'_>,
438     target: TargetSelection,
439     cfg: &mut cmake::Config,
440     use_compiler_launcher: bool,
441 ) {
442     // Do not print installation messages for up-to-date files.
443     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
444     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
445
446     // Do not allow the user's value of DESTDIR to influence where
447     // LLVM will install itself. LLVM must always be installed in our
448     // own build directories.
449     cfg.env("DESTDIR", "");
450
451     if builder.ninja() {
452         cfg.generator("Ninja");
453     }
454     cfg.target(&target.triple).host(&builder.config.build.triple);
455
456     if target != builder.config.build {
457         if target.contains("netbsd") {
458             cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
459         } else if target.contains("freebsd") {
460             cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
461         } else if target.contains("windows") {
462             cfg.define("CMAKE_SYSTEM_NAME", "Windows");
463         } else if target.contains("haiku") {
464             cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
465         } else if target.contains("solaris") || target.contains("illumos") {
466             cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
467         }
468         // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
469         // that case like CMake we cannot easily determine system version either.
470         //
471         // Since, the LLVM itself makes rather limited use of version checks in
472         // CMakeFiles (and then only in tests), and so far no issues have been
473         // reported, the system version is currently left unset.
474     }
475
476     let sanitize_cc = |cc: &Path| {
477         if target.contains("msvc") {
478             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
479         } else {
480             cc.as_os_str().to_owned()
481         }
482     };
483
484     // MSVC with CMake uses msbuild by default which doesn't respect these
485     // vars that we'd otherwise configure. In that case we just skip this
486     // entirely.
487     if target.contains("msvc") && !builder.ninja() {
488         return;
489     }
490
491     let (cc, cxx) = match builder.config.llvm_clang_cl {
492         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
493         None => (builder.cc(target), builder.cxx(target).unwrap()),
494     };
495
496     // Handle msvc + ninja + ccache specially (this is what the bots use)
497     if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
498         let mut wrap_cc = env::current_exe().expect("failed to get cwd");
499         wrap_cc.set_file_name("sccache-plus-cl.exe");
500
501         cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
502             .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
503         cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
504             .env("SCCACHE_TARGET", target.triple)
505             .env("SCCACHE_CC", &cc)
506             .env("SCCACHE_CXX", &cxx);
507
508         // Building LLVM on MSVC can be a little ludicrous at times. We're so far
509         // off the beaten path here that I'm not really sure this is even half
510         // supported any more. Here we're trying to:
511         //
512         // * Build LLVM on MSVC
513         // * Build LLVM with `clang-cl` instead of `cl.exe`
514         // * Build a project with `sccache`
515         // * Build for 32-bit as well
516         // * Build with Ninja
517         //
518         // For `cl.exe` there are different binaries to compile 32/64 bit which
519         // we use but for `clang-cl` there's only one which internally
520         // multiplexes via flags. As a result it appears that CMake's detection
521         // of a compiler's architecture and such on MSVC **doesn't** pass any
522         // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
523         // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
524         // definitely causes problems since all the env vars are pointing to
525         // 32-bit libraries.
526         //
527         // To hack around this... again... we pass an argument that's
528         // unconditionally passed in the sccache shim. This'll get CMake to
529         // correctly diagnose it's doing a 32-bit compilation and LLVM will
530         // internally configure itself appropriately.
531         if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
532             cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
533         }
534     } else {
535         // If ccache is configured we inform the build a little differently how
536         // to invoke ccache while also invoking our compilers.
537         if use_compiler_launcher {
538             if let Some(ref ccache) = builder.config.ccache {
539                 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
540                     .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
541             }
542         }
543         cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
544             .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
545             .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
546     }
547
548     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
549     let mut cflags = builder.cflags(target, GitRepo::Llvm).join(" ");
550     if let Some(ref s) = builder.config.llvm_cflags {
551         cflags.push_str(&format!(" {}", s));
552     }
553     // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
554     if target.contains("apple-ios") {
555         if target.contains("86-") {
556             cflags.push_str(" -miphonesimulator-version-min=10.0");
557         } else {
558             cflags.push_str(" -miphoneos-version-min=10.0");
559         }
560     }
561     if builder.config.llvm_clang_cl.is_some() {
562         cflags.push_str(&format!(" --target={}", target))
563     }
564     cfg.define("CMAKE_C_FLAGS", cflags);
565     let mut cxxflags = builder.cflags(target, GitRepo::Llvm).join(" ");
566     if builder.config.llvm_static_stdcpp && !target.contains("msvc") && !target.contains("netbsd") {
567         cxxflags.push_str(" -static-libstdc++");
568     }
569     if let Some(ref s) = builder.config.llvm_cxxflags {
570         cxxflags.push_str(&format!(" {}", s));
571     }
572     if builder.config.llvm_clang_cl.is_some() {
573         cxxflags.push_str(&format!(" --target={}", target))
574     }
575     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
576     if let Some(ar) = builder.ar(target) {
577         if ar.is_absolute() {
578             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
579             // tries to resolve this path in the LLVM build directory.
580             cfg.define("CMAKE_AR", sanitize_cc(ar));
581         }
582     }
583
584     if let Some(ranlib) = builder.ranlib(target) {
585         if ranlib.is_absolute() {
586             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
587             // tries to resolve this path in the LLVM build directory.
588             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
589         }
590     }
591
592     if let Some(ref s) = builder.config.llvm_ldflags {
593         cfg.define("CMAKE_SHARED_LINKER_FLAGS", s);
594         cfg.define("CMAKE_MODULE_LINKER_FLAGS", s);
595         cfg.define("CMAKE_EXE_LINKER_FLAGS", s);
596     }
597
598     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
599         cfg.env("RUSTC_LOG", "sccache=warn");
600     }
601 }
602
603 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
604 pub struct Lld {
605     pub target: TargetSelection,
606 }
607
608 impl Step for Lld {
609     type Output = PathBuf;
610     const ONLY_HOSTS: bool = true;
611
612     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
613         run.path("src/llvm-project/lld").path("src/tools/lld")
614     }
615
616     fn make_run(run: RunConfig<'_>) {
617         run.builder.ensure(Lld { target: run.target });
618     }
619
620     /// Compile LLD for `target`.
621     fn run(self, builder: &Builder<'_>) -> PathBuf {
622         if builder.config.dry_run {
623             return PathBuf::from("lld-out-dir-test-gen");
624         }
625         let target = self.target;
626
627         let llvm_config = builder.ensure(Llvm { target: self.target });
628
629         let out_dir = builder.lld_out(target);
630         let done_stamp = out_dir.join("lld-finished-building");
631         if done_stamp.exists() {
632             return out_dir;
633         }
634
635         builder.info(&format!("Building LLD for {}", target));
636         let _time = util::timeit(&builder);
637         t!(fs::create_dir_all(&out_dir));
638
639         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
640         configure_cmake(builder, target, &mut cfg, true);
641
642         // This is an awful, awful hack. Discovered when we migrated to using
643         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
644         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
645         // that directory for later processing. Unfortunately if this path has
646         // forward slashes in it (which it basically always does on Windows)
647         // then CMake will hit a syntax error later on as... something isn't
648         // escaped it seems?
649         //
650         // Instead of attempting to fix this problem in upstream CMake and/or
651         // LLVM/LLD we just hack around it here. This thin wrapper will take the
652         // output from llvm-config and replace all instances of `\` with `/` to
653         // ensure we don't hit the same bugs with escaping. It means that you
654         // can't build on a system where your paths require `\` on Windows, but
655         // there's probably a lot of reasons you can't do that other than this.
656         let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
657
658         cfg.out_dir(&out_dir)
659             .profile("Release")
660             .env("LLVM_CONFIG_REAL", &llvm_config)
661             .define("LLVM_CONFIG_PATH", llvm_config_shim)
662             .define("LLVM_INCLUDE_TESTS", "OFF");
663
664         // While we're using this horrible workaround to shim the execution of
665         // llvm-config, let's just pile on more. I can't seem to figure out how
666         // to build LLD as a standalone project and also cross-compile it at the
667         // same time. It wants a natively executable `llvm-config` to learn
668         // about LLVM, but then it learns about all the host configuration of
669         // LLVM and tries to link to host LLVM libraries.
670         //
671         // To work around that we tell our shim to replace anything with the
672         // build target with the actual target instead. This'll break parts of
673         // LLD though which try to execute host tools, such as llvm-tblgen, so
674         // we specifically tell it where to find those. This is likely super
675         // brittle and will break over time. If anyone knows better how to
676         // cross-compile LLD it would be much appreciated to fix this!
677         if target != builder.config.build {
678             cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
679                 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
680                 .define(
681                     "LLVM_TABLEGEN_EXE",
682                     llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
683                 );
684         }
685
686         // Explicitly set C++ standard, because upstream doesn't do so
687         // for standalone builds.
688         cfg.define("CMAKE_CXX_STANDARD", "14");
689
690         cfg.build();
691
692         t!(File::create(&done_stamp));
693         out_dir
694     }
695 }
696
697 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
698 pub struct TestHelpers {
699     pub target: TargetSelection,
700 }
701
702 impl Step for TestHelpers {
703     type Output = ();
704
705     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
706         run.path("src/test/auxiliary/rust_test_helpers.c")
707     }
708
709     fn make_run(run: RunConfig<'_>) {
710         run.builder.ensure(TestHelpers { target: run.target })
711     }
712
713     /// Compiles the `rust_test_helpers.c` library which we used in various
714     /// `run-pass` tests for ABI testing.
715     fn run(self, builder: &Builder<'_>) {
716         if builder.config.dry_run {
717             return;
718         }
719         // The x86_64-fortanix-unknown-sgx target doesn't have a working C
720         // toolchain. However, some x86_64 ELF objects can be linked
721         // without issues. Use this hack to compile the test helpers.
722         let target = if self.target == "x86_64-fortanix-unknown-sgx" {
723             TargetSelection::from_user("x86_64-unknown-linux-gnu")
724         } else {
725             self.target
726         };
727         let dst = builder.test_helpers_out(target);
728         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
729         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
730             return;
731         }
732
733         builder.info("Building test helpers");
734         t!(fs::create_dir_all(&dst));
735         let mut cfg = cc::Build::new();
736         // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
737         if target.contains("emscripten") {
738             cfg.pic(false);
739         }
740
741         // We may have found various cross-compilers a little differently due to our
742         // extra configuration, so inform cc of these compilers. Note, though, that
743         // on MSVC we still need cc's detection of env vars (ugh).
744         if !target.contains("msvc") {
745             if let Some(ar) = builder.ar(target) {
746                 cfg.archiver(ar);
747             }
748             cfg.compiler(builder.cc(target));
749         }
750         cfg.cargo_metadata(false)
751             .out_dir(&dst)
752             .target(&target.triple)
753             .host(&builder.config.build.triple)
754             .opt_level(0)
755             .warnings(false)
756             .debug(false)
757             .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
758             .compile("rust_test_helpers");
759     }
760 }
761
762 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
763 pub struct Sanitizers {
764     pub target: TargetSelection,
765 }
766
767 impl Step for Sanitizers {
768     type Output = Vec<SanitizerRuntime>;
769
770     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
771         run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
772     }
773
774     fn make_run(run: RunConfig<'_>) {
775         run.builder.ensure(Sanitizers { target: run.target });
776     }
777
778     /// Builds sanitizer runtime libraries.
779     fn run(self, builder: &Builder<'_>) -> Self::Output {
780         let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
781         if !compiler_rt_dir.exists() {
782             return Vec::new();
783         }
784
785         let out_dir = builder.native_dir(self.target).join("sanitizers");
786         let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
787         if runtimes.is_empty() {
788             return runtimes;
789         }
790
791         let llvm_config = builder.ensure(Llvm { target: builder.config.build });
792         if builder.config.dry_run {
793             return runtimes;
794         }
795
796         let stamp = out_dir.join("sanitizers-finished-building");
797         let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
798
799         if stamp.is_done() {
800             if stamp.hash.is_none() {
801                 builder.info(&format!(
802                     "Rebuild sanitizers by removing the file `{}`",
803                     stamp.path.display()
804                 ));
805             }
806             return runtimes;
807         }
808
809         builder.info(&format!("Building sanitizers for {}", self.target));
810         t!(stamp.remove());
811         let _time = util::timeit(&builder);
812
813         let mut cfg = cmake::Config::new(&compiler_rt_dir);
814         cfg.profile("Release");
815         cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
816         cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
817         cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
818         cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
819         cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
820         cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
821         cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
822         cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
823         cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
824         cfg.define("LLVM_CONFIG_PATH", &llvm_config);
825
826         // On Darwin targets the sanitizer runtimes are build as universal binaries.
827         // Unfortunately sccache currently lacks support to build them successfully.
828         // Disable compiler launcher on Darwin targets to avoid potential issues.
829         let use_compiler_launcher = !self.target.contains("apple-darwin");
830         configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher);
831
832         t!(fs::create_dir_all(&out_dir));
833         cfg.out_dir(out_dir);
834
835         for runtime in &runtimes {
836             cfg.build_target(&runtime.cmake_target);
837             cfg.build();
838         }
839         t!(stamp.write());
840
841         runtimes
842     }
843 }
844
845 #[derive(Clone, Debug)]
846 pub struct SanitizerRuntime {
847     /// CMake target used to build the runtime.
848     pub cmake_target: String,
849     /// Path to the built runtime library.
850     pub path: PathBuf,
851     /// Library filename that will be used rustc.
852     pub name: String,
853 }
854
855 /// Returns sanitizers available on a given target.
856 fn supported_sanitizers(
857     out_dir: &Path,
858     target: TargetSelection,
859     channel: &str,
860 ) -> Vec<SanitizerRuntime> {
861     let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
862         components
863             .iter()
864             .map(move |c| SanitizerRuntime {
865                 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
866                 path: out_dir
867                     .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
868                 name: format!("librustc-{}_rt.{}.dylib", channel, c),
869             })
870             .collect()
871     };
872
873     let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
874         components
875             .iter()
876             .map(move |c| SanitizerRuntime {
877                 cmake_target: format!("clang_rt.{}-{}", c, arch),
878                 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
879                 name: format!("librustc-{}_rt.{}.a", channel, c),
880             })
881             .collect()
882     };
883
884     match &*target.triple {
885         "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
886         "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
887         "aarch64-unknown-linux-gnu" => {
888             common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
889         }
890         "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
891         "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
892         "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
893         "x86_64-unknown-linux-gnu" => {
894             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
895         }
896         "x86_64-unknown-linux-musl" => {
897             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
898         }
899         _ => Vec::new(),
900     }
901 }
902
903 struct HashStamp {
904     path: PathBuf,
905     hash: Option<Vec<u8>>,
906 }
907
908 impl HashStamp {
909     fn new(path: PathBuf, hash: Option<&str>) -> Self {
910         HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
911     }
912
913     fn is_done(&self) -> bool {
914         match fs::read(&self.path) {
915             Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
916             Err(e) if e.kind() == io::ErrorKind::NotFound => false,
917             Err(e) => {
918                 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
919             }
920         }
921     }
922
923     fn remove(&self) -> io::Result<()> {
924         match fs::remove_file(&self.path) {
925             Ok(()) => Ok(()),
926             Err(e) => {
927                 if e.kind() == io::ErrorKind::NotFound {
928                     Ok(())
929                 } else {
930                     Err(e)
931                 }
932             }
933         }
934     }
935
936     fn write(&self) -> io::Result<()> {
937         fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
938     }
939 }
940
941 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
942 pub struct CrtBeginEnd {
943     pub target: TargetSelection,
944 }
945
946 impl Step for CrtBeginEnd {
947     type Output = PathBuf;
948
949     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
950         run.path("src/llvm-project/compiler-rt/lib/crt")
951     }
952
953     fn make_run(run: RunConfig<'_>) {
954         run.builder.ensure(CrtBeginEnd { target: run.target });
955     }
956
957     /// Build crtbegin.o/crtend.o for musl target.
958     fn run(self, builder: &Builder<'_>) -> Self::Output {
959         let out_dir = builder.native_dir(self.target).join("crt");
960
961         if builder.config.dry_run {
962             return out_dir;
963         }
964
965         let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
966         let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
967         if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
968             && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
969         {
970             return out_dir;
971         }
972
973         builder.info("Building crtbegin.o and crtend.o");
974         t!(fs::create_dir_all(&out_dir));
975
976         let mut cfg = cc::Build::new();
977
978         if let Some(ar) = builder.ar(self.target) {
979             cfg.archiver(ar);
980         }
981         cfg.compiler(builder.cc(self.target));
982         cfg.cargo_metadata(false)
983             .out_dir(&out_dir)
984             .target(&self.target.triple)
985             .host(&builder.config.build.triple)
986             .warnings(false)
987             .debug(false)
988             .opt_level(3)
989             .file(crtbegin_src)
990             .file(crtend_src);
991
992         // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
993         // Currently only consumer of those objects is musl, which use .init_array/.fini_array
994         // instead of .ctors/.dtors
995         cfg.flag("-std=c11")
996             .define("CRT_HAS_INITFINI_ARRAY", None)
997             .define("EH_USE_FRAME_REGISTRY", None);
998
999         cfg.compile("crt");
1000
1001         t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1002         t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1003         out_dir
1004     }
1005 }