Skip to main content

rustc_session/
session.rs

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