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, NATIVE_CPU, OptLevel, OutFileName,
42    OutputType, 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) {
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::FinalizedOrRemoved;
714    }
715
716    pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
717        let incr_comp_session = self.incr_comp_session.borrow();
718        ReadGuard::map(incr_comp_session, |incr_comp_session| match incr_comp_session {
719            IncrCompSession::NotInitialized | IncrCompSession::FinalizedOrRemoved => {
    ::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
            incr_comp_session));
}panic!(
720                "trying to get session directory from `IncrCompSession`: {:?}",
721                incr_comp_session,
722            ),
723            IncrCompSession::Active { session_directory, .. } => session_directory,
724        })
725    }
726
727    pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
728        self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
729    }
730
731    /// Is this edition 2015?
732    pub fn is_rust_2015(&self) -> bool {
733        self.edition().is_rust_2015()
734    }
735
736    /// Are we allowed to use features from the Rust 2018 edition?
737    pub fn at_least_rust_2018(&self) -> bool {
738        self.edition().at_least_rust_2018()
739    }
740
741    /// Are we allowed to use features from the Rust 2021 edition?
742    pub fn at_least_rust_2021(&self) -> bool {
743        self.edition().at_least_rust_2021()
744    }
745
746    /// Are we allowed to use features from the Rust 2024 edition?
747    pub fn at_least_rust_2024(&self) -> bool {
748        self.edition().at_least_rust_2024()
749    }
750
751    /// Returns `true` if we should use the PLT for shared library calls.
752    pub fn needs_plt(&self) -> bool {
753        // Check if the current target usually wants PLT to be enabled.
754        // The user can use the command line flag to override it.
755        let want_plt = self.target.plt_by_default;
756
757        let dbg_opts = &self.opts.unstable_opts;
758
759        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
760
761        // Only enable this optimization by default if full relro is also enabled.
762        // In this case, lazy binding was already unavailable, so nothing is lost.
763        // This also ensures `-Wl,-z,now` is supported by the linker.
764        let full_relro = RelroLevel::Full == relro_level;
765
766        // If user didn't explicitly forced us to use / skip the PLT,
767        // then use it unless the target doesn't want it by default or the full relro forces it on.
768        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
769    }
770
771    /// Checks if LLVM lifetime markers should be emitted.
772    pub fn emit_lifetime_markers(&self) -> bool {
773        self.opts.optimize != config::OptLevel::No
774        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
775        //
776        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
777        //
778        // HWAddressSanitizer and KernelHWAddressSanitizer will use lifetimes to detect use after
779        // scope bugs in the future.
780        || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
781        // Lifetimes are necessary for retagging semantics.
782        || self.opts.unstable_opts.codegen_emit_retag.is_some()
783    }
784
785    pub fn diagnostic_width(&self) -> usize {
786        let default_column_width = 140;
787        if let Some(width) = self.opts.diagnostic_width {
788            width
789        } else if self.opts.unstable_opts.ui_testing {
790            default_column_width
791        } else {
792            termize::dimensions().map_or(default_column_width, |(w, _)| w)
793        }
794    }
795
796    /// Returns the default symbol visibility.
797    pub fn default_visibility(&self) -> SymbolVisibility {
798        self.opts
799            .unstable_opts
800            .default_visibility
801            .or(self.target.options.default_visibility)
802            .unwrap_or(SymbolVisibility::Interposable)
803    }
804
805    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
806        if verbatim {
807            ("", "")
808        } else {
809            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
810        }
811    }
812
813    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
814        match self.lint_store {
815            Some(ref lint_store) => lint_store.lint_groups_iter(),
816            None => Box::new(std::iter::empty()),
817        }
818    }
819}
820
821// JUSTIFICATION: defn of the suggested wrapper fns
822#[allow(rustc::bad_opt_access)]
823impl Session {
824    pub fn verbose_internals(&self) -> bool {
825        self.opts.unstable_opts.verbose_internals
826    }
827
828    pub fn print_llvm_stats(&self) -> bool {
829        self.opts.unstable_opts.print_codegen_stats
830    }
831
832    pub fn print_llvm_stats_json(&self) -> Option<&String> {
833        self.opts.unstable_opts.print_codegen_stats_json.as_ref()
834    }
835
836    pub fn verify_llvm_ir(&self) -> bool {
837        self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
838    }
839
840    pub fn binary_dep_depinfo(&self) -> bool {
841        self.opts.unstable_opts.binary_dep_depinfo
842    }
843
844    pub fn mir_opt_level(&self) -> usize {
845        self.opts
846            .unstable_opts
847            .mir_opt_level
848            .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
849    }
850
851    /// Calculates the flavor of LTO to use for this compilation.
852    pub fn lto(&self) -> config::Lto {
853        // If our target has codegen requirements ignore the command line
854        if self.target.requires_lto {
855            return config::Lto::Fat;
856        }
857
858        // If the user specified something, return that. If they only said `-C
859        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
860        // then ensure we can't use a ThinLTO.
861        match self.opts.cg.lto {
862            config::LtoCli::Unspecified => {
863                // The compiler was invoked without the `-Clto` flag. Fall
864                // through to the default handling
865            }
866            config::LtoCli::No => {
867                // The user explicitly opted out of any kind of LTO
868                return config::Lto::No;
869            }
870            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
871                // All of these mean fat LTO
872                return config::Lto::Fat;
873            }
874            config::LtoCli::Thin => {
875                // The user explicitly asked for ThinLTO
876                if !self.thin_lto_supported {
877                    // Backend doesn't support ThinLTO, fallback to fat LTO.
878                    self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
879                    return config::Lto::Fat;
880                }
881                return config::Lto::Thin;
882            }
883        }
884
885        if !self.thin_lto_supported {
886            return config::Lto::No;
887        }
888
889        // Ok at this point the target doesn't require anything and the user
890        // hasn't asked for anything. Our next decision is whether or not
891        // we enable "auto" ThinLTO where we use multiple codegen units and
892        // then do ThinLTO over those codegen units. The logic below will
893        // either return `No` or `ThinLocal`.
894
895        // If processing command line options determined that we're incompatible
896        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
897        if self.opts.cli_forced_local_thinlto_off {
898            return config::Lto::No;
899        }
900
901        // If `-Z thinlto` specified process that, but note that this is mostly
902        // a deprecated option now that `-C lto=thin` exists.
903        if let Some(enabled) = self.opts.unstable_opts.thinlto {
904            if enabled {
905                return config::Lto::ThinLocal;
906            } else {
907                return config::Lto::No;
908            }
909        }
910
911        // If there's only one codegen unit and LTO isn't enabled then there's
912        // no need for ThinLTO so just return false.
913        if self.codegen_units().as_usize() == 1 {
914            return config::Lto::No;
915        }
916
917        // Now we're in "defaults" territory. By default we enable ThinLTO for
918        // optimized compiles (anything greater than O0).
919        match self.opts.optimize {
920            config::OptLevel::No => config::Lto::No,
921            _ => config::Lto::ThinLocal,
922        }
923    }
924
925    /// Returns the panic strategy for this compile session. If the user explicitly selected one
926    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
927    pub fn panic_strategy(&self) -> PanicStrategy {
928        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
929    }
930
931    pub fn fewer_names(&self) -> bool {
932        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
933            fewer_names
934        } else {
935            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
936                || self.opts.output_types.contains_key(&OutputType::Bitcode)
937                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
938                || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
939            !more_names
940        }
941    }
942
943    pub fn unstable_options(&self) -> bool {
944        self.opts.unstable_opts.unstable_options
945    }
946
947    pub fn is_nightly_build(&self) -> bool {
948        self.opts.unstable_features.is_nightly_build()
949    }
950
951    pub fn overflow_checks(&self) -> bool {
952        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
953    }
954
955    pub fn ub_checks(&self) -> bool {
956        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
957    }
958
959    pub fn contract_checks(&self) -> bool {
960        self.opts.unstable_opts.contract_checks.unwrap_or(false)
961    }
962
963    pub fn relocation_model(&self) -> RelocModel {
964        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
965    }
966
967    pub fn code_model(&self) -> Option<CodeModel> {
968        self.opts.cg.code_model.or(self.target.code_model)
969    }
970
971    pub fn tls_model(&self) -> TlsModel {
972        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
973    }
974
975    pub fn direct_access_external_data(&self) -> Option<bool> {
976        self.opts
977            .unstable_opts
978            .direct_access_external_data
979            .or(self.target.direct_access_external_data)
980    }
981
982    pub fn split_debuginfo(&self) -> SplitDebuginfo {
983        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
984    }
985
986    /// Returns the DWARF version passed on the CLI or the default for the target.
987    pub fn dwarf_version(&self) -> u32 {
988        self.opts
989            .cg
990            .dwarf_version
991            .or(self.opts.unstable_opts.dwarf_version)
992            .unwrap_or(self.target.default_dwarf_version)
993    }
994
995    pub fn stack_protector(&self) -> StackProtector {
996        if self.target.options.supports_stack_protector {
997            self.opts.unstable_opts.stack_protector
998        } else {
999            StackProtector::None
1000        }
1001    }
1002
1003    pub fn must_emit_unwind_tables(&self) -> bool {
1004        // This is used to control the emission of the `uwtable` attribute on
1005        // LLVM functions. The `uwtable` attribute according to LLVM is:
1006        //
1007        //     This attribute indicates that the ABI being targeted requires that an
1008        //     unwind table entry be produced for this function even if we can show
1009        //     that no exceptions passes by it. This is normally the case for the
1010        //     ELF x86-64 abi, but it can be disabled for some compilation units.
1011        //
1012        // Typically when we're compiling with `-C panic=abort` we don't need
1013        // `uwtable` because we can't generate any exceptions! But note that
1014        // some targets require unwind tables to generate backtraces.
1015        // Unwind tables are needed when compiling with `-C panic=unwind`, but
1016        // LLVM won't omit unwind tables unless the function is also marked as
1017        // `nounwind`, so users are allowed to disable `uwtable` emission.
1018        // Historically rustc always emits `uwtable` attributes by default, so
1019        // even they can be disabled, they're still emitted by default.
1020        //
1021        // On some targets (including windows), however, exceptions include
1022        // other events such as illegal instructions, segfaults, etc. This means
1023        // that on Windows we end up still needing unwind tables even if the `-C
1024        // panic=abort` flag is passed.
1025        //
1026        // You can also find more info on why Windows needs unwind tables in:
1027        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1028        //
1029        // If a target requires unwind tables, then they must be emitted.
1030        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1031        // value, if it is provided, or disable them, if not.
1032        self.target.requires_uwtable
1033            || self
1034                .opts
1035                .cg
1036                .force_unwind_tables
1037                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1038    }
1039
1040    /// Returns the number of threads used for the thread pool.
1041    ///
1042    /// `None` means thread pool is not used and synchronization is disabled.
1043    /// `Some(n)` means synchronization is enabled with `n` worker threads.
1044    #[inline]
1045    pub fn threads(&self) -> Option<usize> {
1046        self.opts.unstable_opts.threads
1047    }
1048
1049    /// Returns the number of codegen units that should be used for this
1050    /// compilation
1051    pub fn codegen_units(&self) -> CodegenUnits {
1052        if let Some(n) = self.opts.cli_forced_codegen_units {
1053            return CodegenUnits::User(n);
1054        }
1055        if let Some(n) = self.target.default_codegen_units {
1056            return CodegenUnits::Default(n as usize);
1057        }
1058
1059        // If incremental compilation is turned on, we default to a high number
1060        // codegen units in order to reduce the "collateral damage" small
1061        // changes cause.
1062        if self.opts.incremental.is_some() {
1063            return CodegenUnits::Default(256);
1064        }
1065
1066        // Why is 16 codegen units the default all the time?
1067        //
1068        // The main reason for enabling multiple codegen units by default is to
1069        // leverage the ability for the codegen backend to do codegen and
1070        // optimization in parallel. This allows us, especially for large crates, to
1071        // make good use of all available resources on the machine once we've
1072        // hit that stage of compilation. Large crates especially then often
1073        // take a long time in codegen/optimization and this helps us amortize that
1074        // cost.
1075        //
1076        // Note that a high number here doesn't mean that we'll be spawning a
1077        // large number of threads in parallel. The backend of rustc contains
1078        // global rate limiting through the `jobserver` crate so we'll never
1079        // overload the system with too much work, but rather we'll only be
1080        // optimizing when we're otherwise cooperating with other instances of
1081        // rustc.
1082        //
1083        // Rather a high number here means that we should be able to keep a lot
1084        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1085        // to build we'll be guaranteed that all cpus will finish pretty closely
1086        // to one another and we should make relatively optimal use of system
1087        // resources
1088        //
1089        // Note that the main cost of codegen units is that it prevents LLVM
1090        // from inlining across codegen units. Users in general don't have a lot
1091        // of control over how codegen units are split up so it's our job in the
1092        // compiler to ensure that undue performance isn't lost when using
1093        // codegen units (aka we can't require everyone to slap `#[inline]` on
1094        // everything).
1095        //
1096        // If we're compiling at `-O0` then the number doesn't really matter too
1097        // much because performance doesn't matter and inlining is ok to lose.
1098        // In debug mode we just want to try to guarantee that no cpu is stuck
1099        // doing work that could otherwise be farmed to others.
1100        //
1101        // In release mode, however (O1 and above) performance does indeed
1102        // matter! To recover the loss in performance due to inlining we'll be
1103        // enabling ThinLTO by default (the function for which is just below).
1104        // This will ensure that we recover any inlining wins we otherwise lost
1105        // through codegen unit partitioning.
1106        //
1107        // ---
1108        //
1109        // Ok that's a lot of words but the basic tl;dr; is that we want a high
1110        // number here -- but not too high. Additionally we're "safe" to have it
1111        // always at the same number at all optimization levels.
1112        //
1113        // As a result 16 was chosen here! Mostly because it was a power of 2
1114        // and most benchmarks agreed it was roughly a local optimum. Not very
1115        // scientific.
1116        CodegenUnits::Default(16)
1117    }
1118
1119    pub fn teach(&self, code: ErrCode) -> bool {
1120        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1121    }
1122
1123    pub fn edition(&self) -> Edition {
1124        self.opts.edition
1125    }
1126
1127    pub fn link_dead_code(&self) -> bool {
1128        self.opts.cg.link_dead_code.unwrap_or(false)
1129    }
1130
1131    /// Get the deployment target on Apple platforms based on the standard environment variables,
1132    /// or fall back to the minimum version supported by `rustc`.
1133    ///
1134    /// This should be guarded behind `if sess.target.is_like_darwin`.
1135    pub fn apple_deployment_target(&self) -> apple::OSVersion {
1136        let min = apple::OSVersion::minimum_deployment_target(&self.target);
1137        let env_var = apple::deployment_target_env_var(&self.target.os);
1138
1139        // FIXME(madsmtm): Track changes to this.
1140        if let Ok(deployment_target) = env::var(env_var) {
1141            match apple::OSVersion::from_str(&deployment_target) {
1142                Ok(version) => {
1143                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
1144                    // It is common that the deployment target is set a bit too low, for example on
1145                    // macOS Aarch64 to also target older x86_64. So we only want to warn when variable
1146                    // is lower than the minimum OS supported by rustc, not when the variable is lower
1147                    // than the minimum for a specific target.
1148                    if version < os_min {
1149                        self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
1150                            env_var,
1151                            version: version.fmt_pretty().to_string(),
1152                            os_min: os_min.fmt_pretty().to_string(),
1153                        });
1154                    }
1155
1156                    // Raise the deployment target to the minimum supported.
1157                    version.max(min)
1158                }
1159                Err(error) => {
1160                    self.dcx()
1161                        .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
1162                    min
1163                }
1164            }
1165        } else {
1166            // If no deployment target variable is set, default to the minimum found above.
1167            min
1168        }
1169    }
1170
1171    pub fn sanitizers(&self) -> SanitizerSet {
1172        return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
1173    }
1174
1175    pub fn pointer_authentication(&self) -> bool {
1176        self.pointer_auth_config.is_some()
1177    }
1178
1179    pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1180        self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1181    }
1182
1183    pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1184        self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1185    }
1186}
1187
1188// JUSTIFICATION: part of session construction
1189#[allow(rustc::bad_opt_access)]
1190fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1191    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1192    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1193    let terminal_url = match sopts.unstable_opts.terminal_urls {
1194        TerminalUrl::Auto => {
1195            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1196                (Ok("truecolor"), Ok("xterm-256color"))
1197                    if sopts.unstable_features.is_nightly_build() =>
1198                {
1199                    TerminalUrl::Yes
1200                }
1201                _ => TerminalUrl::No,
1202            }
1203        }
1204        t => t,
1205    };
1206
1207    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1208
1209    match sopts.error_format {
1210        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1211            HumanReadableErrorType { short, unicode } => {
1212                let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1213                    .sm(source_map)
1214                    .short_message(short)
1215                    .diagnostic_width(sopts.diagnostic_width)
1216                    .macro_backtrace(macro_backtrace)
1217                    .track_diagnostics(track_diagnostics)
1218                    .terminal_url(terminal_url)
1219                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1220                    .ignored_directories_in_source_blocks(
1221                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1222                    );
1223                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1224            }
1225        },
1226        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1227            JsonEmitter::new(
1228                Box::new(io::BufWriter::new(io::stderr())),
1229                source_map,
1230                pretty,
1231                json_rendered,
1232                color_config,
1233            )
1234            .ui_testing(sopts.unstable_opts.ui_testing)
1235            .ignored_directories_in_source_blocks(
1236                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1237            )
1238            .diagnostic_width(sopts.diagnostic_width)
1239            .macro_backtrace(macro_backtrace)
1240            .track_diagnostics(track_diagnostics)
1241            .terminal_url(terminal_url),
1242        ),
1243    }
1244}
1245
1246// JUSTIFICATION: literally session construction
1247#[allow(rustc::bad_opt_access)]
1248pub fn build_session(
1249    sopts: config::Options,
1250    io: CompilerIO,
1251    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1252    target: Target,
1253    cfg_version: &'static str,
1254    ice_file: Option<PathBuf>,
1255    using_internal_features: &'static AtomicBool,
1256) -> Session {
1257    // FIXME: This is not general enough to make the warning lint completely override
1258    // normal diagnostic warnings, since the warning lint can also be denied and changed
1259    // later via the source code.
1260    let warnings_allow = sopts
1261        .lint_opts
1262        .iter()
1263        .rfind(|&(key, _)| *key == "warnings")
1264        .is_some_and(|&(_, level)| level == lint::Allow);
1265    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1266    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1267
1268    let source_map = rustc_span::source_map::get_source_map().unwrap();
1269    let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1270
1271    let mut dcx =
1272        DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1273    if let Some(ice_file) = ice_file {
1274        dcx = dcx.with_ice_file(ice_file);
1275    }
1276
1277    if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1278        dcx = dcx.with_msrv(msrv);
1279    }
1280
1281    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1282    let (host, target_warnings) =
1283        Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1284            .unwrap_or_else(|e| {
1285                dcx.handle().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading host specification: {0}",
                e))
    })format!("Error loading host specification: {e}"))
1286            });
1287    for warning in target_warnings.warning_messages() {
1288        dcx.handle().warn(warning)
1289    }
1290
1291    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1292    {
1293        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1294
1295        let profiler = SelfProfiler::new(
1296            directory,
1297            sopts.crate_name.as_deref(),
1298            sopts.unstable_opts.self_profile_events.as_deref(),
1299            &sopts.unstable_opts.self_profile_counter,
1300        );
1301        match profiler {
1302            Ok(profiler) => Some(Arc::new(profiler)),
1303            Err(e) => {
1304                dcx.handle().emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1305                None
1306            }
1307        }
1308    } else {
1309        None
1310    };
1311
1312    let psess = ParseSess::with_dcx(dcx, source_map);
1313
1314    let host_triple = config::host_tuple();
1315    let target_triple = sopts.target_triple.tuple();
1316    // FIXME use host sysroot?
1317    let host_tlib_path =
1318        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1319    let target_tlib_path = if host_triple == target_triple {
1320        // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1321        // rescanning of the target lib path and an unnecessary allocation.
1322        Arc::clone(&host_tlib_path)
1323    } else {
1324        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1325    };
1326
1327    let prof = SelfProfilerRef::new(
1328        self_profiler,
1329        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1330    );
1331
1332    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1333        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1334        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1335        _ => CtfeBacktrace::Disabled,
1336    });
1337
1338    let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1339    let target_filesearch =
1340        filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1341    let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1342
1343    let timings = TimingSectionHandler::new(sopts.json_timings);
1344
1345    let pointer_auth_config: Option<PointerAuthConfig> =
1346        PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1347
1348    let sess = Session {
1349        target,
1350        host,
1351        opts: sopts,
1352        target_tlib_path,
1353        psess,
1354        unstable_features: UnstableFeatures::from_environment(None),
1355        config: Cfg::default(),
1356        check_config: CheckCfg::default(),
1357        proc_macro_quoted_spans: Default::default(),
1358        io,
1359        incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1360        prof,
1361        timings,
1362        code_stats: Default::default(),
1363        lint_store: None,
1364        driver_lint_caps,
1365        ctfe_backtrace,
1366        miri_unleashed_features: Lock::new(Default::default()),
1367        asm_arch,
1368        target_features: Default::default(),
1369        unstable_target_features: Default::default(),
1370        cfg_version,
1371        using_internal_features,
1372        env_depinfo: Default::default(),
1373        file_depinfo: Default::default(),
1374        target_filesearch,
1375        host_filesearch,
1376        replaced_intrinsics: FxHashSet::default(), // filled by `run_compiler`
1377        fallback_intrinsics: FxHashSet::default(), // filled by `run_compiler`
1378        thin_lto_supported: true,                  // filled by `run_compiler`
1379        mir_opt_bisect_eval_count: AtomicUsize::new(0),
1380        used_features: Lock::default(),
1381        removed_rustc_main_attr: AtomicBool::new(false),
1382        pointer_auth_config,
1383    };
1384
1385    validate_commandline_args_with_session_available(&sess);
1386
1387    sess
1388}
1389
1390pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1391    ::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())
1392}
1393
1394/// Validate command line arguments with a `Session`.
1395///
1396/// If it is useful to have a Session available already for validating a commandline argument, you
1397/// can do so here.
1398// JUSTIFICATION: needs to access args to validate them
1399#[allow(rustc::bad_opt_access)]
1400fn validate_commandline_args_with_session_available(sess: &Session) {
1401    // Since we don't know if code in an rlib will be linked to statically or
1402    // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1403    // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1404    // these manually generated symbols confuse LLD when it tries to merge
1405    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1406    // when compiling for LLD ThinLTO. This way we can validly just not generate
1407    // the `dllimport` attributes and `__imp_` symbols in that case.
1408    if sess.opts.cg.linker_plugin_lto.enabled()
1409        && sess.opts.cg.prefer_dynamic
1410        && sess.target.is_like_windows
1411    {
1412        sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1413    }
1414
1415    if sess
1416        .pointer_auth_config
1417        .as_ref()
1418        .and_then(|cfg| cfg.function_pointers.as_ref())
1419        .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
    PointerAuthDiscrimination::Type => true,
    _ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1420    {
1421        sess.dcx().emit_err(
1422            diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1423                target_triple: &sess.opts.target_triple,
1424            },
1425        );
1426    }
1427
1428    if sess.target.cfg_abi != CfgAbi::Pauthtest
1429        && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1430    {
1431        sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1432            target_triple: &sess.opts.target_triple,
1433        });
1434    }
1435
1436    // Make sure that any given profiling data actually exists so LLVM can't
1437    // decide to silently skip PGO.
1438    if let Some(ref path) = sess.opts.cg.profile_use {
1439        if !path.exists() {
1440            sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1441        }
1442    }
1443
1444    // Do the same for sample profile data.
1445    if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1446        if !path.exists() {
1447            sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1448        }
1449    }
1450
1451    // Unwind tables cannot be disabled if the target requires them.
1452    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1453        if sess.target.requires_uwtable && !include_uwtables {
1454            sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1455        }
1456    }
1457
1458    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1459    let supported_sanitizers = sess.target.options.supported_sanitizers;
1460    let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1461    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled
1462    // we should allow Shadow Call Stack sanitizer.
1463    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1464        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1465    }
1466    match unsupported_sanitizers.into_iter().count() {
1467        0 => {}
1468        1 => {
1469            sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1470                us: unsupported_sanitizers.to_string(),
1471            });
1472        }
1473        _ => {
1474            sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1475                us: unsupported_sanitizers.to_string(),
1476            });
1477        }
1478    }
1479
1480    // Cannot mix and match mutually-exclusive sanitizers.
1481    if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1482        sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1483            first: first.to_string(),
1484            second: second.to_string(),
1485        });
1486    }
1487
1488    // Cannot enable crt-static with sanitizers on Linux
1489    if sess.crt_static(None)
1490        && !sess.opts.unstable_opts.sanitizer.is_empty()
1491        && !sess.target.is_like_msvc
1492    {
1493        sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1494    }
1495
1496    // FIXME(jchlanda) Pauthtest does not support static linking. It must be dynamically linked,
1497    // with a dynamic linker acting as the ELF interpreter that can resolve pauth relocations and
1498    // enforce pointer authentication constraints.
1499    if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1500        sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1501    }
1502
1503    // LLVM CFI requires LTO.
1504    if sess.is_sanitizer_cfi_enabled()
1505        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1506    {
1507        sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1508    }
1509
1510    // KCFI requires panic=abort
1511    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1512        sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1513    }
1514
1515    // LLVM CFI using rustc LTO requires a single codegen unit.
1516    if sess.is_sanitizer_cfi_enabled()
1517        && sess.lto() == config::Lto::Fat
1518        && (sess.codegen_units().as_usize() != 1)
1519    {
1520        sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1521    }
1522
1523    // Canonical jump tables requires CFI.
1524    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1525        if !sess.is_sanitizer_cfi_enabled() {
1526            sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1527        }
1528    }
1529
1530    // KCFI arity indicator requires KCFI.
1531    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1532        sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1533    }
1534
1535    // LLVM CFI pointer generalization requires CFI or KCFI.
1536    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1537        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1538            sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1539        }
1540    }
1541
1542    // LLVM CFI integer normalization requires CFI or KCFI.
1543    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1544        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1545            sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1546        }
1547    }
1548
1549    // LTO unit splitting requires LTO.
1550    if sess.is_split_lto_unit_enabled()
1551        && !(sess.lto() == config::Lto::Fat
1552            || sess.lto() == config::Lto::Thin
1553            || sess.opts.cg.linker_plugin_lto.enabled())
1554    {
1555        sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1556    }
1557
1558    // VFE requires LTO.
1559    if sess.lto() != config::Lto::Fat {
1560        if sess.opts.unstable_opts.virtual_function_elimination {
1561            sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1562        }
1563    }
1564
1565    if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1566        if !sess.target.options.supports_stack_protector {
1567            sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1568                stack_protector: sess.opts.unstable_opts.stack_protector,
1569                target_triple: &sess.opts.target_triple,
1570            });
1571        }
1572    }
1573
1574    if sess.opts.unstable_opts.small_data_threshold.is_some() {
1575        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1576            sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1577                target_triple: &sess.opts.target_triple,
1578            })
1579        }
1580    }
1581
1582    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1583        sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1584    }
1585
1586    if let Some(dwarf_version) =
1587        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1588    {
1589        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.
1590        if dwarf_version < 2 || dwarf_version > 5 {
1591            sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1592        }
1593    }
1594
1595    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1596        && !sess.opts.unstable_opts.unstable_options
1597    {
1598        sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1599            debuginfo: sess.split_debuginfo(),
1600        });
1601    }
1602
1603    if sess.opts.unstable_opts.embed_source {
1604        let dwarf_version = sess.dwarf_version();
1605
1606        if dwarf_version < 5 {
1607            sess.dcx()
1608                .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1609        }
1610
1611        if sess.opts.debuginfo == DebugInfo::None {
1612            sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1613        }
1614    }
1615
1616    if sess.opts.unstable_opts.instrument_mcount == InstrumentMcount::Fentry
1617        && !sess.target.options.supports_fentry
1618    {
1619        sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1620    }
1621
1622    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1623        sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1624    }
1625
1626    if let Some(flavor) = sess.opts.cg.linker_flavor
1627        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1628    {
1629        let flavor = flavor.desc();
1630        sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1631    }
1632
1633    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1634        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) {
1635            sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1636        }
1637    }
1638
1639    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1640        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) {
1641            sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1642        }
1643    }
1644
1645    if let Some(regparm) = sess.opts.unstable_opts.regparm {
1646        if regparm > 3 {
1647            sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1648        }
1649        if sess.target.arch != Arch::X86 {
1650            sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1651        }
1652    }
1653    if sess.opts.unstable_opts.reg_struct_return {
1654        if sess.target.arch != Arch::X86 {
1655            sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1656        }
1657    }
1658
1659    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1660    // kept as a `match` to force a change if new ones are added, even if we currently only support
1661    // `thunk-extern` like Clang.
1662    match sess.opts.unstable_opts.function_return {
1663        FunctionReturn::Keep => (),
1664        FunctionReturn::ThunkExtern => {
1665            // FIXME: In principle, the inherited base LLVM target code model could be large,
1666            // but this only checks whether we were passed one explicitly (like Clang does).
1667            if let Some(code_model) = sess.code_model()
1668                && code_model == CodeModel::Large
1669            {
1670                sess.dcx()
1671                    .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1672            }
1673        }
1674    }
1675
1676    if sess.opts.unstable_opts.packed_stack {
1677        if sess.target.arch != Arch::S390x {
1678            sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1679        }
1680    }
1681
1682    if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1683        if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1684            sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1685                target_triple: &sess.opts.target_triple,
1686                need_explicit_cpu: sess.target.need_explicit_cpu,
1687            });
1688        }
1689    }
1690}
1691
1692/// Holds data on the current incremental compilation session, if there is one.
1693#[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::FinalizedOrRemoved =>
                ::core::fmt::Formatter::write_str(f, "FinalizedOrRemoved"),
        }
    }
}Debug)]
1694enum IncrCompSession {
1695    /// This is the state the session will be in until the incr. comp. dir is
1696    /// needed.
1697    NotInitialized,
1698    /// This is the state during which the session directory is private and can
1699    /// be modified. `_lock_file` is never directly used, but its presence
1700    /// alone has an effect, because the file will unlock when the session is
1701    /// dropped.
1702    Active { session_directory: PathBuf, _lock_file: flock::Lock },
1703    /// This is the state after the session directory has been finalized or
1704    /// removed after errors. In this state, the contents of the directory must
1705    /// not be modified any more.
1706    FinalizedOrRemoved,
1707}
1708
1709/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1710pub struct EarlyDiagCtxt {
1711    dcx: DiagCtxt,
1712}
1713
1714impl EarlyDiagCtxt {
1715    pub fn new(output: ErrorOutputType) -> Self {
1716        let emitter = mk_emitter(output);
1717        Self { dcx: DiagCtxt::new(emitter) }
1718    }
1719
1720    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1721    /// format. If `early_err` was previously called this will panic.
1722    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1723        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());
1724
1725        let emitter = mk_emitter(output);
1726        self.dcx = DiagCtxt::new(emitter);
1727    }
1728
1729    pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1730        self.dcx.handle().note(msg)
1731    }
1732
1733    pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1734        self.dcx.handle().struct_help(msg).emit()
1735    }
1736
1737    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1738    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1739        self.dcx.handle().err(msg)
1740    }
1741
1742    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1743        self.dcx.handle().fatal(msg)
1744    }
1745
1746    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1747        self.dcx.handle().struct_fatal(msg)
1748    }
1749
1750    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1751        self.dcx.handle().warn(msg)
1752    }
1753
1754    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1755        self.dcx.handle().struct_warn(msg)
1756    }
1757}
1758
1759fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1760    let emitter: Box<DynEmitter> = match output {
1761        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1762            HumanReadableErrorType { short, unicode } => Box::new(
1763                AnnotateSnippetEmitter::new(stderr_destination(color_config))
1764                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1765                    .short_message(short),
1766            ),
1767        },
1768        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1769            Box::new(JsonEmitter::new(
1770                Box::new(io::BufWriter::new(io::stderr())),
1771                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1772                pretty,
1773                json_rendered,
1774                color_config,
1775            ))
1776        }
1777    };
1778    emitter
1779}