Skip to main content

rustc_session/
session.rs

1use std::any::Any;
2use std::ops::{Deref, DerefMut};
3use std::path::Component::Prefix;
4use std::path::PathBuf;
5use std::str::FromStr;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, AtomicUsize};
8use std::{env, io};
9
10use rustc_data_structures::flock;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
13use rustc_data_structures::sync::{AppendOnlyVec, DynSend, DynSync, Lock};
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, PResult,
21    TerminalUrl,
22};
23use rustc_feature::UnstableFeatures;
24use rustc_macros::StableHash;
25pub use rustc_span::def_id::StableCrateId;
26use rustc_span::edition::Edition;
27use rustc_span::source_map::{FilePathMapping, SourceMap};
28use rustc_span::{RealFileName, Span, Symbol};
29use rustc_structures::{CrateType, Limit};
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, BranchProtection, Cfg, CheckCfg, CoverageLevel, CoverageOptions, DebugInfo,
41    ErrorOutputType, FunctionReturn, Input, InstrumentCoverage, InstrumentMcount, LtoCli,
42    NATIVE_CPU, OutFileName, OutputType, PAuthKey, 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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CtfeBacktrace { }
#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Limits { }
#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PointerAuthARM8_3Key { }
#[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::marker::StructuralPartialEq for PointerAuthARM8_3Key { }
#[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 { }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/// Partial session built before the full session. More specifically, `EarlySession` is used to
328/// init the codegen backend, and then both pieces are used to build the full `Session`.
329pub struct EarlySession {
330    pub target: Target,
331    pub host: Target,
332    pub opts: config::Options,
333    pub psess: ParseSess,
334}
335
336// JUSTIFICATION: defn of the suggested wrapper fns
337#[allow(rustc::bad_opt_access)]
338impl EarlySession {
339    #[inline]
340    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
341        self.psess.dcx()
342    }
343
344    #[inline]
345    pub fn source_map(&self) -> &SourceMap {
346        self.psess.source_map()
347    }
348
349    /// Note: this is simpler than `Session::lto`, hence the `early_` prefix (to more clearly
350    /// distinguish it).
351    pub fn early_lto(&self) -> LtoCli {
352        self.opts.cg.lto
353    }
354
355    pub fn print_llvm_stats(&self) -> bool {
356        self.opts.unstable_opts.print_codegen_stats
357    }
358
359    pub fn print_llvm_stats_json(&self) -> Option<&String> {
360        self.opts.unstable_opts.print_codegen_stats_json.as_ref()
361    }
362
363    pub fn relocation_model(&self) -> RelocModel {
364        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
365    }
366
367    pub fn code_model(&self) -> Option<CodeModel> {
368        self.opts.cg.code_model.or(self.target.code_model)
369    }
370
371    pub fn tls_model(&self) -> TlsModel {
372        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
373    }
374
375    /// Returns the panic strategy for this compile session. If the user explicitly selected one
376    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
377    pub fn panic_strategy(&self) -> PanicStrategy {
378        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
379    }
380
381    /// Get the deployment target on Apple platforms based on the standard environment variables,
382    /// or fall back to the minimum version supported by `rustc`.
383    ///
384    /// This should be guarded behind `if sess.target.is_like_darwin`.
385    pub fn apple_deployment_target(&self) -> apple::OSVersion {
386        let min = apple::OSVersion::minimum_deployment_target(&self.target);
387        let env_var = apple::deployment_target_env_var(&self.target.os);
388
389        // FIXME(madsmtm): Track changes to this.
390        if let Ok(deployment_target) = env::var(env_var) {
391            match apple::OSVersion::from_str(&deployment_target) {
392                Ok(version) => {
393                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
394                    // It is common that the deployment target is set a bit too low, for example on
395                    // macOS Aarch64 to also target older x86_64. So we only want to warn when
396                    // variable is lower than the minimum OS supported by rustc, not when the
397                    // variable is lower than the minimum for a specific target.
398                    if version < os_min {
399                        self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
400                            env_var,
401                            version: version.fmt_pretty().to_string(),
402                            os_min: os_min.fmt_pretty().to_string(),
403                        });
404                    }
405
406                    // Raise the deployment target to the minimum supported.
407                    version.max(min)
408                }
409                Err(error) => {
410                    self.dcx()
411                        .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
412                    min
413                }
414            }
415        } else {
416            // If no deployment target variable is set, default to the minimum found above.
417            min
418        }
419    }
420
421    pub fn sanitizers(&self) -> SanitizerSet {
422        self.opts
423            .unstable_opts
424            .sanitizer
425            .combine_with_defaults(self.target.options.default_sanitizers)
426    }
427}
428
429/// Some info about the backend, returned by `CodegenBackend::init` and put into the `Session`.
430#[derive(#[automatically_derived]
impl ::core::default::Default for CodegenBackendInit {
    #[inline]
    fn default() -> CodegenBackendInit {
        CodegenBackendInit {
            global_backend_features: ::core::default::Default::default(),
            replaced_intrinsics: ::core::default::Default::default(),
            fallback_intrinsics: ::core::default::Default::default(),
            thin_lto_supported: const true,
        }
    }
}Default)]
431pub struct CodegenBackendInit {
432    /// See `Session::global_backend_features`.
433    pub global_backend_features: Vec<String>,
434
435    /// See `Session::replaced_intrinsics`.
436    pub replaced_intrinsics: Vec<Symbol>,
437
438    /// See `Session::fallback_intrinsics`.
439    pub fallback_intrinsics: Vec<Symbol>,
440
441    /// See `Session::thin_lto_supported`.
442    pub thin_lto_supported: bool = true,
443}
444
445/// Represents the data associated with a compilation
446/// session for a single crate.
447pub struct Session {
448    /// The `EarlySession` is embedded so it can be passed to functions that need it.
449    /// `Session::deref{_,mut}` exist so the fields within can be accessed as if they were direct
450    /// fields of `Session`.
451    pub early_sess: EarlySession,
452    pub wasm_proc_macro_tuple: TargetTuple,
453    pub wasm_proc_macro_target: Target,
454    pub target_tlib_path: SearchPath,
455    pub unstable_features: UnstableFeatures,
456    pub config: Cfg,
457    pub check_config: CheckCfg,
458    /// Spans passed to `proc_macro::quote_span`. Each span has a numerical
459    /// identifier represented by its position in the vector.
460    proc_macro_quoted_spans: AppendOnlyVec<Span>,
461
462    /// Input, input file path and output file path to this compilation process.
463    pub io: CompilerIO,
464
465    /// Used by `-Z self-profile`.
466    pub prof: SelfProfilerRef,
467
468    /// Used to emit section timings events (enabled by `--json=timings`).
469    pub timings: TimingSectionHandler,
470
471    /// Data about code being compiled, gathered during compilation.
472    pub code_stats: CodeStats,
473
474    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
475    pub lint_store: Option<Arc<dyn DynLintStore>>,
476
477    /// Cap lint level specified by a driver specifically.
478    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
479
480    /// Tracks the current behavior of the CTFE engine when an error occurs.
481    /// Options range from returning the error without a backtrace to returning an error
482    /// and immediately printing the backtrace to stderr.
483    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
484    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
485    /// errors.
486    pub ctfe_backtrace: Lock<CtfeBacktrace>,
487
488    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
489    /// const check, optionally with the relevant feature gate. We use this to
490    /// warn about unleashing, but with a single diagnostic instead of dozens that
491    /// drown everything else in noise.
492    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
493
494    /// Architecture to use for interpreting asm!.
495    pub asm_arch: Option<InlineAsmArch>,
496
497    /// Set of actually enabled features for the current target, including ones that are not
498    /// in `cfg(target_feature)` because they are unstable or internal-only.
499    /// This is used by the compiler itself when it needs to know which target features are actually
500    /// going to be enabled in the backend (e.g. for knowing which registers inline asm can use).
501    pub internal_target_features: FxIndexSet<Symbol>,
502
503    /// The list of backend target features for this session. Not used by Rust itself because the
504    /// concrete feature names can be backend-specific. This is computed from the target's base
505    /// features, `-Ctarget-cpu`, `-Ctarget-feature`, and other flags that the current backend
506    /// models as target features (but that are not considered target features in Rust).
507    pub global_backend_features: Vec<String>,
508
509    /// The version of the rustc process, possibly including a commit hash and description.
510    pub cfg_version: &'static str,
511
512    /// The inner atomic value is set to true when a feature marked as `internal` is
513    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
514    /// internal features are wontfix, and they are usually the cause of the ICEs.
515    /// None signifies that this is not tracked.
516    pub using_internal_features: &'static AtomicBool,
517
518    /// Environment variables accessed during the build and their values when they exist.
519    pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
520
521    /// File paths accessed during the build.
522    pub file_depinfo: Lock<FxIndexSet<Symbol>>,
523
524    target_filesearch: Arc<FileSearch>,
525    host_filesearch: Arc<FileSearch>,
526    wasm_proc_macro_filesearch: Option<Arc<FileSearch>>,
527
528    /// A list of all intrinsics that the current codegen backend definitely replaces with its own
529    /// implementations, which means their fallback bodies do not need to be monomorphized.
530    pub replaced_intrinsics: FxHashSet<Symbol>,
531
532    /// A list of all intrinsics that the current codegen backend definitely does *not* replace
533    /// with its own implementations, which means their fallback bodies can be MIR-inlined.
534    pub fallback_intrinsics: FxHashSet<Symbol>,
535
536    /// Does the codegen backend support ThinLTO?
537    pub thin_lto_supported: bool,
538
539    /// Global per-session counter for MIR optimization pass applications.
540    ///
541    /// Used by `-Zmir-opt-bisect-limit` to assign an index to each
542    /// optimization-pass execution candidate during this compilation.
543    pub mir_opt_bisect_eval_count: AtomicUsize,
544
545    /// Whether the test harness removed a user-written `#[rustc_main]` attribute
546    /// while generating the synthetic test entry point.
547    pub removed_rustc_main_attr: AtomicBool,
548
549    /// Config specifying targets' pointer authentication preference.
550    pub pointer_auth_config: Option<PointerAuthConfig>,
551
552    /// Cached sanitizer set. Cached because it is accessed frequently.
553    sanitizers: SanitizerSet,
554}
555
556impl Deref for Session {
557    type Target = EarlySession;
558
559    fn deref(&self) -> &EarlySession {
560        &self.early_sess
561    }
562}
563
564impl DerefMut for Session {
565    fn deref_mut(&mut self) -> &mut EarlySession {
566        &mut self.early_sess
567    }
568}
569
570#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CodegenUnits { }
#[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)]
571pub enum CodegenUnits {
572    /// Specified by the user. In this case we try fairly hard to produce the
573    /// number of CGUs requested.
574    User(usize),
575
576    /// A default value, i.e. not specified by the user. In this case we take
577    /// more liberties about CGU formation, e.g. avoid producing very small
578    /// CGUs.
579    Default(usize),
580}
581
582impl CodegenUnits {
583    pub fn as_usize(self) -> usize {
584        match self {
585            CodegenUnits::User(n) => n,
586            CodegenUnits::Default(n) => n,
587        }
588    }
589}
590
591pub struct LintGroup {
592    pub name: &'static str,
593    pub lints: Vec<LintId>,
594    pub is_externally_loaded: bool,
595}
596
597impl Session {
598    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
599        self.miri_unleashed_features.lock().push((span, feature_gate));
600    }
601
602    pub fn local_crate_source_file(&self) -> Option<RealFileName> {
603        Some(
604            self.source_map()
605                .path_mapping()
606                .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
607        )
608    }
609
610    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
611        let mut guar = None;
612        let unleashed_features = self.miri_unleashed_features.lock();
613        if !unleashed_features.is_empty() {
614            let mut must_err = false;
615            // Create a diagnostic pointing at where things got unleashed.
616            self.dcx().emit_warn(diagnostics::SkippingConstChecks {
617                unleashed_features: unleashed_features
618                    .iter()
619                    .map(|(span, gate)| {
620                        gate.map(|gate| {
621                            must_err = true;
622                            diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
623                        })
624                        .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
625                    })
626                    .collect(),
627            });
628
629            // If we should err, make sure we did.
630            if must_err && self.dcx().has_errors().is_none() {
631                // We have skipped a feature gate, and not run into other errors... reject.
632                guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
633            }
634        }
635        guar
636    }
637
638    /// Invoked all the way at the end to finish off diagnostics printing.
639    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
640        let mut guar = None;
641        guar = guar.or(self.check_miri_unleashed_features());
642        guar = guar.or(self.dcx().emit_stashed_diagnostics());
643        self.dcx().print_error_count();
644        if self.opts.json_future_incompat {
645            self.dcx().emit_future_breakage_report();
646        }
647        guar
648    }
649
650    /// Returns true if the crate is a testing one.
651    pub fn is_test_crate(&self) -> bool {
652        self.opts.test
653    }
654
655    /// `feature` must be a language feature.
656    #[track_caller]
657    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
658        let mut err = self.dcx().create_err(err);
659        if err.code.is_none() {
660            err.code(E0658);
661        }
662        diagnostics::add_feature_diagnostics(&mut err, self, feature);
663        err
664    }
665
666    /// Record the fact that we called `trimmed_def_paths`, and do some
667    /// checking about whether its cost was justified.
668    pub fn record_trimmed_def_paths(&self) {
669        if self.opts.unstable_opts.print_type_sizes
670            || self.opts.unstable_opts.query_dep_graph
671            || self.opts.unstable_opts.dump_mir.is_some()
672            || self.opts.unstable_opts.unpretty.is_some()
673            || self.prof.is_args_recording_enabled()
674            || self.opts.output_types.contains_key(&OutputType::Mir)
675            || std::env::var_os("RUSTC_LOG").is_some()
676        {
677            return;
678        }
679
680        self.dcx().set_must_produce_diag()
681    }
682
683    pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
684        // This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for
685        // AppendOnlyVec, so we resort to this scheme.
686        self.proc_macro_quoted_spans.iter_enumerated()
687    }
688
689    pub fn save_proc_macro_span(&self, span: Span) -> usize {
690        self.proc_macro_quoted_spans.push(span)
691    }
692
693    /// Returns `true` if internal lints should be added to the lint store - i.e. if
694    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
695    /// to be emitted under rustdoc).
696    pub fn enable_internal_lints(&self) -> bool {
697        self.unstable_options() && !self.opts.actually_rustdoc
698    }
699
700    pub fn instrument_coverage(&self) -> bool {
701        self.opts.cg.instrument_coverage() != InstrumentCoverage::No
702    }
703
704    pub fn instrument_coverage_branch(&self) -> bool {
705        self.instrument_coverage()
706            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
707    }
708
709    pub fn instrument_coverage_condition(&self) -> bool {
710        self.instrument_coverage()
711            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
712    }
713
714    /// Provides direct access to the `CoverageOptions` struct, so that
715    /// individual flags for debugging/testing coverage instrumetation don't
716    /// need separate accessors.
717    pub fn coverage_options(&self) -> &CoverageOptions {
718        &self.opts.unstable_opts.coverage_options
719    }
720
721    pub fn is_sanitizer_cfi_enabled(&self) -> bool {
722        self.sanitizers().contains(SanitizerSet::CFI)
723    }
724
725    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
726        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
727    }
728
729    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
730        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
731    }
732
733    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
734        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
735    }
736
737    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
738        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
739    }
740
741    pub fn is_sanitizer_cfi_recover_enabled(&self) -> bool {
742        self.opts.unstable_opts.sanitizer_cfi_recover == Some(true)
743    }
744
745    pub fn is_sanitizer_cfi_diag_enabled(&self) -> bool {
746        self.opts.unstable_opts.sanitizer_cfi_diag == Some(true)
747    }
748
749    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
750        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
751    }
752
753    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
754        self.sanitizers().contains(SanitizerSet::KCFI)
755    }
756
757    pub fn is_split_lto_unit_enabled(&self) -> bool {
758        self.opts.unstable_opts.split_lto_unit == Some(true)
759    }
760
761    /// Check whether this compile session and crate type use static crt.
762    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
763        if !self.target.crt_static_respected {
764            // If the target does not opt in to crt-static support, use its default.
765            return self.target.crt_static_default;
766        }
767
768        let requested_features = self.opts.cg.target_feature.split(',');
769        let found_negative = requested_features.clone().any(|r| r == "-crt-static");
770        let found_positive = requested_features.clone().any(|r| r == "+crt-static");
771
772        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
773        #[allow(rustc::bad_opt_access)]
774        if found_positive || found_negative {
775            found_positive
776        } else if crate_type == Some(CrateType::ProcMacro)
777            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
778        {
779            // FIXME: When crate_type is not available,
780            // we use compiler options to determine the crate_type.
781            // We can't check `#![crate_type = "proc-macro"]` here.
782            false
783        } else {
784            self.target.crt_static_default
785        }
786    }
787
788    pub fn is_wasi_reactor(&self) -> bool {
789        self.target.options.os == Os::Wasi
790            && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
    {
    Some(config::WasiExecModel::Reactor) => true,
    _ => false,
}matches!(
791                self.opts.unstable_opts.wasi_exec_model,
792                Some(config::WasiExecModel::Reactor)
793            )
794    }
795
796    /// Returns `true` if the target can use the current split debuginfo configuration.
797    pub fn target_can_use_split_dwarf(&self) -> bool {
798        self.target.debuginfo_kind == DebuginfoKind::Dwarf
799    }
800
801    pub fn target_filesearch(&self) -> &filesearch::FileSearch {
802        &self.target_filesearch
803    }
804    pub fn host_filesearch(&self) -> &filesearch::FileSearch {
805        &self.host_filesearch
806    }
807    pub fn wasm_proc_macro_filesearch(&self) -> &filesearch::FileSearch {
808        self.wasm_proc_macro_filesearch.as_ref().expect("wasm_filesearch not set")
809    }
810
811    /// Returns a list of directories where target-specific tool binaries are located. Some fallback
812    /// directories are also returned, for example if `--sysroot` is used but tools are missing
813    /// (#125246): we also add the bin directories to the sysroot where rustc is located.
814    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
815        let search_paths = self
816            .opts
817            .sysroot
818            .all_paths()
819            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
820
821        if self_contained {
822            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the
823            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the
824            // fallback paths.
825            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
826        } else {
827            search_paths.collect()
828        }
829    }
830
831    /// Is this edition 2015?
832    pub fn is_rust_2015(&self) -> bool {
833        self.edition().is_rust_2015()
834    }
835
836    /// Are we allowed to use features from the Rust 2018 edition?
837    pub fn at_least_rust_2018(&self) -> bool {
838        self.edition().at_least_rust_2018()
839    }
840
841    /// Are we allowed to use features from the Rust 2021 edition?
842    pub fn at_least_rust_2021(&self) -> bool {
843        self.edition().at_least_rust_2021()
844    }
845
846    /// Are we allowed to use features from the Rust 2024 edition?
847    pub fn at_least_rust_2024(&self) -> bool {
848        self.edition().at_least_rust_2024()
849    }
850
851    /// Returns `true` if we should use the PLT for shared library calls.
852    pub fn needs_plt(&self) -> bool {
853        // Check if the current target usually wants PLT to be enabled.
854        // The user can use the command line flag to override it.
855        let want_plt = self.target.plt_by_default;
856
857        let dbg_opts = &self.opts.unstable_opts;
858
859        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
860
861        // Only enable this optimization by default if full relro is also enabled.
862        // In this case, lazy binding was already unavailable, so nothing is lost.
863        // This also ensures `-Wl,-z,now` is supported by the linker.
864        let full_relro = RelroLevel::Full == relro_level;
865
866        // If user didn't explicitly forced us to use / skip the PLT,
867        // then use it unless the target doesn't want it by default or the full relro forces it on.
868        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
869    }
870
871    /// Checks if LLVM lifetime markers should be emitted.
872    pub fn emit_lifetime_markers(&self) -> bool {
873        self.opts.optimize != config::OptLevel::No
874        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
875        //
876        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
877        //
878        // HWAddressSanitizer and KernelHWAddressSanitizer will use lifetimes to detect use after
879        // scope bugs in the future.
880        || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
881        // Lifetimes are necessary for retagging semantics.
882        || self.opts.unstable_opts.codegen_emit_retag.is_some()
883    }
884
885    pub fn diagnostic_width(&self) -> usize {
886        let default_column_width = 140;
887        if let Some(width) = self.opts.diagnostic_width {
888            width
889        } else if self.opts.unstable_opts.ui_testing {
890            default_column_width
891        } else {
892            termize::dimensions().map_or(default_column_width, |(w, _)| w)
893        }
894    }
895
896    /// Returns the default symbol visibility.
897    pub fn default_visibility(&self) -> SymbolVisibility {
898        self.opts
899            .unstable_opts
900            .default_visibility
901            .or(self.target.options.default_visibility)
902            .unwrap_or(SymbolVisibility::Interposable)
903    }
904
905    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
906        if verbatim {
907            ("", "")
908        } else {
909            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
910        }
911    }
912
913    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
914        match self.lint_store {
915            Some(ref lint_store) => lint_store.lint_groups_iter(),
916            None => Box::new(std::iter::empty()),
917        }
918    }
919
920    /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
921    ///
922    /// This unifies the logic used for resolving `include_*!` and debugger visualizers.
923    pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PResult<'_, PathBuf> {
924        let path = path.into();
925
926        // Relative paths are resolved relative to the file in which they are found
927        // after macro expansion (that is, they are unhygienic).
928        if !path.is_absolute() {
929            let callsite = span.source_callsite();
930            let source_map = self.source_map();
931            let Some(mut base_path) = source_map.span_to_filename(callsite).into_local_path()
932            else {
933                return Err(self.dcx().create_err(diagnostics::ResolveRelativePath {
934                    span,
935                    path: source_map
936                        .filename_for_diagnostics(&source_map.span_to_filename(callsite))
937                        .to_string(),
938                }));
939            };
940            base_path.pop();
941            base_path.push(path);
942            Ok(base_path)
943        } else {
944            // This ensures that Windows verbatim paths are fixed if mixed path separators are used,
945            // which can happen when `concat!` is used to join paths.
946            match path.components().next() {
947                Some(Prefix(prefix)) if prefix.kind().is_verbatim() => {
948                    Ok(path.components().collect())
949                }
950                _ => Ok(path),
951            }
952        }
953    }
954}
955
956// JUSTIFICATION: defn of the suggested wrapper fns
957#[allow(rustc::bad_opt_access)]
958impl Session {
959    pub fn verbose_internals(&self) -> bool {
960        self.opts.unstable_opts.verbose_internals
961    }
962
963    pub fn verify_llvm_ir(&self) -> bool {
964        self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
965    }
966
967    pub fn binary_dep_depinfo(&self) -> bool {
968        self.opts.unstable_opts.binary_dep_depinfo
969    }
970
971    pub fn mir_opt_level(&self) -> usize {
972        self.opts.unstable_opts.mir_opt_level.unwrap_or_else(|| self.opts.optimize.mir_opt_level())
973    }
974
975    /// Calculates the flavor of LTO to use for this compilation.
976    pub fn lto(&self) -> config::Lto {
977        // If our target has codegen requirements ignore the command line
978        if self.target.requires_lto {
979            return config::Lto::Fat;
980        }
981
982        // If the user specified something, return that. If they only said `-C
983        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
984        // then ensure we can't use a ThinLTO.
985        match self.opts.cg.lto {
986            config::LtoCli::Unspecified => {
987                // The compiler was invoked without the `-Clto` flag. Fall
988                // through to the default handling
989            }
990            config::LtoCli::No => {
991                // The user explicitly opted out of any kind of LTO
992                return config::Lto::No;
993            }
994            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
995                // All of these mean fat LTO
996                return config::Lto::Fat;
997            }
998            config::LtoCli::Thin => {
999                // The user explicitly asked for ThinLTO
1000                if !self.thin_lto_supported {
1001                    // Backend doesn't support ThinLTO, fallback to fat LTO.
1002                    self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
1003                    return config::Lto::Fat;
1004                }
1005                return config::Lto::Thin;
1006            }
1007        }
1008
1009        if !self.thin_lto_supported {
1010            return config::Lto::No;
1011        }
1012
1013        // Ok at this point the target doesn't require anything and the user
1014        // hasn't asked for anything. Our next decision is whether or not
1015        // we enable "auto" ThinLTO where we use multiple codegen units and
1016        // then do ThinLTO over those codegen units. The logic below will
1017        // either return `No` or `ThinLocal`.
1018
1019        // If processing command line options determined that we're incompatible
1020        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
1021        if self.opts.cli_forced_local_thinlto_off {
1022            return config::Lto::No;
1023        }
1024
1025        // If `-Z thinlto` specified process that, but note that this is mostly
1026        // a deprecated option now that `-C lto=thin` exists.
1027        if let Some(enabled) = self.opts.unstable_opts.thinlto {
1028            if enabled {
1029                return config::Lto::ThinLocal;
1030            } else {
1031                return config::Lto::No;
1032            }
1033        }
1034
1035        // If there's only one codegen unit and LTO isn't enabled then there's
1036        // no need for ThinLTO so just return false.
1037        if self.codegen_units().as_usize() == 1 {
1038            return config::Lto::No;
1039        }
1040
1041        // Now we're in "defaults" territory. By default we enable ThinLTO for
1042        // optimized compiles (anything greater than O0).
1043        match self.opts.optimize {
1044            config::OptLevel::No => config::Lto::No,
1045            _ => config::Lto::ThinLocal,
1046        }
1047    }
1048
1049    pub fn fewer_names(&self) -> bool {
1050        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1051            fewer_names
1052        } else {
1053            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1054                || self.opts.output_types.contains_key(&OutputType::Bitcode)
1055                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1056                || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1057            !more_names
1058        }
1059    }
1060
1061    pub fn unstable_options(&self) -> bool {
1062        self.opts.unstable_opts.unstable_options
1063    }
1064
1065    pub fn is_nightly_build(&self) -> bool {
1066        self.opts.unstable_features.is_nightly_build()
1067    }
1068
1069    pub fn overflow_checks(&self) -> bool {
1070        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1071    }
1072
1073    pub fn ub_checks(&self) -> bool {
1074        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
1075    }
1076
1077    pub fn contract_checks(&self) -> bool {
1078        self.opts.unstable_opts.contract_checks.unwrap_or(false)
1079    }
1080
1081    pub fn direct_access_external_data(&self) -> Option<bool> {
1082        self.opts
1083            .unstable_opts
1084            .direct_access_external_data
1085            .or(self.target.direct_access_external_data)
1086    }
1087
1088    pub fn split_debuginfo(&self) -> SplitDebuginfo {
1089        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1090    }
1091
1092    /// Returns the DWARF version passed on the CLI or the default for the target.
1093    pub fn dwarf_version(&self) -> u32 {
1094        self.opts
1095            .cg
1096            .dwarf_version
1097            .or(self.opts.unstable_opts.dwarf_version)
1098            .unwrap_or(self.target.default_dwarf_version)
1099    }
1100
1101    pub fn stack_protector(&self) -> StackProtector {
1102        if self.target.options.supports_stack_protector {
1103            self.opts.unstable_opts.stack_protector
1104        } else {
1105            StackProtector::None
1106        }
1107    }
1108
1109    /// Returns the `-Zbranch-protection` info. Note that it is adjusted to the current target, e.g.
1110    /// some targets only support certain Pointer Authentication Code keys.
1111    ///
1112    /// Accessing the session's unstable `branch_protection` option fields directly is linted
1113    /// against.
1114    pub fn branch_protection(&self) -> Option<BranchProtection> {
1115        let mut bp = self.opts.unstable_opts.branch_protection;
1116
1117        if let Some(bp) = bp.as_mut() {
1118            // Windows on Arm only supports PAC Key B for return address signing, as shown in
1119            // https://github.com/llvm/llvm-project/pull/203989. We parse the CLI flags for branch
1120            // protection and target separately though, so we adjust this possible discrepancy here.
1121            if self.target.os == Os::Windows && self.target.arch == Arch::AArch64 {
1122                if let Some(pac_ret) = bp.pac_ret.as_mut()
1123                    && pac_ret.key == PAuthKey::A
1124                {
1125                    pac_ret.key = PAuthKey::B;
1126                }
1127            }
1128        }
1129
1130        bp
1131    }
1132
1133    pub fn must_emit_unwind_tables(&self) -> bool {
1134        // This is used to control the emission of the `uwtable` attribute on
1135        // LLVM functions. The `uwtable` attribute according to LLVM is:
1136        //
1137        //     This attribute indicates that the ABI being targeted requires that an
1138        //     unwind table entry be produced for this function even if we can show
1139        //     that no exceptions passes by it. This is normally the case for the
1140        //     ELF x86-64 abi, but it can be disabled for some compilation units.
1141        //
1142        // Typically when we're compiling with `-C panic=abort` we don't need
1143        // `uwtable` because we can't generate any exceptions! But note that
1144        // some targets require unwind tables to generate backtraces.
1145        // Unwind tables are needed when compiling with `-C panic=unwind`, but
1146        // LLVM won't omit unwind tables unless the function is also marked as
1147        // `nounwind`, so users are allowed to disable `uwtable` emission.
1148        // Historically rustc always emits `uwtable` attributes by default, so
1149        // even they can be disabled, they're still emitted by default.
1150        //
1151        // On some targets (including windows), however, exceptions include
1152        // other events such as illegal instructions, segfaults, etc. This means
1153        // that on Windows we end up still needing unwind tables even if the `-C
1154        // panic=abort` flag is passed.
1155        //
1156        // You can also find more info on why Windows needs unwind tables in:
1157        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1158        //
1159        // If a target requires unwind tables, then they must be emitted.
1160        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1161        // value, if it is provided, or disable them, if not.
1162        self.target.requires_uwtable
1163            || self
1164                .opts
1165                .cg
1166                .force_unwind_tables
1167                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
1168    }
1169
1170    /// Returns the number of codegen units that should be used for this
1171    /// compilation
1172    pub fn codegen_units(&self) -> CodegenUnits {
1173        if let Some(n) = self.opts.cli_forced_codegen_units {
1174            return CodegenUnits::User(n);
1175        }
1176        if let Some(n) = self.target.default_codegen_units {
1177            return CodegenUnits::Default(n as usize);
1178        }
1179
1180        // If incremental compilation is turned on, we default to a high number
1181        // codegen units in order to reduce the "collateral damage" small
1182        // changes cause.
1183        if self.opts.incremental.is_some() {
1184            return CodegenUnits::Default(256);
1185        }
1186
1187        // Why is 16 codegen units the default all the time?
1188        //
1189        // The main reason for enabling multiple codegen units by default is to
1190        // leverage the ability for the codegen backend to do codegen and
1191        // optimization in parallel. This allows us, especially for large crates, to
1192        // make good use of all available resources on the machine once we've
1193        // hit that stage of compilation. Large crates especially then often
1194        // take a long time in codegen/optimization and this helps us amortize that
1195        // cost.
1196        //
1197        // Note that a high number here doesn't mean that we'll be spawning a
1198        // large number of threads in parallel. The backend of rustc contains
1199        // global rate limiting through the `jobserver` crate so we'll never
1200        // overload the system with too much work, but rather we'll only be
1201        // optimizing when we're otherwise cooperating with other instances of
1202        // rustc.
1203        //
1204        // Rather a high number here means that we should be able to keep a lot
1205        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1206        // to build we'll be guaranteed that all cpus will finish pretty closely
1207        // to one another and we should make relatively optimal use of system
1208        // resources
1209        //
1210        // Note that the main cost of codegen units is that it prevents LLVM
1211        // from inlining across codegen units. Users in general don't have a lot
1212        // of control over how codegen units are split up so it's our job in the
1213        // compiler to ensure that undue performance isn't lost when using
1214        // codegen units (aka we can't require everyone to slap `#[inline]` on
1215        // everything).
1216        //
1217        // If we're compiling at `-O0` then the number doesn't really matter too
1218        // much because performance doesn't matter and inlining is ok to lose.
1219        // In debug mode we just want to try to guarantee that no cpu is stuck
1220        // doing work that could otherwise be farmed to others.
1221        //
1222        // In release mode, however (O1 and above) performance does indeed
1223        // matter! To recover the loss in performance due to inlining we'll be
1224        // enabling ThinLTO by default (the function for which is just below).
1225        // This will ensure that we recover any inlining wins we otherwise lost
1226        // through codegen unit partitioning.
1227        //
1228        // ---
1229        //
1230        // Ok that's a lot of words but the basic tl;dr; is that we want a high
1231        // number here -- but not too high. Additionally we're "safe" to have it
1232        // always at the same number at all optimization levels.
1233        //
1234        // As a result 16 was chosen here! Mostly because it was a power of 2
1235        // and most benchmarks agreed it was roughly a local optimum. Not very
1236        // scientific.
1237        CodegenUnits::Default(16)
1238    }
1239
1240    pub fn teach(&self, code: ErrCode) -> bool {
1241        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
1242    }
1243
1244    pub fn edition(&self) -> Edition {
1245        self.opts.edition
1246    }
1247
1248    pub fn link_dead_code(&self) -> bool {
1249        self.opts.cg.link_dead_code.unwrap_or(false)
1250    }
1251
1252    pub fn sanitizers(&self) -> SanitizerSet {
1253        self.sanitizers
1254    }
1255
1256    pub fn pointer_authentication(&self) -> bool {
1257        self.pointer_auth_config.is_some()
1258    }
1259
1260    pub fn pointer_authentication_functions(&self) -> Option<&PointerAuthSchema> {
1261        self.pointer_auth_config.as_ref().and_then(|cfg| cfg.function_pointers.as_ref())
1262    }
1263
1264    pub fn pointer_authentication_init_fini(&self) -> Option<&PointerAuthSchema> {
1265        self.pointer_auth_config.as_ref().and_then(|cfg| cfg.init_fini.as_ref())
1266    }
1267}
1268
1269// JUSTIFICATION: part of session construction
1270#[allow(rustc::bad_opt_access)]
1271fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
1272    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1273    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1274    let terminal_url = match sopts.unstable_opts.terminal_urls {
1275        TerminalUrl::Auto => {
1276            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
1277                (Ok("truecolor"), Ok("xterm-256color"))
1278                    if sopts.unstable_features.is_nightly_build() =>
1279                {
1280                    TerminalUrl::Yes
1281                }
1282                _ => TerminalUrl::No,
1283            }
1284        }
1285        t => t,
1286    };
1287
1288    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1289
1290    match sopts.error_format {
1291        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1292            HumanReadableErrorType { short, unicode } => {
1293                let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
1294                    .sm(source_map)
1295                    .short_message(short)
1296                    .diagnostic_width(sopts.diagnostic_width)
1297                    .macro_backtrace(macro_backtrace)
1298                    .track_diagnostics(track_diagnostics)
1299                    .terminal_url(terminal_url)
1300                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1301                    .ignored_directories_in_source_blocks(
1302                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1303                    );
1304                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1305            }
1306        },
1307        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1308            JsonEmitter::new(
1309                Box::new(io::BufWriter::new(io::stderr())),
1310                source_map,
1311                pretty,
1312                json_rendered,
1313                color_config,
1314            )
1315            .ui_testing(sopts.unstable_opts.ui_testing)
1316            .ignored_directories_in_source_blocks(
1317                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1318            )
1319            .diagnostic_width(sopts.diagnostic_width)
1320            .macro_backtrace(macro_backtrace)
1321            .track_diagnostics(track_diagnostics)
1322            .terminal_url(terminal_url),
1323        ),
1324    }
1325}
1326
1327// JUSTIFICATION: literally session construction
1328#[allow(rustc::bad_opt_access)]
1329pub fn build_early_session(
1330    sopts: config::Options,
1331    target: Target,
1332    ice_file: Option<PathBuf>,
1333) -> EarlySession {
1334    // FIXME: This is not general enough to make the warning lint completely override
1335    // normal diagnostic warnings, since the warning lint can also be denied and changed
1336    // later via the source code.
1337    let warnings_allow = sopts
1338        .lint_opts
1339        .iter()
1340        .rfind(|&(key, _)| *key == "warnings")
1341        .is_some_and(|&(_, level)| level == lint::Allow);
1342    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1343    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1344
1345    let source_map = rustc_span::source_map::get_source_map().unwrap();
1346    let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1347
1348    let mut dcx =
1349        DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1350    if let Some(ice_file) = ice_file {
1351        dcx = dcx.with_ice_file(ice_file);
1352    }
1353
1354    if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1355        dcx = dcx.with_msrv(msrv);
1356    }
1357
1358    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1359    let (host, target_warnings) =
1360        Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1361            .unwrap_or_else(|e| {
1362                dcx.handle().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading host specification: {0}",
                e))
    })format!("Error loading host specification: {e}"))
1363            });
1364    for warning in target_warnings.warning_messages() {
1365        dcx.handle().warn(warning)
1366    }
1367
1368    let psess = ParseSess::with_dcx(dcx, source_map);
1369
1370    EarlySession { target, host, opts: sopts, psess }
1371}
1372
1373// JUSTIFICATION: literally session construction
1374#[allow(rustc::bad_opt_access)]
1375pub fn build_session(
1376    early_sess: EarlySession,
1377    codegen_backend_init: CodegenBackendInit,
1378    io: CompilerIO,
1379    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1380    cfg_version: &'static str,
1381    using_internal_features: &'static AtomicBool,
1382) -> Session {
1383    let EarlySession { target, host, opts: sopts, psess } = &early_sess;
1384    let dcx = psess.dcx();
1385
1386    let wasm_proc_macro_tuple = TargetTuple::from_tuple("wasm32-wasip2");
1387    let (wasm_proc_macro_target, target_warnings) = Target::search(
1388        &wasm_proc_macro_tuple,
1389        sopts.sysroot.path(),
1390        sopts.unstable_opts.unstable_options,
1391    )
1392    .unwrap_or_else(|e| {
1393        dcx.fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Error loading wasm proc-macro target specification: {0}",
                e))
    })format!("Error loading wasm proc-macro target specification: {e}"))
1394    });
1395    for warning in target_warnings.warning_messages() {
1396        dcx.warn(warning)
1397    }
1398
1399    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1400    {
1401        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1402
1403        let profiler = SelfProfiler::new(
1404            directory,
1405            sopts.crate_name.as_deref(),
1406            sopts.unstable_opts.self_profile_events.as_deref(),
1407            &sopts.unstable_opts.self_profile_counter,
1408        );
1409        match profiler {
1410            Ok(profiler) => Some(Arc::new(profiler)),
1411            Err(e) => {
1412                dcx.emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1413                None
1414            }
1415        }
1416    } else {
1417        None
1418    };
1419
1420    let host_triple = config::host_tuple();
1421    let target_triple = sopts.target_triple.tuple();
1422    // FIXME use host sysroot?
1423    let host_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple);
1424    let target_tlib_path = SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple);
1425    let wasm_proc_macro_tlib_path =
1426        SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), wasm_proc_macro_tuple.tuple());
1427
1428    let prof = SelfProfilerRef::new(
1429        self_profiler,
1430        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1431    );
1432
1433    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1434        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1435        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1436        _ => CtfeBacktrace::Disabled,
1437    });
1438
1439    let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1440    let target_filesearch = Arc::new(filesearch::FileSearch::new(
1441        &sopts.search_paths,
1442        &target_tlib_path,
1443        &target,
1444        sopts.unstable_opts.implicit_sysroot_deps,
1445    ));
1446    let host_filesearch = if target == host {
1447        Arc::clone(&target_filesearch)
1448    } else {
1449        Arc::new(filesearch::FileSearch::new(
1450            &sopts.search_paths,
1451            &host_tlib_path,
1452            &host,
1453            sopts.unstable_opts.implicit_sysroot_deps,
1454        ))
1455    };
1456    let wasm_proc_macro_filesearch = if sopts.unstable_opts.wasm_proc_macros {
1457        Some(Arc::new(FileSearch::new(
1458            &sopts.search_paths,
1459            &wasm_proc_macro_tlib_path,
1460            &wasm_proc_macro_target,
1461            sopts.unstable_opts.implicit_sysroot_deps,
1462        )))
1463    } else {
1464        None
1465    };
1466
1467    let timings = TimingSectionHandler::new(sopts.json_timings);
1468
1469    let pointer_auth_config: Option<PointerAuthConfig> =
1470        PointerAuthConfig::from_raw(&sopts.unstable_opts.pointer_authentication, &target);
1471
1472    // `EarlySess::sanitizers` does some computation but is called infrequently. `Sess::sanitizers`
1473    // is called much more often so we cache the value.
1474    let sanitizers = early_sess.sanitizers();
1475
1476    let CodegenBackendInit {
1477        global_backend_features,
1478        replaced_intrinsics,
1479        fallback_intrinsics,
1480        thin_lto_supported,
1481    } = codegen_backend_init;
1482
1483    let sess = Session {
1484        early_sess,
1485        wasm_proc_macro_tuple,
1486        wasm_proc_macro_target,
1487        target_tlib_path,
1488        unstable_features: UnstableFeatures::from_environment(None),
1489        config: Cfg::default(),
1490        check_config: CheckCfg::default(),
1491        proc_macro_quoted_spans: Default::default(),
1492        io,
1493        prof,
1494        timings,
1495        code_stats: Default::default(),
1496        lint_store: None,
1497        driver_lint_caps,
1498        ctfe_backtrace,
1499        miri_unleashed_features: Lock::new(Default::default()),
1500        asm_arch,
1501        internal_target_features: Default::default(),
1502        global_backend_features,
1503        cfg_version,
1504        using_internal_features,
1505        env_depinfo: Default::default(),
1506        file_depinfo: Default::default(),
1507        target_filesearch,
1508        host_filesearch,
1509        wasm_proc_macro_filesearch,
1510        replaced_intrinsics: FxHashSet::from_iter(replaced_intrinsics),
1511        fallback_intrinsics: FxHashSet::from_iter(fallback_intrinsics),
1512        thin_lto_supported,
1513        mir_opt_bisect_eval_count: AtomicUsize::new(0),
1514        removed_rustc_main_attr: AtomicBool::new(false),
1515        pointer_auth_config,
1516        sanitizers,
1517    };
1518
1519    validate_commandline_args_with_session_available(&sess);
1520
1521    sess
1522}
1523
1524pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1525    ::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())
1526}
1527
1528/// Validate command line arguments with a `Session`.
1529///
1530/// If it is useful to have a Session available already for validating a commandline argument, you
1531/// can do so here.
1532// JUSTIFICATION: needs to access args to validate them
1533#[allow(rustc::bad_opt_access)]
1534fn validate_commandline_args_with_session_available(sess: &Session) {
1535    // Since we don't know if code in an rlib will be linked to statically or
1536    // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1537    // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1538    // these manually generated symbols confuse LLD when it tries to merge
1539    // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1540    // when compiling for LLD ThinLTO. This way we can validly just not generate
1541    // the `dllimport` attributes and `__imp_` symbols in that case.
1542    if sess.opts.cg.linker_plugin_lto.enabled()
1543        && sess.opts.cg.prefer_dynamic
1544        && sess.target.is_like_windows
1545    {
1546        sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1547    }
1548
1549    if sess
1550        .pointer_auth_config
1551        .as_ref()
1552        .and_then(|cfg| cfg.function_pointers.as_ref())
1553        .is_some_and(|schema| #[allow(non_exhaustive_omitted_patterns)] match schema.discrimination_kind {
    PointerAuthDiscrimination::Type => true,
    _ => false,
}matches!(schema.discrimination_kind, PointerAuthDiscrimination::Type))
1554    {
1555        sess.dcx().emit_err(
1556            diagnostics::PointerAuthenticationTypeDiscriminationNotSupportedForTarget {
1557                target_triple: &sess.opts.target_triple,
1558            },
1559        );
1560    }
1561
1562    if sess.target.cfg_abi != CfgAbi::Pauthtest
1563        && !sess.opts.unstable_opts.pointer_authentication.is_empty()
1564    {
1565        sess.dcx().emit_warn(diagnostics::PointerAuthenticationNotSupportedForTarget {
1566            target_triple: &sess.opts.target_triple,
1567        });
1568    }
1569
1570    // Make sure that any given profiling data actually exists so LLVM can't
1571    // decide to silently skip PGO.
1572    if let Some(ref path) = sess.opts.cg.profile_use {
1573        if !path.exists() {
1574            sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1575        }
1576    }
1577
1578    // Do the same for sample profile data.
1579    if let Some(ref path) = sess.opts.cg.profile_sample_use {
1580        if !path.exists() {
1581            sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1582        }
1583    }
1584
1585    // Unwind tables cannot be disabled if the target requires them.
1586    if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1587        if sess.target.requires_uwtable && !include_uwtables {
1588            sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1589        }
1590    }
1591
1592    // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1593    let supported_sanitizers = sess.target.options.supported_sanitizers;
1594    let mut unsupported_sanitizers = sess.sanitizers() - supported_sanitizers;
1595    // Niche: if `fixed-x18`, or effectively switching on `reserved-x18` flag, is enabled
1596    // we should allow Shadow Call Stack sanitizer.
1597    if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1598        unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1599    }
1600    match unsupported_sanitizers.into_iter().count() {
1601        0 => {}
1602        1 => {
1603            sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1604                us: unsupported_sanitizers.to_string(),
1605            });
1606        }
1607        _ => {
1608            sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1609                us: unsupported_sanitizers.to_string(),
1610            });
1611        }
1612    }
1613
1614    // Cannot mix and match mutually-exclusive sanitizers.
1615    if let Some((first, second)) = sess.sanitizers().mutually_exclusive() {
1616        sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1617            first: first.to_string(),
1618            second: second.to_string(),
1619        });
1620    }
1621
1622    // Cannot enable crt-static with sanitizers on Linux
1623    if sess.crt_static(None) && !sess.sanitizers().is_empty() && !sess.target.is_like_msvc {
1624        sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1625    }
1626
1627    // FIXME(jchlanda) Pauthtest does not support static linking. It must be dynamically linked,
1628    // with a dynamic linker acting as the ELF interpreter that can resolve pauth relocations and
1629    // enforce pointer authentication constraints.
1630    if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1631        sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1632    }
1633
1634    // LLVM CFI requires LTO.
1635    if sess.is_sanitizer_cfi_enabled()
1636        && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1637    {
1638        sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1639    }
1640
1641    // KCFI requires panic=abort
1642    if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1643        sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1644    }
1645
1646    // LLVM CFI using rustc LTO requires a single codegen unit.
1647    if sess.is_sanitizer_cfi_enabled()
1648        && sess.lto() == config::Lto::Fat
1649        && (sess.codegen_units().as_usize() != 1)
1650    {
1651        sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1652    }
1653
1654    // Canonical jump tables requires CFI.
1655    if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1656        if !sess.is_sanitizer_cfi_enabled() {
1657            sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1658        }
1659    }
1660
1661    // KCFI arity indicator requires KCFI.
1662    if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1663        sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1664    }
1665
1666    // LLVM CFI pointer generalization requires CFI or KCFI.
1667    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1668        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1669            sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1670        }
1671    }
1672
1673    // LLVM CFI recovery requires CFI.
1674    if sess.is_sanitizer_cfi_recover_enabled() {
1675        if !sess.is_sanitizer_cfi_enabled() {
1676            sess.dcx().emit_err(diagnostics::SanitizerCfiRecoverRequiresCfi);
1677        }
1678    }
1679
1680    // LLVM CFI diagnostics requires CFI.
1681    if sess.is_sanitizer_cfi_diag_enabled() {
1682        if !sess.is_sanitizer_cfi_enabled() {
1683            sess.dcx().emit_err(diagnostics::SanitizerCfiDiagRequiresCfi);
1684        }
1685    }
1686
1687    // LLVM CFI integer normalization requires CFI or KCFI.
1688    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1689        if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1690            sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1691        }
1692    }
1693
1694    // LTO unit splitting requires LTO.
1695    if sess.is_split_lto_unit_enabled()
1696        && !(sess.lto() == config::Lto::Fat
1697            || sess.lto() == config::Lto::Thin
1698            || sess.opts.cg.linker_plugin_lto.enabled())
1699    {
1700        sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1701    }
1702
1703    // VFE requires LTO.
1704    if sess.lto() != config::Lto::Fat {
1705        if sess.opts.unstable_opts.virtual_function_elimination {
1706            sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1707        }
1708    }
1709
1710    if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1711        if !sess.target.options.supports_stack_protector {
1712            sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1713                stack_protector: sess.opts.unstable_opts.stack_protector,
1714                target_triple: &sess.opts.target_triple,
1715            });
1716        }
1717    }
1718
1719    if sess.opts.unstable_opts.small_data_threshold.is_some() {
1720        if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1721            sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1722                target_triple: &sess.opts.target_triple,
1723            })
1724        }
1725    }
1726
1727    if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1728        sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1729    }
1730
1731    if let Some(dwarf_version) =
1732        sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1733    {
1734        // DWARF 1 is not supported by LLVM and DWARF 6 is not yet finalized.
1735        if dwarf_version < 2 || dwarf_version > 5 {
1736            sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1737        }
1738    }
1739
1740    if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1741        && !sess.opts.unstable_opts.unstable_options
1742    {
1743        sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1744            debuginfo: sess.split_debuginfo(),
1745        });
1746    }
1747
1748    if sess.opts.unstable_opts.embed_source {
1749        let dwarf_version = sess.dwarf_version();
1750
1751        if dwarf_version < 5 {
1752            sess.dcx()
1753                .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1754        }
1755
1756        if sess.opts.debuginfo == DebugInfo::None {
1757            sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1758        }
1759    }
1760
1761    if let InstrumentMcount::Fentry(opts) = sess.opts.unstable_opts.instrument_mcount {
1762        if !sess.target.options.supports_fentry {
1763            sess.dcx()
1764                .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1765        }
1766        if (opts.no_call || opts.record) && sess.target.arch != Arch::S390x {
1767            sess.dcx()
1768                .emit_err(diagnostics::InstrumentationNotSupported { us: "fentry-*".to_string() });
1769        }
1770    }
1771
1772    if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1773        sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1774    }
1775
1776    if let Some(flavor) = sess.opts.cg.linker_flavor
1777        && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1778    {
1779        let flavor = flavor.desc();
1780        sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1781    }
1782
1783    if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1784        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) {
1785            sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1786        }
1787    }
1788
1789    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1790        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) {
1791            sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1792        }
1793    }
1794
1795    if let Some(regparm) = sess.opts.unstable_opts.regparm {
1796        if regparm > 3 {
1797            sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1798        }
1799        if sess.target.arch != Arch::X86 {
1800            sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1801        }
1802    }
1803    if sess.opts.unstable_opts.reg_struct_return {
1804        if sess.target.arch != Arch::X86 {
1805            sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1806        }
1807    }
1808
1809    // The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1810    // kept as a `match` to force a change if new ones are added, even if we currently only support
1811    // `thunk-extern` like Clang.
1812    match sess.opts.unstable_opts.function_return {
1813        FunctionReturn::Keep => (),
1814        FunctionReturn::ThunkExtern => {
1815            // FIXME: In principle, the inherited base LLVM target code model could be large,
1816            // but this only checks whether we were passed one explicitly (like Clang does).
1817            if let Some(code_model) = sess.code_model()
1818                && code_model == CodeModel::Large
1819            {
1820                sess.dcx()
1821                    .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1822            }
1823        }
1824    }
1825
1826    if sess.opts.unstable_opts.packed_stack {
1827        if sess.target.arch != Arch::S390x {
1828            sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1829        }
1830    }
1831
1832    if let Some(ref cpu_name) = sess.opts.cg.target_cpu {
1833        if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu {
1834            sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed {
1835                target_triple: &sess.opts.target_triple,
1836                need_explicit_cpu: sess.target.need_explicit_cpu,
1837            });
1838        }
1839    }
1840}
1841
1842/// Holds data on the current incremental compilation session, if there is one.
1843pub struct IncrCompSession {
1844    /// The directory containing all cached data. Cached data from a previous
1845    /// session can be read out of it and new data for the current session will
1846    /// be written into it.
1847    pub session_directory: PathBuf,
1848    /// `_lock_file` is never directly used, but its presence
1849    /// alone has an effect, because the file will unlock when the session is
1850    /// dropped.
1851    pub _lock_file: flock::Lock,
1852}
1853
1854/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1855pub struct EarlyDiagCtxt {
1856    dcx: DiagCtxt,
1857}
1858
1859impl EarlyDiagCtxt {
1860    pub fn new(output: ErrorOutputType) -> Self {
1861        let emitter = mk_emitter(output);
1862        Self { dcx: DiagCtxt::new(emitter) }
1863    }
1864
1865    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1866    /// format. If `early_err` was previously called this will panic.
1867    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1868        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());
1869
1870        let emitter = mk_emitter(output);
1871        self.dcx = DiagCtxt::new(emitter);
1872    }
1873
1874    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1875    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1876        self.dcx.handle().err(msg)
1877    }
1878
1879    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1880        self.dcx.handle().fatal(msg)
1881    }
1882
1883    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1884        self.dcx.handle().struct_fatal(msg)
1885    }
1886
1887    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1888        self.dcx.handle().warn(msg)
1889    }
1890
1891    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1892        self.dcx.handle().struct_warn(msg)
1893    }
1894}
1895
1896fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1897    let emitter: Box<DynEmitter> = match output {
1898        config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1899            HumanReadableErrorType { short, unicode } => Box::new(
1900                AnnotateSnippetEmitter::new(stderr_destination(color_config))
1901                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1902                    .short_message(short),
1903            ),
1904        },
1905        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1906            Box::new(JsonEmitter::new(
1907                Box::new(io::BufWriter::new(io::stderr())),
1908                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1909                pretty,
1910                json_rendered,
1911                color_config,
1912            ))
1913        }
1914    };
1915    emitter
1916}