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