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