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