rustc_session/
session.rs

1use std::any::Any;
2use std::path::PathBuf;
3use std::str::FromStr;
4use std::sync::Arc;
5use std::sync::atomic::AtomicBool;
6use std::{env, io};
7
8use rand::{RngCore, rng};
9use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
10use rustc_data_structures::flock;
11use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
13use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
14use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
15use rustc_errors::codes::*;
16use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
17use rustc_errors::json::JsonEmitter;
18use rustc_errors::timings::TimingSectionHandler;
19use rustc_errors::translation::Translator;
20use rustc_errors::{
21    Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
22    TerminalUrl, fallback_fluent_bundle,
23};
24use rustc_hir::limit::Limit;
25use rustc_macros::HashStable_Generic;
26pub use rustc_span::def_id::StableCrateId;
27use rustc_span::edition::Edition;
28use rustc_span::source_map::{FilePathMapping, SourceMap};
29use rustc_span::{RealFileName, Span, Symbol};
30use rustc_target::asm::InlineAsmArch;
31use rustc_target::spec::{
32    Arch, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
33    SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
34    TargetTuple, TlsModel, apple,
35};
36
37use crate::code_stats::CodeStats;
38pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
39use crate::config::{
40    self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
41    Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, SwitchWithOptPath,
42};
43use crate::filesearch::FileSearch;
44use crate::lint::LintId;
45use crate::parse::{ParseSess, add_feature_diagnostics};
46use crate::search_paths::SearchPath;
47use crate::{errors, filesearch, lint};
48
49/// The behavior of the CTFE engine when an error occurs with regards to backtraces.
50#[derive(#[automatically_derived]
impl ::core::clone::Clone for CtfeBacktrace {
    #[inline]
    fn clone(&self) -> CtfeBacktrace { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CtfeBacktrace { }Copy)]
51pub enum CtfeBacktrace {
52    /// Do nothing special, return the error as usual without a backtrace.
53    Disabled,
54    /// Capture a backtrace at the point the error is created and return it in the error
55    /// (to be printed later if/when the error ever actually gets shown to the user).
56    Capture,
57    /// Capture a backtrace at the point the error is created and immediately print it out.
58    Immediate,
59}
60
61#[derive(#[automatically_derived]
impl ::core::clone::Clone for Limits {
    #[inline]
    fn clone(&self) -> Limits {
        let _: ::core::clone::AssertParamIsClone<Limit>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Limits { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Limits {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "Limits",
            "recursion_limit", &self.recursion_limit, "move_size_limit",
            &self.move_size_limit, "type_length_limit",
            &self.type_length_limit, "pattern_complexity_limit",
            &&self.pattern_complexity_limit)
    }
}Debug, const _: () =
    {
        impl<__CTX> ::rustc_data_structures::stable_hasher::HashStable<__CTX>
            for Limits where __CTX: crate::HashStableContext {
            #[inline]
            fn hash_stable(&self, __hcx: &mut __CTX,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    Limits {
                        recursion_limit: ref __binding_0,
                        move_size_limit: ref __binding_1,
                        type_length_limit: ref __binding_2,
                        pattern_complexity_limit: ref __binding_3 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                        { __binding_2.hash_stable(__hcx, __hasher); }
                        { __binding_3.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable_Generic)]
62pub struct Limits {
63    /// The maximum recursion limit for potentially infinitely recursive
64    /// operations such as auto-dereference and monomorphization.
65    pub recursion_limit: Limit,
66    /// The size at which the `large_assignments` lint starts
67    /// being emitted.
68    pub move_size_limit: Limit,
69    /// The maximum length of types during monomorphization.
70    pub type_length_limit: Limit,
71    /// The maximum pattern complexity allowed (internal only).
72    pub pattern_complexity_limit: Limit,
73}
74
75pub struct CompilerIO {
76    pub input: Input,
77    pub output_dir: Option<PathBuf>,
78    pub output_file: Option<OutFileName>,
79    pub temps_dir: Option<PathBuf>,
80}
81
82pub trait DynLintStore: Any + DynSync + DynSend {
83    /// Provides a way to access lint groups without depending on `rustc_lint`
84    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
85}
86
87/// Represents the data associated with a compilation
88/// session for a single crate.
89pub struct Session {
90    pub target: Target,
91    pub host: Target,
92    pub opts: config::Options,
93    pub target_tlib_path: Arc<SearchPath>,
94    pub psess: ParseSess,
95    /// Input, input file path and output file path to this compilation process.
96    pub io: CompilerIO,
97
98    incr_comp_session: RwLock<IncrCompSession>,
99
100    /// Used by `-Z self-profile`.
101    pub prof: SelfProfilerRef,
102
103    /// Used to emit section timings events (enabled by `--json=timings`).
104    pub timings: TimingSectionHandler,
105
106    /// Data about code being compiled, gathered during compilation.
107    pub code_stats: CodeStats,
108
109    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
110    pub lint_store: Option<Arc<dyn DynLintStore>>,
111
112    /// Cap lint level specified by a driver specifically.
113    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
114
115    /// Tracks the current behavior of the CTFE engine when an error occurs.
116    /// Options range from returning the error without a backtrace to returning an error
117    /// and immediately printing the backtrace to stderr.
118    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
119    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
120    /// errors.
121    pub ctfe_backtrace: Lock<CtfeBacktrace>,
122
123    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
124    /// const check, optionally with the relevant feature gate. We use this to
125    /// warn about unleashing, but with a single diagnostic instead of dozens that
126    /// drown everything else in noise.
127    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
128
129    /// Architecture to use for interpreting asm!.
130    pub asm_arch: Option<InlineAsmArch>,
131
132    /// Set of enabled features for the current target.
133    pub target_features: FxIndexSet<Symbol>,
134
135    /// Set of enabled features for the current target, including unstable ones.
136    pub unstable_target_features: FxIndexSet<Symbol>,
137
138    /// The version of the rustc process, possibly including a commit hash and description.
139    pub cfg_version: &'static str,
140
141    /// The inner atomic value is set to true when a feature marked as `internal` is
142    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
143    /// internal features are wontfix, and they are usually the cause of the ICEs.
144    /// None signifies that this is not tracked.
145    pub using_internal_features: &'static AtomicBool,
146
147    target_filesearch: FileSearch,
148    host_filesearch: FileSearch,
149
150    /// A random string generated per invocation of rustc.
151    ///
152    /// This is prepended to all temporary files so that they do not collide
153    /// during concurrent invocations of rustc, or past invocations that were
154    /// preserved with a flag like `-C save-temps`, since these files may be
155    /// hard linked.
156    pub invocation_temp: Option<String>,
157}
158
159#[derive(#[automatically_derived]
impl ::core::clone::Clone for CodegenUnits {
    #[inline]
    fn clone(&self) -> CodegenUnits {
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CodegenUnits { }Copy)]
160pub enum CodegenUnits {
161    /// Specified by the user. In this case we try fairly hard to produce the
162    /// number of CGUs requested.
163    User(usize),
164
165    /// A default value, i.e. not specified by the user. In this case we take
166    /// more liberties about CGU formation, e.g. avoid producing very small
167    /// CGUs.
168    Default(usize),
169}
170
171impl CodegenUnits {
172    pub fn as_usize(self) -> usize {
173        match self {
174            CodegenUnits::User(n) => n,
175            CodegenUnits::Default(n) => n,
176        }
177    }
178}
179
180pub struct LintGroup {
181    pub name: &'static str,
182    pub lints: Vec<LintId>,
183    pub is_externally_loaded: bool,
184}
185
186impl Session {
187    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
188        self.miri_unleashed_features.lock().push((span, feature_gate));
189    }
190
191    pub fn local_crate_source_file(&self) -> Option<RealFileName> {
192        Some(
193            self.source_map()
194                .path_mapping()
195                .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
196        )
197    }
198
199    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
200        let mut guar = None;
201        let unleashed_features = self.miri_unleashed_features.lock();
202        if !unleashed_features.is_empty() {
203            let mut must_err = false;
204            // Create a diagnostic pointing at where things got unleashed.
205            self.dcx().emit_warn(errors::SkippingConstChecks {
206                unleashed_features: unleashed_features
207                    .iter()
208                    .map(|(span, gate)| {
209                        gate.map(|gate| {
210                            must_err = true;
211                            errors::UnleashedFeatureHelp::Named { span: *span, gate }
212                        })
213                        .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
214                    })
215                    .collect(),
216            });
217
218            // If we should err, make sure we did.
219            if must_err && self.dcx().has_errors().is_none() {
220                // We have skipped a feature gate, and not run into other errors... reject.
221                guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
222            }
223        }
224        guar
225    }
226
227    /// Invoked all the way at the end to finish off diagnostics printing.
228    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
229        let mut guar = None;
230        guar = guar.or(self.check_miri_unleashed_features());
231        guar = guar.or(self.dcx().emit_stashed_diagnostics());
232        self.dcx().print_error_count();
233        if self.opts.json_future_incompat {
234            self.dcx().emit_future_breakage_report();
235        }
236        guar
237    }
238
239    /// Returns true if the crate is a testing one.
240    pub fn is_test_crate(&self) -> bool {
241        self.opts.test
242    }
243
244    /// `feature` must be a language feature.
245    #[track_caller]
246    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
247        let mut err = self.dcx().create_err(err);
248        if err.code.is_none() {
249            #[allow(rustc::diagnostic_outside_of_impl)]
250            err.code(E0658);
251        }
252        add_feature_diagnostics(&mut err, self, feature);
253        err
254    }
255
256    /// Record the fact that we called `trimmed_def_paths`, and do some
257    /// checking about whether its cost was justified.
258    pub fn record_trimmed_def_paths(&self) {
259        if self.opts.unstable_opts.print_type_sizes
260            || self.opts.unstable_opts.query_dep_graph
261            || self.opts.unstable_opts.dump_mir.is_some()
262            || self.opts.unstable_opts.unpretty.is_some()
263            || self.prof.is_args_recording_enabled()
264            || self.opts.output_types.contains_key(&OutputType::Mir)
265            || std::env::var_os("RUSTC_LOG").is_some()
266        {
267            return;
268        }
269
270        self.dcx().set_must_produce_diag()
271    }
272
273    #[inline]
274    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
275        self.psess.dcx()
276    }
277
278    #[inline]
279    pub fn source_map(&self) -> &SourceMap {
280        self.psess.source_map()
281    }
282
283    /// Returns `true` if internal lints should be added to the lint store - i.e. if
284    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
285    /// to be emitted under rustdoc).
286    pub fn enable_internal_lints(&self) -> bool {
287        self.unstable_options() && !self.opts.actually_rustdoc
288    }
289
290    pub fn instrument_coverage(&self) -> bool {
291        self.opts.cg.instrument_coverage() != InstrumentCoverage::No
292    }
293
294    pub fn instrument_coverage_branch(&self) -> bool {
295        self.instrument_coverage()
296            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
297    }
298
299    pub fn instrument_coverage_condition(&self) -> bool {
300        self.instrument_coverage()
301            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
302    }
303
304    /// Provides direct access to the `CoverageOptions` struct, so that
305    /// individual flags for debugging/testing coverage instrumetation don't
306    /// need separate accessors.
307    pub fn coverage_options(&self) -> &CoverageOptions {
308        &self.opts.unstable_opts.coverage_options
309    }
310
311    pub fn is_sanitizer_cfi_enabled(&self) -> bool {
312        self.sanitizers().contains(SanitizerSet::CFI)
313    }
314
315    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
316        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
317    }
318
319    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
320        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
321    }
322
323    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
324        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
325    }
326
327    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
328        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
329    }
330
331    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
332        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
333    }
334
335    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
336        self.sanitizers().contains(SanitizerSet::KCFI)
337    }
338
339    pub fn is_split_lto_unit_enabled(&self) -> bool {
340        self.opts.unstable_opts.split_lto_unit == Some(true)
341    }
342
343    /// Check whether this compile session and crate type use static crt.
344    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
345        if !self.target.crt_static_respected {
346            // If the target does not opt in to crt-static support, use its default.
347            return self.target.crt_static_default;
348        }
349
350        let requested_features = self.opts.cg.target_feature.split(',');
351        let found_negative = requested_features.clone().any(|r| r == "-crt-static");
352        let found_positive = requested_features.clone().any(|r| r == "+crt-static");
353
354        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
355        #[allow(rustc::bad_opt_access)]
356        if found_positive || found_negative {
357            found_positive
358        } else if crate_type == Some(CrateType::ProcMacro)
359            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
360        {
361            // FIXME: When crate_type is not available,
362            // we use compiler options to determine the crate_type.
363            // We can't check `#![crate_type = "proc-macro"]` here.
364            false
365        } else {
366            self.target.crt_static_default
367        }
368    }
369
370    pub fn is_wasi_reactor(&self) -> bool {
371        self.target.options.os == Os::Wasi
372            && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
    {
    Some(config::WasiExecModel::Reactor) => true,
    _ => false,
}matches!(
373                self.opts.unstable_opts.wasi_exec_model,
374                Some(config::WasiExecModel::Reactor)
375            )
376    }
377
378    /// Returns `true` if the target can use the current split debuginfo configuration.
379    pub fn target_can_use_split_dwarf(&self) -> bool {
380        self.target.debuginfo_kind == DebuginfoKind::Dwarf
381    }
382
383    pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
384        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__rustc_proc_macro_decls_{0:08x}__",
                stable_crate_id.as_u64()))
    })format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
385    }
386
387    pub fn target_filesearch(&self) -> &filesearch::FileSearch {
388        &self.target_filesearch
389    }
390    pub fn host_filesearch(&self) -> &filesearch::FileSearch {
391        &self.host_filesearch
392    }
393
394    /// Returns a list of directories where target-specific tool binaries are located. Some fallback
395    /// directories are also returned, for example if `--sysroot` is used but tools are missing
396    /// (#125246): we also add the bin directories to the sysroot where rustc is located.
397    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
398        let search_paths = self
399            .opts
400            .sysroot
401            .all_paths()
402            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
403
404        if self_contained {
405            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the
406            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the
407            // fallback paths.
408            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
409        } else {
410            search_paths.collect()
411        }
412    }
413
414    pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
415        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
416
417        if let IncrCompSession::NotInitialized = *incr_comp_session {
418        } else {
419            {
    ::core::panicking::panic_fmt(format_args!("Trying to initialize IncrCompSession `{0:?}`",
            *incr_comp_session));
}panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
420        }
421
422        *incr_comp_session =
423            IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
424    }
425
426    pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
427        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
428
429        if let IncrCompSession::Active { .. } = *incr_comp_session {
430        } else {
431            {
    ::core::panicking::panic_fmt(format_args!("trying to finalize `IncrCompSession` `{0:?}`",
            *incr_comp_session));
};panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
432        }
433
434        // Note: this will also drop the lock file, thus unlocking the directory.
435        *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
436    }
437
438    pub fn mark_incr_comp_session_as_invalid(&self) {
439        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
440
441        let session_directory = match *incr_comp_session {
442            IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
443            IncrCompSession::InvalidBecauseOfErrors { .. } => return,
444            _ => {
    ::core::panicking::panic_fmt(format_args!("trying to invalidate `IncrCompSession` `{0:?}`",
            *incr_comp_session));
}panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
445        };
446
447        // Note: this will also drop the lock file, thus unlocking the directory.
448        *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
449    }
450
451    pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
452        let incr_comp_session = self.incr_comp_session.borrow();
453        ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
454            IncrCompSession::NotInitialized => {
    ::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
            *incr_comp_session));
}panic!(
455                "trying to get session directory from `IncrCompSession`: {:?}",
456                *incr_comp_session,
457            ),
458            IncrCompSession::Active { ref session_directory, .. }
459            | IncrCompSession::Finalized { ref session_directory }
460            | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
461                session_directory
462            }
463        })
464    }
465
466    pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
467        self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
468    }
469
470    /// Is this edition 2015?
471    pub fn is_rust_2015(&self) -> bool {
472        self.edition().is_rust_2015()
473    }
474
475    /// Are we allowed to use features from the Rust 2018 edition?
476    pub fn at_least_rust_2018(&self) -> bool {
477        self.edition().at_least_rust_2018()
478    }
479
480    /// Are we allowed to use features from the Rust 2021 edition?
481    pub fn at_least_rust_2021(&self) -> bool {
482        self.edition().at_least_rust_2021()
483    }
484
485    /// Are we allowed to use features from the Rust 2024 edition?
486    pub fn at_least_rust_2024(&self) -> bool {
487        self.edition().at_least_rust_2024()
488    }
489
490    /// Returns `true` if we should use the PLT for shared library calls.
491    pub fn needs_plt(&self) -> bool {
492        // Check if the current target usually wants PLT to be enabled.
493        // The user can use the command line flag to override it.
494        let want_plt = self.target.plt_by_default;
495
496        let dbg_opts = &self.opts.unstable_opts;
497
498        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
499
500        // Only enable this optimization by default if full relro is also enabled.
501        // In this case, lazy binding was already unavailable, so nothing is lost.
502        // This also ensures `-Wl,-z,now` is supported by the linker.
503        let full_relro = RelroLevel::Full == relro_level;
504
505        // If user didn't explicitly forced us to use / skip the PLT,
506        // then use it unless the target doesn't want it by default or the full relro forces it on.
507        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
508    }
509
510    /// Checks if LLVM lifetime markers should be emitted.
511    pub fn emit_lifetime_markers(&self) -> bool {
512        self.opts.optimize != config::OptLevel::No
513        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
514        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
515        // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
516        || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
517    }
518
519    pub fn diagnostic_width(&self) -> usize {
520        let default_column_width = 140;
521        if let Some(width) = self.opts.diagnostic_width {
522            width
523        } else if self.opts.unstable_opts.ui_testing {
524            default_column_width
525        } else {
526            termize::dimensions().map_or(default_column_width, |(w, _)| w)
527        }
528    }
529
530    /// Returns the default symbol visibility.
531    pub fn default_visibility(&self) -> SymbolVisibility {
532        self.opts
533            .unstable_opts
534            .default_visibility
535            .or(self.target.options.default_visibility)
536            .unwrap_or(SymbolVisibility::Interposable)
537    }
538
539    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
540        if verbatim {
541            ("", "")
542        } else {
543            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
544        }
545    }
546
547    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
548        match self.lint_store {
549            Some(ref lint_store) => lint_store.lint_groups_iter(),
550            None => Box::new(std::iter::empty()),
551        }
552    }
553}
554
555// JUSTIFICATION: defn of the suggested wrapper fns
556#[allow(rustc::bad_opt_access)]
557impl Session {
558    pub fn verbose_internals(&self) -> bool {
559        self.opts.unstable_opts.verbose_internals
560    }
561
562    pub fn print_llvm_stats(&self) -> bool {
563        self.opts.unstable_opts.print_codegen_stats
564    }
565
566    pub fn verify_llvm_ir(&self) -> bool {
567        self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
568    }
569
570    pub fn binary_dep_depinfo(&self) -> bool {
571        self.opts.unstable_opts.binary_dep_depinfo
572    }
573
574    pub fn mir_opt_level(&self) -> usize {
575        self.opts
576            .unstable_opts
577            .mir_opt_level
578            .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
579    }
580
581    /// Calculates the flavor of LTO to use for this compilation.
582    pub fn lto(&self) -> config::Lto {
583        // If our target has codegen requirements ignore the command line
584        if self.target.requires_lto {
585            return config::Lto::Fat;
586        }
587
588        // If the user specified something, return that. If they only said `-C
589        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
590        // then ensure we can't use a ThinLTO.
591        match self.opts.cg.lto {
592            config::LtoCli::Unspecified => {
593                // The compiler was invoked without the `-Clto` flag. Fall
594                // through to the default handling
595            }
596            config::LtoCli::No => {
597                // The user explicitly opted out of any kind of LTO
598                return config::Lto::No;
599            }
600            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
601                // All of these mean fat LTO
602                return config::Lto::Fat;
603            }
604            config::LtoCli::Thin => {
605                // The user explicitly asked for ThinLTO
606                return config::Lto::Thin;
607            }
608        }
609
610        // Ok at this point the target doesn't require anything and the user
611        // hasn't asked for anything. Our next decision is whether or not
612        // we enable "auto" ThinLTO where we use multiple codegen units and
613        // then do ThinLTO over those codegen units. The logic below will
614        // either return `No` or `ThinLocal`.
615
616        // If processing command line options determined that we're incompatible
617        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
618        if self.opts.cli_forced_local_thinlto_off {
619            return config::Lto::No;
620        }
621
622        // If `-Z thinlto` specified process that, but note that this is mostly
623        // a deprecated option now that `-C lto=thin` exists.
624        if let Some(enabled) = self.opts.unstable_opts.thinlto {
625            if enabled {
626                return config::Lto::ThinLocal;
627            } else {
628                return config::Lto::No;
629            }
630        }
631
632        // If there's only one codegen unit and LTO isn't enabled then there's
633        // no need for ThinLTO so just return false.
634        if self.codegen_units().as_usize() == 1 {
635            return config::Lto::No;
636        }
637
638        // Now we're in "defaults" territory. By default we enable ThinLTO for
639        // optimized compiles (anything greater than O0).
640        match self.opts.optimize {
641            config::OptLevel::No => config::Lto::No,
642            _ => config::Lto::ThinLocal,
643        }
644    }
645
646    /// Returns the panic strategy for this compile session. If the user explicitly selected one
647    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
648    pub fn panic_strategy(&self) -> PanicStrategy {
649        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
650    }
651
652    pub fn fewer_names(&self) -> bool {
653        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
654            fewer_names
655        } else {
656            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
657                || self.opts.output_types.contains_key(&OutputType::Bitcode)
658                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
659                || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
660            !more_names
661        }
662    }
663
664    pub fn unstable_options(&self) -> bool {
665        self.opts.unstable_opts.unstable_options
666    }
667
668    pub fn is_nightly_build(&self) -> bool {
669        self.opts.unstable_features.is_nightly_build()
670    }
671
672    pub fn overflow_checks(&self) -> bool {
673        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
674    }
675
676    pub fn ub_checks(&self) -> bool {
677        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
678    }
679
680    pub fn contract_checks(&self) -> bool {
681        self.opts.unstable_opts.contract_checks.unwrap_or(false)
682    }
683
684    pub fn relocation_model(&self) -> RelocModel {
685        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
686    }
687
688    pub fn code_model(&self) -> Option<CodeModel> {
689        self.opts.cg.code_model.or(self.target.code_model)
690    }
691
692    pub fn tls_model(&self) -> TlsModel {
693        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
694    }
695
696    pub fn direct_access_external_data(&self) -> Option<bool> {
697        self.opts
698            .unstable_opts
699            .direct_access_external_data
700            .or(self.target.direct_access_external_data)
701    }
702
703    pub fn split_debuginfo(&self) -> SplitDebuginfo {
704        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
705    }
706
707    /// Returns the DWARF version passed on the CLI or the default for the target.
708    pub fn dwarf_version(&self) -> u32 {
709        self.opts
710            .cg
711            .dwarf_version
712            .or(self.opts.unstable_opts.dwarf_version)
713            .unwrap_or(self.target.default_dwarf_version)
714    }
715
716    pub fn stack_protector(&self) -> StackProtector {
717        if self.target.options.supports_stack_protector {
718            self.opts.unstable_opts.stack_protector
719        } else {
720            StackProtector::None
721        }
722    }
723
724    pub fn must_emit_unwind_tables(&self) -> bool {
725        // This is used to control the emission of the `uwtable` attribute on
726        // LLVM functions. The `uwtable` attribute according to LLVM is:
727        //
728        //     This attribute indicates that the ABI being targeted requires that an
729        //     unwind table entry be produced for this function even if we can show
730        //     that no exceptions passes by it. This is normally the case for the
731        //     ELF x86-64 abi, but it can be disabled for some compilation units.
732        //
733        // Typically when we're compiling with `-C panic=abort` we don't need
734        // `uwtable` because we can't generate any exceptions! But note that
735        // some targets require unwind tables to generate backtraces.
736        // Unwind tables are needed when compiling with `-C panic=unwind`, but
737        // LLVM won't omit unwind tables unless the function is also marked as
738        // `nounwind`, so users are allowed to disable `uwtable` emission.
739        // Historically rustc always emits `uwtable` attributes by default, so
740        // even they can be disabled, they're still emitted by default.
741        //
742        // On some targets (including windows), however, exceptions include
743        // other events such as illegal instructions, segfaults, etc. This means
744        // that on Windows we end up still needing unwind tables even if the `-C
745        // panic=abort` flag is passed.
746        //
747        // You can also find more info on why Windows needs unwind tables in:
748        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
749        //
750        // If a target requires unwind tables, then they must be emitted.
751        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
752        // value, if it is provided, or disable them, if not.
753        self.target.requires_uwtable
754            || self
755                .opts
756                .cg
757                .force_unwind_tables
758                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
759    }
760
761    /// Returns the number of query threads that should be used for this
762    /// compilation
763    #[inline]
764    pub fn threads(&self) -> usize {
765        self.opts.unstable_opts.threads
766    }
767
768    /// Returns the number of codegen units that should be used for this
769    /// compilation
770    pub fn codegen_units(&self) -> CodegenUnits {
771        if let Some(n) = self.opts.cli_forced_codegen_units {
772            return CodegenUnits::User(n);
773        }
774        if let Some(n) = self.target.default_codegen_units {
775            return CodegenUnits::Default(n as usize);
776        }
777
778        // If incremental compilation is turned on, we default to a high number
779        // codegen units in order to reduce the "collateral damage" small
780        // changes cause.
781        if self.opts.incremental.is_some() {
782            return CodegenUnits::Default(256);
783        }
784
785        // Why is 16 codegen units the default all the time?
786        //
787        // The main reason for enabling multiple codegen units by default is to
788        // leverage the ability for the codegen backend to do codegen and
789        // optimization in parallel. This allows us, especially for large crates, to
790        // make good use of all available resources on the machine once we've
791        // hit that stage of compilation. Large crates especially then often
792        // take a long time in codegen/optimization and this helps us amortize that
793        // cost.
794        //
795        // Note that a high number here doesn't mean that we'll be spawning a
796        // large number of threads in parallel. The backend of rustc contains
797        // global rate limiting through the `jobserver` crate so we'll never
798        // overload the system with too much work, but rather we'll only be
799        // optimizing when we're otherwise cooperating with other instances of
800        // rustc.
801        //
802        // Rather a high number here means that we should be able to keep a lot
803        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
804        // to build we'll be guaranteed that all cpus will finish pretty closely
805        // to one another and we should make relatively optimal use of system
806        // resources
807        //
808        // Note that the main cost of codegen units is that it prevents LLVM
809        // from inlining across codegen units. Users in general don't have a lot
810        // of control over how codegen units are split up so it's our job in the
811        // compiler to ensure that undue performance isn't lost when using
812        // codegen units (aka we can't require everyone to slap `#[inline]` on
813        // everything).
814        //
815        // If we're compiling at `-O0` then the number doesn't really matter too
816        // much because performance doesn't matter and inlining is ok to lose.
817        // In debug mode we just want to try to guarantee that no cpu is stuck
818        // doing work that could otherwise be farmed to others.
819        //
820        // In release mode, however (O1 and above) performance does indeed
821        // matter! To recover the loss in performance due to inlining we'll be
822        // enabling ThinLTO by default (the function for which is just below).
823        // This will ensure that we recover any inlining wins we otherwise lost
824        // through codegen unit partitioning.
825        //
826        // ---
827        //
828        // Ok that's a lot of words but the basic tl;dr; is that we want a high
829        // number here -- but not too high. Additionally we're "safe" to have it
830        // always at the same number at all optimization levels.
831        //
832        // As a result 16 was chosen here! Mostly because it was a power of 2
833        // and most benchmarks agreed it was roughly a local optimum. Not very
834        // scientific.
835        CodegenUnits::Default(16)
836    }
837
838    pub fn teach(&self, code: ErrCode) -> bool {
839        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
840    }
841
842    pub fn edition(&self) -> Edition {
843        self.opts.edition
844    }
845
846    pub fn link_dead_code(&self) -> bool {
847        self.opts.cg.link_dead_code.unwrap_or(false)
848    }
849
850    /// Get the deployment target on Apple platforms based on the standard environment variables,
851    /// or fall back to the minimum version supported by `rustc`.
852    ///
853    /// This should be guarded behind `if sess.target.is_like_darwin`.
854    pub fn apple_deployment_target(&self) -> apple::OSVersion {
855        let min = apple::OSVersion::minimum_deployment_target(&self.target);
856        let env_var = apple::deployment_target_env_var(&self.target.os);
857
858        // FIXME(madsmtm): Track changes to this.
859        if let Ok(deployment_target) = env::var(env_var) {
860            match apple::OSVersion::from_str(&deployment_target) {
861                Ok(version) => {
862                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
863                    // It is common that the deployment target is set a bit too low, for example on
864                    // macOS Aarch64 to also target older x86_64. So we only want to warn when variable
865                    // is lower than the minimum OS supported by rustc, not when the variable is lower
866                    // than the minimum for a specific target.
867                    if version < os_min {
868                        self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
869                            env_var,
870                            version: version.fmt_pretty().to_string(),
871                            os_min: os_min.fmt_pretty().to_string(),
872                        });
873                    }
874
875                    // Raise the deployment target to the minimum supported.
876                    version.max(min)
877                }
878                Err(error) => {
879                    self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
880                    min
881                }
882            }
883        } else {
884            // If no deployment target variable is set, default to the minimum found above.
885            min
886        }
887    }
888
889    pub fn sanitizers(&self) -> SanitizerSet {
890        return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
891    }
892}
893
894// JUSTIFICATION: part of session construction
895#[allow(rustc::bad_opt_access)]
896fn default_emitter(
897    sopts: &config::Options,
898    source_map: Arc<SourceMap>,
899    translator: Translator,
900) -> Box<DynEmitter> {
901    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
902    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
903    let terminal_url = match sopts.unstable_opts.terminal_urls {
904        TerminalUrl::Auto => {
905            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
906                (Ok("truecolor"), Ok("xterm-256color"))
907                    if sopts.unstable_features.is_nightly_build() =>
908                {
909                    TerminalUrl::Yes
910                }
911                _ => TerminalUrl::No,
912            }
913        }
914        t => t,
915    };
916
917    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
918
919    match sopts.error_format {
920        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
921            HumanReadableErrorType { short, unicode } => {
922                let emitter =
923                    AnnotateSnippetEmitter::new(stderr_destination(color_config), translator)
924                        .sm(source_map)
925                        .short_message(short)
926                        .diagnostic_width(sopts.diagnostic_width)
927                        .macro_backtrace(macro_backtrace)
928                        .track_diagnostics(track_diagnostics)
929                        .terminal_url(terminal_url)
930                        .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
931                        .ignored_directories_in_source_blocks(
932                            sopts
933                                .unstable_opts
934                                .ignore_directory_in_diagnostics_source_blocks
935                                .clone(),
936                        );
937                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
938            }
939        },
940        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
941            JsonEmitter::new(
942                Box::new(io::BufWriter::new(io::stderr())),
943                source_map,
944                translator,
945                pretty,
946                json_rendered,
947                color_config,
948            )
949            .ui_testing(sopts.unstable_opts.ui_testing)
950            .ignored_directories_in_source_blocks(
951                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
952            )
953            .diagnostic_width(sopts.diagnostic_width)
954            .macro_backtrace(macro_backtrace)
955            .track_diagnostics(track_diagnostics)
956            .terminal_url(terminal_url),
957        ),
958    }
959}
960
961// JUSTIFICATION: literally session construction
962#[allow(rustc::bad_opt_access)]
963#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
964pub fn build_session(
965    sopts: config::Options,
966    io: CompilerIO,
967    fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
968    registry: rustc_errors::registry::Registry,
969    fluent_resources: Vec<&'static str>,
970    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
971    target: Target,
972    cfg_version: &'static str,
973    ice_file: Option<PathBuf>,
974    using_internal_features: &'static AtomicBool,
975) -> Session {
976    // FIXME: This is not general enough to make the warning lint completely override
977    // normal diagnostic warnings, since the warning lint can also be denied and changed
978    // later via the source code.
979    let warnings_allow = sopts
980        .lint_opts
981        .iter()
982        .rfind(|&(key, _)| *key == "warnings")
983        .is_some_and(|&(_, level)| level == lint::Allow);
984    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
985    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
986
987    let translator = Translator {
988        fluent_bundle,
989        fallback_fluent_bundle: fallback_fluent_bundle(
990            fluent_resources,
991            sopts.unstable_opts.translate_directionality_markers,
992        ),
993    };
994    let source_map = rustc_span::source_map::get_source_map().unwrap();
995    let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
996
997    let mut dcx = DiagCtxt::new(emitter)
998        .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
999        .with_registry(registry);
1000    if let Some(ice_file) = ice_file {
1001        dcx = dcx.with_ice_file(ice_file);
1002    }
1003
1004    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1005    let (host, target_warnings) =
1006        Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1007            .unwrap_or_else(|e| {
1008                dcx.handle().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading host specification: {0}",
                e))
    })format!("Error loading host specification: {e}"))
1009            });
1010    for warning in target_warnings.warning_messages() {
1011        dcx.handle().warn(warning)
1012    }
1013
1014    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1015    {
1016        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1017
1018        let profiler = SelfProfiler::new(
1019            directory,
1020            sopts.crate_name.as_deref(),
1021            sopts.unstable_opts.self_profile_events.as_deref(),
1022            &sopts.unstable_opts.self_profile_counter,
1023        );
1024        match profiler {
1025            Ok(profiler) => Some(Arc::new(profiler)),
1026            Err(e) => {
1027                dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1028                None
1029            }
1030        }
1031    } else {
1032        None
1033    };
1034
1035    let mut psess = ParseSess::with_dcx(dcx, source_map);
1036    psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1037
1038    let host_triple = config::host_tuple();
1039    let target_triple = sopts.target_triple.tuple();
1040    // FIXME use host sysroot?
1041    let host_tlib_path =
1042        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1043    let target_tlib_path = if host_triple == target_triple {
1044        // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1045        // rescanning of the target lib path and an unnecessary allocation.
1046        Arc::clone(&host_tlib_path)
1047    } else {
1048        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1049    };
1050
1051    let prof = SelfProfilerRef::new(
1052        self_profiler,
1053        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1054    );
1055
1056    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1057        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1058        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1059        _ => CtfeBacktrace::Disabled,
1060    });
1061
1062    let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1063    let target_filesearch =
1064        filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1065    let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1066
1067    let invocation_temp = sopts
1068        .incremental
1069        .as_ref()
1070        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1071
1072    let timings = TimingSectionHandler::new(sopts.json_timings);
1073
1074    let sess = Session {
1075        target,
1076        host,
1077        opts: sopts,
1078        target_tlib_path,
1079        psess,
1080        io,
1081        incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1082        prof,
1083        timings,
1084        code_stats: Default::default(),
1085        lint_store: None,
1086        driver_lint_caps,
1087        ctfe_backtrace,
1088        miri_unleashed_features: Lock::new(Default::default()),
1089        asm_arch,
1090        target_features: Default::default(),
1091        unstable_target_features: Default::default(),
1092        cfg_version,
1093        using_internal_features,
1094        target_filesearch,
1095        host_filesearch,
1096        invocation_temp,
1097    };
1098
1099    validate_commandline_args_with_session_available(&sess);
1100
1101    sess
1102}
1103
1104/// Validate command line arguments with a `Session`.
1105///
1106/// If it is useful to have a Session available already for validating a commandline argument, you
1107/// can do so here.
1108// JUSTIFICATION: needs to access args to validate them
1109#[allow(rustc::bad_opt_access)]
1110fn validate_commandline_args_with_session_available(sess: &Session) {
1111    // Since we don't know if code in an rlib will be linked to statically or
1112    // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1113    // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1114    // these manually generated symbols confuse LLD when it tries to merge
1115    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1116    // when compiling for LLD ThinLTO. This way we can validly just not generate
1117    // the `dllimport` attributes and `__imp_` symbols in that case.
1118    if sess.opts.cg.linker_plugin_lto.enabled()
1119        && sess.opts.cg.prefer_dynamic
1120        && sess.target.is_like_windows
1121    {
1122        sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1123    }
1124
1125    // Make sure that any given profiling data actually exists so LLVM can't
1126    // decide to silently skip PGO.
1127    if let Some(ref path) = sess.opts.cg.profile_use {
1128        if !path.exists() {
1129            sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1130        }
1131    }
1132
1133    // Do the same for sample profile data.
1134    if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1135        if !path.exists() {
1136            sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1137        }
1138    }
1139
1140    // Unwind tables cannot be disabled if the target requires them.
1141    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1142        if sess.target.requires_uwtable && !include_uwtables {
1143            sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1144        }
1145    }
1146
1147    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1148    let supported_sanitizers = sess.target.options.supported_sanitizers;
1149    let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1150    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled
1151    // we should allow Shadow Call Stack sanitizer.
1152    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1153        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1154    }
1155    match unsupported_sanitizers.into_iter().count() {
1156        0 => {}
1157        1 => {
1158            sess.dcx()
1159                .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1160        }
1161        _ => {
1162            sess.dcx().emit_err(errors::SanitizersNotSupported {
1163                us: unsupported_sanitizers.to_string(),
1164            });
1165        }
1166    }
1167
1168    // Cannot mix and match mutually-exclusive sanitizers.
1169    if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1170        sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1171            first: first.to_string(),
1172            second: second.to_string(),
1173        });
1174    }
1175
1176    // Cannot enable crt-static with sanitizers on Linux
1177    if sess.crt_static(None)
1178        && !sess.opts.unstable_opts.sanitizer.is_empty()
1179        && !sess.target.is_like_msvc
1180    {
1181        sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1182    }
1183
1184    // LLVM CFI requires LTO.
1185    if sess.is_sanitizer_cfi_enabled()
1186        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1187    {
1188        sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1189    }
1190
1191    // KCFI requires panic=abort
1192    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1193        sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1194    }
1195
1196    // LLVM CFI using rustc LTO requires a single codegen unit.
1197    if sess.is_sanitizer_cfi_enabled()
1198        && sess.lto() == config::Lto::Fat
1199        && (sess.codegen_units().as_usize() != 1)
1200    {
1201        sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1202    }
1203
1204    // Canonical jump tables requires CFI.
1205    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1206        if !sess.is_sanitizer_cfi_enabled() {
1207            sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1208        }
1209    }
1210
1211    // KCFI arity indicator requires KCFI.
1212    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1213        sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1214    }
1215
1216    // LLVM CFI pointer generalization requires CFI or KCFI.
1217    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1218        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1219            sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1220        }
1221    }
1222
1223    // LLVM CFI integer normalization requires CFI or KCFI.
1224    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1225        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1226            sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1227        }
1228    }
1229
1230    // LTO unit splitting requires LTO.
1231    if sess.is_split_lto_unit_enabled()
1232        && !(sess.lto() == config::Lto::Fat
1233            || sess.lto() == config::Lto::Thin
1234            || sess.opts.cg.linker_plugin_lto.enabled())
1235    {
1236        sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1237    }
1238
1239    // VFE requires LTO.
1240    if sess.lto() != config::Lto::Fat {
1241        if sess.opts.unstable_opts.virtual_function_elimination {
1242            sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1243        }
1244    }
1245
1246    if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1247        if !sess.target.options.supports_stack_protector {
1248            sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1249                stack_protector: sess.opts.unstable_opts.stack_protector,
1250                target_triple: &sess.opts.target_triple,
1251            });
1252        }
1253    }
1254
1255    if sess.opts.unstable_opts.small_data_threshold.is_some() {
1256        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1257            sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1258                target_triple: &sess.opts.target_triple,
1259            })
1260        }
1261    }
1262
1263    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1264        sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1265    }
1266
1267    if let Some(dwarf_version) =
1268        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1269    {
1270        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.
1271        if dwarf_version < 2 || dwarf_version > 5 {
1272            sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1273        }
1274    }
1275
1276    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1277        && !sess.opts.unstable_opts.unstable_options
1278    {
1279        sess.dcx()
1280            .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1281    }
1282
1283    if sess.opts.unstable_opts.embed_source {
1284        let dwarf_version = sess.dwarf_version();
1285
1286        if dwarf_version < 5 {
1287            sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1288        }
1289
1290        if sess.opts.debuginfo == DebugInfo::None {
1291            sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1292        }
1293    }
1294
1295    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1296        sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1297    }
1298
1299    if let Some(flavor) = sess.opts.cg.linker_flavor
1300        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1301    {
1302        let flavor = flavor.desc();
1303        sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1304    }
1305
1306    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1307        if !#[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
    Arch::X86 | Arch::X86_64 => true,
    _ => false,
}matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {
1308            sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1309        }
1310    }
1311
1312    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1313        if !#[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
    Arch::X86 | Arch::X86_64 => true,
    _ => false,
}matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {
1314            sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1315        }
1316    }
1317
1318    if let Some(regparm) = sess.opts.unstable_opts.regparm {
1319        if regparm > 3 {
1320            sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1321        }
1322        if sess.target.arch != Arch::X86 {
1323            sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1324        }
1325    }
1326    if sess.opts.unstable_opts.reg_struct_return {
1327        if sess.target.arch != Arch::X86 {
1328            sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1329        }
1330    }
1331
1332    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1333    // kept as a `match` to force a change if new ones are added, even if we currently only support
1334    // `thunk-extern` like Clang.
1335    match sess.opts.unstable_opts.function_return {
1336        FunctionReturn::Keep => (),
1337        FunctionReturn::ThunkExtern => {
1338            // FIXME: In principle, the inherited base LLVM target code model could be large,
1339            // but this only checks whether we were passed one explicitly (like Clang does).
1340            if let Some(code_model) = sess.code_model()
1341                && code_model == CodeModel::Large
1342            {
1343                sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1344            }
1345        }
1346    }
1347
1348    if sess.opts.cg.soft_float {
1349        if sess.target.arch == Arch::Arm {
1350            sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1351        } else {
1352            // All `use_softfp` does is the equivalent of `-mfloat-abi` in GCC/clang, which only exists on ARM targets.
1353            // We document this flag to only affect `*eabihf` targets, so let's show a warning for all other targets.
1354            sess.dcx().emit_warn(errors::SoftFloatIgnored);
1355        }
1356    }
1357}
1358
1359/// Holds data on the current incremental compilation session, if there is one.
1360#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IncrCompSession {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            IncrCompSession::NotInitialized =>
                ::core::fmt::Formatter::write_str(f, "NotInitialized"),
            IncrCompSession::Active {
                session_directory: __self_0, _lock_file: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Active", "session_directory", __self_0, "_lock_file",
                    &__self_1),
            IncrCompSession::Finalized { session_directory: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Finalized", "session_directory", &__self_0),
            IncrCompSession::InvalidBecauseOfErrors {
                session_directory: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "InvalidBecauseOfErrors", "session_directory", &__self_0),
        }
    }
}Debug)]
1361enum IncrCompSession {
1362    /// This is the state the session will be in until the incr. comp. dir is
1363    /// needed.
1364    NotInitialized,
1365    /// This is the state during which the session directory is private and can
1366    /// be modified. `_lock_file` is never directly used, but its presence
1367    /// alone has an effect, because the file will unlock when the session is
1368    /// dropped.
1369    Active { session_directory: PathBuf, _lock_file: flock::Lock },
1370    /// This is the state after the session directory has been finalized. In this
1371    /// state, the contents of the directory must not be modified any more.
1372    Finalized { session_directory: PathBuf },
1373    /// This is an error state that is reached when some compilation error has
1374    /// occurred. It indicates that the contents of the session directory must
1375    /// not be used, since they might be invalid.
1376    InvalidBecauseOfErrors { session_directory: PathBuf },
1377}
1378
1379/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1380pub struct EarlyDiagCtxt {
1381    dcx: DiagCtxt,
1382}
1383
1384impl EarlyDiagCtxt {
1385    pub fn new(output: ErrorOutputType) -> Self {
1386        let emitter = mk_emitter(output);
1387        Self { dcx: DiagCtxt::new(emitter) }
1388    }
1389
1390    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1391    /// format. If `early_err` was previously called this will panic.
1392    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1393        if !self.dcx.handle().has_errors().is_none() {
    ::core::panicking::panic("assertion failed: self.dcx.handle().has_errors().is_none()")
};assert!(self.dcx.handle().has_errors().is_none());
1394
1395        let emitter = mk_emitter(output);
1396        self.dcx = DiagCtxt::new(emitter);
1397    }
1398
1399    #[allow(rustc::untranslatable_diagnostic)]
1400    #[allow(rustc::diagnostic_outside_of_impl)]
1401    pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1402        self.dcx.handle().note(msg)
1403    }
1404
1405    #[allow(rustc::untranslatable_diagnostic)]
1406    #[allow(rustc::diagnostic_outside_of_impl)]
1407    pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1408        self.dcx.handle().struct_help(msg).emit()
1409    }
1410
1411    #[allow(rustc::untranslatable_diagnostic)]
1412    #[allow(rustc::diagnostic_outside_of_impl)]
1413    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1414    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1415        self.dcx.handle().err(msg)
1416    }
1417
1418    #[allow(rustc::untranslatable_diagnostic)]
1419    #[allow(rustc::diagnostic_outside_of_impl)]
1420    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1421        self.dcx.handle().fatal(msg)
1422    }
1423
1424    #[allow(rustc::untranslatable_diagnostic)]
1425    #[allow(rustc::diagnostic_outside_of_impl)]
1426    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1427        self.dcx.handle().struct_fatal(msg)
1428    }
1429
1430    #[allow(rustc::untranslatable_diagnostic)]
1431    #[allow(rustc::diagnostic_outside_of_impl)]
1432    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1433        self.dcx.handle().warn(msg)
1434    }
1435
1436    #[allow(rustc::untranslatable_diagnostic)]
1437    #[allow(rustc::diagnostic_outside_of_impl)]
1438    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1439        self.dcx.handle().struct_warn(msg)
1440    }
1441}
1442
1443fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1444    // FIXME(#100717): early errors aren't translated at the moment, so this is fine, but it will
1445    // need to reference every crate that might emit an early error for translation to work.
1446    let translator =
1447        Translator::with_fallback_bundle(<[_]>::into_vec(::alloc::boxed::box_new([rustc_errors::DEFAULT_LOCALE_RESOURCE]))vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1448    let emitter: Box<DynEmitter> = match output {
1449        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1450            HumanReadableErrorType { short, unicode } => Box::new(
1451                AnnotateSnippetEmitter::new(stderr_destination(color_config), translator)
1452                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1453                    .short_message(short),
1454            ),
1455        },
1456        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1457            Box::new(JsonEmitter::new(
1458                Box::new(io::BufWriter::new(io::stderr())),
1459                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1460                translator,
1461                pretty,
1462                json_rendered,
1463                color_config,
1464            ))
1465        }
1466    };
1467    emitter
1468}