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