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