]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/session.rs
Fix font color for help button in ayu and dark themes
[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::attr::MarkedAttrs;
11 pub use rustc_ast::crate_disambiguator::CrateDisambiguator;
12 pub use rustc_ast::Attribute;
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     #[track_caller]
441     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
442         self.diagnostic().delay_span_bug(sp, msg)
443     }
444     pub fn note_without_error(&self, msg: &str) {
445         self.diagnostic().note_without_error(msg)
446     }
447     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
448         self.diagnostic().span_note_without_error(sp, msg)
449     }
450     pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
451         self.diagnostic().struct_note_without_error(msg)
452     }
453
454     pub fn diagnostic(&self) -> &rustc_errors::Handler {
455         &self.parse_sess.span_diagnostic
456     }
457
458     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
459     /// deduplicates on lint ID, span (if any), and message for this `Session`
460     fn diag_once<'a, 'b>(
461         &'a self,
462         diag_builder: &'b mut DiagnosticBuilder<'a>,
463         method: DiagnosticBuilderMethod,
464         msg_id: DiagnosticMessageId,
465         message: &str,
466         span_maybe: Option<Span>,
467     ) {
468         let id_span_message = (msg_id, span_maybe, message.to_owned());
469         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
470         if fresh {
471             match method {
472                 DiagnosticBuilderMethod::Note => {
473                     diag_builder.note(message);
474                 }
475                 DiagnosticBuilderMethod::SpanNote => {
476                     let span = span_maybe.expect("`span_note` needs a span");
477                     diag_builder.span_note(span, message);
478                 }
479                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
480                     let span = span_maybe.expect("`span_suggestion_*` needs a span");
481                     diag_builder.span_suggestion(
482                         span,
483                         message,
484                         suggestion,
485                         Applicability::Unspecified,
486                     );
487                 }
488             }
489         }
490     }
491
492     pub fn diag_span_note_once<'a, 'b>(
493         &'a self,
494         diag_builder: &'b mut DiagnosticBuilder<'a>,
495         msg_id: DiagnosticMessageId,
496         span: Span,
497         message: &str,
498     ) {
499         self.diag_once(
500             diag_builder,
501             DiagnosticBuilderMethod::SpanNote,
502             msg_id,
503             message,
504             Some(span),
505         );
506     }
507
508     pub fn diag_note_once<'a, 'b>(
509         &'a self,
510         diag_builder: &'b mut DiagnosticBuilder<'a>,
511         msg_id: DiagnosticMessageId,
512         message: &str,
513     ) {
514         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
515     }
516
517     pub fn diag_span_suggestion_once<'a, 'b>(
518         &'a self,
519         diag_builder: &'b mut DiagnosticBuilder<'a>,
520         msg_id: DiagnosticMessageId,
521         span: Span,
522         message: &str,
523         suggestion: String,
524     ) {
525         self.diag_once(
526             diag_builder,
527             DiagnosticBuilderMethod::SpanSuggestion(suggestion),
528             msg_id,
529             message,
530             Some(span),
531         );
532     }
533
534     #[inline]
535     pub fn source_map(&self) -> &SourceMap {
536         self.parse_sess.source_map()
537     }
538     pub fn verbose(&self) -> bool {
539         self.opts.debugging_opts.verbose
540     }
541     pub fn time_passes(&self) -> bool {
542         self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
543     }
544     pub fn instrument_mcount(&self) -> bool {
545         self.opts.debugging_opts.instrument_mcount
546     }
547     pub fn time_llvm_passes(&self) -> bool {
548         self.opts.debugging_opts.time_llvm_passes
549     }
550     pub fn meta_stats(&self) -> bool {
551         self.opts.debugging_opts.meta_stats
552     }
553     pub fn asm_comments(&self) -> bool {
554         self.opts.debugging_opts.asm_comments
555     }
556     pub fn verify_llvm_ir(&self) -> bool {
557         self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
558     }
559     pub fn borrowck_stats(&self) -> bool {
560         self.opts.debugging_opts.borrowck_stats
561     }
562     pub fn print_llvm_passes(&self) -> bool {
563         self.opts.debugging_opts.print_llvm_passes
564     }
565     pub fn binary_dep_depinfo(&self) -> bool {
566         self.opts.debugging_opts.binary_dep_depinfo
567     }
568
569     /// Gets the features enabled for the current compilation session.
570     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
571     /// dependency tracking. Use tcx.features() instead.
572     #[inline]
573     pub fn features_untracked(&self) -> &rustc_feature::Features {
574         self.features.get().unwrap()
575     }
576
577     pub fn init_features(&self, features: rustc_feature::Features) {
578         match self.features.set(features) {
579             Ok(()) => {}
580             Err(_) => panic!("`features` was initialized twice"),
581         }
582     }
583
584     /// Calculates the flavor of LTO to use for this compilation.
585     pub fn lto(&self) -> config::Lto {
586         // If our target has codegen requirements ignore the command line
587         if self.target.target.options.requires_lto {
588             return config::Lto::Fat;
589         }
590
591         // If the user specified something, return that. If they only said `-C
592         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
593         // then ensure we can't use a ThinLTO.
594         match self.opts.cg.lto {
595             config::LtoCli::Unspecified => {
596                 // The compiler was invoked without the `-Clto` flag. Fall
597                 // through to the default handling
598             }
599             config::LtoCli::No => {
600                 // The user explicitly opted out of any kind of LTO
601                 return config::Lto::No;
602             }
603             config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
604                 // All of these mean fat LTO
605                 return config::Lto::Fat;
606             }
607             config::LtoCli::Thin => {
608                 return if self.opts.cli_forced_thinlto_off {
609                     config::Lto::Fat
610                 } else {
611                     config::Lto::Thin
612                 };
613             }
614         }
615
616         // Ok at this point the target doesn't require anything and the user
617         // hasn't asked for anything. Our next decision is whether or not
618         // we enable "auto" ThinLTO where we use multiple codegen units and
619         // then do ThinLTO over those codegen units. The logic below will
620         // either return `No` or `ThinLocal`.
621
622         // If processing command line options determined that we're incompatible
623         // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
624         if self.opts.cli_forced_thinlto_off {
625             return config::Lto::No;
626         }
627
628         // If `-Z thinlto` specified process that, but note that this is mostly
629         // a deprecated option now that `-C lto=thin` exists.
630         if let Some(enabled) = self.opts.debugging_opts.thinlto {
631             if enabled {
632                 return config::Lto::ThinLocal;
633             } else {
634                 return config::Lto::No;
635             }
636         }
637
638         // If there's only one codegen unit and LTO isn't enabled then there's
639         // no need for ThinLTO so just return false.
640         if self.codegen_units() == 1 {
641             return config::Lto::No;
642         }
643
644         // Now we're in "defaults" territory. By default we enable ThinLTO for
645         // optimized compiles (anything greater than O0).
646         match self.opts.optimize {
647             config::OptLevel::No => config::Lto::No,
648             _ => config::Lto::ThinLocal,
649         }
650     }
651
652     /// Returns the panic strategy for this compile session. If the user explicitly selected one
653     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
654     pub fn panic_strategy(&self) -> PanicStrategy {
655         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
656     }
657     pub fn fewer_names(&self) -> bool {
658         let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
659             || self.opts.output_types.contains_key(&OutputType::Bitcode)
660             // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
661             || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
662
663         self.opts.debugging_opts.fewer_names || !more_names
664     }
665
666     pub fn unstable_options(&self) -> bool {
667         self.opts.debugging_opts.unstable_options
668     }
669     pub fn overflow_checks(&self) -> bool {
670         self.opts
671             .cg
672             .overflow_checks
673             .or(self.opts.debugging_opts.force_overflow_checks)
674             .unwrap_or(self.opts.debug_assertions)
675     }
676
677     /// Check whether this compile session and crate type use static crt.
678     pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
679         if !self.target.target.options.crt_static_respected {
680             // If the target does not opt in to crt-static support, use its default.
681             return self.target.target.options.crt_static_default;
682         }
683
684         let requested_features = self.opts.cg.target_feature.split(',');
685         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
686         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
687
688         if found_positive || found_negative {
689             found_positive
690         } else if crate_type == Some(CrateType::ProcMacro)
691             || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
692         {
693             // FIXME: When crate_type is not available,
694             // we use compiler options to determine the crate_type.
695             // We can't check `#![crate_type = "proc-macro"]` here.
696             false
697         } else {
698             self.target.target.options.crt_static_default
699         }
700     }
701
702     pub fn relocation_model(&self) -> RelocModel {
703         self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
704     }
705
706     pub fn code_model(&self) -> Option<CodeModel> {
707         self.opts.cg.code_model.or(self.target.target.options.code_model)
708     }
709
710     pub fn tls_model(&self) -> TlsModel {
711         self.opts.debugging_opts.tls_model.unwrap_or(self.target.target.options.tls_model)
712     }
713
714     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
715         // "mcount" function relies on stack pointer.
716         // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
717         if self.instrument_mcount() {
718             true
719         } else if let Some(x) = self.opts.cg.force_frame_pointers {
720             x
721         } else {
722             !self.target.target.options.eliminate_frame_pointer
723         }
724     }
725
726     pub fn must_emit_unwind_tables(&self) -> bool {
727         // This is used to control the emission of the `uwtable` attribute on
728         // LLVM functions.
729         //
730         // At the very least, unwind tables are needed when compiling with
731         // `-C panic=unwind`.
732         //
733         // On some targets (including windows), however, exceptions include
734         // other events such as illegal instructions, segfaults, etc. This means
735         // that on Windows we end up still needing unwind tables even if the `-C
736         // panic=abort` flag is passed.
737         //
738         // You can also find more info on why Windows needs unwind tables in:
739         //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
740         //
741         // If a target requires unwind tables, then they must be emitted.
742         // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
743         // value, if it is provided, or disable them, if not.
744         if self.panic_strategy() == PanicStrategy::Unwind {
745             true
746         } else if self.target.target.options.requires_uwtable {
747             true
748         } else {
749             self.opts.cg.force_unwind_tables.unwrap_or(false)
750         }
751     }
752
753     /// Returns the symbol name for the registrar function,
754     /// given the crate `Svh` and the function `DefIndex`.
755     pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
756         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
757     }
758
759     pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
760         format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
761     }
762
763     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
764         filesearch::FileSearch::new(
765             &self.sysroot,
766             self.opts.target_triple.triple(),
767             &self.opts.search_paths,
768             // `target_tlib_path == None` means it's the same as `host_tlib_path`.
769             self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
770             kind,
771         )
772     }
773     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
774         filesearch::FileSearch::new(
775             &self.sysroot,
776             config::host_triple(),
777             &self.opts.search_paths,
778             &self.host_tlib_path,
779             kind,
780         )
781     }
782
783     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
784         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
785
786         if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
787             *load_dep_graph = load;
788         }
789     }
790
791     pub fn incr_session_load_dep_graph(&self) -> bool {
792         let incr_comp_session = self.incr_comp_session.borrow();
793         match *incr_comp_session {
794             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
795             _ => false,
796         }
797     }
798
799     pub fn init_incr_comp_session(
800         &self,
801         session_dir: PathBuf,
802         lock_file: flock::Lock,
803         load_dep_graph: bool,
804     ) {
805         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
806
807         if let IncrCompSession::NotInitialized = *incr_comp_session {
808         } else {
809             panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
810         }
811
812         *incr_comp_session =
813             IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
814     }
815
816     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
817         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
818
819         if let IncrCompSession::Active { .. } = *incr_comp_session {
820         } else {
821             panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
822         }
823
824         // Note: this will also drop the lock file, thus unlocking the directory.
825         *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
826     }
827
828     pub fn mark_incr_comp_session_as_invalid(&self) {
829         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
830
831         let session_directory = match *incr_comp_session {
832             IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
833             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
834             _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
835         };
836
837         // Note: this will also drop the lock file, thus unlocking the directory.
838         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
839     }
840
841     pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
842         let incr_comp_session = self.incr_comp_session.borrow();
843         cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
844             IncrCompSession::NotInitialized => panic!(
845                 "trying to get session directory from `IncrCompSession`: {:?}",
846                 *incr_comp_session,
847             ),
848             IncrCompSession::Active { ref session_directory, .. }
849             | IncrCompSession::Finalized { ref session_directory }
850             | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
851                 session_directory
852             }
853         })
854     }
855
856     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
857         self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
858     }
859
860     pub fn print_perf_stats(&self) {
861         println!(
862             "Total time spent computing symbol hashes:      {}",
863             duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
864         );
865         println!(
866             "Total time spent decoding DefPath tables:      {}",
867             duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
868         );
869         println!(
870             "Total queries canonicalized:                   {}",
871             self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
872         );
873         println!(
874             "normalize_generic_arg_after_erasing_regions:   {}",
875             self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
876         );
877         println!(
878             "normalize_projection_ty:                       {}",
879             self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
880         );
881     }
882
883     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
884     /// This expends fuel if applicable, and records fuel if applicable.
885     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
886         let mut ret = true;
887         if let Some(ref c) = self.optimization_fuel_crate {
888             if c == crate_name {
889                 assert_eq!(self.threads(), 1);
890                 let mut fuel = self.optimization_fuel.lock();
891                 ret = fuel.remaining != 0;
892                 if fuel.remaining == 0 && !fuel.out_of_fuel {
893                     self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
894                     fuel.out_of_fuel = true;
895                 } else if fuel.remaining > 0 {
896                     fuel.remaining -= 1;
897                 }
898             }
899         }
900         if let Some(ref c) = self.print_fuel_crate {
901             if c == crate_name {
902                 assert_eq!(self.threads(), 1);
903                 self.print_fuel.fetch_add(1, SeqCst);
904             }
905         }
906         ret
907     }
908
909     /// Returns the number of query threads that should be used for this
910     /// compilation
911     pub fn threads(&self) -> usize {
912         self.opts.debugging_opts.threads
913     }
914
915     /// Returns the number of codegen units that should be used for this
916     /// compilation
917     pub fn codegen_units(&self) -> usize {
918         if let Some(n) = self.opts.cli_forced_codegen_units {
919             return n;
920         }
921         if let Some(n) = self.target.target.options.default_codegen_units {
922             return n as usize;
923         }
924
925         // If incremental compilation is turned on, we default to a high number
926         // codegen units in order to reduce the "collateral damage" small
927         // changes cause.
928         if self.opts.incremental.is_some() {
929             return 256;
930         }
931
932         // Why is 16 codegen units the default all the time?
933         //
934         // The main reason for enabling multiple codegen units by default is to
935         // leverage the ability for the codegen backend to do codegen and
936         // optimization in parallel. This allows us, especially for large crates, to
937         // make good use of all available resources on the machine once we've
938         // hit that stage of compilation. Large crates especially then often
939         // take a long time in codegen/optimization and this helps us amortize that
940         // cost.
941         //
942         // Note that a high number here doesn't mean that we'll be spawning a
943         // large number of threads in parallel. The backend of rustc contains
944         // global rate limiting through the `jobserver` crate so we'll never
945         // overload the system with too much work, but rather we'll only be
946         // optimizing when we're otherwise cooperating with other instances of
947         // rustc.
948         //
949         // Rather a high number here means that we should be able to keep a lot
950         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
951         // to build we'll be guaranteed that all cpus will finish pretty closely
952         // to one another and we should make relatively optimal use of system
953         // resources
954         //
955         // Note that the main cost of codegen units is that it prevents LLVM
956         // from inlining across codegen units. Users in general don't have a lot
957         // of control over how codegen units are split up so it's our job in the
958         // compiler to ensure that undue performance isn't lost when using
959         // codegen units (aka we can't require everyone to slap `#[inline]` on
960         // everything).
961         //
962         // If we're compiling at `-O0` then the number doesn't really matter too
963         // much because performance doesn't matter and inlining is ok to lose.
964         // In debug mode we just want to try to guarantee that no cpu is stuck
965         // doing work that could otherwise be farmed to others.
966         //
967         // In release mode, however (O1 and above) performance does indeed
968         // matter! To recover the loss in performance due to inlining we'll be
969         // enabling ThinLTO by default (the function for which is just below).
970         // This will ensure that we recover any inlining wins we otherwise lost
971         // through codegen unit partitioning.
972         //
973         // ---
974         //
975         // Ok that's a lot of words but the basic tl;dr; is that we want a high
976         // number here -- but not too high. Additionally we're "safe" to have it
977         // always at the same number at all optimization levels.
978         //
979         // As a result 16 was chosen here! Mostly because it was a power of 2
980         // and most benchmarks agreed it was roughly a local optimum. Not very
981         // scientific.
982         16
983     }
984
985     pub fn teach(&self, code: &DiagnosticId) -> bool {
986         self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
987     }
988
989     pub fn rust_2015(&self) -> bool {
990         self.opts.edition == Edition::Edition2015
991     }
992
993     /// Are we allowed to use features from the Rust 2018 edition?
994     pub fn rust_2018(&self) -> bool {
995         self.opts.edition >= Edition::Edition2018
996     }
997
998     pub fn edition(&self) -> Edition {
999         self.opts.edition
1000     }
1001
1002     /// Returns `true` if we cannot skip the PLT for shared library calls.
1003     pub fn needs_plt(&self) -> bool {
1004         // Check if the current target usually needs PLT to be enabled.
1005         // The user can use the command line flag to override it.
1006         let needs_plt = self.target.target.options.needs_plt;
1007
1008         let dbg_opts = &self.opts.debugging_opts;
1009
1010         let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
1011
1012         // Only enable this optimization by default if full relro is also enabled.
1013         // In this case, lazy binding was already unavailable, so nothing is lost.
1014         // This also ensures `-Wl,-z,now` is supported by the linker.
1015         let full_relro = RelroLevel::Full == relro_level;
1016
1017         // If user didn't explicitly forced us to use / skip the PLT,
1018         // then try to skip it where possible.
1019         dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1020     }
1021
1022     /// Checks if LLVM lifetime markers should be emitted.
1023     pub fn emit_lifetime_markers(&self) -> bool {
1024         self.opts.optimize != config::OptLevel::No
1025         // AddressSanitizer uses lifetimes to detect use after scope bugs.
1026         // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1027         || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY)
1028     }
1029
1030     pub fn mark_attr_known(&self, attr: &Attribute) {
1031         self.known_attrs.lock().mark(attr)
1032     }
1033
1034     pub fn is_attr_known(&self, attr: &Attribute) -> bool {
1035         self.known_attrs.lock().is_marked(attr)
1036     }
1037
1038     pub fn mark_attr_used(&self, attr: &Attribute) {
1039         self.used_attrs.lock().mark(attr)
1040     }
1041
1042     pub fn is_attr_used(&self, attr: &Attribute) -> bool {
1043         self.used_attrs.lock().is_marked(attr)
1044     }
1045
1046     /// Returns `true` if the attribute's path matches the argument. If it matches, then the
1047     /// attribute is marked as used.
1048
1049     /// Returns `true` if the attribute's path matches the argument. If it
1050     /// matches, then the attribute is marked as used.
1051     ///
1052     /// This method should only be used by rustc, other tools can use
1053     /// `Attribute::has_name` instead, because only rustc is supposed to report
1054     /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1055     /// produced by lowering an `Attribute` and don't have identity, so they
1056     /// only have the `has_name` method, and you need to mark the original
1057     /// `Attribute` as used when necessary.)
1058     pub fn check_name(&self, attr: &Attribute, name: Symbol) -> bool {
1059         let matches = attr.has_name(name);
1060         if matches {
1061             self.mark_attr_used(attr);
1062         }
1063         matches
1064     }
1065
1066     pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1067         [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1068             .iter()
1069             .any(|kind| self.check_name(attr, *kind))
1070     }
1071
1072     pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1073         attrs.iter().any(|item| self.check_name(item, name))
1074     }
1075
1076     pub fn find_by_name<'a>(
1077         &'a self,
1078         attrs: &'a [Attribute],
1079         name: Symbol,
1080     ) -> Option<&'a Attribute> {
1081         attrs.iter().find(|attr| self.check_name(attr, name))
1082     }
1083
1084     pub fn filter_by_name<'a>(
1085         &'a self,
1086         attrs: &'a [Attribute],
1087         name: Symbol,
1088     ) -> impl Iterator<Item = &'a Attribute> {
1089         attrs.iter().filter(move |attr| self.check_name(attr, name))
1090     }
1091
1092     pub fn first_attr_value_str_by_name(
1093         &self,
1094         attrs: &[Attribute],
1095         name: Symbol,
1096     ) -> Option<Symbol> {
1097         attrs.iter().find(|at| self.check_name(at, name)).and_then(|at| at.value_str())
1098     }
1099 }
1100
1101 fn default_emitter(
1102     sopts: &config::Options,
1103     registry: rustc_errors::registry::Registry,
1104     source_map: Lrc<SourceMap>,
1105     emitter_dest: Option<Box<dyn Write + Send>>,
1106 ) -> Box<dyn Emitter + sync::Send> {
1107     let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1108     match (sopts.error_format, emitter_dest) {
1109         (config::ErrorOutputType::HumanReadable(kind), dst) => {
1110             let (short, color_config) = kind.unzip();
1111
1112             if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1113                 let emitter =
1114                     AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1115                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1116             } else {
1117                 let emitter = match dst {
1118                     None => EmitterWriter::stderr(
1119                         color_config,
1120                         Some(source_map),
1121                         short,
1122                         sopts.debugging_opts.teach,
1123                         sopts.debugging_opts.terminal_width,
1124                         macro_backtrace,
1125                     ),
1126                     Some(dst) => EmitterWriter::new(
1127                         dst,
1128                         Some(source_map),
1129                         short,
1130                         false, // no teach messages when writing to a buffer
1131                         false, // no colors when writing to a buffer
1132                         None,  // no terminal width
1133                         macro_backtrace,
1134                     ),
1135                 };
1136                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1137             }
1138         }
1139         (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1140             JsonEmitter::stderr(
1141                 Some(registry),
1142                 source_map,
1143                 pretty,
1144                 json_rendered,
1145                 sopts.debugging_opts.terminal_width,
1146                 macro_backtrace,
1147             )
1148             .ui_testing(sopts.debugging_opts.ui_testing),
1149         ),
1150         (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1151             JsonEmitter::new(
1152                 dst,
1153                 Some(registry),
1154                 source_map,
1155                 pretty,
1156                 json_rendered,
1157                 sopts.debugging_opts.terminal_width,
1158                 macro_backtrace,
1159             )
1160             .ui_testing(sopts.debugging_opts.ui_testing),
1161         ),
1162     }
1163 }
1164
1165 pub enum DiagnosticOutput {
1166     Default,
1167     Raw(Box<dyn Write + Send>),
1168 }
1169
1170 pub fn build_session(
1171     sopts: config::Options,
1172     local_crate_source_file: Option<PathBuf>,
1173     registry: rustc_errors::registry::Registry,
1174     diagnostics_output: DiagnosticOutput,
1175     driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1176     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1177 ) -> Session {
1178     // FIXME: This is not general enough to make the warning lint completely override
1179     // normal diagnostic warnings, since the warning lint can also be denied and changed
1180     // later via the source code.
1181     let warnings_allow = sopts
1182         .lint_opts
1183         .iter()
1184         .filter(|&&(ref key, _)| *key == "warnings")
1185         .map(|&(_, ref level)| *level == lint::Allow)
1186         .last()
1187         .unwrap_or(false);
1188     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1189     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1190
1191     let write_dest = match diagnostics_output {
1192         DiagnosticOutput::Default => None,
1193         DiagnosticOutput::Raw(write) => Some(write),
1194     };
1195
1196     let target_cfg = config::build_target_config(&sopts, sopts.error_format);
1197     let host_triple = TargetTriple::from_triple(config::host_triple());
1198     let host = Target::search(&host_triple).unwrap_or_else(|e| {
1199         early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1200     });
1201
1202     let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
1203     let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1204         if target_cfg.target.options.is_like_msvc {
1205             SourceFileHashAlgorithm::Sha1
1206         } else {
1207             SourceFileHashAlgorithm::Md5
1208         }
1209     });
1210     let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1211         loader,
1212         sopts.file_path_mapping(),
1213         hash_kind,
1214     ));
1215     let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1216
1217     let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1218         emitter,
1219         sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1220     );
1221
1222     let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1223     {
1224         let directory =
1225             if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1226
1227         let profiler = SelfProfiler::new(
1228             directory,
1229             sopts.crate_name.as_ref().map(|s| &s[..]),
1230             &sopts.debugging_opts.self_profile_events,
1231         );
1232         match profiler {
1233             Ok(profiler) => Some(Arc::new(profiler)),
1234             Err(e) => {
1235                 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1236                 None
1237             }
1238         }
1239     } else {
1240         None
1241     };
1242
1243     let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1244     let sysroot = match &sopts.maybe_sysroot {
1245         Some(sysroot) => sysroot.clone(),
1246         None => filesearch::get_or_default_sysroot(),
1247     };
1248
1249     let host_triple = config::host_triple();
1250     let target_triple = sopts.target_triple.triple();
1251     let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1252     let target_tlib_path = if host_triple == target_triple {
1253         None
1254     } else {
1255         Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1256     };
1257
1258     let file_path_mapping = sopts.file_path_mapping();
1259
1260     let local_crate_source_file =
1261         local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1262
1263     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1264     let optimization_fuel = Lock::new(OptimizationFuel {
1265         remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1266         out_of_fuel: false,
1267     });
1268     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1269     let print_fuel = AtomicU64::new(0);
1270
1271     let working_dir = env::current_dir().unwrap_or_else(|e| {
1272         parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1273     });
1274     let working_dir = file_path_mapping.map_prefix(working_dir);
1275
1276     let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1277         CguReuseTracker::new()
1278     } else {
1279         CguReuseTracker::new_disabled()
1280     };
1281
1282     let prof = SelfProfilerRef::new(
1283         self_profiler,
1284         sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1285         sopts.debugging_opts.time_passes,
1286     );
1287
1288     let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1289         Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1290         Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1291         _ => CtfeBacktrace::Disabled,
1292     });
1293
1294     // Try to find a directory containing the Rust `src`, for more details see
1295     // the doc comment on the `real_rust_source_base_dir` field.
1296     let real_rust_source_base_dir = {
1297         // This is the location used by the `rust-src` `rustup` component.
1298         let mut candidate = sysroot.join("lib/rustlib/src/rust");
1299         if let Ok(metadata) = candidate.symlink_metadata() {
1300             // Replace the symlink rustbuild creates, with its destination.
1301             // We could try to use `fs::canonicalize` instead, but that might
1302             // produce unnecessarily verbose path.
1303             if metadata.file_type().is_symlink() {
1304                 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1305                     candidate = symlink_dest;
1306                 }
1307             }
1308         }
1309
1310         // Only use this directory if it has a file we can expect to always find.
1311         if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None }
1312     };
1313
1314     let asm_arch = if target_cfg.target.options.allow_asm {
1315         InlineAsmArch::from_str(&target_cfg.target.arch).ok()
1316     } else {
1317         None
1318     };
1319
1320     let sess = Session {
1321         target: target_cfg,
1322         host,
1323         opts: sopts,
1324         host_tlib_path,
1325         target_tlib_path,
1326         parse_sess,
1327         sysroot,
1328         local_crate_source_file,
1329         working_dir,
1330         one_time_diagnostics: Default::default(),
1331         crate_types: OnceCell::new(),
1332         crate_disambiguator: OnceCell::new(),
1333         features: OnceCell::new(),
1334         recursion_limit: OnceCell::new(),
1335         type_length_limit: OnceCell::new(),
1336         const_eval_limit: OnceCell::new(),
1337         incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1338         cgu_reuse_tracker,
1339         prof,
1340         perf_stats: PerfStats {
1341             symbol_hash_time: Lock::new(Duration::from_secs(0)),
1342             decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1343             queries_canonicalized: AtomicUsize::new(0),
1344             normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1345             normalize_projection_ty: AtomicUsize::new(0),
1346         },
1347         code_stats: Default::default(),
1348         optimization_fuel_crate,
1349         optimization_fuel,
1350         print_fuel_crate,
1351         print_fuel,
1352         jobserver: jobserver::client(),
1353         driver_lint_caps,
1354         trait_methods_not_found: Lock::new(Default::default()),
1355         confused_type_with_std_module: Lock::new(Default::default()),
1356         system_library_path: OneThread::new(RefCell::new(Default::default())),
1357         ctfe_backtrace,
1358         miri_unleashed_features: Lock::new(Default::default()),
1359         real_rust_source_base_dir,
1360         asm_arch,
1361         target_features: FxHashSet::default(),
1362         known_attrs: Lock::new(MarkedAttrs::new()),
1363         used_attrs: Lock::new(MarkedAttrs::new()),
1364     };
1365
1366     validate_commandline_args_with_session_available(&sess);
1367
1368     sess
1369 }
1370
1371 // If it is useful to have a Session available already for validating a
1372 // commandline argument, you can do so here.
1373 fn validate_commandline_args_with_session_available(sess: &Session) {
1374     // Since we don't know if code in an rlib will be linked to statically or
1375     // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1376     // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1377     // these manually generated symbols confuse LLD when it tries to merge
1378     // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1379     // when compiling for LLD ThinLTO. This way we can validly just not generate
1380     // the `dllimport` attributes and `__imp_` symbols in that case.
1381     if sess.opts.cg.linker_plugin_lto.enabled()
1382         && sess.opts.cg.prefer_dynamic
1383         && sess.target.target.options.is_like_windows
1384     {
1385         sess.err(
1386             "Linker plugin based LTO is not supported together with \
1387                   `-C prefer-dynamic` when targeting Windows-like targets",
1388         );
1389     }
1390
1391     // Make sure that any given profiling data actually exists so LLVM can't
1392     // decide to silently skip PGO.
1393     if let Some(ref path) = sess.opts.cg.profile_use {
1394         if !path.exists() {
1395             sess.err(&format!(
1396                 "File `{}` passed to `-C profile-use` does not exist.",
1397                 path.display()
1398             ));
1399         }
1400     }
1401
1402     // Unwind tables cannot be disabled if the target requires them.
1403     if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1404         if sess.panic_strategy() == PanicStrategy::Unwind && !include_uwtables {
1405             sess.err(
1406                 "panic=unwind requires unwind tables, they cannot be disabled \
1407                      with `-C force-unwind-tables=no`.",
1408             );
1409         }
1410
1411         if sess.target.target.options.requires_uwtable && !include_uwtables {
1412             sess.err(
1413                 "target requires unwind tables, they cannot be disabled with \
1414                      `-C force-unwind-tables=no`.",
1415             );
1416         }
1417     }
1418
1419     // PGO does not work reliably with panic=unwind on Windows. Let's make it
1420     // an error to combine the two for now. It always runs into an assertions
1421     // if LLVM is built with assertions, but without assertions it sometimes
1422     // does not crash and will probably generate a corrupted binary.
1423     // We should only display this error if we're actually going to run PGO.
1424     // If we're just supposed to print out some data, don't show the error (#61002).
1425     if sess.opts.cg.profile_generate.enabled()
1426         && sess.target.target.options.is_like_msvc
1427         && sess.panic_strategy() == PanicStrategy::Unwind
1428         && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1429     {
1430         sess.err(
1431             "Profile-guided optimization does not yet work in conjunction \
1432                   with `-Cpanic=unwind` on Windows when targeting MSVC. \
1433                   See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1434                   for more information.",
1435         );
1436     }
1437
1438     // FIXME(richkadel): See `src/test/run-make-fulldeps/instrument-coverage/Makefile`. After
1439     // compiling with `-Zinstrument-coverage`, the resulting binary generates a segfault during
1440     // the program's exit process (likely while attempting to generate the coverage stats in
1441     // the "*.profraw" file). An investigation to resolve the problem on Windows is ongoing,
1442     // but until this is resolved, the option is disabled on Windows, and the test is skipped
1443     // when targeting `MSVC`.
1444     if sess.opts.debugging_opts.instrument_coverage && sess.target.target.options.is_like_msvc {
1445         sess.warn(
1446             "Rust source-based code coverage instrumentation (with `-Z instrument-coverage`) \
1447             is not yet supported on Windows when targeting MSVC. The resulting binaries will \
1448             still be instrumented for experimentation purposes, but may not execute correctly.",
1449         );
1450     }
1451
1452     const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1453         "aarch64-fuchsia",
1454         "aarch64-unknown-linux-gnu",
1455         "x86_64-apple-darwin",
1456         "x86_64-fuchsia",
1457         "x86_64-unknown-freebsd",
1458         "x86_64-unknown-linux-gnu",
1459     ];
1460     const LSAN_SUPPORTED_TARGETS: &[&str] =
1461         &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1462     const MSAN_SUPPORTED_TARGETS: &[&str] =
1463         &["aarch64-unknown-linux-gnu", "x86_64-unknown-freebsd", "x86_64-unknown-linux-gnu"];
1464     const TSAN_SUPPORTED_TARGETS: &[&str] = &[
1465         "aarch64-unknown-linux-gnu",
1466         "x86_64-apple-darwin",
1467         "x86_64-unknown-freebsd",
1468         "x86_64-unknown-linux-gnu",
1469     ];
1470
1471     // Sanitizers can only be used on some tested platforms.
1472     for s in sess.opts.debugging_opts.sanitizer {
1473         let supported_targets = match s {
1474             SanitizerSet::ADDRESS => ASAN_SUPPORTED_TARGETS,
1475             SanitizerSet::LEAK => LSAN_SUPPORTED_TARGETS,
1476             SanitizerSet::MEMORY => MSAN_SUPPORTED_TARGETS,
1477             SanitizerSet::THREAD => TSAN_SUPPORTED_TARGETS,
1478             _ => panic!("unrecognized sanitizer {}", s),
1479         };
1480         if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1481             sess.err(&format!(
1482                 "`-Zsanitizer={}` only works with targets: {}",
1483                 s,
1484                 supported_targets.join(", ")
1485             ));
1486         }
1487         let conflicting = sess.opts.debugging_opts.sanitizer - s;
1488         if !conflicting.is_empty() {
1489             sess.err(&format!(
1490                 "`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`",
1491                 s, conflicting,
1492             ));
1493             // Don't report additional errors.
1494             break;
1495         }
1496     }
1497 }
1498
1499 /// Holds data on the current incremental compilation session, if there is one.
1500 #[derive(Debug)]
1501 pub enum IncrCompSession {
1502     /// This is the state the session will be in until the incr. comp. dir is
1503     /// needed.
1504     NotInitialized,
1505     /// This is the state during which the session directory is private and can
1506     /// be modified.
1507     Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1508     /// This is the state after the session directory has been finalized. In this
1509     /// state, the contents of the directory must not be modified any more.
1510     Finalized { session_directory: PathBuf },
1511     /// This is an error state that is reached when some compilation error has
1512     /// occurred. It indicates that the contents of the session directory must
1513     /// not be used, since they might be invalid.
1514     InvalidBecauseOfErrors { session_directory: PathBuf },
1515 }
1516
1517 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1518     let emitter: Box<dyn Emitter + sync::Send> = match output {
1519         config::ErrorOutputType::HumanReadable(kind) => {
1520             let (short, color_config) = kind.unzip();
1521             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1522         }
1523         config::ErrorOutputType::Json { pretty, json_rendered } => {
1524             Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1525         }
1526     };
1527     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1528     handler.struct_fatal(msg).emit();
1529     rustc_errors::FatalError.raise();
1530 }
1531
1532 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1533     let emitter: Box<dyn Emitter + sync::Send> = match output {
1534         config::ErrorOutputType::HumanReadable(kind) => {
1535             let (short, color_config) = kind.unzip();
1536             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1537         }
1538         config::ErrorOutputType::Json { pretty, json_rendered } => {
1539             Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1540         }
1541     };
1542     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1543     handler.struct_warn(msg).emit();
1544 }
1545
1546 pub type CompileResult = Result<(), ErrorReported>;