]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Rollup merge of #61054 - estebank:mut-ref-reassign, r=zackmdavis
[rust.git] / src / bootstrap / compile.rs
1 //! Implementation of compiling various phases of the compiler and standard
2 //! library.
3 //!
4 //! This module contains some of the real meat in the rustbuild build system
5 //! which is where Cargo is used to compiler the standard library, libtest, and
6 //! compiler. This module is also responsible for assembling the sysroot as it
7 //! goes along from the output of the previous stage.
8
9 use std::borrow::Cow;
10 use std::env;
11 use std::fs;
12 use std::io::BufReader;
13 use std::io::prelude::*;
14 use std::path::{Path, PathBuf};
15 use std::process::{Command, Stdio, exit};
16 use std::str;
17
18 use build_helper::{output, mtime, t, up_to_date};
19 use filetime::FileTime;
20 use serde::Deserialize;
21 use serde_json;
22
23 use crate::dist;
24 use crate::util::{exe, is_dylib};
25 use crate::{Compiler, Mode, GitRepo};
26 use crate::native;
27
28 use crate::cache::{INTERNER, Interned};
29 use crate::builder::{Step, RunConfig, ShouldRun, Builder};
30
31 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
32 pub struct Std {
33     pub target: Interned<String>,
34     pub compiler: Compiler,
35 }
36
37 impl Step for Std {
38     type Output = ();
39     const DEFAULT: bool = true;
40
41     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
42         run.all_krates("std")
43     }
44
45     fn make_run(run: RunConfig<'_>) {
46         run.builder.ensure(Std {
47             compiler: run.builder.compiler(run.builder.top_stage, run.host),
48             target: run.target,
49         });
50     }
51
52     /// Builds the standard library.
53     ///
54     /// This will build the standard library for a particular stage of the build
55     /// using the `compiler` targeting the `target` architecture. The artifacts
56     /// created will also be linked into the sysroot directory.
57     fn run(self, builder: &Builder<'_>) {
58         let target = self.target;
59         let compiler = self.compiler;
60
61         if builder.config.keep_stage.contains(&compiler.stage) {
62             builder.info("Warning: Using a potentially old libstd. This may not behave well.");
63             builder.ensure(StdLink {
64                 compiler,
65                 target_compiler: compiler,
66                 target,
67             });
68             return;
69         }
70
71         builder.ensure(StartupObjects { compiler, target });
72
73         if builder.force_use_stage1(compiler, target) {
74             let from = builder.compiler(1, builder.config.build);
75             builder.ensure(Std {
76                 compiler: from,
77                 target,
78             });
79             builder.info(&format!("Uplifting stage1 std ({} -> {})", from.host, target));
80
81             // Even if we're not building std this stage, the new sysroot must
82             // still contain the third party objects needed by various targets.
83             copy_third_party_objects(builder, &compiler, target);
84
85             builder.ensure(StdLink {
86                 compiler: from,
87                 target_compiler: compiler,
88                 target,
89             });
90             return;
91         }
92
93         copy_third_party_objects(builder, &compiler, target);
94
95         let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
96         std_cargo(builder, &compiler, target, &mut cargo);
97
98         let _folder = builder.fold_output(|| format!("stage{}-std", compiler.stage));
99         builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
100                 &compiler.host, target));
101         run_cargo(builder,
102                   &mut cargo,
103                   &libstd_stamp(builder, compiler, target),
104                   false);
105
106         builder.ensure(StdLink {
107             compiler: builder.compiler(compiler.stage, builder.config.build),
108             target_compiler: compiler,
109             target,
110         });
111     }
112 }
113
114 /// Copies third pary objects needed by various targets.
115 fn copy_third_party_objects(builder: &Builder<'_>, compiler: &Compiler, target: Interned<String>) {
116     let libdir = builder.sysroot_libdir(*compiler, target);
117
118     // Copies the crt(1,i,n).o startup objects
119     //
120     // Since musl supports fully static linking, we can cross link for it even
121     // with a glibc-targeting toolchain, given we have the appropriate startup
122     // files. As those shipped with glibc won't work, copy the ones provided by
123     // musl so we have them on linux-gnu hosts.
124     if target.contains("musl") {
125         for &obj in &["crt1.o", "crti.o", "crtn.o"] {
126             builder.copy(
127                 &builder.musl_root(target).unwrap().join("lib").join(obj),
128                 &libdir.join(obj),
129             );
130         }
131     } else if target.ends_with("-wasi") {
132         for &obj in &["crt1.o"] {
133             builder.copy(
134                 &builder.wasi_root(target).unwrap().join("lib/wasm32-wasi").join(obj),
135                 &libdir.join(obj),
136             );
137         }
138     }
139
140     // Copies libunwind.a compiled to be linked wit x86_64-fortanix-unknown-sgx.
141     //
142     // This target needs to be linked to Fortanix's port of llvm's libunwind.
143     // libunwind requires support for rwlock and printing to stderr,
144     // which is provided by std for this target.
145     if target == "x86_64-fortanix-unknown-sgx" {
146         let src_path_env = "X86_FORTANIX_SGX_LIBS";
147         let obj = "libunwind.a";
148         let src = env::var(src_path_env).expect(&format!("{} not found in env", src_path_env));
149         let src = Path::new(&src).join(obj);
150         builder.copy(&src, &libdir.join(obj));
151     }
152 }
153
154 /// Configure cargo to compile the standard library, adding appropriate env vars
155 /// and such.
156 pub fn std_cargo(builder: &Builder<'_>,
157                  compiler: &Compiler,
158                  target: Interned<String>,
159                  cargo: &mut Command) {
160     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
161         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
162     }
163
164     // Determine if we're going to compile in optimized C intrinsics to
165     // the `compiler-builtins` crate. These intrinsics live in LLVM's
166     // `compiler-rt` repository, but our `src/llvm-project` submodule isn't
167     // always checked out, so we need to conditionally look for this. (e.g. if
168     // an external LLVM is used we skip the LLVM submodule checkout).
169     //
170     // Note that this shouldn't affect the correctness of `compiler-builtins`,
171     // but only its speed. Some intrinsics in C haven't been translated to Rust
172     // yet but that's pretty rare. Other intrinsics have optimized
173     // implementations in C which have only had slower versions ported to Rust,
174     // so we favor the C version where we can, but it's not critical.
175     //
176     // If `compiler-rt` is available ensure that the `c` feature of the
177     // `compiler-builtins` crate is enabled and it's configured to learn where
178     // `compiler-rt` is located.
179     let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
180     let compiler_builtins_c_feature = if compiler_builtins_root.exists() {
181         cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
182         " compiler-builtins-c".to_string()
183     } else {
184         String::new()
185     };
186
187     if builder.no_std(target) == Some(true) {
188         let mut features = "compiler-builtins-mem".to_string();
189         features.push_str(&compiler_builtins_c_feature);
190
191         // for no-std targets we only compile a few no_std crates
192         cargo
193             .args(&["-p", "alloc"])
194             .arg("--manifest-path")
195             .arg(builder.src.join("src/liballoc/Cargo.toml"))
196             .arg("--features")
197             .arg("compiler-builtins-mem compiler-builtins-c");
198     } else {
199         let mut features = builder.std_features();
200         features.push_str(&compiler_builtins_c_feature);
201
202         if compiler.stage != 0 && builder.config.sanitizers {
203             // This variable is used by the sanitizer runtime crates, e.g.
204             // rustc_lsan, to build the sanitizer runtime from C code
205             // When this variable is missing, those crates won't compile the C code,
206             // so we don't set this variable during stage0 where llvm-config is
207             // missing
208             // We also only build the runtimes when --enable-sanitizers (or its
209             // config.toml equivalent) is used
210             let llvm_config = builder.ensure(native::Llvm {
211                 target: builder.config.build,
212                 emscripten: false,
213             });
214             cargo.env("LLVM_CONFIG", llvm_config);
215         }
216
217         cargo.arg("--features").arg(features)
218             .arg("--manifest-path")
219             .arg(builder.src.join("src/libstd/Cargo.toml"));
220
221         if target.contains("musl") {
222             if let Some(p) = builder.musl_root(target) {
223                 cargo.env("MUSL_ROOT", p);
224             }
225         }
226
227         if target.ends_with("-wasi") {
228             if let Some(p) = builder.wasi_root(target) {
229                 cargo.env("WASI_ROOT", p);
230             }
231         }
232     }
233 }
234
235 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
236 struct StdLink {
237     pub compiler: Compiler,
238     pub target_compiler: Compiler,
239     pub target: Interned<String>,
240 }
241
242 impl Step for StdLink {
243     type Output = ();
244
245     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
246         run.never()
247     }
248
249     /// Link all libstd rlibs/dylibs into the sysroot location.
250     ///
251     /// Links those artifacts generated by `compiler` to the `stage` compiler's
252     /// sysroot for the specified `host` and `target`.
253     ///
254     /// Note that this assumes that `compiler` has already generated the libstd
255     /// libraries for `target`, and this method will find them in the relevant
256     /// output directory.
257     fn run(self, builder: &Builder<'_>) {
258         let compiler = self.compiler;
259         let target_compiler = self.target_compiler;
260         let target = self.target;
261         builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
262                 target_compiler.stage,
263                 compiler.stage,
264                 &compiler.host,
265                 target_compiler.host,
266                 target));
267         let libdir = builder.sysroot_libdir(target_compiler, target);
268         let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
269         add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
270
271         if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
272             // The sanitizers are only built in stage1 or above, so the dylibs will
273             // be missing in stage0 and causes panic. See the `std()` function above
274             // for reason why the sanitizers are not built in stage0.
275             copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
276         }
277
278         builder.cargo(target_compiler, Mode::ToolStd, target, "clean");
279     }
280 }
281
282 fn copy_apple_sanitizer_dylibs(
283     builder: &Builder<'_>,
284     native_dir: &Path,
285     platform: &str,
286     into: &Path,
287 ) {
288     for &sanitizer in &["asan", "tsan"] {
289         let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
290         let mut src_path = native_dir.join(sanitizer);
291         src_path.push("build");
292         src_path.push("lib");
293         src_path.push("darwin");
294         src_path.push(&filename);
295         builder.copy(&src_path, &into.join(filename));
296     }
297 }
298
299 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
300 pub struct StartupObjects {
301     pub compiler: Compiler,
302     pub target: Interned<String>,
303 }
304
305 impl Step for StartupObjects {
306     type Output = ();
307
308     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
309         run.path("src/rtstartup")
310     }
311
312     fn make_run(run: RunConfig<'_>) {
313         run.builder.ensure(StartupObjects {
314             compiler: run.builder.compiler(run.builder.top_stage, run.host),
315             target: run.target,
316         });
317     }
318
319     /// Builds and prepare startup objects like rsbegin.o and rsend.o
320     ///
321     /// These are primarily used on Windows right now for linking executables/dlls.
322     /// They don't require any library support as they're just plain old object
323     /// files, so we just use the nightly snapshot compiler to always build them (as
324     /// no other compilers are guaranteed to be available).
325     fn run(self, builder: &Builder<'_>) {
326         let for_compiler = self.compiler;
327         let target = self.target;
328         if !target.contains("pc-windows-gnu") {
329             return
330         }
331
332         let src_dir = &builder.src.join("src/rtstartup");
333         let dst_dir = &builder.native_dir(target).join("rtstartup");
334         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
335         t!(fs::create_dir_all(dst_dir));
336
337         for file in &["rsbegin", "rsend"] {
338             let src_file = &src_dir.join(file.to_string() + ".rs");
339             let dst_file = &dst_dir.join(file.to_string() + ".o");
340             if !up_to_date(src_file, dst_file) {
341                 let mut cmd = Command::new(&builder.initial_rustc);
342                 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
343                             .arg("--cfg").arg("stage0")
344                             .arg("--target").arg(target)
345                             .arg("--emit=obj")
346                             .arg("-o").arg(dst_file)
347                             .arg(src_file));
348             }
349
350             builder.copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
351         }
352
353         for obj in ["crt2.o", "dllcrt2.o"].iter() {
354             let src = compiler_file(builder,
355                                     builder.cc(target),
356                                     target,
357                                     obj);
358             builder.copy(&src, &sysroot_dir.join(obj));
359         }
360     }
361 }
362
363 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
364 pub struct Test {
365     pub target: Interned<String>,
366     pub compiler: Compiler,
367 }
368
369 impl Step for Test {
370     type Output = ();
371     const DEFAULT: bool = true;
372
373     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
374         run.all_krates("test")
375     }
376
377     fn make_run(run: RunConfig<'_>) {
378         run.builder.ensure(Test {
379             compiler: run.builder.compiler(run.builder.top_stage, run.host),
380             target: run.target,
381         });
382     }
383
384     /// Builds libtest.
385     ///
386     /// This will build libtest and supporting libraries for a particular stage of
387     /// the build using the `compiler` targeting the `target` architecture. The
388     /// artifacts created will also be linked into the sysroot directory.
389     fn run(self, builder: &Builder<'_>) {
390         let target = self.target;
391         let compiler = self.compiler;
392
393         builder.ensure(Std { compiler, target });
394
395         if builder.config.keep_stage.contains(&compiler.stage) {
396             builder.info("Warning: Using a potentially old libtest. This may not behave well.");
397             builder.ensure(TestLink {
398                 compiler,
399                 target_compiler: compiler,
400                 target,
401             });
402             return;
403         }
404
405         if builder.force_use_stage1(compiler, target) {
406             builder.ensure(Test {
407                 compiler: builder.compiler(1, builder.config.build),
408                 target,
409             });
410             builder.info(
411                 &format!("Uplifting stage1 test ({} -> {})", builder.config.build, target));
412             builder.ensure(TestLink {
413                 compiler: builder.compiler(1, builder.config.build),
414                 target_compiler: compiler,
415                 target,
416             });
417             return;
418         }
419
420         let mut cargo = builder.cargo(compiler, Mode::Test, target, "build");
421         test_cargo(builder, &compiler, target, &mut cargo);
422
423         let _folder = builder.fold_output(|| format!("stage{}-test", compiler.stage));
424         builder.info(&format!("Building stage{} test artifacts ({} -> {})", compiler.stage,
425                 &compiler.host, target));
426         run_cargo(builder,
427                   &mut cargo,
428                   &libtest_stamp(builder, compiler, target),
429                   false);
430
431         builder.ensure(TestLink {
432             compiler: builder.compiler(compiler.stage, builder.config.build),
433             target_compiler: compiler,
434             target,
435         });
436     }
437 }
438
439 /// Same as `std_cargo`, but for libtest
440 pub fn test_cargo(builder: &Builder<'_>,
441                   _compiler: &Compiler,
442                   _target: Interned<String>,
443                   cargo: &mut Command) {
444     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
445         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
446     }
447     cargo.arg("--manifest-path")
448         .arg(builder.src.join("src/libtest/Cargo.toml"));
449 }
450
451 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
452 pub struct TestLink {
453     pub compiler: Compiler,
454     pub target_compiler: Compiler,
455     pub target: Interned<String>,
456 }
457
458 impl Step for TestLink {
459     type Output = ();
460
461     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
462         run.never()
463     }
464
465     /// Same as `std_link`, only for libtest
466     fn run(self, builder: &Builder<'_>) {
467         let compiler = self.compiler;
468         let target_compiler = self.target_compiler;
469         let target = self.target;
470         builder.info(&format!("Copying stage{} test from stage{} ({} -> {} / {})",
471                 target_compiler.stage,
472                 compiler.stage,
473                 &compiler.host,
474                 target_compiler.host,
475                 target));
476         add_to_sysroot(
477             builder,
478             &builder.sysroot_libdir(target_compiler, target),
479             &builder.sysroot_libdir(target_compiler, compiler.host),
480             &libtest_stamp(builder, compiler, target)
481         );
482
483         builder.cargo(target_compiler, Mode::ToolTest, target, "clean");
484     }
485 }
486
487 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
488 pub struct Rustc {
489     pub target: Interned<String>,
490     pub compiler: Compiler,
491 }
492
493 impl Step for Rustc {
494     type Output = ();
495     const ONLY_HOSTS: bool = true;
496     const DEFAULT: bool = true;
497
498     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
499         run.all_krates("rustc-main")
500     }
501
502     fn make_run(run: RunConfig<'_>) {
503         run.builder.ensure(Rustc {
504             compiler: run.builder.compiler(run.builder.top_stage, run.host),
505             target: run.target,
506         });
507     }
508
509     /// Builds the compiler.
510     ///
511     /// This will build the compiler for a particular stage of the build using
512     /// the `compiler` targeting the `target` architecture. The artifacts
513     /// created will also be linked into the sysroot directory.
514     fn run(self, builder: &Builder<'_>) {
515         let compiler = self.compiler;
516         let target = self.target;
517
518         builder.ensure(Test { compiler, target });
519
520         if builder.config.keep_stage.contains(&compiler.stage) {
521             builder.info("Warning: Using a potentially old librustc. This may not behave well.");
522             builder.ensure(RustcLink {
523                 compiler,
524                 target_compiler: compiler,
525                 target,
526             });
527             return;
528         }
529
530         if builder.force_use_stage1(compiler, target) {
531             builder.ensure(Rustc {
532                 compiler: builder.compiler(1, builder.config.build),
533                 target,
534             });
535             builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
536                 builder.config.build, target));
537             builder.ensure(RustcLink {
538                 compiler: builder.compiler(1, builder.config.build),
539                 target_compiler: compiler,
540                 target,
541             });
542             return;
543         }
544
545         // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
546         builder.ensure(Test {
547             compiler: builder.compiler(self.compiler.stage, builder.config.build),
548             target: builder.config.build,
549         });
550
551         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
552         rustc_cargo(builder, &mut cargo);
553
554         let _folder = builder.fold_output(|| format!("stage{}-rustc", compiler.stage));
555         builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
556                  compiler.stage, &compiler.host, target));
557         run_cargo(builder,
558                   &mut cargo,
559                   &librustc_stamp(builder, compiler, target),
560                   false);
561
562         builder.ensure(RustcLink {
563             compiler: builder.compiler(compiler.stage, builder.config.build),
564             target_compiler: compiler,
565             target,
566         });
567     }
568 }
569
570 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Command) {
571     cargo.arg("--features").arg(builder.rustc_features())
572          .arg("--manifest-path")
573          .arg(builder.src.join("src/rustc/Cargo.toml"));
574     rustc_cargo_env(builder, cargo);
575 }
576
577 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Command) {
578     // Set some configuration variables picked up by build scripts and
579     // the compiler alike
580     cargo.env("CFG_RELEASE", builder.rust_release())
581          .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
582          .env("CFG_VERSION", builder.rust_version())
583          .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default())
584          .env("CFG_CODEGEN_BACKENDS_DIR", &builder.config.rust_codegen_backends_dir);
585
586     let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
587     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
588
589     // If we're not building a compiler with debugging information then remove
590     // these two env vars which would be set otherwise.
591     if builder.config.rust_debuginfo_only_std {
592         cargo.env_remove("RUSTC_DEBUGINFO");
593         cargo.env_remove("RUSTC_DEBUGINFO_LINES");
594     }
595
596     if let Some(ref ver_date) = builder.rust_info.commit_date() {
597         cargo.env("CFG_VER_DATE", ver_date);
598     }
599     if let Some(ref ver_hash) = builder.rust_info.sha() {
600         cargo.env("CFG_VER_HASH", ver_hash);
601     }
602     if !builder.unstable_features() {
603         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
604     }
605     if let Some(ref s) = builder.config.rustc_default_linker {
606         cargo.env("CFG_DEFAULT_LINKER", s);
607     }
608     if builder.config.rustc_parallel {
609         cargo.env("RUSTC_PARALLEL_COMPILER", "1");
610     }
611     if builder.config.rust_verify_llvm_ir {
612         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
613     }
614 }
615
616 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
617 struct RustcLink {
618     pub compiler: Compiler,
619     pub target_compiler: Compiler,
620     pub target: Interned<String>,
621 }
622
623 impl Step for RustcLink {
624     type Output = ();
625
626     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
627         run.never()
628     }
629
630     /// Same as `std_link`, only for librustc
631     fn run(self, builder: &Builder<'_>) {
632         let compiler = self.compiler;
633         let target_compiler = self.target_compiler;
634         let target = self.target;
635         builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
636                  target_compiler.stage,
637                  compiler.stage,
638                  &compiler.host,
639                  target_compiler.host,
640                  target));
641         add_to_sysroot(
642             builder,
643             &builder.sysroot_libdir(target_compiler, target),
644             &builder.sysroot_libdir(target_compiler, compiler.host),
645             &librustc_stamp(builder, compiler, target)
646         );
647         builder.cargo(target_compiler, Mode::ToolRustc, target, "clean");
648     }
649 }
650
651 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
652 pub struct CodegenBackend {
653     pub compiler: Compiler,
654     pub target: Interned<String>,
655     pub backend: Interned<String>,
656 }
657
658 impl Step for CodegenBackend {
659     type Output = ();
660     const ONLY_HOSTS: bool = true;
661     const DEFAULT: bool = true;
662
663     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
664         run.all_krates("rustc_codegen_llvm")
665     }
666
667     fn make_run(run: RunConfig<'_>) {
668         let backend = run.builder.config.rust_codegen_backends.get(0);
669         let backend = backend.cloned().unwrap_or_else(|| {
670             INTERNER.intern_str("llvm")
671         });
672         run.builder.ensure(CodegenBackend {
673             compiler: run.builder.compiler(run.builder.top_stage, run.host),
674             target: run.target,
675             backend,
676         });
677     }
678
679     fn run(self, builder: &Builder<'_>) {
680         let compiler = self.compiler;
681         let target = self.target;
682         let backend = self.backend;
683
684         builder.ensure(Rustc { compiler, target });
685
686         if builder.config.keep_stage.contains(&compiler.stage) {
687             builder.info("Warning: Using a potentially old codegen backend. \
688                 This may not behave well.");
689             // Codegen backends are linked separately from this step today, so we don't do
690             // anything here.
691             return;
692         }
693
694         if builder.force_use_stage1(compiler, target) {
695             builder.ensure(CodegenBackend {
696                 compiler: builder.compiler(1, builder.config.build),
697                 target,
698                 backend,
699             });
700             return;
701         }
702
703         let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
704
705         let mut cargo = builder.cargo(compiler, Mode::Codegen, target, "build");
706         cargo.arg("--manifest-path")
707             .arg(builder.src.join("src/librustc_codegen_llvm/Cargo.toml"));
708         rustc_cargo_env(builder, &mut cargo);
709
710         let features = build_codegen_backend(&builder, &mut cargo, &compiler, target, backend);
711
712         let tmp_stamp = out_dir.join(".tmp.stamp");
713
714         let _folder = builder.fold_output(|| format!("stage{}-rustc_codegen_llvm", compiler.stage));
715         let files = run_cargo(builder,
716                               cargo.arg("--features").arg(features),
717                               &tmp_stamp,
718                               false);
719         if builder.config.dry_run {
720             return;
721         }
722         let mut files = files.into_iter()
723             .filter(|f| {
724                 let filename = f.file_name().unwrap().to_str().unwrap();
725                 is_dylib(filename) && filename.contains("rustc_codegen_llvm-")
726             });
727         let codegen_backend = match files.next() {
728             Some(f) => f,
729             None => panic!("no dylibs built for codegen backend?"),
730         };
731         if let Some(f) = files.next() {
732             panic!("codegen backend built two dylibs:\n{}\n{}",
733                    codegen_backend.display(),
734                    f.display());
735         }
736         let stamp = codegen_backend_stamp(builder, compiler, target, backend);
737         let codegen_backend = codegen_backend.to_str().unwrap();
738         t!(fs::write(&stamp, &codegen_backend));
739     }
740 }
741
742 pub fn build_codegen_backend(builder: &Builder<'_>,
743                              cargo: &mut Command,
744                              compiler: &Compiler,
745                              target: Interned<String>,
746                              backend: Interned<String>) -> String {
747     let mut features = String::new();
748
749     match &*backend {
750         "llvm" | "emscripten" => {
751             // Build LLVM for our target. This will implicitly build the
752             // host LLVM if necessary.
753             let llvm_config = builder.ensure(native::Llvm {
754                 target,
755                 emscripten: backend == "emscripten",
756             });
757
758             if backend == "emscripten" {
759                 features.push_str(" emscripten");
760             }
761
762             builder.info(&format!("Building stage{} codegen artifacts ({} -> {}, {})",
763                      compiler.stage, &compiler.host, target, backend));
764
765             // Pass down configuration from the LLVM build into the build of
766             // librustc_llvm and librustc_codegen_llvm.
767             if builder.is_rust_llvm(target) && backend != "emscripten" {
768                 cargo.env("LLVM_RUSTLLVM", "1");
769             }
770
771             cargo.env("LLVM_CONFIG", &llvm_config);
772             if backend != "emscripten" {
773                 let target_config = builder.config.target_config.get(&target);
774                 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
775                     cargo.env("CFG_LLVM_ROOT", s);
776                 }
777             }
778             // Building with a static libstdc++ is only supported on linux right now,
779             // not for MSVC or macOS
780             if builder.config.llvm_static_stdcpp &&
781                !target.contains("freebsd") &&
782                !target.contains("windows") &&
783                !target.contains("apple") {
784                 let file = compiler_file(builder,
785                                          builder.cxx(target).unwrap(),
786                                          target,
787                                          "libstdc++.a");
788                 cargo.env("LLVM_STATIC_STDCPP", file);
789             }
790             if builder.config.llvm_link_shared ||
791                 (builder.config.llvm_thin_lto && backend != "emscripten")
792             {
793                 cargo.env("LLVM_LINK_SHARED", "1");
794             }
795             if builder.config.llvm_use_libcxx {
796                 cargo.env("LLVM_USE_LIBCXX", "1");
797             }
798         }
799         _ => panic!("unknown backend: {}", backend),
800     }
801
802     features
803 }
804
805 /// Creates the `codegen-backends` folder for a compiler that's about to be
806 /// assembled as a complete compiler.
807 ///
808 /// This will take the codegen artifacts produced by `compiler` and link them
809 /// into an appropriate location for `target_compiler` to be a functional
810 /// compiler.
811 fn copy_codegen_backends_to_sysroot(builder: &Builder<'_>,
812                                     compiler: Compiler,
813                                     target_compiler: Compiler) {
814     let target = target_compiler.host;
815
816     // Note that this step is different than all the other `*Link` steps in
817     // that it's not assembling a bunch of libraries but rather is primarily
818     // moving the codegen backend into place. The codegen backend of rustc is
819     // not linked into the main compiler by default but is rather dynamically
820     // selected at runtime for inclusion.
821     //
822     // Here we're looking for the output dylib of the `CodegenBackend` step and
823     // we're copying that into the `codegen-backends` folder.
824     let dst = builder.sysroot_codegen_backends(target_compiler);
825     t!(fs::create_dir_all(&dst));
826
827     if builder.config.dry_run {
828         return;
829     }
830
831     for backend in builder.config.rust_codegen_backends.iter() {
832         let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
833         let dylib = t!(fs::read_to_string(&stamp));
834         let file = Path::new(&dylib);
835         let filename = file.file_name().unwrap().to_str().unwrap();
836         // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
837         let target_filename = {
838             let dash = filename.find('-').unwrap();
839             let dot = filename.find('.').unwrap();
840             format!("{}-{}{}",
841                     &filename[..dash],
842                     backend,
843                     &filename[dot..])
844         };
845         builder.copy(&file, &dst.join(target_filename));
846     }
847 }
848
849 fn copy_lld_to_sysroot(builder: &Builder<'_>,
850                        target_compiler: Compiler,
851                        lld_install_root: &Path) {
852     let target = target_compiler.host;
853
854     let dst = builder.sysroot_libdir(target_compiler, target)
855         .parent()
856         .unwrap()
857         .join("bin");
858     t!(fs::create_dir_all(&dst));
859
860     let src_exe = exe("lld", &target);
861     let dst_exe = exe("rust-lld", &target);
862     // we prepend this bin directory to the user PATH when linking Rust binaries. To
863     // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
864     builder.copy(&lld_install_root.join("bin").join(&src_exe), &dst.join(&dst_exe));
865 }
866
867 /// Cargo's output path for the standard library in a given stage, compiled
868 /// by a particular compiler for the specified target.
869 pub fn libstd_stamp(
870     builder: &Builder<'_>,
871     compiler: Compiler,
872     target: Interned<String>,
873 ) -> PathBuf {
874     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
875 }
876
877 /// Cargo's output path for libtest in a given stage, compiled by a particular
878 /// compiler for the specified target.
879 pub fn libtest_stamp(
880     builder: &Builder<'_>,
881     compiler: Compiler,
882     target: Interned<String>,
883 ) -> PathBuf {
884     builder.cargo_out(compiler, Mode::Test, target).join(".libtest.stamp")
885 }
886
887 /// Cargo's output path for librustc in a given stage, compiled by a particular
888 /// compiler for the specified target.
889 pub fn librustc_stamp(
890     builder: &Builder<'_>,
891     compiler: Compiler,
892     target: Interned<String>,
893 ) -> PathBuf {
894     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
895 }
896
897 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
898 /// compiler for the specified target and backend.
899 fn codegen_backend_stamp(builder: &Builder<'_>,
900                          compiler: Compiler,
901                          target: Interned<String>,
902                          backend: Interned<String>) -> PathBuf {
903     builder.cargo_out(compiler, Mode::Codegen, target)
904         .join(format!(".librustc_codegen_llvm-{}.stamp", backend))
905 }
906
907 pub fn compiler_file(
908     builder: &Builder<'_>,
909     compiler: &Path,
910     target: Interned<String>,
911     file: &str,
912 ) -> PathBuf {
913     let mut cmd = Command::new(compiler);
914     cmd.args(builder.cflags(target, GitRepo::Rustc));
915     cmd.arg(format!("-print-file-name={}", file));
916     let out = output(&mut cmd);
917     PathBuf::from(out.trim())
918 }
919
920 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
921 pub struct Sysroot {
922     pub compiler: Compiler,
923 }
924
925 impl Step for Sysroot {
926     type Output = Interned<PathBuf>;
927
928     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
929         run.never()
930     }
931
932     /// Returns the sysroot for the `compiler` specified that *this build system
933     /// generates*.
934     ///
935     /// That is, the sysroot for the stage0 compiler is not what the compiler
936     /// thinks it is by default, but it's the same as the default for stages
937     /// 1-3.
938     fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
939         let compiler = self.compiler;
940         let sysroot = if compiler.stage == 0 {
941             builder.out.join(&compiler.host).join("stage0-sysroot")
942         } else {
943             builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
944         };
945         let _ = fs::remove_dir_all(&sysroot);
946         t!(fs::create_dir_all(&sysroot));
947         INTERNER.intern_path(sysroot)
948     }
949 }
950
951 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
952 pub struct Assemble {
953     /// The compiler which we will produce in this step. Assemble itself will
954     /// take care of ensuring that the necessary prerequisites to do so exist,
955     /// that is, this target can be a stage2 compiler and Assemble will build
956     /// previous stages for you.
957     pub target_compiler: Compiler,
958 }
959
960 impl Step for Assemble {
961     type Output = Compiler;
962
963     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
964         run.never()
965     }
966
967     /// Prepare a new compiler from the artifacts in `stage`
968     ///
969     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
970     /// must have been previously produced by the `stage - 1` builder.build
971     /// compiler.
972     fn run(self, builder: &Builder<'_>) -> Compiler {
973         let target_compiler = self.target_compiler;
974
975         if target_compiler.stage == 0 {
976             assert_eq!(builder.config.build, target_compiler.host,
977                 "Cannot obtain compiler for non-native build triple at stage 0");
978             // The stage 0 compiler for the build triple is always pre-built.
979             return target_compiler;
980         }
981
982         // Get the compiler that we'll use to bootstrap ourselves.
983         //
984         // Note that this is where the recursive nature of the bootstrap
985         // happens, as this will request the previous stage's compiler on
986         // downwards to stage 0.
987         //
988         // Also note that we're building a compiler for the host platform. We
989         // only assume that we can run `build` artifacts, which means that to
990         // produce some other architecture compiler we need to start from
991         // `build` to get there.
992         //
993         // FIXME: Perhaps we should download those libraries?
994         //        It would make builds faster...
995         //
996         // FIXME: It may be faster if we build just a stage 1 compiler and then
997         //        use that to bootstrap this compiler forward.
998         let build_compiler =
999             builder.compiler(target_compiler.stage - 1, builder.config.build);
1000
1001         // Build the libraries for this compiler to link to (i.e., the libraries
1002         // it uses at runtime). NOTE: Crates the target compiler compiles don't
1003         // link to these. (FIXME: Is that correct? It seems to be correct most
1004         // of the time but I think we do link to these for stage2/bin compilers
1005         // when not performing a full bootstrap).
1006         builder.ensure(Rustc {
1007             compiler: build_compiler,
1008             target: target_compiler.host,
1009         });
1010         for &backend in builder.config.rust_codegen_backends.iter() {
1011             builder.ensure(CodegenBackend {
1012                 compiler: build_compiler,
1013                 target: target_compiler.host,
1014                 backend,
1015             });
1016         }
1017
1018         let lld_install = if builder.config.lld_enabled {
1019             Some(builder.ensure(native::Lld {
1020                 target: target_compiler.host,
1021             }))
1022         } else {
1023             None
1024         };
1025
1026         let stage = target_compiler.stage;
1027         let host = target_compiler.host;
1028         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
1029
1030         // Link in all dylibs to the libdir
1031         let sysroot = builder.sysroot(target_compiler);
1032         let rustc_libdir = builder.rustc_libdir(target_compiler);
1033         t!(fs::create_dir_all(&rustc_libdir));
1034         let src_libdir = builder.sysroot_libdir(build_compiler, host);
1035         for f in builder.read_dir(&src_libdir) {
1036             let filename = f.file_name().into_string().unwrap();
1037             if is_dylib(&filename) {
1038                 builder.copy(&f.path(), &rustc_libdir.join(&filename));
1039             }
1040         }
1041
1042         copy_codegen_backends_to_sysroot(builder,
1043                                          build_compiler,
1044                                          target_compiler);
1045         if let Some(lld_install) = lld_install {
1046             copy_lld_to_sysroot(builder, target_compiler, &lld_install);
1047         }
1048
1049         dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
1050
1051         // Link the compiler binary itself into place
1052         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
1053         let rustc = out_dir.join(exe("rustc_binary", &*host));
1054         let bindir = sysroot.join("bin");
1055         t!(fs::create_dir_all(&bindir));
1056         let compiler = builder.rustc(target_compiler);
1057         let _ = fs::remove_file(&compiler);
1058         builder.copy(&rustc, &compiler);
1059
1060         target_compiler
1061     }
1062 }
1063
1064 /// Link some files into a rustc sysroot.
1065 ///
1066 /// For a particular stage this will link the file listed in `stamp` into the
1067 /// `sysroot_dst` provided.
1068 pub fn add_to_sysroot(
1069     builder: &Builder<'_>,
1070     sysroot_dst: &Path,
1071     sysroot_host_dst: &Path,
1072     stamp: &Path
1073 ) {
1074     t!(fs::create_dir_all(&sysroot_dst));
1075     t!(fs::create_dir_all(&sysroot_host_dst));
1076     for (path, host) in builder.read_stamp_file(stamp) {
1077         if host {
1078             builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
1079         } else {
1080             builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
1081         }
1082     }
1083 }
1084
1085 pub fn run_cargo(builder: &Builder<'_>,
1086                  cargo: &mut Command,
1087                  stamp: &Path,
1088                  is_check: bool)
1089     -> Vec<PathBuf>
1090 {
1091     if builder.config.dry_run {
1092         return Vec::new();
1093     }
1094
1095     // `target_root_dir` looks like $dir/$target/release
1096     let target_root_dir = stamp.parent().unwrap();
1097     // `target_deps_dir` looks like $dir/$target/release/deps
1098     let target_deps_dir = target_root_dir.join("deps");
1099     // `host_root_dir` looks like $dir/release
1100     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
1101                                        .parent().unwrap() // chop off `$target`
1102                                        .join(target_root_dir.file_name().unwrap());
1103
1104     // Spawn Cargo slurping up its JSON output. We'll start building up the
1105     // `deps` array of all files it generated along with a `toplevel` array of
1106     // files we need to probe for later.
1107     let mut deps = Vec::new();
1108     let mut toplevel = Vec::new();
1109     let ok = stream_cargo(builder, cargo, &mut |msg| {
1110         let (filenames, crate_types) = match msg {
1111             CargoMessage::CompilerArtifact {
1112                 filenames,
1113                 target: CargoTarget {
1114                     crate_types,
1115                 },
1116                 ..
1117             } => (filenames, crate_types),
1118             _ => return,
1119         };
1120         for filename in filenames {
1121             // Skip files like executables
1122             if !filename.ends_with(".rlib") &&
1123                !filename.ends_with(".lib") &&
1124                !is_dylib(&filename) &&
1125                !(is_check && filename.ends_with(".rmeta")) {
1126                 continue;
1127             }
1128
1129             let filename = Path::new(&*filename);
1130
1131             // If this was an output file in the "host dir" we don't actually
1132             // worry about it, it's not relevant for us
1133             if filename.starts_with(&host_root_dir) {
1134                 // Unless it's a proc macro used in the compiler
1135                 if crate_types.iter().any(|t| t == "proc-macro") {
1136                     deps.push((filename.to_path_buf(), true));
1137                 }
1138                 continue;
1139             }
1140
1141             // If this was output in the `deps` dir then this is a precise file
1142             // name (hash included) so we start tracking it.
1143             if filename.starts_with(&target_deps_dir) {
1144                 deps.push((filename.to_path_buf(), false));
1145                 continue;
1146             }
1147
1148             // Otherwise this was a "top level artifact" which right now doesn't
1149             // have a hash in the name, but there's a version of this file in
1150             // the `deps` folder which *does* have a hash in the name. That's
1151             // the one we'll want to we'll probe for it later.
1152             //
1153             // We do not use `Path::file_stem` or `Path::extension` here,
1154             // because some generated files may have multiple extensions e.g.
1155             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1156             // split the file name by the last extension (`.lib`) while we need
1157             // to split by all extensions (`.dll.lib`).
1158             let expected_len = t!(filename.metadata()).len();
1159             let filename = filename.file_name().unwrap().to_str().unwrap();
1160             let mut parts = filename.splitn(2, '.');
1161             let file_stem = parts.next().unwrap().to_owned();
1162             let extension = parts.next().unwrap().to_owned();
1163
1164             toplevel.push((file_stem, extension, expected_len));
1165         }
1166     });
1167
1168     if !ok {
1169         exit(1);
1170     }
1171
1172     // Ok now we need to actually find all the files listed in `toplevel`. We've
1173     // got a list of prefix/extensions and we basically just need to find the
1174     // most recent file in the `deps` folder corresponding to each one.
1175     let contents = t!(target_deps_dir.read_dir())
1176         .map(|e| t!(e))
1177         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1178         .collect::<Vec<_>>();
1179     for (prefix, extension, expected_len) in toplevel {
1180         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1181             filename.starts_with(&prefix[..]) &&
1182                 filename[prefix.len()..].starts_with("-") &&
1183                 filename.ends_with(&extension[..]) &&
1184                 meta.len() == expected_len
1185         });
1186         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1187             FileTime::from_last_modification_time(metadata)
1188         });
1189         let path_to_add = match max {
1190             Some(triple) => triple.0.to_str().unwrap(),
1191             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1192         };
1193         if is_dylib(path_to_add) {
1194             let candidate = format!("{}.lib", path_to_add);
1195             let candidate = PathBuf::from(candidate);
1196             if candidate.exists() {
1197                 deps.push((candidate, false));
1198             }
1199         }
1200         deps.push((path_to_add.into(), false));
1201     }
1202
1203     // Now we want to update the contents of the stamp file, if necessary. First
1204     // we read off the previous contents along with its mtime. If our new
1205     // contents (the list of files to copy) is different or if any dep's mtime
1206     // is newer then we rewrite the stamp file.
1207     deps.sort();
1208     let stamp_contents = fs::read(stamp);
1209     let stamp_mtime = mtime(&stamp);
1210     let mut new_contents = Vec::new();
1211     let mut max = None;
1212     let mut max_path = None;
1213     for (dep, proc_macro) in deps.iter() {
1214         let mtime = mtime(dep);
1215         if Some(mtime) > max {
1216             max = Some(mtime);
1217             max_path = Some(dep.clone());
1218         }
1219         new_contents.extend(if *proc_macro { b"h" } else { b"t" });
1220         new_contents.extend(dep.to_str().unwrap().as_bytes());
1221         new_contents.extend(b"\0");
1222     }
1223     let max = max.unwrap();
1224     let max_path = max_path.unwrap();
1225     let contents_equal = stamp_contents
1226         .map(|contents| contents == new_contents)
1227         .unwrap_or_default();
1228     if contents_equal && max <= stamp_mtime {
1229         builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}",
1230                 stamp, max, stamp_mtime));
1231         return deps.into_iter().map(|(d, _)| d).collect()
1232     }
1233     if max > stamp_mtime {
1234         builder.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1235     } else {
1236         builder.verbose(&format!("updating {:?} as deps changed", stamp));
1237     }
1238     t!(fs::write(&stamp, &new_contents));
1239     deps.into_iter().map(|(d, _)| d).collect()
1240 }
1241
1242 pub fn stream_cargo(
1243     builder: &Builder<'_>,
1244     cargo: &mut Command,
1245     cb: &mut dyn FnMut(CargoMessage<'_>),
1246 ) -> bool {
1247     if builder.config.dry_run {
1248         return true;
1249     }
1250     // Instruct Cargo to give us json messages on stdout, critically leaving
1251     // stderr as piped so we can get those pretty colors.
1252     cargo.arg("--message-format").arg("json")
1253          .stdout(Stdio::piped());
1254
1255     builder.verbose(&format!("running: {:?}", cargo));
1256     let mut child = match cargo.spawn() {
1257         Ok(child) => child,
1258         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1259     };
1260
1261     // Spawn Cargo slurping up its JSON output. We'll start building up the
1262     // `deps` array of all files it generated along with a `toplevel` array of
1263     // files we need to probe for later.
1264     let stdout = BufReader::new(child.stdout.take().unwrap());
1265     for line in stdout.lines() {
1266         let line = t!(line);
1267         match serde_json::from_str::<CargoMessage<'_>>(&line) {
1268             Ok(msg) => cb(msg),
1269             // If this was informational, just print it out and continue
1270             Err(_) => println!("{}", line)
1271         }
1272     }
1273
1274     // Make sure Cargo actually succeeded after we read all of its stdout.
1275     let status = t!(child.wait());
1276     if !status.success() {
1277         eprintln!("command did not execute successfully: {:?}\n\
1278                   expected success, got: {}",
1279                  cargo,
1280                  status);
1281     }
1282     status.success()
1283 }
1284
1285 #[derive(Deserialize)]
1286 pub struct CargoTarget<'a> {
1287     crate_types: Vec<Cow<'a, str>>,
1288 }
1289
1290 #[derive(Deserialize)]
1291 #[serde(tag = "reason", rename_all = "kebab-case")]
1292 pub enum CargoMessage<'a> {
1293     CompilerArtifact {
1294         package_id: Cow<'a, str>,
1295         features: Vec<Cow<'a, str>>,
1296         filenames: Vec<Cow<'a, str>>,
1297         target: CargoTarget<'a>,
1298     },
1299     BuildScriptExecuted {
1300         package_id: Cow<'a, str>,
1301     }
1302 }