]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Rollup merge of #69481 - matthiaskrgr:single_char, r=ecstatic-morse
[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::ffi::OsString;
13 use std::fs::{self, File};
14 use std::path::{Path, PathBuf};
15 use std::process::Command;
16
17 use build_helper::{output, t};
18
19 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
20 use crate::cache::Interned;
21 use crate::channel;
22 use crate::util::{self, exe};
23 use crate::GitRepo;
24 use build_helper::up_to_date;
25
26 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
27 pub struct Llvm {
28     pub target: Interned<String>,
29 }
30
31 impl Step for Llvm {
32     type Output = PathBuf; // path to llvm-config
33
34     const ONLY_HOSTS: bool = true;
35
36     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
37         run.path("src/llvm-project").path("src/llvm-project/llvm").path("src/llvm")
38     }
39
40     fn make_run(run: RunConfig<'_>) {
41         run.builder.ensure(Llvm { target: run.target });
42     }
43
44     /// Compile LLVM for `target`.
45     fn run(self, builder: &Builder<'_>) -> PathBuf {
46         let target = self.target;
47
48         // If we're using a custom LLVM bail out here, but we can only use a
49         // custom LLVM for the build triple.
50         if let Some(config) = builder.config.target_config.get(&target) {
51             if let Some(ref s) = config.llvm_config {
52                 check_llvm_version(builder, s);
53                 return s.to_path_buf();
54             }
55         }
56
57         let llvm_info = &builder.in_tree_llvm_info;
58         let root = "src/llvm-project/llvm";
59         let out_dir = builder.llvm_out(target);
60         let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
61         if !builder.config.build.contains("msvc") || builder.config.ninja {
62             llvm_config_ret_dir.push("build");
63         }
64         llvm_config_ret_dir.push("bin");
65
66         let build_llvm_config =
67             llvm_config_ret_dir.join(exe("llvm-config", &*builder.config.build));
68         let done_stamp = out_dir.join("llvm-finished-building");
69
70         if done_stamp.exists() {
71             if builder.config.llvm_skip_rebuild {
72                 builder.info(
73                     "Warning: \
74                     Using a potentially stale build of LLVM; \
75                     This may not behave well.",
76                 );
77                 return build_llvm_config;
78             }
79
80             if let Some(llvm_commit) = llvm_info.sha() {
81                 let done_contents = t!(fs::read(&done_stamp));
82
83                 // If LLVM was already built previously and the submodule's commit didn't change
84                 // from the previous build, then no action is required.
85                 if done_contents == llvm_commit.as_bytes() {
86                     return build_llvm_config;
87                 }
88             } else {
89                 builder.info(
90                     "Could not determine the LLVM submodule commit hash. \
91                      Assuming that an LLVM rebuild is not necessary.",
92                 );
93                 builder.info(&format!(
94                     "To force LLVM to rebuild, remove the file `{}`",
95                     done_stamp.display()
96                 ));
97                 return build_llvm_config;
98             }
99         }
100
101         builder.info(&format!("Building LLVM for {}", target));
102         let _time = util::timeit(&builder);
103         t!(fs::create_dir_all(&out_dir));
104
105         // http://llvm.org/docs/CMake.html
106         let mut cfg = cmake::Config::new(builder.src.join(root));
107
108         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
109             (false, _) => "Debug",
110             (true, false) => "Release",
111             (true, true) => "RelWithDebInfo",
112         };
113
114         // NOTE: remember to also update `config.toml.example` when changing the
115         // defaults!
116         let llvm_targets = match &builder.config.llvm_targets {
117             Some(s) => s,
118             None => {
119                 "AArch64;ARM;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
120                      Sparc;SystemZ;WebAssembly;X86"
121             }
122         };
123
124         let llvm_exp_targets = match builder.config.llvm_experimental_targets {
125             Some(ref s) => s,
126             None => "",
127         };
128
129         let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
130
131         cfg.out_dir(&out_dir)
132             .profile(profile)
133             .define("LLVM_ENABLE_ASSERTIONS", assertions)
134             .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
135             .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
136             .define("LLVM_INCLUDE_EXAMPLES", "OFF")
137             .define("LLVM_INCLUDE_TESTS", "OFF")
138             .define("LLVM_INCLUDE_DOCS", "OFF")
139             .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
140             .define("LLVM_ENABLE_ZLIB", "OFF")
141             .define("WITH_POLLY", "OFF")
142             .define("LLVM_ENABLE_TERMINFO", "OFF")
143             .define("LLVM_ENABLE_LIBEDIT", "OFF")
144             .define("LLVM_ENABLE_BINDINGS", "OFF")
145             .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
146             .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
147             .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
148             .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
149
150         if builder.config.llvm_thin_lto {
151             cfg.define("LLVM_ENABLE_LTO", "Thin");
152             if !target.contains("apple") {
153                 cfg.define("LLVM_ENABLE_LLD", "ON");
154             }
155         }
156
157         // This setting makes the LLVM tools link to the dynamic LLVM library,
158         // which saves both memory during parallel links and overall disk space
159         // for the tools. We don't do this on every platform as it doesn't work
160         // equally well everywhere.
161         if builder.llvm_link_tools_dynamically(target) {
162             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
163         }
164
165         // For distribution we want the LLVM tools to be *statically* linked to libstdc++
166         if builder.config.llvm_tools_enabled || builder.config.lldb_enabled {
167             if !target.contains("msvc") {
168                 if target.contains("apple") {
169                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
170                 } else {
171                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
172                 }
173             }
174         }
175
176         if target.contains("msvc") {
177             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
178             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
179             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
180             cfg.static_crt(true);
181         }
182
183         if target.starts_with("i686") {
184             cfg.define("LLVM_BUILD_32_BITS", "ON");
185         }
186
187         let mut enabled_llvm_projects = Vec::new();
188
189         if util::forcing_clang_based_tests() {
190             enabled_llvm_projects.push("clang");
191             enabled_llvm_projects.push("compiler-rt");
192         }
193
194         if builder.config.lldb_enabled {
195             enabled_llvm_projects.push("clang");
196             enabled_llvm_projects.push("lldb");
197             // For the time being, disable code signing.
198             cfg.define("LLDB_CODESIGN_IDENTITY", "");
199             cfg.define("LLDB_NO_DEBUGSERVER", "ON");
200         } else {
201             // LLDB requires libxml2; but otherwise we want it to be disabled.
202             // See https://github.com/rust-lang/rust/pull/50104
203             cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
204         }
205
206         if !enabled_llvm_projects.is_empty() {
207             enabled_llvm_projects.sort();
208             enabled_llvm_projects.dedup();
209             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
210         }
211
212         if let Some(num_linkers) = builder.config.llvm_link_jobs {
213             if num_linkers > 0 {
214                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
215             }
216         }
217
218         // http://llvm.org/docs/HowToCrossCompileLLVM.html
219         if target != builder.config.build {
220             builder.ensure(Llvm { target: builder.config.build });
221             // FIXME: if the llvm root for the build triple is overridden then we
222             //        should use llvm-tblgen from there, also should verify that it
223             //        actually exists most of the time in normal installs of LLVM.
224             let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
225             cfg.define("CMAKE_CROSSCOMPILING", "True").define("LLVM_TABLEGEN", &host);
226
227             if target.contains("netbsd") {
228                 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
229             } else if target.contains("freebsd") {
230                 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
231             } else if target.contains("windows") {
232                 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
233             }
234
235             cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
236         }
237
238         if let Some(ref suffix) = builder.config.llvm_version_suffix {
239             // Allow version-suffix="" to not define a version suffix at all.
240             if !suffix.is_empty() {
241                 cfg.define("LLVM_VERSION_SUFFIX", suffix);
242             }
243         } else {
244             let mut default_suffix =
245                 format!("-rust-{}-{}", channel::CFG_RELEASE_NUM, builder.config.channel,);
246             if let Some(sha) = llvm_info.sha_short() {
247                 default_suffix.push_str("-");
248                 default_suffix.push_str(sha);
249             }
250             cfg.define("LLVM_VERSION_SUFFIX", default_suffix);
251         }
252
253         if let Some(ref linker) = builder.config.llvm_use_linker {
254             cfg.define("LLVM_USE_LINKER", linker);
255         }
256
257         if let Some(true) = builder.config.llvm_allow_old_toolchain {
258             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
259         }
260
261         if let Some(ref python) = builder.config.python {
262             cfg.define("PYTHON_EXECUTABLE", python);
263         }
264
265         configure_cmake(builder, target, &mut cfg, true);
266
267         // FIXME: we don't actually need to build all LLVM tools and all LLVM
268         //        libraries here, e.g., we just want a few components and a few
269         //        tools. Figure out how to filter them down and only build the right
270         //        tools and libs on all platforms.
271
272         if builder.config.dry_run {
273             return build_llvm_config;
274         }
275
276         cfg.build();
277
278         t!(fs::write(&done_stamp, llvm_info.sha().unwrap_or("")));
279
280         build_llvm_config
281     }
282 }
283
284 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
285     if !builder.config.llvm_version_check {
286         return;
287     }
288
289     if builder.config.dry_run {
290         return;
291     }
292
293     let mut cmd = Command::new(llvm_config);
294     let version = output(cmd.arg("--version"));
295     let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
296     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
297         if major >= 7 {
298             return;
299         }
300     }
301     panic!("\n\nbad LLVM version: {}, need >=7.0\n\n", version)
302 }
303
304 fn configure_cmake(
305     builder: &Builder<'_>,
306     target: Interned<String>,
307     cfg: &mut cmake::Config,
308     use_compiler_launcher: bool,
309 ) {
310     // Do not print installation messages for up-to-date files.
311     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
312     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
313
314     if builder.config.ninja {
315         cfg.generator("Ninja");
316     }
317     cfg.target(&target).host(&builder.config.build);
318
319     let sanitize_cc = |cc: &Path| {
320         if target.contains("msvc") {
321             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
322         } else {
323             cc.as_os_str().to_owned()
324         }
325     };
326
327     // MSVC with CMake uses msbuild by default which doesn't respect these
328     // vars that we'd otherwise configure. In that case we just skip this
329     // entirely.
330     if target.contains("msvc") && !builder.config.ninja {
331         return;
332     }
333
334     let (cc, cxx) = match builder.config.llvm_clang_cl {
335         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
336         None => (builder.cc(target), builder.cxx(target).unwrap()),
337     };
338
339     // Handle msvc + ninja + ccache specially (this is what the bots use)
340     if target.contains("msvc") && builder.config.ninja && builder.config.ccache.is_some() {
341         let mut wrap_cc = env::current_exe().expect("failed to get cwd");
342         wrap_cc.set_file_name("sccache-plus-cl.exe");
343
344         cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
345             .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
346         cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
347             .env("SCCACHE_TARGET", target)
348             .env("SCCACHE_CC", &cc)
349             .env("SCCACHE_CXX", &cxx);
350
351         // Building LLVM on MSVC can be a little ludicrous at times. We're so far
352         // off the beaten path here that I'm not really sure this is even half
353         // supported any more. Here we're trying to:
354         //
355         // * Build LLVM on MSVC
356         // * Build LLVM with `clang-cl` instead of `cl.exe`
357         // * Build a project with `sccache`
358         // * Build for 32-bit as well
359         // * Build with Ninja
360         //
361         // For `cl.exe` there are different binaries to compile 32/64 bit which
362         // we use but for `clang-cl` there's only one which internally
363         // multiplexes via flags. As a result it appears that CMake's detection
364         // of a compiler's architecture and such on MSVC **doesn't** pass any
365         // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
366         // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
367         // definitely causes problems since all the env vars are pointing to
368         // 32-bit libraries.
369         //
370         // To hack around this... again... we pass an argument that's
371         // unconditionally passed in the sccache shim. This'll get CMake to
372         // correctly diagnose it's doing a 32-bit compilation and LLVM will
373         // internally configure itself appropriately.
374         if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
375             cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
376         }
377     } else {
378         // If ccache is configured we inform the build a little differently how
379         // to invoke ccache while also invoking our compilers.
380         if use_compiler_launcher {
381             if let Some(ref ccache) = builder.config.ccache {
382                 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
383                     .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
384             }
385         }
386         cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
387             .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
388     }
389
390     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
391     let mut cflags = builder.cflags(target, GitRepo::Llvm).join(" ");
392     if let Some(ref s) = builder.config.llvm_cflags {
393         cflags.push_str(&format!(" {}", s));
394     }
395     cfg.define("CMAKE_C_FLAGS", cflags);
396     let mut cxxflags = builder.cflags(target, GitRepo::Llvm).join(" ");
397     if builder.config.llvm_static_stdcpp && !target.contains("msvc") && !target.contains("netbsd") {
398         cxxflags.push_str(" -static-libstdc++");
399     }
400     if let Some(ref s) = builder.config.llvm_cxxflags {
401         cxxflags.push_str(&format!(" {}", s));
402     }
403     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
404     if let Some(ar) = builder.ar(target) {
405         if ar.is_absolute() {
406             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
407             // tries to resolve this path in the LLVM build directory.
408             cfg.define("CMAKE_AR", sanitize_cc(ar));
409         }
410     }
411
412     if let Some(ranlib) = builder.ranlib(target) {
413         if ranlib.is_absolute() {
414             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
415             // tries to resolve this path in the LLVM build directory.
416             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
417         }
418     }
419
420     if let Some(ref s) = builder.config.llvm_ldflags {
421         cfg.define("CMAKE_SHARED_LINKER_FLAGS", s);
422         cfg.define("CMAKE_MODULE_LINKER_FLAGS", s);
423         cfg.define("CMAKE_EXE_LINKER_FLAGS", s);
424     }
425
426     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
427         cfg.env("RUSTC_LOG", "sccache=warn");
428     }
429 }
430
431 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
432 pub struct Lld {
433     pub target: Interned<String>,
434 }
435
436 impl Step for Lld {
437     type Output = PathBuf;
438     const ONLY_HOSTS: bool = true;
439
440     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
441         run.path("src/llvm-project/lld").path("src/tools/lld")
442     }
443
444     fn make_run(run: RunConfig<'_>) {
445         run.builder.ensure(Lld { target: run.target });
446     }
447
448     /// Compile LLVM for `target`.
449     fn run(self, builder: &Builder<'_>) -> PathBuf {
450         if builder.config.dry_run {
451             return PathBuf::from("lld-out-dir-test-gen");
452         }
453         let target = self.target;
454
455         let llvm_config = builder.ensure(Llvm { target: self.target });
456
457         let out_dir = builder.lld_out(target);
458         let done_stamp = out_dir.join("lld-finished-building");
459         if done_stamp.exists() {
460             return out_dir;
461         }
462
463         builder.info(&format!("Building LLD for {}", target));
464         let _time = util::timeit(&builder);
465         t!(fs::create_dir_all(&out_dir));
466
467         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
468         configure_cmake(builder, target, &mut cfg, true);
469
470         // This is an awful, awful hack. Discovered when we migrated to using
471         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
472         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
473         // that directory for later processing. Unfortunately if this path has
474         // forward slashes in it (which it basically always does on Windows)
475         // then CMake will hit a syntax error later on as... something isn't
476         // escaped it seems?
477         //
478         // Instead of attempting to fix this problem in upstream CMake and/or
479         // LLVM/LLD we just hack around it here. This thin wrapper will take the
480         // output from llvm-config and replace all instances of `\` with `/` to
481         // ensure we don't hit the same bugs with escaping. It means that you
482         // can't build on a system where your paths require `\` on Windows, but
483         // there's probably a lot of reasons you can't do that other than this.
484         let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
485         cfg.out_dir(&out_dir)
486             .profile("Release")
487             .env("LLVM_CONFIG_REAL", llvm_config)
488             .define("LLVM_CONFIG_PATH", llvm_config_shim)
489             .define("LLVM_INCLUDE_TESTS", "OFF");
490
491         cfg.build();
492
493         t!(File::create(&done_stamp));
494         out_dir
495     }
496 }
497
498 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
499 pub struct TestHelpers {
500     pub target: Interned<String>,
501 }
502
503 impl Step for TestHelpers {
504     type Output = ();
505
506     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
507         run.path("src/test/auxiliary/rust_test_helpers.c")
508     }
509
510     fn make_run(run: RunConfig<'_>) {
511         run.builder.ensure(TestHelpers { target: run.target })
512     }
513
514     /// Compiles the `rust_test_helpers.c` library which we used in various
515     /// `run-pass` tests for ABI testing.
516     fn run(self, builder: &Builder<'_>) {
517         if builder.config.dry_run {
518             return;
519         }
520         let target = self.target;
521         let dst = builder.test_helpers_out(target);
522         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
523         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
524             return;
525         }
526
527         builder.info("Building test helpers");
528         t!(fs::create_dir_all(&dst));
529         let mut cfg = cc::Build::new();
530         // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
531         if target.contains("emscripten") {
532             cfg.pic(false);
533         }
534
535         // We may have found various cross-compilers a little differently due to our
536         // extra configuration, so inform gcc of these compilers. Note, though, that
537         // on MSVC we still need gcc's detection of env vars (ugh).
538         if !target.contains("msvc") {
539             if let Some(ar) = builder.ar(target) {
540                 cfg.archiver(ar);
541             }
542             cfg.compiler(builder.cc(target));
543         }
544
545         cfg.cargo_metadata(false)
546             .out_dir(&dst)
547             .target(&target)
548             .host(&builder.config.build)
549             .opt_level(0)
550             .warnings(false)
551             .debug(false)
552             .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
553             .compile("rust_test_helpers");
554     }
555 }
556
557 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
558 pub struct Sanitizers {
559     pub target: Interned<String>,
560 }
561
562 impl Step for Sanitizers {
563     type Output = Vec<SanitizerRuntime>;
564
565     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
566         run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
567     }
568
569     fn make_run(run: RunConfig<'_>) {
570         run.builder.ensure(Sanitizers { target: run.target });
571     }
572
573     /// Builds sanitizer runtime libraries.
574     fn run(self, builder: &Builder<'_>) -> Self::Output {
575         let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
576         if !compiler_rt_dir.exists() {
577             return Vec::new();
578         }
579
580         let out_dir = builder.native_dir(self.target).join("sanitizers");
581         let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
582         if runtimes.is_empty() {
583             return runtimes;
584         }
585
586         let llvm_config = builder.ensure(Llvm { target: builder.config.build });
587         if builder.config.dry_run {
588             return runtimes;
589         }
590
591         let done_stamp = out_dir.join("sanitizers-finished-building");
592         if done_stamp.exists() {
593             builder.info(&format!(
594                 "Assuming that sanitizers rebuild is not necessary. \
595                 To force a rebuild, remove the file `{}`",
596                 done_stamp.display()
597             ));
598             return runtimes;
599         }
600
601         builder.info(&format!("Building sanitizers for {}", self.target));
602         let _time = util::timeit(&builder);
603
604         let mut cfg = cmake::Config::new(&compiler_rt_dir);
605         cfg.profile("Release");
606         cfg.define("CMAKE_C_COMPILER_TARGET", self.target);
607         cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
608         cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
609         cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
610         cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
611         cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
612         cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
613         cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
614         cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
615         cfg.define("LLVM_CONFIG_PATH", &llvm_config);
616
617         // On Darwin targets the sanitizer runtimes are build as universal binaries.
618         // Unfortunately sccache currently lacks support to build them successfully.
619         // Disable compiler launcher on Darwin targets to avoid potential issues.
620         let use_compiler_launcher = !self.target.contains("apple-darwin");
621         configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher);
622
623         t!(fs::create_dir_all(&out_dir));
624         cfg.out_dir(out_dir);
625
626         for runtime in &runtimes {
627             cfg.build_target(&runtime.cmake_target);
628             cfg.build();
629         }
630
631         t!(fs::write(&done_stamp, b""));
632
633         runtimes
634     }
635 }
636
637 #[derive(Clone, Debug)]
638 pub struct SanitizerRuntime {
639     /// CMake target used to build the runtime.
640     pub cmake_target: String,
641     /// Path to the built runtime library.
642     pub path: PathBuf,
643     /// Library filename that will be used rustc.
644     pub name: String,
645 }
646
647 /// Returns sanitizers available on a given target.
648 fn supported_sanitizers(
649     out_dir: &Path,
650     target: Interned<String>,
651     channel: &str,
652 ) -> Vec<SanitizerRuntime> {
653     let mut result = Vec::new();
654     match &*target {
655         "x86_64-apple-darwin" => {
656             for s in &["asan", "lsan", "tsan"] {
657                 result.push(SanitizerRuntime {
658                     cmake_target: format!("clang_rt.{}_osx_dynamic", s),
659                     path: out_dir
660                         .join(&format!("build/lib/darwin/libclang_rt.{}_osx_dynamic.dylib", s)),
661                     name: format!("librustc-{}_rt.{}.dylib", channel, s),
662                 });
663             }
664         }
665         "x86_64-unknown-linux-gnu" => {
666             for s in &["asan", "lsan", "msan", "tsan"] {
667                 result.push(SanitizerRuntime {
668                     cmake_target: format!("clang_rt.{}-x86_64", s),
669                     path: out_dir.join(&format!("build/lib/linux/libclang_rt.{}-x86_64.a", s)),
670                     name: format!("librustc-{}_rt.{}.a", channel, s),
671                 });
672             }
673         }
674         "x86_64-fuchsia" => {
675             for s in &["asan"] {
676                 result.push(SanitizerRuntime {
677                     cmake_target: format!("clang_rt.{}-x86_64", s),
678                     path: out_dir.join(&format!("build/lib/fuchsia/libclang_rt.{}-x86_64.a", s)),
679                     name: format!("librustc-{}_rt.{}.a", channel, s),
680                 });
681             }
682         }
683         "aarch64-fuchsia" => {
684             for s in &["asan"] {
685                 result.push(SanitizerRuntime {
686                     cmake_target: format!("clang_rt.{}-aarch64", s),
687                     path: out_dir.join(&format!("build/lib/fuchsia/libclang_rt.{}-aarch64.a", s)),
688                     name: format!("librustc-{}_rt.{}.a", channel, s),
689                 });
690             }
691         }
692         _ => {}
693     }
694     result
695 }