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