]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/session.rs
Merge branch 'master' into feature/incorporate-tracing
[rust.git] / src / librustc_session / session.rs
1 use crate::cgu_reuse_tracker::CguReuseTracker;
2 use crate::code_stats::CodeStats;
3 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::config::{self, CrateType, OutputType, PrintRequest, SanitizerSet, SwitchWithOptPath};
5 use crate::filesearch;
6 use crate::lint;
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
9
10 pub use rustc_ast::ast::Attribute;
11 pub use rustc_ast::attr::MarkedAttrs;
12 pub use rustc_ast::crate_disambiguator::CrateDisambiguator;
13 use rustc_data_structures::flock;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_data_structures::jobserver::{self, Client};
16 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
17 use rustc_data_structures::sync::{
18     self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
19 };
20 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
21 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
22 use rustc_errors::json::JsonEmitter;
23 use rustc_errors::registry::Registry;
24 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported};
25 use rustc_span::edition::Edition;
26 use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
27 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
28 use rustc_target::asm::InlineAsmArch;
29 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
30 use rustc_target::spec::{Target, TargetTriple, TlsModel};
31
32 use std::cell::{self, RefCell};
33 use std::env;
34 use std::fmt;
35 use std::io::Write;
36 use std::num::NonZeroU32;
37 use std::ops::{Div, Mul};
38 use std::path::PathBuf;
39 use std::str::FromStr;
40 use std::sync::Arc;
41 use std::time::Duration;
42
43 pub struct OptimizationFuel {
44     /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
45     remaining: u64,
46     /// We're rejecting all further optimizations.
47     out_of_fuel: bool,
48 }
49
50 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
51 #[derive(Clone, Copy)]
52 pub enum CtfeBacktrace {
53     /// Do nothing special, return the error as usual without a backtrace.
54     Disabled,
55     /// Capture a backtrace at the point the error is created and return it in the error
56     /// (to be printed later if/when the error ever actually gets shown to the user).
57     Capture,
58     /// Capture a backtrace at the point the error is created and immediately print it out.
59     Immediate,
60 }
61
62 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
63 /// limits are consistent throughout the compiler.
64 #[derive(Clone, Copy, Debug)]
65 pub struct Limit(pub usize);
66
67 impl Limit {
68     /// Create a new limit from a `usize`.
69     pub fn new(value: usize) -> Self {
70         Limit(value)
71     }
72
73     /// Check that `value` is within the limit. Ensures that the same comparisons are used
74     /// throughout the compiler, as mismatches can cause ICEs, see #72540.
75     pub fn value_within_limit(&self, value: usize) -> bool {
76         value <= self.0
77     }
78 }
79
80 impl fmt::Display for Limit {
81     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82         write!(f, "{}", self.0)
83     }
84 }
85
86 impl Div<usize> for Limit {
87     type Output = Limit;
88
89     fn div(self, rhs: usize) -> Self::Output {
90         Limit::new(self.0 / rhs)
91     }
92 }
93
94 impl Mul<usize> for Limit {
95     type Output = Limit;
96
97     fn mul(self, rhs: usize) -> Self::Output {
98         Limit::new(self.0 * rhs)
99     }
100 }
101
102 /// Represents the data associated with a compilation
103 /// session for a single crate.
104 pub struct Session {
105     pub target: config::Config,
106     pub host: Target,
107     pub opts: config::Options,
108     pub host_tlib_path: SearchPath,
109     /// `None` if the host and target are the same.
110     pub target_tlib_path: Option<SearchPath>,
111     pub parse_sess: ParseSess,
112     pub sysroot: PathBuf,
113     /// The name of the root source file of the crate, in the local file system.
114     /// `None` means that there is no source file.
115     pub local_crate_source_file: Option<PathBuf>,
116     /// The directory the compiler has been executed in plus a flag indicating
117     /// if the value stored here has been affected by path remapping.
118     pub working_dir: (PathBuf, bool),
119
120     /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
121     /// (sub)diagnostics that have been set once, but should not be set again,
122     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
123     pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
124     crate_types: OnceCell<Vec<CrateType>>,
125     /// The `crate_disambiguator` is constructed out of all the `-C metadata`
126     /// arguments passed to the compiler. Its value together with the crate-name
127     /// forms a unique global identifier for the crate. It is used to allow
128     /// multiple crates with the same name to coexist. See the
129     /// `rustc_codegen_llvm::back::symbol_names` module for more information.
130     pub crate_disambiguator: OnceCell<CrateDisambiguator>,
131
132     features: OnceCell<rustc_feature::Features>,
133
134     /// The maximum recursion limit for potentially infinitely recursive
135     /// operations such as auto-dereference and monomorphization.
136     pub recursion_limit: OnceCell<Limit>,
137
138     /// The maximum length of types during monomorphization.
139     pub type_length_limit: OnceCell<Limit>,
140
141     /// The maximum blocks a const expression can evaluate.
142     pub const_eval_limit: OnceCell<Limit>,
143
144     incr_comp_session: OneThread<RefCell<IncrCompSession>>,
145     /// Used for incremental compilation tests. Will only be populated if
146     /// `-Zquery-dep-graph` is specified.
147     pub cgu_reuse_tracker: CguReuseTracker,
148
149     /// Used by `-Z self-profile`.
150     pub prof: SelfProfilerRef,
151
152     /// Some measurements that are being gathered during compilation.
153     pub perf_stats: PerfStats,
154
155     /// Data about code being compiled, gathered during compilation.
156     pub code_stats: CodeStats,
157
158     /// If `-zfuel=crate=n` is specified, `Some(crate)`.
159     optimization_fuel_crate: Option<String>,
160
161     /// Tracks fuel info if `-zfuel=crate=n` is specified.
162     optimization_fuel: Lock<OptimizationFuel>,
163
164     // The next two are public because the driver needs to read them.
165     /// If `-zprint-fuel=crate`, `Some(crate)`.
166     pub print_fuel_crate: Option<String>,
167     /// Always set to zero and incremented so that we can print fuel expended by a crate.
168     pub print_fuel: AtomicU64,
169
170     /// Loaded up early on in the initialization of this `Session` to avoid
171     /// false positives about a job server in our environment.
172     pub jobserver: Client,
173
174     /// Cap lint level specified by a driver specifically.
175     pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
176
177     /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
178     pub trait_methods_not_found: Lock<FxHashSet<Span>>,
179
180     /// Mapping from ident span to path span for paths that don't exist as written, but that
181     /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
182     pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
183
184     /// Path for libraries that will take preference over libraries shipped by Rust.
185     /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
186     pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
187
188     /// Tracks the current behavior of the CTFE engine when an error occurs.
189     /// Options range from returning the error without a backtrace to returning an error
190     /// and immediately printing the backtrace to stderr.
191     pub ctfe_backtrace: Lock<CtfeBacktrace>,
192
193     /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
194     /// const check, optionally with the relevant feature gate.  We use this to
195     /// warn about unleashing, but with a single diagnostic instead of dozens that
196     /// drown everything else in noise.
197     miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
198
199     /// Base directory containing the `src/` for the Rust standard library, and
200     /// potentially `rustc` as well, if we can can find it. Right now it's always
201     /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
202     ///
203     /// This directory is what the virtual `/rustc/$hash` is translated back to,
204     /// if Rust was built with path remapping to `/rustc/$hash` enabled
205     /// (the `rust.remap-debuginfo` option in `config.toml`).
206     pub real_rust_source_base_dir: Option<PathBuf>,
207
208     /// Architecture to use for interpreting asm!.
209     pub asm_arch: Option<InlineAsmArch>,
210
211     /// Set of enabled features for the current target.
212     pub target_features: FxHashSet<Symbol>,
213
214     known_attrs: Lock<MarkedAttrs>,
215     used_attrs: Lock<MarkedAttrs>,
216 }
217
218 pub struct PerfStats {
219     /// The accumulated time spent on computing symbol hashes.
220     pub symbol_hash_time: Lock<Duration>,
221     /// The accumulated time spent decoding def path tables from metadata.
222     pub decode_def_path_tables_time: Lock<Duration>,
223     /// Total number of values canonicalized queries constructed.
224     pub queries_canonicalized: AtomicUsize,
225     /// Number of times this query is invoked.
226     pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
227     /// Number of times this query is invoked.
228     pub normalize_projection_ty: AtomicUsize,
229 }
230
231 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
232 enum DiagnosticBuilderMethod {
233     Note,
234     SpanNote,
235     SpanSuggestion(String), // suggestion
236                             // Add more variants as needed to support one-time diagnostics.
237 }
238
239 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
240 /// emitting the same message more than once.
241 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
242 pub enum DiagnosticMessageId {
243     ErrorId(u16), // EXXXX error code as integer
244     LintId(lint::LintId),
245     StabilityId(Option<NonZeroU32>), // issue number
246 }
247
248 impl From<&'static lint::Lint> for DiagnosticMessageId {
249     fn from(lint: &'static lint::Lint) -> Self {
250         DiagnosticMessageId::LintId(lint::LintId::of(lint))
251     }
252 }
253
254 impl Session {
255     pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
256         self.miri_unleashed_features.lock().push((span, feature_gate));
257     }
258
259     fn check_miri_unleashed_features(&self) {
260         let unleashed_features = self.miri_unleashed_features.lock();
261         if !unleashed_features.is_empty() {
262             let mut must_err = false;
263             // Create a diagnostic pointing at where things got unleashed.
264             let mut diag = self.struct_warn("skipping const checks");
265             for &(span, feature_gate) in unleashed_features.iter() {
266                 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
267                 if let Some(feature_gate) = feature_gate {
268                     diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate));
269                     // The unleash flag must *not* be used to just "hack around" feature gates.
270                     must_err = true;
271                 } else {
272                     diag.span_help(span, "skipping check that does not even have a feature gate");
273                 }
274             }
275             diag.emit();
276             // If we should err, make sure we did.
277             if must_err && !self.has_errors() {
278                 // We have skipped a feature gate, and not run into other errors... reject.
279                 self.err(
280                     "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
281                      gates, except when testing error paths in the CTFE engine",
282                 );
283             }
284         }
285     }
286
287     /// Invoked all the way at the end to finish off diagnostics printing.
288     pub fn finish_diagnostics(&self, registry: &Registry) {
289         self.check_miri_unleashed_features();
290         self.diagnostic().print_error_count(registry);
291     }
292
293     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
294         self.crate_disambiguator.get().copied().unwrap()
295     }
296
297     pub fn crate_types(&self) -> &[CrateType] {
298         self.crate_types.get().unwrap().as_slice()
299     }
300
301     pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
302         self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
303     }
304
305     pub fn recursion_limit(&self) -> Limit {
306         self.recursion_limit.get().copied().unwrap()
307     }
308
309     pub fn type_length_limit(&self) -> Limit {
310         self.type_length_limit.get().copied().unwrap()
311     }
312
313     pub fn const_eval_limit(&self) -> Limit {
314         self.const_eval_limit.get().copied().unwrap()
315     }
316
317     pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
318         self.diagnostic().struct_span_warn(sp, msg)
319     }
320     pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
321         &self,
322         sp: S,
323         msg: &str,
324         code: DiagnosticId,
325     ) -> DiagnosticBuilder<'_> {
326         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
327     }
328     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
329         self.diagnostic().struct_warn(msg)
330     }
331     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
332         self.diagnostic().struct_span_err(sp, msg)
333     }
334     pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
335         &self,
336         sp: S,
337         msg: &str,
338         code: DiagnosticId,
339     ) -> DiagnosticBuilder<'_> {
340         self.diagnostic().struct_span_err_with_code(sp, msg, code)
341     }
342     // FIXME: This method should be removed (every error should have an associated error code).
343     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
344         self.diagnostic().struct_err(msg)
345     }
346     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
347         self.diagnostic().struct_err_with_code(msg, code)
348     }
349     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
350         self.diagnostic().struct_span_fatal(sp, msg)
351     }
352     pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
353         &self,
354         sp: S,
355         msg: &str,
356         code: DiagnosticId,
357     ) -> DiagnosticBuilder<'_> {
358         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
359     }
360     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
361         self.diagnostic().struct_fatal(msg)
362     }
363
364     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
365         self.diagnostic().span_fatal(sp, msg).raise()
366     }
367     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
368         &self,
369         sp: S,
370         msg: &str,
371         code: DiagnosticId,
372     ) -> ! {
373         self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
374     }
375     pub fn fatal(&self, msg: &str) -> ! {
376         self.diagnostic().fatal(msg).raise()
377     }
378     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
379         if is_warning {
380             self.span_warn(sp, msg);
381         } else {
382             self.span_err(sp, msg);
383         }
384     }
385     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
386         self.diagnostic().span_err(sp, msg)
387     }
388     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
389         self.diagnostic().span_err_with_code(sp, &msg, code)
390     }
391     pub fn err(&self, msg: &str) {
392         self.diagnostic().err(msg)
393     }
394     pub fn err_count(&self) -> usize {
395         self.diagnostic().err_count()
396     }
397     pub fn has_errors(&self) -> bool {
398         self.diagnostic().has_errors()
399     }
400     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
401         self.diagnostic().has_errors_or_delayed_span_bugs()
402     }
403     pub fn abort_if_errors(&self) {
404         self.diagnostic().abort_if_errors();
405     }
406     pub fn compile_status(&self) -> Result<(), ErrorReported> {
407         if self.has_errors() {
408             self.diagnostic().emit_stashed_diagnostics();
409             Err(ErrorReported)
410         } else {
411             Ok(())
412         }
413     }
414     // FIXME(matthewjasper) Remove this method, it should never be needed.
415     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
416     where
417         F: FnOnce() -> T,
418     {
419         let old_count = self.err_count();
420         let result = f();
421         let errors = self.err_count() - old_count;
422         if errors == 0 { Ok(result) } else { Err(ErrorReported) }
423     }
424     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
425         self.diagnostic().span_warn(sp, msg)
426     }
427     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
428         self.diagnostic().span_warn_with_code(sp, msg, code)
429     }
430     pub fn warn(&self, msg: &str) {
431         self.diagnostic().warn(msg)
432     }
433     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
434         match opt_sp {
435             Some(sp) => self.span_warn(sp, msg),
436             None => self.warn(msg),
437         }
438     }
439     /// Delay a span_bug() call until abort_if_errors()
440     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
441         self.diagnostic().delay_span_bug(sp, msg)
442     }
443     pub fn note_without_error(&self, msg: &str) {
444         self.diagnostic().note_without_error(msg)
445     }
446     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
447         self.diagnostic().span_note_without_error(sp, msg)
448     }
449     pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
450         self.diagnostic().struct_note_without_error(msg)
451     }
452
453     pub fn diagnostic(&self) -> &rustc_errors::Handler {
454         &self.parse_sess.span_diagnostic
455     }
456
457     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
458     /// deduplicates on lint ID, span (if any), and message for this `Session`
459     fn diag_once<'a, 'b>(
460         &'a self,
461         diag_builder: &'b mut DiagnosticBuilder<'a>,
462         method: DiagnosticBuilderMethod,
463         msg_id: DiagnosticMessageId,
464         message: &str,
465         span_maybe: Option<Span>,
466     ) {
467         let id_span_message = (msg_id, span_maybe, message.to_owned());
468         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
469         if fresh {
470             match method {
471                 DiagnosticBuilderMethod::Note => {
472                     diag_builder.note(message);
473                 }
474                 DiagnosticBuilderMethod::SpanNote => {
475                     let span = span_maybe.expect("`span_note` needs a span");
476                     diag_builder.span_note(span, message);
477                 }
478                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
479                     let span = span_maybe.expect("`span_suggestion_*` needs a span");
480                     diag_builder.span_suggestion(
481                         span,
482                         message,
483                         suggestion,
484                         Applicability::Unspecified,
485                     );
486                 }
487             }
488         }
489     }
490
491     pub fn diag_span_note_once<'a, 'b>(
492         &'a self,
493         diag_builder: &'b mut DiagnosticBuilder<'a>,
494         msg_id: DiagnosticMessageId,
495         span: Span,
496         message: &str,
497     ) {
498         self.diag_once(
499             diag_builder,
500             DiagnosticBuilderMethod::SpanNote,
501             msg_id,
502             message,
503             Some(span),
504         );
505     }
506
507     pub fn diag_note_once<'a, 'b>(
508         &'a self,
509         diag_builder: &'b mut DiagnosticBuilder<'a>,
510         msg_id: DiagnosticMessageId,
511         message: &str,
512     ) {
513         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
514     }
515
516     pub fn diag_span_suggestion_once<'a, 'b>(
517         &'a self,
518         diag_builder: &'b mut DiagnosticBuilder<'a>,
519         msg_id: DiagnosticMessageId,
520         span: Span,
521         message: &str,
522         suggestion: String,
523     ) {
524         self.diag_once(
525             diag_builder,
526             DiagnosticBuilderMethod::SpanSuggestion(suggestion),
527             msg_id,
528             message,
529             Some(span),
530         );
531     }
532
533     #[inline]
534     pub fn source_map(&self) -> &SourceMap {
535         self.parse_sess.source_map()
536     }
537     pub fn verbose(&self) -> bool {
538         self.opts.debugging_opts.verbose
539     }
540     pub fn time_passes(&self) -> bool {
541         self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
542     }
543     pub fn instrument_mcount(&self) -> bool {
544         self.opts.debugging_opts.instrument_mcount
545     }
546     pub fn time_llvm_passes(&self) -> bool {
547         self.opts.debugging_opts.time_llvm_passes
548     }
549     pub fn meta_stats(&self) -> bool {
550         self.opts.debugging_opts.meta_stats
551     }
552     pub fn asm_comments(&self) -> bool {
553         self.opts.debugging_opts.asm_comments
554     }
555     pub fn verify_llvm_ir(&self) -> bool {
556         self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
557     }
558     pub fn borrowck_stats(&self) -> bool {
559         self.opts.debugging_opts.borrowck_stats
560     }
561     pub fn print_llvm_passes(&self) -> bool {
562         self.opts.debugging_opts.print_llvm_passes
563     }
564     pub fn binary_dep_depinfo(&self) -> bool {
565         self.opts.debugging_opts.binary_dep_depinfo
566     }
567
568     /// Gets the features enabled for the current compilation session.
569     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
570     /// dependency tracking. Use tcx.features() instead.
571     #[inline]
572     pub fn features_untracked(&self) -> &rustc_feature::Features {
573         self.features.get().unwrap()
574     }
575
576     pub fn init_features(&self, features: rustc_feature::Features) {
577         match self.features.set(features) {
578             Ok(()) => {}
579             Err(_) => panic!("`features` was initialized twice"),
580         }
581     }
582
583     /// Calculates the flavor of LTO to use for this compilation.
584     pub fn lto(&self) -> config::Lto {
585         // If our target has codegen requirements ignore the command line
586         if self.target.target.options.requires_lto {
587             return config::Lto::Fat;
588         }
589
590         // If the user specified something, return that. If they only said `-C
591         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
592         // then ensure we can't use a ThinLTO.
593         match self.opts.cg.lto {
594             config::LtoCli::Unspecified => {
595                 // The compiler was invoked without the `-Clto` flag. Fall
596                 // through to the default handling
597             }
598             config::LtoCli::No => {
599                 // The user explicitly opted out of any kind of LTO
600                 return config::Lto::No;
601             }
602             config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
603                 // All of these mean fat LTO
604                 return config::Lto::Fat;
605             }
606             config::LtoCli::Thin => {
607                 return if self.opts.cli_forced_thinlto_off {
608                     config::Lto::Fat
609                 } else {
610                     config::Lto::Thin
611                 };
612             }
613         }
614
615         // Ok at this point the target doesn't require anything and the user
616         // hasn't asked for anything. Our next decision is whether or not
617         // we enable "auto" ThinLTO where we use multiple codegen units and
618         // then do ThinLTO over those codegen units. The logic below will
619         // either return `No` or `ThinLocal`.
620
621         // If processing command line options determined that we're incompatible
622         // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
623         if self.opts.cli_forced_thinlto_off {
624             return config::Lto::No;
625         }
626
627         // If `-Z thinlto` specified process that, but note that this is mostly
628         // a deprecated option now that `-C lto=thin` exists.
629         if let Some(enabled) = self.opts.debugging_opts.thinlto {
630             if enabled {
631                 return config::Lto::ThinLocal;
632             } else {
633                 return config::Lto::No;
634             }
635         }
636
637         // If there's only one codegen unit and LTO isn't enabled then there's
638         // no need for ThinLTO so just return false.
639         if self.codegen_units() == 1 {
640             return config::Lto::No;
641         }
642
643         // Now we're in "defaults" territory. By default we enable ThinLTO for
644         // optimized compiles (anything greater than O0).
645         match self.opts.optimize {
646             config::OptLevel::No => config::Lto::No,
647             _ => config::Lto::ThinLocal,
648         }
649     }
650
651     /// Returns the panic strategy for this compile session. If the user explicitly selected one
652     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
653     pub fn panic_strategy(&self) -> PanicStrategy {
654         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
655     }
656     pub fn fewer_names(&self) -> bool {
657         let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
658             || self.opts.output_types.contains_key(&OutputType::Bitcode)
659             // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
660             || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
661
662         self.opts.debugging_opts.fewer_names || !more_names
663     }
664
665     pub fn unstable_options(&self) -> bool {
666         self.opts.debugging_opts.unstable_options
667     }
668     pub fn overflow_checks(&self) -> bool {
669         self.opts
670             .cg
671             .overflow_checks
672             .or(self.opts.debugging_opts.force_overflow_checks)
673             .unwrap_or(self.opts.debug_assertions)
674     }
675
676     /// Check whether this compile session and crate type use static crt.
677     pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
678         if !self.target.target.options.crt_static_respected {
679             // If the target does not opt in to crt-static support, use its default.
680             return self.target.target.options.crt_static_default;
681         }
682
683         let requested_features = self.opts.cg.target_feature.split(',');
684         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
685         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
686
687         if found_positive || found_negative {
688             found_positive
689         } else if crate_type == Some(CrateType::ProcMacro)
690             || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
691         {
692             // FIXME: When crate_type is not available,
693             // we use compiler options to determine the crate_type.
694             // We can't check `#![crate_type = "proc-macro"]` here.
695             false
696         } else {
697             self.target.target.options.crt_static_default
698         }
699     }
700
701     pub fn relocation_model(&self) -> RelocModel {
702         self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
703     }
704
705     pub fn code_model(&self) -> Option<CodeModel> {
706         self.opts.cg.code_model.or(self.target.target.options.code_model)
707     }
708
709     pub fn tls_model(&self) -> TlsModel {
710         self.opts.debugging_opts.tls_model.unwrap_or(self.target.target.options.tls_model)
711     }
712
713     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
714         // "mcount" function relies on stack pointer.
715         // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
716         if self.instrument_mcount() {
717             true
718         } else if let Some(x) = self.opts.cg.force_frame_pointers {
719             x
720         } else {
721             !self.target.target.options.eliminate_frame_pointer
722         }
723     }
724
725     pub fn must_emit_unwind_tables(&self) -> bool {
726         // This is used to control the emission of the `uwtable` attribute on
727         // LLVM functions.
728         //
729         // At the very least, unwind tables are needed when compiling with
730         // `-C panic=unwind`.
731         //
732         // On some targets (including windows), however, exceptions include
733         // other events such as illegal instructions, segfaults, etc. This means
734         // that on Windows we end up still needing unwind tables even if the `-C
735         // panic=abort` flag is passed.
736         //
737         // You can also find more info on why Windows needs unwind tables in:
738         //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
739         //
740         // If a target requires unwind tables, then they must be emitted.
741         // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
742         // value, if it is provided, or disable them, if not.
743         if self.panic_strategy() == PanicStrategy::Unwind {
744             true
745         } else if self.target.target.options.requires_uwtable {
746             true
747         } else {
748             self.opts.cg.force_unwind_tables.unwrap_or(false)
749         }
750     }
751
752     /// Returns the symbol name for the registrar function,
753     /// given the crate `Svh` and the function `DefIndex`.
754     pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
755         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
756     }
757
758     pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
759         format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
760     }
761
762     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
763         filesearch::FileSearch::new(
764             &self.sysroot,
765             self.opts.target_triple.triple(),
766             &self.opts.search_paths,
767             // `target_tlib_path == None` means it's the same as `host_tlib_path`.
768             self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
769             kind,
770         )
771     }
772     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
773         filesearch::FileSearch::new(
774             &self.sysroot,
775             config::host_triple(),
776             &self.opts.search_paths,
777             &self.host_tlib_path,
778             kind,
779         )
780     }
781
782     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
783         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
784
785         if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
786             *load_dep_graph = load;
787         }
788     }
789
790     pub fn incr_session_load_dep_graph(&self) -> bool {
791         let incr_comp_session = self.incr_comp_session.borrow();
792         match *incr_comp_session {
793             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
794             _ => false,
795         }
796     }
797
798     pub fn init_incr_comp_session(
799         &self,
800         session_dir: PathBuf,
801         lock_file: flock::Lock,
802         load_dep_graph: bool,
803     ) {
804         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
805
806         if let IncrCompSession::NotInitialized = *incr_comp_session {
807         } else {
808             panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
809         }
810
811         *incr_comp_session =
812             IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
813     }
814
815     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
816         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
817
818         if let IncrCompSession::Active { .. } = *incr_comp_session {
819         } else {
820             panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
821         }
822
823         // Note: this will also drop the lock file, thus unlocking the directory.
824         *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
825     }
826
827     pub fn mark_incr_comp_session_as_invalid(&self) {
828         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
829
830         let session_directory = match *incr_comp_session {
831             IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
832             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
833             _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
834         };
835
836         // Note: this will also drop the lock file, thus unlocking the directory.
837         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
838     }
839
840     pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
841         let incr_comp_session = self.incr_comp_session.borrow();
842         cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
843             IncrCompSession::NotInitialized => panic!(
844                 "trying to get session directory from `IncrCompSession`: {:?}",
845                 *incr_comp_session,
846             ),
847             IncrCompSession::Active { ref session_directory, .. }
848             | IncrCompSession::Finalized { ref session_directory }
849             | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
850                 session_directory
851             }
852         })
853     }
854
855     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
856         self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
857     }
858
859     pub fn print_perf_stats(&self) {
860         println!(
861             "Total time spent computing symbol hashes:      {}",
862             duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
863         );
864         println!(
865             "Total time spent decoding DefPath tables:      {}",
866             duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
867         );
868         println!(
869             "Total queries canonicalized:                   {}",
870             self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
871         );
872         println!(
873             "normalize_generic_arg_after_erasing_regions:   {}",
874             self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
875         );
876         println!(
877             "normalize_projection_ty:                       {}",
878             self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
879         );
880     }
881
882     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
883     /// This expends fuel if applicable, and records fuel if applicable.
884     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
885         let mut ret = true;
886         if let Some(ref c) = self.optimization_fuel_crate {
887             if c == crate_name {
888                 assert_eq!(self.threads(), 1);
889                 let mut fuel = self.optimization_fuel.lock();
890                 ret = fuel.remaining != 0;
891                 if fuel.remaining == 0 && !fuel.out_of_fuel {
892                     self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
893                     fuel.out_of_fuel = true;
894                 } else if fuel.remaining > 0 {
895                     fuel.remaining -= 1;
896                 }
897             }
898         }
899         if let Some(ref c) = self.print_fuel_crate {
900             if c == crate_name {
901                 assert_eq!(self.threads(), 1);
902                 self.print_fuel.fetch_add(1, SeqCst);
903             }
904         }
905         ret
906     }
907
908     /// Returns the number of query threads that should be used for this
909     /// compilation
910     pub fn threads(&self) -> usize {
911         self.opts.debugging_opts.threads
912     }
913
914     /// Returns the number of codegen units that should be used for this
915     /// compilation
916     pub fn codegen_units(&self) -> usize {
917         if let Some(n) = self.opts.cli_forced_codegen_units {
918             return n;
919         }
920         if let Some(n) = self.target.target.options.default_codegen_units {
921             return n as usize;
922         }
923
924         // If incremental compilation is turned on, we default to a high number
925         // codegen units in order to reduce the "collateral damage" small
926         // changes cause.
927         if self.opts.incremental.is_some() {
928             return 256;
929         }
930
931         // Why is 16 codegen units the default all the time?
932         //
933         // The main reason for enabling multiple codegen units by default is to
934         // leverage the ability for the codegen backend to do codegen and
935         // optimization in parallel. This allows us, especially for large crates, to
936         // make good use of all available resources on the machine once we've
937         // hit that stage of compilation. Large crates especially then often
938         // take a long time in codegen/optimization and this helps us amortize that
939         // cost.
940         //
941         // Note that a high number here doesn't mean that we'll be spawning a
942         // large number of threads in parallel. The backend of rustc contains
943         // global rate limiting through the `jobserver` crate so we'll never
944         // overload the system with too much work, but rather we'll only be
945         // optimizing when we're otherwise cooperating with other instances of
946         // rustc.
947         //
948         // Rather a high number here means that we should be able to keep a lot
949         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
950         // to build we'll be guaranteed that all cpus will finish pretty closely
951         // to one another and we should make relatively optimal use of system
952         // resources
953         //
954         // Note that the main cost of codegen units is that it prevents LLVM
955         // from inlining across codegen units. Users in general don't have a lot
956         // of control over how codegen units are split up so it's our job in the
957         // compiler to ensure that undue performance isn't lost when using
958         // codegen units (aka we can't require everyone to slap `#[inline]` on
959         // everything).
960         //
961         // If we're compiling at `-O0` then the number doesn't really matter too
962         // much because performance doesn't matter and inlining is ok to lose.
963         // In debug mode we just want to try to guarantee that no cpu is stuck
964         // doing work that could otherwise be farmed to others.
965         //
966         // In release mode, however (O1 and above) performance does indeed
967         // matter! To recover the loss in performance due to inlining we'll be
968         // enabling ThinLTO by default (the function for which is just below).
969         // This will ensure that we recover any inlining wins we otherwise lost
970         // through codegen unit partitioning.
971         //
972         // ---
973         //
974         // Ok that's a lot of words but the basic tl;dr; is that we want a high
975         // number here -- but not too high. Additionally we're "safe" to have it
976         // always at the same number at all optimization levels.
977         //
978         // As a result 16 was chosen here! Mostly because it was a power of 2
979         // and most benchmarks agreed it was roughly a local optimum. Not very
980         // scientific.
981         16
982     }
983
984     pub fn teach(&self, code: &DiagnosticId) -> bool {
985         self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
986     }
987
988     pub fn rust_2015(&self) -> bool {
989         self.opts.edition == Edition::Edition2015
990     }
991
992     /// Are we allowed to use features from the Rust 2018 edition?
993     pub fn rust_2018(&self) -> bool {
994         self.opts.edition >= Edition::Edition2018
995     }
996
997     pub fn edition(&self) -> Edition {
998         self.opts.edition
999     }
1000
1001     /// Returns `true` if we cannot skip the PLT for shared library calls.
1002     pub fn needs_plt(&self) -> bool {
1003         // Check if the current target usually needs PLT to be enabled.
1004         // The user can use the command line flag to override it.
1005         let needs_plt = self.target.target.options.needs_plt;
1006
1007         let dbg_opts = &self.opts.debugging_opts;
1008
1009         let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
1010
1011         // Only enable this optimization by default if full relro is also enabled.
1012         // In this case, lazy binding was already unavailable, so nothing is lost.
1013         // This also ensures `-Wl,-z,now` is supported by the linker.
1014         let full_relro = RelroLevel::Full == relro_level;
1015
1016         // If user didn't explicitly forced us to use / skip the PLT,
1017         // then try to skip it where possible.
1018         dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1019     }
1020
1021     /// Checks if LLVM lifetime markers should be emitted.
1022     pub fn emit_lifetime_markers(&self) -> bool {
1023         self.opts.optimize != config::OptLevel::No
1024         // AddressSanitizer uses lifetimes to detect use after scope bugs.
1025         // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1026         || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY)
1027     }
1028
1029     pub fn mark_attr_known(&self, attr: &Attribute) {
1030         self.known_attrs.lock().mark(attr)
1031     }
1032
1033     pub fn is_attr_known(&self, attr: &Attribute) -> bool {
1034         self.known_attrs.lock().is_marked(attr)
1035     }
1036
1037     pub fn mark_attr_used(&self, attr: &Attribute) {
1038         self.used_attrs.lock().mark(attr)
1039     }
1040
1041     pub fn is_attr_used(&self, attr: &Attribute) -> bool {
1042         self.used_attrs.lock().is_marked(attr)
1043     }
1044
1045     /// Returns `true` if the attribute's path matches the argument. If it matches, then the
1046     /// attribute is marked as used.
1047
1048     /// Returns `true` if the attribute's path matches the argument. If it
1049     /// matches, then the attribute is marked as used.
1050     ///
1051     /// This method should only be used by rustc, other tools can use
1052     /// `Attribute::has_name` instead, because only rustc is supposed to report
1053     /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1054     /// produced by lowering an `Attribute` and don't have identity, so they
1055     /// only have the `has_name` method, and you need to mark the original
1056     /// `Attribute` as used when necessary.)
1057     pub fn check_name(&self, attr: &Attribute, name: Symbol) -> bool {
1058         let matches = attr.has_name(name);
1059         if matches {
1060             self.mark_attr_used(attr);
1061         }
1062         matches
1063     }
1064
1065     pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1066         [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1067             .iter()
1068             .any(|kind| self.check_name(attr, *kind))
1069     }
1070
1071     pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1072         attrs.iter().any(|item| self.check_name(item, name))
1073     }
1074
1075     pub fn find_by_name<'a>(
1076         &'a self,
1077         attrs: &'a [Attribute],
1078         name: Symbol,
1079     ) -> Option<&'a Attribute> {
1080         attrs.iter().find(|attr| self.check_name(attr, name))
1081     }
1082
1083     pub fn filter_by_name<'a>(
1084         &'a self,
1085         attrs: &'a [Attribute],
1086         name: Symbol,
1087     ) -> impl Iterator<Item = &'a Attribute> {
1088         attrs.iter().filter(move |attr| self.check_name(attr, name))
1089     }
1090
1091     pub fn first_attr_value_str_by_name(
1092         &self,
1093         attrs: &[Attribute],
1094         name: Symbol,
1095     ) -> Option<Symbol> {
1096         attrs.iter().find(|at| self.check_name(at, name)).and_then(|at| at.value_str())
1097     }
1098 }
1099
1100 fn default_emitter(
1101     sopts: &config::Options,
1102     registry: rustc_errors::registry::Registry,
1103     source_map: Lrc<SourceMap>,
1104     emitter_dest: Option<Box<dyn Write + Send>>,
1105 ) -> Box<dyn Emitter + sync::Send> {
1106     let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1107     match (sopts.error_format, emitter_dest) {
1108         (config::ErrorOutputType::HumanReadable(kind), dst) => {
1109             let (short, color_config) = kind.unzip();
1110
1111             if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1112                 let emitter =
1113                     AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1114                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1115             } else {
1116                 let emitter = match dst {
1117                     None => EmitterWriter::stderr(
1118                         color_config,
1119                         Some(source_map),
1120                         short,
1121                         sopts.debugging_opts.teach,
1122                         sopts.debugging_opts.terminal_width,
1123                         macro_backtrace,
1124                     ),
1125                     Some(dst) => EmitterWriter::new(
1126                         dst,
1127                         Some(source_map),
1128                         short,
1129                         false, // no teach messages when writing to a buffer
1130                         false, // no colors when writing to a buffer
1131                         None,  // no terminal width
1132                         macro_backtrace,
1133                     ),
1134                 };
1135                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1136             }
1137         }
1138         (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1139             JsonEmitter::stderr(
1140                 Some(registry),
1141                 source_map,
1142                 pretty,
1143                 json_rendered,
1144                 sopts.debugging_opts.terminal_width,
1145                 macro_backtrace,
1146             )
1147             .ui_testing(sopts.debugging_opts.ui_testing),
1148         ),
1149         (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1150             JsonEmitter::new(
1151                 dst,
1152                 Some(registry),
1153                 source_map,
1154                 pretty,
1155                 json_rendered,
1156                 sopts.debugging_opts.terminal_width,
1157                 macro_backtrace,
1158             )
1159             .ui_testing(sopts.debugging_opts.ui_testing),
1160         ),
1161     }
1162 }
1163
1164 pub enum DiagnosticOutput {
1165     Default,
1166     Raw(Box<dyn Write + Send>),
1167 }
1168
1169 pub fn build_session(
1170     sopts: config::Options,
1171     local_crate_source_file: Option<PathBuf>,
1172     registry: rustc_errors::registry::Registry,
1173     diagnostics_output: DiagnosticOutput,
1174     driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1175     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1176 ) -> Session {
1177     // FIXME: This is not general enough to make the warning lint completely override
1178     // normal diagnostic warnings, since the warning lint can also be denied and changed
1179     // later via the source code.
1180     let warnings_allow = sopts
1181         .lint_opts
1182         .iter()
1183         .filter(|&&(ref key, _)| *key == "warnings")
1184         .map(|&(_, ref level)| *level == lint::Allow)
1185         .last()
1186         .unwrap_or(false);
1187     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1188     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1189
1190     let write_dest = match diagnostics_output {
1191         DiagnosticOutput::Default => None,
1192         DiagnosticOutput::Raw(write) => Some(write),
1193     };
1194
1195     let target_cfg = config::build_target_config(&sopts, sopts.error_format);
1196     let host_triple = TargetTriple::from_triple(config::host_triple());
1197     let host = Target::search(&host_triple).unwrap_or_else(|e| {
1198         early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1199     });
1200
1201     let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
1202     let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1203         if target_cfg.target.options.is_like_msvc {
1204             SourceFileHashAlgorithm::Sha1
1205         } else {
1206             SourceFileHashAlgorithm::Md5
1207         }
1208     });
1209     let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1210         loader,
1211         sopts.file_path_mapping(),
1212         hash_kind,
1213     ));
1214     let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1215
1216     let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1217         emitter,
1218         sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1219     );
1220
1221     let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1222     {
1223         let directory =
1224             if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1225
1226         let profiler = SelfProfiler::new(
1227             directory,
1228             sopts.crate_name.as_ref().map(|s| &s[..]),
1229             &sopts.debugging_opts.self_profile_events,
1230         );
1231         match profiler {
1232             Ok(profiler) => Some(Arc::new(profiler)),
1233             Err(e) => {
1234                 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1235                 None
1236             }
1237         }
1238     } else {
1239         None
1240     };
1241
1242     let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1243     let sysroot = match &sopts.maybe_sysroot {
1244         Some(sysroot) => sysroot.clone(),
1245         None => filesearch::get_or_default_sysroot(),
1246     };
1247
1248     let host_triple = config::host_triple();
1249     let target_triple = sopts.target_triple.triple();
1250     let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1251     let target_tlib_path = if host_triple == target_triple {
1252         None
1253     } else {
1254         Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1255     };
1256
1257     let file_path_mapping = sopts.file_path_mapping();
1258
1259     let local_crate_source_file =
1260         local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1261
1262     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1263     let optimization_fuel = Lock::new(OptimizationFuel {
1264         remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1265         out_of_fuel: false,
1266     });
1267     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1268     let print_fuel = AtomicU64::new(0);
1269
1270     let working_dir = env::current_dir().unwrap_or_else(|e| {
1271         parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1272     });
1273     let working_dir = file_path_mapping.map_prefix(working_dir);
1274
1275     let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1276         CguReuseTracker::new()
1277     } else {
1278         CguReuseTracker::new_disabled()
1279     };
1280
1281     let prof = SelfProfilerRef::new(
1282         self_profiler,
1283         sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1284         sopts.debugging_opts.time_passes,
1285     );
1286
1287     let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1288         Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1289         Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1290         _ => CtfeBacktrace::Disabled,
1291     });
1292
1293     // Try to find a directory containing the Rust `src`, for more details see
1294     // the doc comment on the `real_rust_source_base_dir` field.
1295     let real_rust_source_base_dir = {
1296         // This is the location used by the `rust-src` `rustup` component.
1297         let mut candidate = sysroot.join("lib/rustlib/src/rust");
1298         if let Ok(metadata) = candidate.symlink_metadata() {
1299             // Replace the symlink rustbuild creates, with its destination.
1300             // We could try to use `fs::canonicalize` instead, but that might
1301             // produce unnecessarily verbose path.
1302             if metadata.file_type().is_symlink() {
1303                 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1304                     candidate = symlink_dest;
1305                 }
1306             }
1307         }
1308
1309         // Only use this directory if it has a file we can expect to always find.
1310         if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None }
1311     };
1312
1313     let asm_arch = if target_cfg.target.options.allow_asm {
1314         InlineAsmArch::from_str(&target_cfg.target.arch).ok()
1315     } else {
1316         None
1317     };
1318
1319     let sess = Session {
1320         target: target_cfg,
1321         host,
1322         opts: sopts,
1323         host_tlib_path,
1324         target_tlib_path,
1325         parse_sess,
1326         sysroot,
1327         local_crate_source_file,
1328         working_dir,
1329         one_time_diagnostics: Default::default(),
1330         crate_types: OnceCell::new(),
1331         crate_disambiguator: OnceCell::new(),
1332         features: OnceCell::new(),
1333         recursion_limit: OnceCell::new(),
1334         type_length_limit: OnceCell::new(),
1335         const_eval_limit: OnceCell::new(),
1336         incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1337         cgu_reuse_tracker,
1338         prof,
1339         perf_stats: PerfStats {
1340             symbol_hash_time: Lock::new(Duration::from_secs(0)),
1341             decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1342             queries_canonicalized: AtomicUsize::new(0),
1343             normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1344             normalize_projection_ty: AtomicUsize::new(0),
1345         },
1346         code_stats: Default::default(),
1347         optimization_fuel_crate,
1348         optimization_fuel,
1349         print_fuel_crate,
1350         print_fuel,
1351         jobserver: jobserver::client(),
1352         driver_lint_caps,
1353         trait_methods_not_found: Lock::new(Default::default()),
1354         confused_type_with_std_module: Lock::new(Default::default()),
1355         system_library_path: OneThread::new(RefCell::new(Default::default())),
1356         ctfe_backtrace,
1357         miri_unleashed_features: Lock::new(Default::default()),
1358         real_rust_source_base_dir,
1359         asm_arch,
1360         target_features: FxHashSet::default(),
1361         known_attrs: Lock::new(MarkedAttrs::new()),
1362         used_attrs: Lock::new(MarkedAttrs::new()),
1363     };
1364
1365     validate_commandline_args_with_session_available(&sess);
1366
1367     sess
1368 }
1369
1370 // If it is useful to have a Session available already for validating a
1371 // commandline argument, you can do so here.
1372 fn validate_commandline_args_with_session_available(sess: &Session) {
1373     // Since we don't know if code in an rlib will be linked to statically or
1374     // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1375     // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1376     // these manually generated symbols confuse LLD when it tries to merge
1377     // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1378     // when compiling for LLD ThinLTO. This way we can validly just not generate
1379     // the `dllimport` attributes and `__imp_` symbols in that case.
1380     if sess.opts.cg.linker_plugin_lto.enabled()
1381         && sess.opts.cg.prefer_dynamic
1382         && sess.target.target.options.is_like_windows
1383     {
1384         sess.err(
1385             "Linker plugin based LTO is not supported together with \
1386                   `-C prefer-dynamic` when targeting Windows-like targets",
1387         );
1388     }
1389
1390     // Make sure that any given profiling data actually exists so LLVM can't
1391     // decide to silently skip PGO.
1392     if let Some(ref path) = sess.opts.cg.profile_use {
1393         if !path.exists() {
1394             sess.err(&format!(
1395                 "File `{}` passed to `-C profile-use` does not exist.",
1396                 path.display()
1397             ));
1398         }
1399     }
1400
1401     // Unwind tables cannot be disabled if the target requires them.
1402     if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1403         if sess.panic_strategy() == PanicStrategy::Unwind && !include_uwtables {
1404             sess.err(
1405                 "panic=unwind requires unwind tables, they cannot be disabled \
1406                      with `-C force-unwind-tables=no`.",
1407             );
1408         }
1409
1410         if sess.target.target.options.requires_uwtable && !include_uwtables {
1411             sess.err(
1412                 "target requires unwind tables, they cannot be disabled with \
1413                      `-C force-unwind-tables=no`.",
1414             );
1415         }
1416     }
1417
1418     // PGO does not work reliably with panic=unwind on Windows. Let's make it
1419     // an error to combine the two for now. It always runs into an assertions
1420     // if LLVM is built with assertions, but without assertions it sometimes
1421     // does not crash and will probably generate a corrupted binary.
1422     // We should only display this error if we're actually going to run PGO.
1423     // If we're just supposed to print out some data, don't show the error (#61002).
1424     if sess.opts.cg.profile_generate.enabled()
1425         && sess.target.target.options.is_like_msvc
1426         && sess.panic_strategy() == PanicStrategy::Unwind
1427         && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1428     {
1429         sess.err(
1430             "Profile-guided optimization does not yet work in conjunction \
1431                   with `-Cpanic=unwind` on Windows when targeting MSVC. \
1432                   See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1433                   for more information.",
1434         );
1435     }
1436
1437     // FIXME(richkadel): See `src/test/run-make-fulldeps/instrument-coverage/Makefile`. After
1438     // compiling with `-Zinstrument-coverage`, the resulting binary generates a segfault during
1439     // the program's exit process (likely while attempting to generate the coverage stats in
1440     // the "*.profraw" file). An investigation to resolve the problem on Windows is ongoing,
1441     // but until this is resolved, the option is disabled on Windows, and the test is skipped
1442     // when targeting `MSVC`.
1443     if sess.opts.debugging_opts.instrument_coverage && sess.target.target.options.is_like_msvc {
1444         sess.warn(
1445             "Rust source-based code coverage instrumentation (with `-Z instrument-coverage`) \
1446             is not yet supported on Windows when targeting MSVC. The resulting binaries will \
1447             still be instrumented for experimentation purposes, but may not execute correctly.",
1448         );
1449     }
1450
1451     const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1452         "aarch64-fuchsia",
1453         "aarch64-unknown-linux-gnu",
1454         "x86_64-apple-darwin",
1455         "x86_64-fuchsia",
1456         "x86_64-unknown-linux-gnu",
1457     ];
1458     const LSAN_SUPPORTED_TARGETS: &[&str] =
1459         &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1460     const MSAN_SUPPORTED_TARGETS: &[&str] =
1461         &["aarch64-unknown-linux-gnu", "x86_64-unknown-linux-gnu"];
1462     const TSAN_SUPPORTED_TARGETS: &[&str] =
1463         &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1464
1465     // Sanitizers can only be used on some tested platforms.
1466     for s in sess.opts.debugging_opts.sanitizer {
1467         let supported_targets = match s {
1468             SanitizerSet::ADDRESS => ASAN_SUPPORTED_TARGETS,
1469             SanitizerSet::LEAK => LSAN_SUPPORTED_TARGETS,
1470             SanitizerSet::MEMORY => MSAN_SUPPORTED_TARGETS,
1471             SanitizerSet::THREAD => TSAN_SUPPORTED_TARGETS,
1472             _ => panic!("unrecognized sanitizer {}", s),
1473         };
1474         if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1475             sess.err(&format!(
1476                 "`-Zsanitizer={}` only works with targets: {}",
1477                 s,
1478                 supported_targets.join(", ")
1479             ));
1480         }
1481         let conflicting = sess.opts.debugging_opts.sanitizer - s;
1482         if !conflicting.is_empty() {
1483             sess.err(&format!(
1484                 "`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`",
1485                 s, conflicting,
1486             ));
1487             // Don't report additional errors.
1488             break;
1489         }
1490     }
1491 }
1492
1493 /// Holds data on the current incremental compilation session, if there is one.
1494 #[derive(Debug)]
1495 pub enum IncrCompSession {
1496     /// This is the state the session will be in until the incr. comp. dir is
1497     /// needed.
1498     NotInitialized,
1499     /// This is the state during which the session directory is private and can
1500     /// be modified.
1501     Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1502     /// This is the state after the session directory has been finalized. In this
1503     /// state, the contents of the directory must not be modified any more.
1504     Finalized { session_directory: PathBuf },
1505     /// This is an error state that is reached when some compilation error has
1506     /// occurred. It indicates that the contents of the session directory must
1507     /// not be used, since they might be invalid.
1508     InvalidBecauseOfErrors { session_directory: PathBuf },
1509 }
1510
1511 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1512     let emitter: Box<dyn Emitter + sync::Send> = match output {
1513         config::ErrorOutputType::HumanReadable(kind) => {
1514             let (short, color_config) = kind.unzip();
1515             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1516         }
1517         config::ErrorOutputType::Json { pretty, json_rendered } => {
1518             Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1519         }
1520     };
1521     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1522     handler.struct_fatal(msg).emit();
1523     rustc_errors::FatalError.raise();
1524 }
1525
1526 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1527     let emitter: Box<dyn Emitter + sync::Send> = match output {
1528         config::ErrorOutputType::HumanReadable(kind) => {
1529             let (short, color_config) = kind.unzip();
1530             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1531         }
1532         config::ErrorOutputType::Json { pretty, json_rendered } => {
1533             Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1534         }
1535     };
1536     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1537     handler.struct_warn(msg).emit();
1538 }
1539
1540 pub type CompileResult = Result<(), ErrorReported>;