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