Skip to main content

rustc_session/
session.rs

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