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