]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Auto merge of #67524 - LukasKalbertodt:improve-into-iter-lint, r=matthewjasper
[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 let Some(llvm_commit) = llvm_info.sha() {
74                 let done_contents = t!(fs::read(&done_stamp));
75
76                 // If LLVM was already built previously and the submodule's commit didn't change
77                 // from the previous build, then no action is required.
78                 if done_contents == llvm_commit.as_bytes() {
79                     return build_llvm_config;
80                 }
81             } else {
82                 builder.info(
83                     "Could not determine the LLVM submodule commit hash. \
84                      Assuming that an LLVM rebuild is not necessary.",
85                 );
86                 builder.info(&format!(
87                     "To force LLVM to rebuild, remove the file `{}`",
88                     done_stamp.display()
89                 ));
90                 return build_llvm_config;
91             }
92         }
93
94         builder.info(&format!("Building LLVM for {}", target));
95         let _time = util::timeit(&builder);
96         t!(fs::create_dir_all(&out_dir));
97
98         // http://llvm.org/docs/CMake.html
99         let mut cfg = cmake::Config::new(builder.src.join(root));
100
101         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
102             (false, _) => "Debug",
103             (true, false) => "Release",
104             (true, true) => "RelWithDebInfo",
105         };
106
107         // NOTE: remember to also update `config.toml.example` when changing the
108         // defaults!
109         let llvm_targets = match &builder.config.llvm_targets {
110             Some(s) => s,
111             None => {
112                 "AArch64;ARM;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
113                      Sparc;SystemZ;WebAssembly;X86"
114             }
115         };
116
117         let llvm_exp_targets = match builder.config.llvm_experimental_targets {
118             Some(ref s) => s,
119             None => "",
120         };
121
122         let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
123
124         cfg.out_dir(&out_dir)
125             .profile(profile)
126             .define("LLVM_ENABLE_ASSERTIONS", assertions)
127             .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
128             .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
129             .define("LLVM_INCLUDE_EXAMPLES", "OFF")
130             .define("LLVM_INCLUDE_TESTS", "OFF")
131             .define("LLVM_INCLUDE_DOCS", "OFF")
132             .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
133             .define("LLVM_ENABLE_ZLIB", "OFF")
134             .define("WITH_POLLY", "OFF")
135             .define("LLVM_ENABLE_TERMINFO", "OFF")
136             .define("LLVM_ENABLE_LIBEDIT", "OFF")
137             .define("LLVM_ENABLE_BINDINGS", "OFF")
138             .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
139             .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
140             .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
141             .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
142
143         if builder.config.llvm_thin_lto {
144             cfg.define("LLVM_ENABLE_LTO", "Thin");
145             if !target.contains("apple") {
146                 cfg.define("LLVM_ENABLE_LLD", "ON");
147             }
148         }
149
150         // This setting makes the LLVM tools link to the dynamic LLVM library,
151         // which saves both memory during parallel links and overall disk space
152         // for the tools. We don't do this on every platform as it doesn't work
153         // equally well everywhere.
154         if builder.llvm_link_tools_dynamically(target) {
155             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
156         }
157
158         // For distribution we want the LLVM tools to be *statically* linked to libstdc++
159         if builder.config.llvm_tools_enabled || builder.config.lldb_enabled {
160             if !target.contains("msvc") {
161                 if target.contains("apple") {
162                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
163                 } else {
164                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
165                 }
166             }
167         }
168
169         if target.contains("msvc") {
170             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
171             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
172             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
173             cfg.static_crt(true);
174         }
175
176         if target.starts_with("i686") {
177             cfg.define("LLVM_BUILD_32_BITS", "ON");
178         }
179
180         let mut enabled_llvm_projects = Vec::new();
181
182         if util::forcing_clang_based_tests() {
183             enabled_llvm_projects.push("clang");
184             enabled_llvm_projects.push("compiler-rt");
185         }
186
187         if builder.config.lldb_enabled {
188             enabled_llvm_projects.push("clang");
189             enabled_llvm_projects.push("lldb");
190             // For the time being, disable code signing.
191             cfg.define("LLDB_CODESIGN_IDENTITY", "");
192             cfg.define("LLDB_NO_DEBUGSERVER", "ON");
193         } else {
194             // LLDB requires libxml2; but otherwise we want it to be disabled.
195             // See https://github.com/rust-lang/rust/pull/50104
196             cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
197         }
198
199         if enabled_llvm_projects.len() > 0 {
200             enabled_llvm_projects.sort();
201             enabled_llvm_projects.dedup();
202             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
203         }
204
205         if let Some(num_linkers) = builder.config.llvm_link_jobs {
206             if num_linkers > 0 {
207                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
208             }
209         }
210
211         // http://llvm.org/docs/HowToCrossCompileLLVM.html
212         if target != builder.config.build {
213             builder.ensure(Llvm { target: builder.config.build });
214             // FIXME: if the llvm root for the build triple is overridden then we
215             //        should use llvm-tblgen from there, also should verify that it
216             //        actually exists most of the time in normal installs of LLVM.
217             let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
218             cfg.define("CMAKE_CROSSCOMPILING", "True").define("LLVM_TABLEGEN", &host);
219
220             if target.contains("netbsd") {
221                 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
222             } else if target.contains("freebsd") {
223                 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
224             }
225
226             cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
227         }
228
229         if let Some(ref suffix) = builder.config.llvm_version_suffix {
230             // Allow version-suffix="" to not define a version suffix at all.
231             if !suffix.is_empty() {
232                 cfg.define("LLVM_VERSION_SUFFIX", suffix);
233             }
234         } else {
235             let mut default_suffix =
236                 format!("-rust-{}-{}", channel::CFG_RELEASE_NUM, builder.config.channel,);
237             if let Some(sha) = llvm_info.sha_short() {
238                 default_suffix.push_str("-");
239                 default_suffix.push_str(sha);
240             }
241             cfg.define("LLVM_VERSION_SUFFIX", default_suffix);
242         }
243
244         if let Some(ref linker) = builder.config.llvm_use_linker {
245             cfg.define("LLVM_USE_LINKER", linker);
246         }
247
248         if let Some(true) = builder.config.llvm_allow_old_toolchain {
249             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
250         }
251
252         if let Some(ref python) = builder.config.python {
253             cfg.define("PYTHON_EXECUTABLE", python);
254         }
255
256         configure_cmake(builder, target, &mut cfg);
257
258         // FIXME: we don't actually need to build all LLVM tools and all LLVM
259         //        libraries here, e.g., we just want a few components and a few
260         //        tools. Figure out how to filter them down and only build the right
261         //        tools and libs on all platforms.
262
263         if builder.config.dry_run {
264             return build_llvm_config;
265         }
266
267         cfg.build();
268
269         t!(fs::write(&done_stamp, llvm_info.sha().unwrap_or("")));
270
271         build_llvm_config
272     }
273 }
274
275 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
276     if !builder.config.llvm_version_check {
277         return;
278     }
279
280     if builder.config.dry_run {
281         return;
282     }
283
284     let mut cmd = Command::new(llvm_config);
285     let version = output(cmd.arg("--version"));
286     let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
287     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
288         if major >= 7 {
289             return;
290         }
291     }
292     panic!("\n\nbad LLVM version: {}, need >=7.0\n\n", version)
293 }
294
295 fn configure_cmake(builder: &Builder<'_>, target: Interned<String>, cfg: &mut cmake::Config) {
296     // Do not print installation messages for up-to-date files.
297     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
298     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
299
300     if builder.config.ninja {
301         cfg.generator("Ninja");
302     }
303     cfg.target(&target).host(&builder.config.build);
304
305     let sanitize_cc = |cc: &Path| {
306         if target.contains("msvc") {
307             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
308         } else {
309             cc.as_os_str().to_owned()
310         }
311     };
312
313     // MSVC with CMake uses msbuild by default which doesn't respect these
314     // vars that we'd otherwise configure. In that case we just skip this
315     // entirely.
316     if target.contains("msvc") && !builder.config.ninja {
317         return;
318     }
319
320     let (cc, cxx) = match builder.config.llvm_clang_cl {
321         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
322         None => (builder.cc(target), builder.cxx(target).unwrap()),
323     };
324
325     // Handle msvc + ninja + ccache specially (this is what the bots use)
326     if target.contains("msvc") && builder.config.ninja && builder.config.ccache.is_some() {
327         let mut wrap_cc = env::current_exe().expect("failed to get cwd");
328         wrap_cc.set_file_name("sccache-plus-cl.exe");
329
330         cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
331             .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
332         cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
333             .env("SCCACHE_TARGET", target)
334             .env("SCCACHE_CC", &cc)
335             .env("SCCACHE_CXX", &cxx);
336
337         // Building LLVM on MSVC can be a little ludicrous at times. We're so far
338         // off the beaten path here that I'm not really sure this is even half
339         // supported any more. Here we're trying to:
340         //
341         // * Build LLVM on MSVC
342         // * Build LLVM with `clang-cl` instead of `cl.exe`
343         // * Build a project with `sccache`
344         // * Build for 32-bit as well
345         // * Build with Ninja
346         //
347         // For `cl.exe` there are different binaries to compile 32/64 bit which
348         // we use but for `clang-cl` there's only one which internally
349         // multiplexes via flags. As a result it appears that CMake's detection
350         // of a compiler's architecture and such on MSVC **doesn't** pass any
351         // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
352         // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
353         // definitely causes problems since all the env vars are pointing to
354         // 32-bit libraries.
355         //
356         // To hack around this... again... we pass an argument that's
357         // unconditionally passed in the sccache shim. This'll get CMake to
358         // correctly diagnose it's doing a 32-bit compilation and LLVM will
359         // internally configure itself appropriately.
360         if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
361             cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
362         }
363     } else {
364         // If ccache is configured we inform the build a little differently how
365         // to invoke ccache while also invoking our compilers.
366         if let Some(ref ccache) = builder.config.ccache {
367             cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
368                 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
369         }
370         cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
371             .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
372     }
373
374     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
375     let mut cflags = builder.cflags(target, GitRepo::Llvm).join(" ");
376     if let Some(ref s) = builder.config.llvm_cflags {
377         cflags.push_str(&format!(" {}", s));
378     }
379     cfg.define("CMAKE_C_FLAGS", cflags);
380     let mut cxxflags = builder.cflags(target, GitRepo::Llvm).join(" ");
381     if builder.config.llvm_static_stdcpp && !target.contains("msvc") && !target.contains("netbsd") {
382         cxxflags.push_str(" -static-libstdc++");
383     }
384     if let Some(ref s) = builder.config.llvm_cxxflags {
385         cxxflags.push_str(&format!(" {}", s));
386     }
387     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
388     if let Some(ar) = builder.ar(target) {
389         if ar.is_absolute() {
390             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
391             // tries to resolve this path in the LLVM build directory.
392             cfg.define("CMAKE_AR", sanitize_cc(ar));
393         }
394     }
395
396     if let Some(ranlib) = builder.ranlib(target) {
397         if ranlib.is_absolute() {
398             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
399             // tries to resolve this path in the LLVM build directory.
400             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
401         }
402     }
403
404     if let Some(ref s) = builder.config.llvm_ldflags {
405         cfg.define("CMAKE_SHARED_LINKER_FLAGS", s);
406         cfg.define("CMAKE_MODULE_LINKER_FLAGS", s);
407         cfg.define("CMAKE_EXE_LINKER_FLAGS", s);
408     }
409
410     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
411         cfg.env("RUSTC_LOG", "sccache=warn");
412     }
413 }
414
415 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
416 pub struct Lld {
417     pub target: Interned<String>,
418 }
419
420 impl Step for Lld {
421     type Output = PathBuf;
422     const ONLY_HOSTS: bool = true;
423
424     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
425         run.path("src/llvm-project/lld").path("src/tools/lld")
426     }
427
428     fn make_run(run: RunConfig<'_>) {
429         run.builder.ensure(Lld { target: run.target });
430     }
431
432     /// Compile LLVM for `target`.
433     fn run(self, builder: &Builder<'_>) -> PathBuf {
434         if builder.config.dry_run {
435             return PathBuf::from("lld-out-dir-test-gen");
436         }
437         let target = self.target;
438
439         let llvm_config = builder.ensure(Llvm { target: self.target });
440
441         let out_dir = builder.lld_out(target);
442         let done_stamp = out_dir.join("lld-finished-building");
443         if done_stamp.exists() {
444             return out_dir;
445         }
446
447         builder.info(&format!("Building LLD for {}", target));
448         let _time = util::timeit(&builder);
449         t!(fs::create_dir_all(&out_dir));
450
451         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
452         configure_cmake(builder, target, &mut cfg);
453
454         // This is an awful, awful hack. Discovered when we migrated to using
455         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
456         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
457         // that directory for later processing. Unfortunately if this path has
458         // forward slashes in it (which it basically always does on Windows)
459         // then CMake will hit a syntax error later on as... something isn't
460         // escaped it seems?
461         //
462         // Instead of attempting to fix this problem in upstream CMake and/or
463         // LLVM/LLD we just hack around it here. This thin wrapper will take the
464         // output from llvm-config and replace all instances of `\` with `/` to
465         // ensure we don't hit the same bugs with escaping. It means that you
466         // can't build on a system where your paths require `\` on Windows, but
467         // there's probably a lot of reasons you can't do that other than this.
468         let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
469         cfg.out_dir(&out_dir)
470             .profile("Release")
471             .env("LLVM_CONFIG_REAL", llvm_config)
472             .define("LLVM_CONFIG_PATH", llvm_config_shim)
473             .define("LLVM_INCLUDE_TESTS", "OFF");
474
475         cfg.build();
476
477         t!(File::create(&done_stamp));
478         out_dir
479     }
480 }
481
482 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
483 pub struct TestHelpers {
484     pub target: Interned<String>,
485 }
486
487 impl Step for TestHelpers {
488     type Output = ();
489
490     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
491         run.path("src/test/auxiliary/rust_test_helpers.c")
492     }
493
494     fn make_run(run: RunConfig<'_>) {
495         run.builder.ensure(TestHelpers { target: run.target })
496     }
497
498     /// Compiles the `rust_test_helpers.c` library which we used in various
499     /// `run-pass` tests for ABI testing.
500     fn run(self, builder: &Builder<'_>) {
501         if builder.config.dry_run {
502             return;
503         }
504         let target = self.target;
505         let dst = builder.test_helpers_out(target);
506         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
507         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
508             return;
509         }
510
511         builder.info("Building test helpers");
512         t!(fs::create_dir_all(&dst));
513         let mut cfg = cc::Build::new();
514         // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
515         if target.contains("emscripten") {
516             cfg.pic(false);
517         }
518
519         // We may have found various cross-compilers a little differently due to our
520         // extra configuration, so inform gcc of these compilers. Note, though, that
521         // on MSVC we still need gcc's detection of env vars (ugh).
522         if !target.contains("msvc") {
523             if let Some(ar) = builder.ar(target) {
524                 cfg.archiver(ar);
525             }
526             cfg.compiler(builder.cc(target));
527         }
528
529         cfg.cargo_metadata(false)
530             .out_dir(&dst)
531             .target(&target)
532             .host(&builder.config.build)
533             .opt_level(0)
534             .warnings(false)
535             .debug(false)
536             .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
537             .compile("rust_test_helpers");
538     }
539 }