]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Auto merge of #71292 - marmeladema:queries-local-def-id, r=eddyb
[rust.git] / src / bootstrap / builder.rs
1 use std::any::Any;
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::env;
5 use std::ffi::OsStr;
6 use std::fmt::Debug;
7 use std::fs;
8 use std::hash::Hash;
9 use std::ops::Deref;
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
13
14 use build_helper::{output, t};
15
16 use crate::cache::{Cache, Interned, INTERNER};
17 use crate::check;
18 use crate::compile;
19 use crate::dist;
20 use crate::doc;
21 use crate::flags::Subcommand;
22 use crate::install;
23 use crate::native;
24 use crate::run;
25 use crate::test;
26 use crate::tool;
27 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir};
28 use crate::{Build, DocTests, GitRepo, Mode};
29
30 pub use crate::Compiler;
31
32 pub struct Builder<'a> {
33     pub build: &'a Build,
34     pub top_stage: u32,
35     pub kind: Kind,
36     cache: Cache,
37     stack: RefCell<Vec<Box<dyn Any>>>,
38     time_spent_on_dependencies: Cell<Duration>,
39     pub paths: Vec<PathBuf>,
40 }
41
42 impl<'a> Deref for Builder<'a> {
43     type Target = Build;
44
45     fn deref(&self) -> &Self::Target {
46         self.build
47     }
48 }
49
50 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
51     /// `PathBuf` when directories are created or to return a `Compiler` once
52     /// it's been assembled.
53     type Output: Clone;
54
55     const DEFAULT: bool = false;
56
57     /// If true, then this rule should be skipped if --target was specified, but --host was not
58     const ONLY_HOSTS: bool = false;
59
60     /// Primary function to execute this rule. Can call `builder.ensure()`
61     /// with other steps to run those.
62     fn run(self, builder: &Builder<'_>) -> Self::Output;
63
64     /// When bootstrap is passed a set of paths, this controls whether this rule
65     /// will execute. However, it does not get called in a "default" context
66     /// when we are not passed any paths; in that case, `make_run` is called
67     /// directly.
68     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
69
70     /// Builds up a "root" rule, either as a default rule or from a path passed
71     /// to us.
72     ///
73     /// When path is `None`, we are executing in a context where no paths were
74     /// passed. When `./x.py build` is run, for example, this rule could get
75     /// called if it is in the correct list below with a path of `None`.
76     fn make_run(_run: RunConfig<'_>) {
77         // It is reasonable to not have an implementation of make_run for rules
78         // who do not want to get called from the root context. This means that
79         // they are likely dependencies (e.g., sysroot creation) or similar, and
80         // as such calling them from ./x.py isn't logical.
81         unimplemented!()
82     }
83 }
84
85 pub struct RunConfig<'a> {
86     pub builder: &'a Builder<'a>,
87     pub host: Interned<String>,
88     pub target: Interned<String>,
89     pub path: PathBuf,
90 }
91
92 struct StepDescription {
93     default: bool,
94     only_hosts: bool,
95     should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
96     make_run: fn(RunConfig<'_>),
97     name: &'static str,
98 }
99
100 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
101 pub enum PathSet {
102     Set(BTreeSet<PathBuf>),
103     Suite(PathBuf),
104 }
105
106 impl PathSet {
107     fn empty() -> PathSet {
108         PathSet::Set(BTreeSet::new())
109     }
110
111     fn one<P: Into<PathBuf>>(path: P) -> PathSet {
112         let mut set = BTreeSet::new();
113         set.insert(path.into());
114         PathSet::Set(set)
115     }
116
117     fn has(&self, needle: &Path) -> bool {
118         match self {
119             PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
120             PathSet::Suite(suite) => suite.ends_with(needle),
121         }
122     }
123
124     fn path(&self, builder: &Builder<'_>) -> PathBuf {
125         match self {
126             PathSet::Set(set) => set.iter().next().unwrap_or(&builder.build.src).to_path_buf(),
127             PathSet::Suite(path) => PathBuf::from(path),
128         }
129     }
130 }
131
132 impl StepDescription {
133     fn from<S: Step>() -> StepDescription {
134         StepDescription {
135             default: S::DEFAULT,
136             only_hosts: S::ONLY_HOSTS,
137             should_run: S::should_run,
138             make_run: S::make_run,
139             name: std::any::type_name::<S>(),
140         }
141     }
142
143     fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
144         if builder.config.exclude.iter().any(|e| pathset.has(e)) {
145             eprintln!("Skipping {:?} because it is excluded", pathset);
146             return;
147         } else if !builder.config.exclude.is_empty() {
148             eprintln!(
149                 "{:?} not skipped for {:?} -- not in {:?}",
150                 pathset, self.name, builder.config.exclude
151             );
152         }
153         let hosts = &builder.hosts;
154
155         // Determine the targets participating in this rule.
156         let targets = if self.only_hosts {
157             if builder.config.skip_only_host_steps {
158                 return; // don't run anything
159             } else {
160                 &builder.hosts
161             }
162         } else {
163             &builder.targets
164         };
165
166         for host in hosts {
167             for target in targets {
168                 let run = RunConfig {
169                     builder,
170                     path: pathset.path(builder),
171                     host: *host,
172                     target: *target,
173                 };
174                 (self.make_run)(run);
175             }
176         }
177     }
178
179     fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
180         let should_runs =
181             v.iter().map(|desc| (desc.should_run)(ShouldRun::new(builder))).collect::<Vec<_>>();
182
183         // sanity checks on rules
184         for (desc, should_run) in v.iter().zip(&should_runs) {
185             assert!(
186                 !should_run.paths.is_empty(),
187                 "{:?} should have at least one pathset",
188                 desc.name
189             );
190         }
191
192         if paths.is_empty() {
193             for (desc, should_run) in v.iter().zip(should_runs) {
194                 if desc.default && should_run.is_really_default {
195                     for pathset in &should_run.paths {
196                         desc.maybe_run(builder, pathset);
197                     }
198                 }
199             }
200         } else {
201             for path in paths {
202                 // strip CurDir prefix if present
203                 let path = match path.strip_prefix(".") {
204                     Ok(p) => p,
205                     Err(_) => path,
206                 };
207
208                 let mut attempted_run = false;
209                 for (desc, should_run) in v.iter().zip(&should_runs) {
210                     if let Some(suite) = should_run.is_suite_path(path) {
211                         attempted_run = true;
212                         desc.maybe_run(builder, suite);
213                     } else if let Some(pathset) = should_run.pathset_for_path(path) {
214                         attempted_run = true;
215                         desc.maybe_run(builder, pathset);
216                     }
217                 }
218
219                 if !attempted_run {
220                     panic!("Error: no rules matched {}.", path.display());
221                 }
222             }
223         }
224     }
225 }
226
227 #[derive(Clone)]
228 pub struct ShouldRun<'a> {
229     pub builder: &'a Builder<'a>,
230     // use a BTreeSet to maintain sort order
231     paths: BTreeSet<PathSet>,
232
233     // If this is a default rule, this is an additional constraint placed on
234     // its run. Generally something like compiler docs being enabled.
235     is_really_default: bool,
236 }
237
238 impl<'a> ShouldRun<'a> {
239     fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
240         ShouldRun {
241             builder,
242             paths: BTreeSet::new(),
243             is_really_default: true, // by default no additional conditions
244         }
245     }
246
247     pub fn default_condition(mut self, cond: bool) -> Self {
248         self.is_really_default = cond;
249         self
250     }
251
252     // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
253     // ever be used, but as we transition to having all rules properly handle passing krate(...) by
254     // actually doing something different for every crate passed.
255     pub fn all_krates(mut self, name: &str) -> Self {
256         let mut set = BTreeSet::new();
257         for krate in self.builder.in_tree_crates(name) {
258             set.insert(PathBuf::from(&krate.path));
259         }
260         self.paths.insert(PathSet::Set(set));
261         self
262     }
263
264     pub fn krate(mut self, name: &str) -> Self {
265         for krate in self.builder.in_tree_crates(name) {
266             self.paths.insert(PathSet::one(&krate.path));
267         }
268         self
269     }
270
271     // single, non-aliased path
272     pub fn path(self, path: &str) -> Self {
273         self.paths(&[path])
274     }
275
276     // multiple aliases for the same job
277     pub fn paths(mut self, paths: &[&str]) -> Self {
278         self.paths.insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
279         self
280     }
281
282     pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
283         self.paths.iter().find(|pathset| match pathset {
284             PathSet::Suite(p) => path.starts_with(p),
285             PathSet::Set(_) => false,
286         })
287     }
288
289     pub fn suite_path(mut self, suite: &str) -> Self {
290         self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
291         self
292     }
293
294     // allows being more explicit about why should_run in Step returns the value passed to it
295     pub fn never(mut self) -> ShouldRun<'a> {
296         self.paths.insert(PathSet::empty());
297         self
298     }
299
300     fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
301         self.paths.iter().find(|pathset| pathset.has(path))
302     }
303 }
304
305 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
306 pub enum Kind {
307     Build,
308     Check,
309     Clippy,
310     Fix,
311     Format,
312     Test,
313     Bench,
314     Dist,
315     Doc,
316     Install,
317     Run,
318 }
319
320 impl<'a> Builder<'a> {
321     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
322         macro_rules! describe {
323             ($($rule:ty),+ $(,)?) => {{
324                 vec![$(StepDescription::from::<$rule>()),+]
325             }};
326         }
327         match kind {
328             Kind::Build => describe!(
329                 compile::Std,
330                 compile::Rustc,
331                 compile::StartupObjects,
332                 tool::BuildManifest,
333                 tool::Rustbook,
334                 tool::ErrorIndex,
335                 tool::UnstableBookGen,
336                 tool::Tidy,
337                 tool::Linkchecker,
338                 tool::CargoTest,
339                 tool::Compiletest,
340                 tool::RemoteTestServer,
341                 tool::RemoteTestClient,
342                 tool::RustInstaller,
343                 tool::Cargo,
344                 tool::Rls,
345                 tool::Rustdoc,
346                 tool::Clippy,
347                 native::Llvm,
348                 native::Sanitizers,
349                 tool::Rustfmt,
350                 tool::Miri,
351                 native::Lld
352             ),
353             Kind::Check | Kind::Clippy | Kind::Fix | Kind::Format => {
354                 describe!(check::Std, check::Rustc, check::Rustdoc)
355             }
356             Kind::Test => describe!(
357                 crate::toolstate::ToolStateCheck,
358                 test::ExpandYamlAnchors,
359                 test::Tidy,
360                 test::Ui,
361                 test::CompileFail,
362                 test::RunFail,
363                 test::RunPassValgrind,
364                 test::MirOpt,
365                 test::Codegen,
366                 test::CodegenUnits,
367                 test::Assembly,
368                 test::Incremental,
369                 test::Debuginfo,
370                 test::UiFullDeps,
371                 test::Rustdoc,
372                 test::Pretty,
373                 test::RunFailPretty,
374                 test::RunPassValgrindPretty,
375                 test::Crate,
376                 test::CrateLibrustc,
377                 test::CrateRustdoc,
378                 test::Linkcheck,
379                 test::Cargotest,
380                 test::Cargo,
381                 test::Rls,
382                 test::ErrorIndex,
383                 test::Distcheck,
384                 test::RunMakeFullDeps,
385                 test::Nomicon,
386                 test::Reference,
387                 test::RustdocBook,
388                 test::RustByExample,
389                 test::TheBook,
390                 test::UnstableBook,
391                 test::RustcBook,
392                 test::RustcGuide,
393                 test::EmbeddedBook,
394                 test::EditionGuide,
395                 test::Rustfmt,
396                 test::Miri,
397                 test::Clippy,
398                 test::CompiletestTest,
399                 test::RustdocJSStd,
400                 test::RustdocJSNotStd,
401                 test::RustdocTheme,
402                 test::RustdocUi,
403                 // Run bootstrap close to the end as it's unlikely to fail
404                 test::Bootstrap,
405                 // Run run-make last, since these won't pass without make on Windows
406                 test::RunMake,
407             ),
408             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
409             Kind::Doc => describe!(
410                 doc::UnstableBook,
411                 doc::UnstableBookGen,
412                 doc::TheBook,
413                 doc::Standalone,
414                 doc::Std,
415                 doc::Rustc,
416                 doc::Rustdoc,
417                 doc::ErrorIndex,
418                 doc::Nomicon,
419                 doc::Reference,
420                 doc::RustdocBook,
421                 doc::RustByExample,
422                 doc::RustcBook,
423                 doc::CargoBook,
424                 doc::EmbeddedBook,
425                 doc::EditionGuide,
426             ),
427             Kind::Dist => describe!(
428                 dist::Docs,
429                 dist::RustcDocs,
430                 dist::Mingw,
431                 dist::Rustc,
432                 dist::DebuggerScripts,
433                 dist::Std,
434                 dist::RustcDev,
435                 dist::Analysis,
436                 dist::Src,
437                 dist::PlainSourceTarball,
438                 dist::Cargo,
439                 dist::Rls,
440                 dist::Rustfmt,
441                 dist::Clippy,
442                 dist::Miri,
443                 dist::LlvmTools,
444                 dist::Lldb,
445                 dist::Extended,
446                 dist::HashSign
447             ),
448             Kind::Install => describe!(
449                 install::Docs,
450                 install::Std,
451                 install::Cargo,
452                 install::Rls,
453                 install::Rustfmt,
454                 install::Clippy,
455                 install::Miri,
456                 install::Analysis,
457                 install::Src,
458                 install::Rustc
459             ),
460             Kind::Run => describe!(run::ExpandYamlAnchors,),
461         }
462     }
463
464     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
465         let kind = match subcommand {
466             "build" => Kind::Build,
467             "doc" => Kind::Doc,
468             "test" => Kind::Test,
469             "bench" => Kind::Bench,
470             "dist" => Kind::Dist,
471             "install" => Kind::Install,
472             _ => return None,
473         };
474
475         let builder = Builder {
476             build,
477             top_stage: build.config.stage.unwrap_or(2),
478             kind,
479             cache: Cache::new(),
480             stack: RefCell::new(Vec::new()),
481             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
482             paths: vec![],
483         };
484
485         let builder = &builder;
486         let mut should_run = ShouldRun::new(builder);
487         for desc in Builder::get_step_descriptions(builder.kind) {
488             should_run = (desc.should_run)(should_run);
489         }
490         let mut help = String::from("Available paths:\n");
491         for pathset in should_run.paths {
492             if let PathSet::Set(set) = pathset {
493                 set.iter().for_each(|path| {
494                     help.push_str(
495                         format!("    ./x.py {} {}\n", subcommand, path.display()).as_str(),
496                     )
497                 })
498             }
499         }
500         Some(help)
501     }
502
503     pub fn new(build: &Build) -> Builder<'_> {
504         let (kind, paths) = match build.config.cmd {
505             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
506             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
507             Subcommand::Clippy { ref paths } => (Kind::Clippy, &paths[..]),
508             Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
509             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
510             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
511             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
512             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
513             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
514             Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
515             Subcommand::Format { .. } | Subcommand::Clean { .. } => panic!(),
516         };
517
518         Builder {
519             build,
520             top_stage: build.config.stage.unwrap_or(2),
521             kind,
522             cache: Cache::new(),
523             stack: RefCell::new(Vec::new()),
524             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
525             paths: paths.to_owned(),
526         }
527     }
528
529     pub fn execute_cli(&self) {
530         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
531     }
532
533     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
534         let paths = paths.unwrap_or(&[]);
535         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
536     }
537
538     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
539         StepDescription::run(v, self, paths);
540     }
541
542     /// Obtain a compiler at a given stage and for a given host. Explicitly does
543     /// not take `Compiler` since all `Compiler` instances are meant to be
544     /// obtained through this function, since it ensures that they are valid
545     /// (i.e., built and assembled).
546     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
547         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
548     }
549
550     /// Similar to `compiler`, except handles the full-bootstrap option to
551     /// silently use the stage1 compiler instead of a stage2 compiler if one is
552     /// requested.
553     ///
554     /// Note that this does *not* have the side effect of creating
555     /// `compiler(stage, host)`, unlike `compiler` above which does have such
556     /// a side effect. The returned compiler here can only be used to compile
557     /// new artifacts, it can't be used to rely on the presence of a particular
558     /// sysroot.
559     ///
560     /// See `force_use_stage1` for documentation on what each argument is.
561     pub fn compiler_for(
562         &self,
563         stage: u32,
564         host: Interned<String>,
565         target: Interned<String>,
566     ) -> Compiler {
567         if self.build.force_use_stage1(Compiler { stage, host }, target) {
568             self.compiler(1, self.config.build)
569         } else {
570             self.compiler(stage, host)
571         }
572     }
573
574     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
575         self.ensure(compile::Sysroot { compiler })
576     }
577
578     /// Returns the libdir where the standard library and other artifacts are
579     /// found for a compiler's sysroot.
580     pub fn sysroot_libdir(
581         &self,
582         compiler: Compiler,
583         target: Interned<String>,
584     ) -> Interned<PathBuf> {
585         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
586         struct Libdir {
587             compiler: Compiler,
588             target: Interned<String>,
589         }
590         impl Step for Libdir {
591             type Output = Interned<PathBuf>;
592
593             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
594                 run.never()
595             }
596
597             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
598                 let lib = builder.sysroot_libdir_relative(self.compiler);
599                 let sysroot = builder
600                     .sysroot(self.compiler)
601                     .join(lib)
602                     .join("rustlib")
603                     .join(self.target)
604                     .join("lib");
605                 let _ = fs::remove_dir_all(&sysroot);
606                 t!(fs::create_dir_all(&sysroot));
607                 INTERNER.intern_path(sysroot)
608             }
609         }
610         self.ensure(Libdir { compiler, target })
611     }
612
613     /// Returns the compiler's libdir where it stores the dynamic libraries that
614     /// it itself links against.
615     ///
616     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
617     /// Windows.
618     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
619         if compiler.is_snapshot(self) {
620             self.rustc_snapshot_libdir()
621         } else {
622             match self.config.libdir_relative() {
623                 Some(relative_libdir) if compiler.stage >= 1 => {
624                     self.sysroot(compiler).join(relative_libdir)
625                 }
626                 _ => self.sysroot(compiler).join(libdir(&compiler.host)),
627             }
628         }
629     }
630
631     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
632     /// it itself links against.
633     ///
634     /// For example this returns `lib` on Unix and `bin` on
635     /// Windows.
636     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
637         if compiler.is_snapshot(self) {
638             libdir(&self.config.build).as_ref()
639         } else {
640             match self.config.libdir_relative() {
641                 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
642                 _ => libdir(&compiler.host).as_ref(),
643             }
644         }
645     }
646
647     /// Returns the compiler's relative libdir where the standard library and other artifacts are
648     /// found for a compiler's sysroot.
649     ///
650     /// For example this returns `lib` on Unix and Windows.
651     pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
652         match self.config.libdir_relative() {
653             Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
654             _ => Path::new("lib"),
655         }
656     }
657
658     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
659     /// library lookup path.
660     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Cargo) {
661         // Windows doesn't need dylib path munging because the dlls for the
662         // compiler live next to the compiler and the system will find them
663         // automatically.
664         if cfg!(windows) {
665             return;
666         }
667
668         add_dylib_path(vec![self.rustc_libdir(compiler)], &mut cmd.command);
669     }
670
671     /// Gets a path to the compiler specified.
672     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
673         if compiler.is_snapshot(self) {
674             self.initial_rustc.clone()
675         } else {
676             self.sysroot(compiler).join("bin").join(exe("rustc", &compiler.host))
677         }
678     }
679
680     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
681         self.ensure(tool::Rustdoc { compiler })
682     }
683
684     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
685         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
686         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
687             .env("RUSTC_SYSROOT", self.sysroot(compiler))
688             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
689             // equivalently to rustc.
690             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
691             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
692             .env("RUSTDOC_REAL", self.rustdoc(compiler))
693             .env("RUSTDOC_CRATE_VERSION", self.rust_version())
694             .env("RUSTC_BOOTSTRAP", "1");
695
696         // Remove make-related flags that can cause jobserver problems.
697         cmd.env_remove("MAKEFLAGS");
698         cmd.env_remove("MFLAGS");
699
700         if let Some(linker) = self.linker(compiler.host, true) {
701             cmd.env("RUSTC_TARGET_LINKER", linker);
702         }
703         cmd
704     }
705
706     /// Return the path to `llvm-config` for the target, if it exists.
707     ///
708     /// Note that this returns `None` if LLVM is disabled, or if we're in a
709     /// check build or dry-run, where there's no need to build all of LLVM.
710     fn llvm_config(&self, target: Interned<String>) -> Option<PathBuf> {
711         if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
712             let llvm_config = self.ensure(native::Llvm { target });
713             if llvm_config.is_file() {
714                 return Some(llvm_config);
715             }
716         }
717         None
718     }
719
720     /// Prepares an invocation of `cargo` to be run.
721     ///
722     /// This will create a `Command` that represents a pending execution of
723     /// Cargo. This cargo will be configured to use `compiler` as the actual
724     /// rustc compiler, its output will be scoped by `mode`'s output directory,
725     /// it will pass the `--target` flag for the specified `target`, and will be
726     /// executing the Cargo command `cmd`.
727     pub fn cargo(
728         &self,
729         compiler: Compiler,
730         mode: Mode,
731         target: Interned<String>,
732         cmd: &str,
733     ) -> Cargo {
734         let mut cargo = Command::new(&self.initial_cargo);
735         let out_dir = self.stage_out(compiler, mode);
736
737         if cmd == "doc" || cmd == "rustdoc" {
738             let my_out = match mode {
739                 // This is the intended out directory for compiler documentation.
740                 Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
741                 _ => self.crate_doc_out(target),
742             };
743             let rustdoc = self.rustdoc(compiler);
744             self.clear_if_dirty(&my_out, &rustdoc);
745         }
746
747         cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
748
749         let profile_var = |name: &str| {
750             let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
751             format!("CARGO_PROFILE_{}_{}", profile, name)
752         };
753
754         // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
755         // needs to not accidentally link to libLLVM in stage0/lib.
756         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
757         if let Some(e) = env::var_os(util::dylib_path_var()) {
758             cargo.env("REAL_LIBRARY_PATH", e);
759         }
760
761         if cmd != "install" {
762             cargo.arg("--target").arg(target);
763         } else {
764             assert_eq!(target, compiler.host);
765         }
766
767         // Set a flag for `check`/`clippy`/`fix`, so that certain build
768         // scripts can do less work (e.g. not building/requiring LLVM).
769         if cmd == "check" || cmd == "clippy" || cmd == "fix" {
770             cargo.env("RUST_CHECK", "1");
771         }
772
773         let stage = if compiler.stage == 0 && self.local_rebuild {
774             // Assume the local-rebuild rustc already has stage1 features.
775             1
776         } else {
777             compiler.stage
778         };
779
780         let mut rustflags = Rustflags::new(&target);
781         if stage != 0 {
782             if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
783                 cargo.args(s.split_whitespace());
784             }
785             rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
786         } else {
787             if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
788                 cargo.args(s.split_whitespace());
789             }
790             rustflags.env("RUSTFLAGS_BOOTSTRAP");
791             rustflags.arg("--cfg=bootstrap");
792         }
793
794         // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
795         // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
796         // #71458.
797         let rustdocflags = rustflags.clone();
798
799         if let Ok(s) = env::var("CARGOFLAGS") {
800             cargo.args(s.split_whitespace());
801         }
802
803         match mode {
804             Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
805             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
806                 // Build proc macros both for the host and the target
807                 if target != compiler.host && cmd != "check" {
808                     cargo.arg("-Zdual-proc-macros");
809                     rustflags.arg("-Zdual-proc-macros");
810                 }
811             }
812         }
813
814         // This tells Cargo (and in turn, rustc) to output more complete
815         // dependency information.  Most importantly for rustbuild, this
816         // includes sysroot artifacts, like libstd, which means that we don't
817         // need to track those in rustbuild (an error prone process!). This
818         // feature is currently unstable as there may be some bugs and such, but
819         // it represents a big improvement in rustbuild's reliability on
820         // rebuilds, so we're using it here.
821         //
822         // For some additional context, see #63470 (the PR originally adding
823         // this), as well as #63012 which is the tracking issue for this
824         // feature on the rustc side.
825         cargo.arg("-Zbinary-dep-depinfo");
826
827         cargo.arg("-j").arg(self.jobs().to_string());
828         // Remove make-related flags to ensure Cargo can correctly set things up
829         cargo.env_remove("MAKEFLAGS");
830         cargo.env_remove("MFLAGS");
831
832         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
833         // Force cargo to output binaries with disambiguating hashes in the name
834         let mut metadata = if compiler.stage == 0 {
835             // Treat stage0 like a special channel, whether it's a normal prior-
836             // release rustc or a local rebuild with the same version, so we
837             // never mix these libraries by accident.
838             "bootstrap".to_string()
839         } else {
840             self.config.channel.to_string()
841         };
842         // We want to make sure that none of the dependencies between
843         // std/test/rustc unify with one another. This is done for weird linkage
844         // reasons but the gist of the problem is that if librustc, libtest, and
845         // libstd all depend on libc from crates.io (which they actually do) we
846         // want to make sure they all get distinct versions. Things get really
847         // weird if we try to unify all these dependencies right now, namely
848         // around how many times the library is linked in dynamic libraries and
849         // such. If rustc were a static executable or if we didn't ship dylibs
850         // this wouldn't be a problem, but we do, so it is. This is in general
851         // just here to make sure things build right. If you can remove this and
852         // things still build right, please do!
853         match mode {
854             Mode::Std => metadata.push_str("std"),
855             // When we're building rustc tools, they're built with a search path
856             // that contains things built during the rustc build. For example,
857             // bitflags is built during the rustc build, and is a dependency of
858             // rustdoc as well. We're building rustdoc in a different target
859             // directory, though, which means that Cargo will rebuild the
860             // dependency. When we go on to build rustdoc, we'll look for
861             // bitflags, and find two different copies: one built during the
862             // rustc step and one that we just built. This isn't always a
863             // problem, somehow -- not really clear why -- but we know that this
864             // fixes things.
865             Mode::ToolRustc => metadata.push_str("tool-rustc"),
866             _ => {}
867         }
868         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
869
870         if cmd == "clippy" {
871             rustflags.arg("-Zforce-unstable-if-unmarked");
872         }
873
874         rustflags.arg("-Zmacro-backtrace");
875
876         let want_rustdoc = self.doc_tests != DocTests::No;
877
878         // We synthetically interpret a stage0 compiler used to build tools as a
879         // "raw" compiler in that it's the exact snapshot we download. Normally
880         // the stage0 build means it uses libraries build by the stage0
881         // compiler, but for tools we just use the precompiled libraries that
882         // we've downloaded
883         let use_snapshot = mode == Mode::ToolBootstrap;
884         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
885
886         let maybe_sysroot = self.sysroot(compiler);
887         let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
888         let libdir = self.rustc_libdir(compiler);
889
890         // Clear the output directory if the real rustc we're using has changed;
891         // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
892         //
893         // Avoid doing this during dry run as that usually means the relevant
894         // compiler is not yet linked/copied properly.
895         //
896         // Only clear out the directory if we're compiling std; otherwise, we
897         // should let Cargo take care of things for us (via depdep info)
898         if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
899             self.clear_if_dirty(&out_dir, &self.rustc(compiler));
900         }
901
902         // Customize the compiler we're running. Specify the compiler to cargo
903         // as our shim and then pass it some various options used to configure
904         // how the actual compiler itself is called.
905         //
906         // These variables are primarily all read by
907         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
908         cargo
909             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
910             .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
911             .env("RUSTC_REAL", self.rustc(compiler))
912             .env("RUSTC_STAGE", stage.to_string())
913             .env("RUSTC_DEBUG_ASSERTIONS", self.config.rust_debug_assertions.to_string())
914             .env("RUSTC_SYSROOT", &sysroot)
915             .env("RUSTC_LIBDIR", &libdir)
916             .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
917             .env(
918                 "RUSTDOC_REAL",
919                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
920                     self.rustdoc(compiler)
921                 } else {
922                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
923                 },
924             )
925             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
926             .env("RUSTC_BREAK_ON_ICE", "1");
927
928         // Dealing with rpath here is a little special, so let's go into some
929         // detail. First off, `-rpath` is a linker option on Unix platforms
930         // which adds to the runtime dynamic loader path when looking for
931         // dynamic libraries. We use this by default on Unix platforms to ensure
932         // that our nightlies behave the same on Windows, that is they work out
933         // of the box. This can be disabled, of course, but basically that's why
934         // we're gated on RUSTC_RPATH here.
935         //
936         // Ok, so the astute might be wondering "why isn't `-C rpath` used
937         // here?" and that is indeed a good question to task. This codegen
938         // option is the compiler's current interface to generating an rpath.
939         // Unfortunately it doesn't quite suffice for us. The flag currently
940         // takes no value as an argument, so the compiler calculates what it
941         // should pass to the linker as `-rpath`. This unfortunately is based on
942         // the **compile time** directory structure which when building with
943         // Cargo will be very different than the runtime directory structure.
944         //
945         // All that's a really long winded way of saying that if we use
946         // `-Crpath` then the executables generated have the wrong rpath of
947         // something like `$ORIGIN/deps` when in fact the way we distribute
948         // rustc requires the rpath to be `$ORIGIN/../lib`.
949         //
950         // So, all in all, to set up the correct rpath we pass the linker
951         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
952         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
953         // to change a flag in a binary?
954         if self.config.rust_rpath && util::use_host_linker(&target) {
955             let rpath = if target.contains("apple") {
956                 // Note that we need to take one extra step on macOS to also pass
957                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
958                 // do that we pass a weird flag to the compiler to get it to do
959                 // so. Note that this is definitely a hack, and we should likely
960                 // flesh out rpath support more fully in the future.
961                 rustflags.arg("-Zosx-rpath-install-name");
962                 Some("-Wl,-rpath,@loader_path/../lib")
963             } else if !target.contains("windows") {
964                 Some("-Wl,-rpath,$ORIGIN/../lib")
965             } else {
966                 None
967             };
968             if let Some(rpath) = rpath {
969                 rustflags.arg(&format!("-Clink-args={}", rpath));
970             }
971         }
972
973         // FIXME: Don't use LLD if we're compiling libtest, since it fails to link it.
974         // See https://github.com/rust-lang/rust/issues/68647.
975         let can_use_lld = mode != Mode::Std;
976
977         if let Some(host_linker) = self.linker(compiler.host, can_use_lld) {
978             cargo.env("RUSTC_HOST_LINKER", host_linker);
979         }
980
981         if let Some(target_linker) = self.linker(target, can_use_lld) {
982             let target = crate::envify(&target);
983             cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
984         }
985         if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
986             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
987         }
988
989         let debuginfo_level = match mode {
990             Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
991             Mode::Std => self.config.rust_debuginfo_level_std,
992             Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
993                 self.config.rust_debuginfo_level_tools
994             }
995         };
996         cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
997
998         if !mode.is_tool() {
999             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1000         }
1001
1002         if let Some(x) = self.crt_static(target) {
1003             if x {
1004                 rustflags.arg("-Ctarget-feature=+crt-static");
1005             } else {
1006                 rustflags.arg("-Ctarget-feature=-crt-static");
1007             }
1008         }
1009
1010         if let Some(x) = self.crt_static(compiler.host) {
1011             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1012         }
1013
1014         if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1015             let map = format!("{}={}", self.build.src.display(), map_to);
1016             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1017
1018             // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1019             // in order to opportunistically reverse it later.
1020             cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1021         }
1022
1023         // Enable usage of unstable features
1024         cargo.env("RUSTC_BOOTSTRAP", "1");
1025         self.add_rust_test_threads(&mut cargo);
1026
1027         // Almost all of the crates that we compile as part of the bootstrap may
1028         // have a build script, including the standard library. To compile a
1029         // build script, however, it itself needs a standard library! This
1030         // introduces a bit of a pickle when we're compiling the standard
1031         // library itself.
1032         //
1033         // To work around this we actually end up using the snapshot compiler
1034         // (stage0) for compiling build scripts of the standard library itself.
1035         // The stage0 compiler is guaranteed to have a libstd available for use.
1036         //
1037         // For other crates, however, we know that we've already got a standard
1038         // library up and running, so we can use the normal compiler to compile
1039         // build scripts in that situation.
1040         if mode == Mode::Std {
1041             cargo
1042                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1043                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1044         } else {
1045             cargo
1046                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1047                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1048         }
1049
1050         // Tools that use compiler libraries may inherit the `-lLLVM` link
1051         // requirement, but the `-L` library path is not propagated across
1052         // separate Cargo projects. We can add LLVM's library path to the
1053         // platform-specific environment variable as a workaround.
1054         if mode == Mode::ToolRustc {
1055             if let Some(llvm_config) = self.llvm_config(target) {
1056                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1057                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1058             }
1059         }
1060
1061         if self.config.incremental {
1062             cargo.env("CARGO_INCREMENTAL", "1");
1063         } else {
1064             // Don't rely on any default setting for incr. comp. in Cargo
1065             cargo.env("CARGO_INCREMENTAL", "0");
1066         }
1067
1068         if let Some(ref on_fail) = self.config.on_fail {
1069             cargo.env("RUSTC_ON_FAIL", on_fail);
1070         }
1071
1072         if self.config.print_step_timings {
1073             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1074         }
1075
1076         if self.config.backtrace_on_ice {
1077             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1078         }
1079
1080         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1081
1082         if !mode.is_tool() {
1083             // When extending this list, add the new lints to the RUSTFLAGS of the
1084             // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1085             // some code doesn't go through this `rustc` wrapper.
1086             rustflags.arg("-Wrust_2018_idioms");
1087             rustflags.arg("-Wunused_lifetimes");
1088
1089             if self.config.deny_warnings {
1090                 rustflags.arg("-Dwarnings");
1091
1092                 // FIXME(#58633) hide "unused attribute" errors in incremental
1093                 // builds of the standard library, as the underlying checks are
1094                 // not yet properly integrated with incremental recompilation.
1095                 if mode == Mode::Std && compiler.stage == 0 && self.config.incremental {
1096                     rustflags.arg("-Aunused-attributes");
1097                 }
1098             }
1099         }
1100
1101         if let Mode::Rustc | Mode::Codegen = mode {
1102             rustflags.arg("-Zunstable-options");
1103             rustflags.arg("-Wrustc::internal");
1104         }
1105
1106         // Throughout the build Cargo can execute a number of build scripts
1107         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1108         // obtained previously to those build scripts.
1109         // Build scripts use either the `cc` crate or `configure/make` so we pass
1110         // the options through environment variables that are fetched and understood by both.
1111         //
1112         // FIXME: the guard against msvc shouldn't need to be here
1113         if target.contains("msvc") {
1114             if let Some(ref cl) = self.config.llvm_clang_cl {
1115                 cargo.env("CC", cl).env("CXX", cl);
1116             }
1117         } else {
1118             let ccache = self.config.ccache.as_ref();
1119             let ccacheify = |s: &Path| {
1120                 let ccache = match ccache {
1121                     Some(ref s) => s,
1122                     None => return s.display().to_string(),
1123                 };
1124                 // FIXME: the cc-rs crate only recognizes the literal strings
1125                 // `ccache` and `sccache` when doing caching compilations, so we
1126                 // mirror that here. It should probably be fixed upstream to
1127                 // accept a new env var or otherwise work with custom ccache
1128                 // vars.
1129                 match &ccache[..] {
1130                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1131                     _ => s.display().to_string(),
1132                 }
1133             };
1134             let cc = ccacheify(&self.cc(target));
1135             cargo.env(format!("CC_{}", target), &cc);
1136
1137             let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1138             cargo.env(format!("CFLAGS_{}", target), cflags.clone());
1139
1140             if let Some(ar) = self.ar(target) {
1141                 let ranlib = format!("{} s", ar.display());
1142                 cargo.env(format!("AR_{}", target), ar).env(format!("RANLIB_{}", target), ranlib);
1143             }
1144
1145             if let Ok(cxx) = self.cxx(target) {
1146                 let cxx = ccacheify(&cxx);
1147                 cargo
1148                     .env(format!("CXX_{}", target), &cxx)
1149                     .env(format!("CXXFLAGS_{}", target), cflags);
1150             }
1151         }
1152
1153         if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1154             rustflags.arg("-Zsave-analysis");
1155             cargo.env(
1156                 "RUST_SAVE_ANALYSIS_CONFIG",
1157                 "{\"output_file\": null,\"full_docs\": false,\
1158                        \"pub_only\": true,\"reachable_only\": false,\
1159                        \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1160             );
1161         }
1162
1163         // If Control Flow Guard is enabled, pass the `control_flow_guard=checks` flag to rustc
1164         // when compiling the standard library, since this might be linked into the final outputs
1165         // produced by rustc. Since this mitigation is only available on Windows, only enable it
1166         // for the standard library in case the compiler is run on a non-Windows platform.
1167         // This is not needed for stage 0 artifacts because these will only be used for building
1168         // the stage 1 compiler.
1169         if cfg!(windows)
1170             && mode == Mode::Std
1171             && self.config.control_flow_guard
1172             && compiler.stage >= 1
1173         {
1174             rustflags.arg("-Zcontrol_flow_guard=checks");
1175         }
1176
1177         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1178         cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1179
1180         // Environment variables *required* throughout the build
1181         //
1182         // FIXME: should update code to not require this env var
1183         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1184
1185         // Set this for all builds to make sure doc builds also get it.
1186         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1187
1188         // This one's a bit tricky. As of the time of this writing the compiler
1189         // links to the `winapi` crate on crates.io. This crate provides raw
1190         // bindings to Windows system functions, sort of like libc does for
1191         // Unix. This crate also, however, provides "import libraries" for the
1192         // MinGW targets. There's an import library per dll in the windows
1193         // distribution which is what's linked to. These custom import libraries
1194         // are used because the winapi crate can reference Windows functions not
1195         // present in the MinGW import libraries.
1196         //
1197         // For example MinGW may ship libdbghelp.a, but it may not have
1198         // references to all the functions in the dbghelp dll. Instead the
1199         // custom import library for dbghelp in the winapi crates has all this
1200         // information.
1201         //
1202         // Unfortunately for us though the import libraries are linked by
1203         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1204         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1205         // conflict with the system MinGW ones). This consequently means that
1206         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1207         // DLL) when linked against *again*, for example with procedural macros
1208         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1209         // `-lwinapi_foo` to the linker again. This isn't actually available in
1210         // our distribution, however, so the link fails.
1211         //
1212         // To solve this problem we tell winapi to not use its bundled import
1213         // libraries. This means that it will link to the system MinGW import
1214         // libraries by default, and the `-ldylib=foo` directives will still get
1215         // passed to the final linker, but they'll look like `-lfoo` which can
1216         // be resolved because MinGW has the import library. The downside is we
1217         // don't get newer functions from Windows, but we don't use any of them
1218         // anyway.
1219         if !mode.is_tool() {
1220             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1221         }
1222
1223         for _ in 1..self.verbosity {
1224             cargo.arg("-v");
1225         }
1226
1227         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1228             (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1229                 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1230             }
1231             _ => {
1232                 // Don't set anything
1233             }
1234         }
1235
1236         if self.config.rust_optimize {
1237             // FIXME: cargo bench/install do not accept `--release`
1238             if cmd != "bench" && cmd != "install" {
1239                 cargo.arg("--release");
1240             }
1241         }
1242
1243         if self.config.locked_deps {
1244             cargo.arg("--locked");
1245         }
1246         if self.config.vendor || self.is_sudo {
1247             cargo.arg("--frozen");
1248         }
1249
1250         // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1251         cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1252
1253         self.ci_env.force_coloring_in_ci(&mut cargo);
1254
1255         // When we build Rust dylibs they're all intended for intermediate
1256         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1257         // linking all deps statically into the dylib.
1258         if let Mode::Std | Mode::Rustc | Mode::Codegen = mode {
1259             rustflags.arg("-Cprefer-dynamic");
1260         }
1261
1262         // When building incrementally we default to a lower ThinLTO import limit
1263         // (unless explicitly specified otherwise). This will produce a somewhat
1264         // slower code but give way better compile times.
1265         {
1266             let limit = match self.config.rust_thin_lto_import_instr_limit {
1267                 Some(limit) => Some(limit),
1268                 None if self.config.incremental => Some(10),
1269                 _ => None,
1270             };
1271
1272             if let Some(limit) = limit {
1273                 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1274             }
1275         }
1276
1277         Cargo { command: cargo, rustflags, rustdocflags }
1278     }
1279
1280     /// Ensure that a given step is built, returning its output. This will
1281     /// cache the step, so it is safe (and good!) to call this as often as
1282     /// needed to ensure that all dependencies are built.
1283     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1284         {
1285             let mut stack = self.stack.borrow_mut();
1286             for stack_step in stack.iter() {
1287                 // should skip
1288                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1289                     continue;
1290                 }
1291                 let mut out = String::new();
1292                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1293                 for el in stack.iter().rev() {
1294                     out += &format!("\t{:?}\n", el);
1295                 }
1296                 panic!(out);
1297             }
1298             if let Some(out) = self.cache.get(&step) {
1299                 self.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
1300
1301                 return out;
1302             }
1303             self.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
1304             stack.push(Box::new(step.clone()));
1305         }
1306
1307         let (out, dur) = {
1308             let start = Instant::now();
1309             let zero = Duration::new(0, 0);
1310             let parent = self.time_spent_on_dependencies.replace(zero);
1311             let out = step.clone().run(self);
1312             let dur = start.elapsed();
1313             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1314             (out, dur - deps)
1315         };
1316
1317         if self.config.print_step_timings && dur > Duration::from_millis(100) {
1318             println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1319         }
1320
1321         {
1322             let mut stack = self.stack.borrow_mut();
1323             let cur_step = stack.pop().expect("step stack empty");
1324             assert_eq!(cur_step.downcast_ref(), Some(&step));
1325         }
1326         self.verbose(&format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
1327         self.cache.put(step, out.clone());
1328         out
1329     }
1330 }
1331
1332 #[cfg(test)]
1333 mod tests;
1334
1335 #[derive(Debug, Clone)]
1336 struct Rustflags(String);
1337
1338 impl Rustflags {
1339     fn new(target: &str) -> Rustflags {
1340         let mut ret = Rustflags(String::new());
1341
1342         // Inherit `RUSTFLAGS` by default ...
1343         ret.env("RUSTFLAGS");
1344
1345         // ... and also handle target-specific env RUSTFLAGS if they're
1346         // configured.
1347         let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(target));
1348         ret.env(&target_specific);
1349
1350         ret
1351     }
1352
1353     fn env(&mut self, env: &str) {
1354         if let Ok(s) = env::var(env) {
1355             for part in s.split_whitespace() {
1356                 self.arg(part);
1357             }
1358         }
1359     }
1360
1361     fn arg(&mut self, arg: &str) -> &mut Self {
1362         assert_eq!(arg.split_whitespace().count(), 1);
1363         if !self.0.is_empty() {
1364             self.0.push_str(" ");
1365         }
1366         self.0.push_str(arg);
1367         self
1368     }
1369 }
1370
1371 #[derive(Debug)]
1372 pub struct Cargo {
1373     command: Command,
1374     rustflags: Rustflags,
1375     rustdocflags: Rustflags,
1376 }
1377
1378 impl Cargo {
1379     pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1380         self.rustflags.arg(arg);
1381         self
1382     }
1383
1384     pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1385         self.command.arg(arg.as_ref());
1386         self
1387     }
1388
1389     pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1390     where
1391         I: IntoIterator<Item = S>,
1392         S: AsRef<OsStr>,
1393     {
1394         for arg in args {
1395             self.arg(arg.as_ref());
1396         }
1397         self
1398     }
1399
1400     pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1401         self.command.env(key.as_ref(), value.as_ref());
1402         self
1403     }
1404 }
1405
1406 impl From<Cargo> for Command {
1407     fn from(mut cargo: Cargo) -> Command {
1408         let rustflags = &cargo.rustflags.0;
1409         if !rustflags.is_empty() {
1410             cargo.command.env("RUSTFLAGS", rustflags);
1411         }
1412
1413         let rustdocflags = &cargo.rustdocflags.0;
1414         if !rustdocflags.is_empty() {
1415             cargo.command.env("RUSTDOCFLAGS", rustdocflags);
1416         }
1417
1418         cargo.command
1419     }
1420 }