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