Skip to main content

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