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