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