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