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