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