rustc_session/
session.rs

1use std::any::Any;
2use std::path::{Path, PathBuf};
3use std::str::FromStr;
4use std::sync::Arc;
5use std::sync::atomic::AtomicBool;
6use std::{env, io};
7
8use rand::{RngCore, rng};
9use rustc_ast::NodeId;
10use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
11use rustc_data_structures::flock;
12use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
13use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
14use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
15use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
16use rustc_errors::codes::*;
17use rustc_errors::emitter::{
18    DynEmitter, HumanEmitter, HumanReadableErrorType, OutputTheme, stderr_destination,
19};
20use rustc_errors::json::JsonEmitter;
21use rustc_errors::timings::TimingSectionHandler;
22use rustc_errors::translation::Translator;
23use rustc_errors::{
24    Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
25    LintEmitter, TerminalUrl, fallback_fluent_bundle,
26};
27use rustc_hir::limit::Limit;
28use rustc_macros::HashStable_Generic;
29pub use rustc_span::def_id::StableCrateId;
30use rustc_span::edition::Edition;
31use rustc_span::source_map::{FilePathMapping, SourceMap};
32use rustc_span::{FileNameDisplayPreference, RealFileName, Span, Symbol};
33use rustc_target::asm::InlineAsmArch;
34use rustc_target::spec::{
35    CodeModel, DebuginfoKind, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
36    SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
37    TargetTuple, TlsModel, apple,
38};
39
40use crate::code_stats::CodeStats;
41pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
42use crate::config::{
43    self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
44    Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents,
45    SwitchWithOptPath,
46};
47use crate::filesearch::FileSearch;
48use crate::lint::LintId;
49use crate::parse::{ParseSess, add_feature_diagnostics};
50use crate::search_paths::SearchPath;
51use crate::{errors, filesearch, lint};
52
53/// The behavior of the CTFE engine when an error occurs with regards to backtraces.
54#[derive(Clone, Copy)]
55pub enum CtfeBacktrace {
56    /// Do nothing special, return the error as usual without a backtrace.
57    Disabled,
58    /// Capture a backtrace at the point the error is created and return it in the error
59    /// (to be printed later if/when the error ever actually gets shown to the user).
60    Capture,
61    /// Capture a backtrace at the point the error is created and immediately print it out.
62    Immediate,
63}
64
65#[derive(Clone, Copy, Debug, HashStable_Generic)]
66pub struct Limits {
67    /// The maximum recursion limit for potentially infinitely recursive
68    /// operations such as auto-dereference and monomorphization.
69    pub recursion_limit: Limit,
70    /// The size at which the `large_assignments` lint starts
71    /// being emitted.
72    pub move_size_limit: Limit,
73    /// The maximum length of types during monomorphization.
74    pub type_length_limit: Limit,
75    /// The maximum pattern complexity allowed (internal only).
76    pub pattern_complexity_limit: Limit,
77}
78
79pub struct CompilerIO {
80    pub input: Input,
81    pub output_dir: Option<PathBuf>,
82    pub output_file: Option<OutFileName>,
83    pub temps_dir: Option<PathBuf>,
84}
85
86pub trait DynLintStore: Any + DynSync + DynSend {
87    /// Provides a way to access lint groups without depending on `rustc_lint`
88    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
89}
90
91/// Represents the data associated with a compilation
92/// session for a single crate.
93pub struct Session {
94    pub target: Target,
95    pub host: Target,
96    pub opts: config::Options,
97    pub target_tlib_path: Arc<SearchPath>,
98    pub psess: ParseSess,
99    /// Input, input file path and output file path to this compilation process.
100    pub io: CompilerIO,
101
102    incr_comp_session: RwLock<IncrCompSession>,
103
104    /// Used by `-Z self-profile`.
105    pub prof: SelfProfilerRef,
106
107    /// Used to emit section timings events (enabled by `--json=timings`).
108    pub timings: TimingSectionHandler,
109
110    /// Data about code being compiled, gathered during compilation.
111    pub code_stats: CodeStats,
112
113    /// This only ever stores a `LintStore` but we don't want a dependency on that type here.
114    pub lint_store: Option<Arc<dyn DynLintStore>>,
115
116    /// Cap lint level specified by a driver specifically.
117    pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
118
119    /// Tracks the current behavior of the CTFE engine when an error occurs.
120    /// Options range from returning the error without a backtrace to returning an error
121    /// and immediately printing the backtrace to stderr.
122    /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
123    /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
124    /// errors.
125    pub ctfe_backtrace: Lock<CtfeBacktrace>,
126
127    /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
128    /// const check, optionally with the relevant feature gate. We use this to
129    /// warn about unleashing, but with a single diagnostic instead of dozens that
130    /// drown everything else in noise.
131    miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
132
133    /// Architecture to use for interpreting asm!.
134    pub asm_arch: Option<InlineAsmArch>,
135
136    /// Set of enabled features for the current target.
137    pub target_features: FxIndexSet<Symbol>,
138
139    /// Set of enabled features for the current target, including unstable ones.
140    pub unstable_target_features: FxIndexSet<Symbol>,
141
142    /// The version of the rustc process, possibly including a commit hash and description.
143    pub cfg_version: &'static str,
144
145    /// The inner atomic value is set to true when a feature marked as `internal` is
146    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
147    /// internal features are wontfix, and they are usually the cause of the ICEs.
148    /// None signifies that this is not tracked.
149    pub using_internal_features: &'static AtomicBool,
150
151    /// All commandline args used to invoke the compiler, with @file args fully expanded.
152    /// This will only be used within debug info, e.g. in the pdb file on windows
153    /// This is mainly useful for other tools that reads that debuginfo to figure out
154    /// how to call the compiler with the same arguments.
155    pub expanded_args: Vec<String>,
156
157    target_filesearch: FileSearch,
158    host_filesearch: FileSearch,
159
160    /// A random string generated per invocation of rustc.
161    ///
162    /// This is prepended to all temporary files so that they do not collide
163    /// during concurrent invocations of rustc, or past invocations that were
164    /// preserved with a flag like `-C save-temps`, since these files may be
165    /// hard linked.
166    pub invocation_temp: Option<String>,
167}
168
169impl LintEmitter for &'_ Session {
170    type Id = NodeId;
171
172    fn emit_node_span_lint(
173        self,
174        lint: &'static rustc_lint_defs::Lint,
175        node_id: Self::Id,
176        span: impl Into<rustc_errors::MultiSpan>,
177        decorator: impl for<'a> rustc_errors::LintDiagnostic<'a, ()> + DynSend + 'static,
178    ) {
179        self.psess.buffer_lint(lint, span, node_id, decorator);
180    }
181}
182
183#[derive(Clone, Copy)]
184pub enum CodegenUnits {
185    /// Specified by the user. In this case we try fairly hard to produce the
186    /// number of CGUs requested.
187    User(usize),
188
189    /// A default value, i.e. not specified by the user. In this case we take
190    /// more liberties about CGU formation, e.g. avoid producing very small
191    /// CGUs.
192    Default(usize),
193}
194
195impl CodegenUnits {
196    pub fn as_usize(self) -> usize {
197        match self {
198            CodegenUnits::User(n) => n,
199            CodegenUnits::Default(n) => n,
200        }
201    }
202}
203
204pub struct LintGroup {
205    pub name: &'static str,
206    pub lints: Vec<LintId>,
207    pub is_externally_loaded: bool,
208}
209
210impl Session {
211    pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
212        self.miri_unleashed_features.lock().push((span, feature_gate));
213    }
214
215    pub fn local_crate_source_file(&self) -> Option<RealFileName> {
216        Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
217    }
218
219    fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
220        let mut guar = None;
221        let unleashed_features = self.miri_unleashed_features.lock();
222        if !unleashed_features.is_empty() {
223            let mut must_err = false;
224            // Create a diagnostic pointing at where things got unleashed.
225            self.dcx().emit_warn(errors::SkippingConstChecks {
226                unleashed_features: unleashed_features
227                    .iter()
228                    .map(|(span, gate)| {
229                        gate.map(|gate| {
230                            must_err = true;
231                            errors::UnleashedFeatureHelp::Named { span: *span, gate }
232                        })
233                        .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
234                    })
235                    .collect(),
236            });
237
238            // If we should err, make sure we did.
239            if must_err && self.dcx().has_errors().is_none() {
240                // We have skipped a feature gate, and not run into other errors... reject.
241                guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
242            }
243        }
244        guar
245    }
246
247    /// Invoked all the way at the end to finish off diagnostics printing.
248    pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
249        let mut guar = None;
250        guar = guar.or(self.check_miri_unleashed_features());
251        guar = guar.or(self.dcx().emit_stashed_diagnostics());
252        self.dcx().print_error_count();
253        if self.opts.json_future_incompat {
254            self.dcx().emit_future_breakage_report();
255        }
256        guar
257    }
258
259    /// Returns true if the crate is a testing one.
260    pub fn is_test_crate(&self) -> bool {
261        self.opts.test
262    }
263
264    /// `feature` must be a language feature.
265    #[track_caller]
266    pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
267        let mut err = self.dcx().create_err(err);
268        if err.code.is_none() {
269            #[allow(rustc::diagnostic_outside_of_impl)]
270            err.code(E0658);
271        }
272        add_feature_diagnostics(&mut err, self, feature);
273        err
274    }
275
276    /// Record the fact that we called `trimmed_def_paths`, and do some
277    /// checking about whether its cost was justified.
278    pub fn record_trimmed_def_paths(&self) {
279        if self.opts.unstable_opts.print_type_sizes
280            || self.opts.unstable_opts.query_dep_graph
281            || self.opts.unstable_opts.dump_mir.is_some()
282            || self.opts.unstable_opts.unpretty.is_some()
283            || self.prof.is_args_recording_enabled()
284            || self.opts.output_types.contains_key(&OutputType::Mir)
285            || std::env::var_os("RUSTC_LOG").is_some()
286        {
287            return;
288        }
289
290        self.dcx().set_must_produce_diag()
291    }
292
293    #[inline]
294    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
295        self.psess.dcx()
296    }
297
298    #[inline]
299    pub fn source_map(&self) -> &SourceMap {
300        self.psess.source_map()
301    }
302
303    /// Returns `true` if internal lints should be added to the lint store - i.e. if
304    /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
305    /// to be emitted under rustdoc).
306    pub fn enable_internal_lints(&self) -> bool {
307        self.unstable_options() && !self.opts.actually_rustdoc
308    }
309
310    pub fn instrument_coverage(&self) -> bool {
311        self.opts.cg.instrument_coverage() != InstrumentCoverage::No
312    }
313
314    pub fn instrument_coverage_branch(&self) -> bool {
315        self.instrument_coverage()
316            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
317    }
318
319    pub fn instrument_coverage_condition(&self) -> bool {
320        self.instrument_coverage()
321            && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
322    }
323
324    /// Provides direct access to the `CoverageOptions` struct, so that
325    /// individual flags for debugging/testing coverage instrumetation don't
326    /// need separate accessors.
327    pub fn coverage_options(&self) -> &CoverageOptions {
328        &self.opts.unstable_opts.coverage_options
329    }
330
331    pub fn is_sanitizer_cfi_enabled(&self) -> bool {
332        self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
333    }
334
335    pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
336        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
337    }
338
339    pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
340        self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
341    }
342
343    pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
344        self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
345    }
346
347    pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
348        self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
349    }
350
351    pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
352        self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
353    }
354
355    pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
356        self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
357    }
358
359    pub fn is_split_lto_unit_enabled(&self) -> bool {
360        self.opts.unstable_opts.split_lto_unit == Some(true)
361    }
362
363    /// Check whether this compile session and crate type use static crt.
364    pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
365        if !self.target.crt_static_respected {
366            // If the target does not opt in to crt-static support, use its default.
367            return self.target.crt_static_default;
368        }
369
370        let requested_features = self.opts.cg.target_feature.split(',');
371        let found_negative = requested_features.clone().any(|r| r == "-crt-static");
372        let found_positive = requested_features.clone().any(|r| r == "+crt-static");
373
374        // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
375        #[allow(rustc::bad_opt_access)]
376        if found_positive || found_negative {
377            found_positive
378        } else if crate_type == Some(CrateType::ProcMacro)
379            || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
380        {
381            // FIXME: When crate_type is not available,
382            // we use compiler options to determine the crate_type.
383            // We can't check `#![crate_type = "proc-macro"]` here.
384            false
385        } else {
386            self.target.crt_static_default
387        }
388    }
389
390    pub fn is_wasi_reactor(&self) -> bool {
391        self.target.options.os == "wasi"
392            && matches!(
393                self.opts.unstable_opts.wasi_exec_model,
394                Some(config::WasiExecModel::Reactor)
395            )
396    }
397
398    /// Returns `true` if the target can use the current split debuginfo configuration.
399    pub fn target_can_use_split_dwarf(&self) -> bool {
400        self.target.debuginfo_kind == DebuginfoKind::Dwarf
401    }
402
403    pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
404        format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
405    }
406
407    pub fn target_filesearch(&self) -> &filesearch::FileSearch {
408        &self.target_filesearch
409    }
410    pub fn host_filesearch(&self) -> &filesearch::FileSearch {
411        &self.host_filesearch
412    }
413
414    /// Returns a list of directories where target-specific tool binaries are located. Some fallback
415    /// directories are also returned, for example if `--sysroot` is used but tools are missing
416    /// (#125246): we also add the bin directories to the sysroot where rustc is located.
417    pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
418        let search_paths = self
419            .opts
420            .sysroot
421            .all_paths()
422            .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
423
424        if self_contained {
425            // The self-contained tools are expected to be e.g. in `bin/self-contained` in the
426            // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the
427            // fallback paths.
428            search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
429        } else {
430            search_paths.collect()
431        }
432    }
433
434    pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
435        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
436
437        if let IncrCompSession::NotInitialized = *incr_comp_session {
438        } else {
439            panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
440        }
441
442        *incr_comp_session =
443            IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
444    }
445
446    pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
447        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
448
449        if let IncrCompSession::Active { .. } = *incr_comp_session {
450        } else {
451            panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
452        }
453
454        // Note: this will also drop the lock file, thus unlocking the directory.
455        *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
456    }
457
458    pub fn mark_incr_comp_session_as_invalid(&self) {
459        let mut incr_comp_session = self.incr_comp_session.borrow_mut();
460
461        let session_directory = match *incr_comp_session {
462            IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
463            IncrCompSession::InvalidBecauseOfErrors { .. } => return,
464            _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
465        };
466
467        // Note: this will also drop the lock file, thus unlocking the directory.
468        *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
469    }
470
471    pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
472        let incr_comp_session = self.incr_comp_session.borrow();
473        ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
474            IncrCompSession::NotInitialized => panic!(
475                "trying to get session directory from `IncrCompSession`: {:?}",
476                *incr_comp_session,
477            ),
478            IncrCompSession::Active { ref session_directory, .. }
479            | IncrCompSession::Finalized { ref session_directory }
480            | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
481                session_directory
482            }
483        })
484    }
485
486    pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
487        self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
488    }
489
490    /// Is this edition 2015?
491    pub fn is_rust_2015(&self) -> bool {
492        self.edition().is_rust_2015()
493    }
494
495    /// Are we allowed to use features from the Rust 2018 edition?
496    pub fn at_least_rust_2018(&self) -> bool {
497        self.edition().at_least_rust_2018()
498    }
499
500    /// Are we allowed to use features from the Rust 2021 edition?
501    pub fn at_least_rust_2021(&self) -> bool {
502        self.edition().at_least_rust_2021()
503    }
504
505    /// Are we allowed to use features from the Rust 2024 edition?
506    pub fn at_least_rust_2024(&self) -> bool {
507        self.edition().at_least_rust_2024()
508    }
509
510    /// Returns `true` if we should use the PLT for shared library calls.
511    pub fn needs_plt(&self) -> bool {
512        // Check if the current target usually wants PLT to be enabled.
513        // The user can use the command line flag to override it.
514        let want_plt = self.target.plt_by_default;
515
516        let dbg_opts = &self.opts.unstable_opts;
517
518        let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
519
520        // Only enable this optimization by default if full relro is also enabled.
521        // In this case, lazy binding was already unavailable, so nothing is lost.
522        // This also ensures `-Wl,-z,now` is supported by the linker.
523        let full_relro = RelroLevel::Full == relro_level;
524
525        // If user didn't explicitly forced us to use / skip the PLT,
526        // then use it unless the target doesn't want it by default or the full relro forces it on.
527        dbg_opts.plt.unwrap_or(want_plt || !full_relro)
528    }
529
530    /// Checks if LLVM lifetime markers should be emitted.
531    pub fn emit_lifetime_markers(&self) -> bool {
532        self.opts.optimize != config::OptLevel::No
533        // AddressSanitizer and KernelAddressSanitizer uses lifetimes to detect use after scope bugs.
534        // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
535        // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
536        || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
537    }
538
539    pub fn diagnostic_width(&self) -> usize {
540        let default_column_width = 140;
541        if let Some(width) = self.opts.diagnostic_width {
542            width
543        } else if self.opts.unstable_opts.ui_testing {
544            default_column_width
545        } else {
546            termize::dimensions().map_or(default_column_width, |(w, _)| w)
547        }
548    }
549
550    /// Returns the default symbol visibility.
551    pub fn default_visibility(&self) -> SymbolVisibility {
552        self.opts
553            .unstable_opts
554            .default_visibility
555            .or(self.target.options.default_visibility)
556            .unwrap_or(SymbolVisibility::Interposable)
557    }
558
559    pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
560        if verbatim {
561            ("", "")
562        } else {
563            (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
564        }
565    }
566
567    pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
568        match self.lint_store {
569            Some(ref lint_store) => lint_store.lint_groups_iter(),
570            None => Box::new(std::iter::empty()),
571        }
572    }
573}
574
575// JUSTIFICATION: defn of the suggested wrapper fns
576#[allow(rustc::bad_opt_access)]
577impl Session {
578    pub fn verbose_internals(&self) -> bool {
579        self.opts.unstable_opts.verbose_internals
580    }
581
582    pub fn print_llvm_stats(&self) -> bool {
583        self.opts.unstable_opts.print_codegen_stats
584    }
585
586    pub fn verify_llvm_ir(&self) -> bool {
587        self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
588    }
589
590    pub fn binary_dep_depinfo(&self) -> bool {
591        self.opts.unstable_opts.binary_dep_depinfo
592    }
593
594    pub fn mir_opt_level(&self) -> usize {
595        self.opts
596            .unstable_opts
597            .mir_opt_level
598            .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
599    }
600
601    /// Calculates the flavor of LTO to use for this compilation.
602    pub fn lto(&self) -> config::Lto {
603        // Autodiff currently requires fat-lto to have access to the llvm-ir of all (indirectly) used functions and types.
604        // fat-lto is the easiest solution to this requirement, but quite expensive.
605        // FIXME(autodiff): Make autodiff also work with embed-bc instead of fat-lto.
606        if self.opts.autodiff_enabled() {
607            return config::Lto::Fat;
608        }
609
610        // If our target has codegen requirements ignore the command line
611        if self.target.requires_lto {
612            return config::Lto::Fat;
613        }
614
615        // If the user specified something, return that. If they only said `-C
616        // lto` and we've for whatever reason forced off ThinLTO via the CLI,
617        // then ensure we can't use a ThinLTO.
618        match self.opts.cg.lto {
619            config::LtoCli::Unspecified => {
620                // The compiler was invoked without the `-Clto` flag. Fall
621                // through to the default handling
622            }
623            config::LtoCli::No => {
624                // The user explicitly opted out of any kind of LTO
625                return config::Lto::No;
626            }
627            config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
628                // All of these mean fat LTO
629                return config::Lto::Fat;
630            }
631            config::LtoCli::Thin => {
632                // The user explicitly asked for ThinLTO
633                return config::Lto::Thin;
634            }
635        }
636
637        // Ok at this point the target doesn't require anything and the user
638        // hasn't asked for anything. Our next decision is whether or not
639        // we enable "auto" ThinLTO where we use multiple codegen units and
640        // then do ThinLTO over those codegen units. The logic below will
641        // either return `No` or `ThinLocal`.
642
643        // If processing command line options determined that we're incompatible
644        // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
645        if self.opts.cli_forced_local_thinlto_off {
646            return config::Lto::No;
647        }
648
649        // If `-Z thinlto` specified process that, but note that this is mostly
650        // a deprecated option now that `-C lto=thin` exists.
651        if let Some(enabled) = self.opts.unstable_opts.thinlto {
652            if enabled {
653                return config::Lto::ThinLocal;
654            } else {
655                return config::Lto::No;
656            }
657        }
658
659        // If there's only one codegen unit and LTO isn't enabled then there's
660        // no need for ThinLTO so just return false.
661        if self.codegen_units().as_usize() == 1 {
662            return config::Lto::No;
663        }
664
665        // Now we're in "defaults" territory. By default we enable ThinLTO for
666        // optimized compiles (anything greater than O0).
667        match self.opts.optimize {
668            config::OptLevel::No => config::Lto::No,
669            _ => config::Lto::ThinLocal,
670        }
671    }
672
673    /// Returns the panic strategy for this compile session. If the user explicitly selected one
674    /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
675    pub fn panic_strategy(&self) -> PanicStrategy {
676        self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
677    }
678
679    pub fn fewer_names(&self) -> bool {
680        if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
681            fewer_names
682        } else {
683            let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
684                || self.opts.output_types.contains_key(&OutputType::Bitcode)
685                // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
686                || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
687            !more_names
688        }
689    }
690
691    pub fn unstable_options(&self) -> bool {
692        self.opts.unstable_opts.unstable_options
693    }
694
695    pub fn is_nightly_build(&self) -> bool {
696        self.opts.unstable_features.is_nightly_build()
697    }
698
699    pub fn overflow_checks(&self) -> bool {
700        self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
701    }
702
703    pub fn ub_checks(&self) -> bool {
704        self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
705    }
706
707    pub fn contract_checks(&self) -> bool {
708        self.opts.unstable_opts.contract_checks.unwrap_or(false)
709    }
710
711    pub fn relocation_model(&self) -> RelocModel {
712        self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
713    }
714
715    pub fn code_model(&self) -> Option<CodeModel> {
716        self.opts.cg.code_model.or(self.target.code_model)
717    }
718
719    pub fn tls_model(&self) -> TlsModel {
720        self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
721    }
722
723    pub fn direct_access_external_data(&self) -> Option<bool> {
724        self.opts
725            .unstable_opts
726            .direct_access_external_data
727            .or(self.target.direct_access_external_data)
728    }
729
730    pub fn split_debuginfo(&self) -> SplitDebuginfo {
731        self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
732    }
733
734    /// Returns the DWARF version passed on the CLI or the default for the target.
735    pub fn dwarf_version(&self) -> u32 {
736        self.opts
737            .cg
738            .dwarf_version
739            .or(self.opts.unstable_opts.dwarf_version)
740            .unwrap_or(self.target.default_dwarf_version)
741    }
742
743    pub fn stack_protector(&self) -> StackProtector {
744        if self.target.options.supports_stack_protector {
745            self.opts.unstable_opts.stack_protector
746        } else {
747            StackProtector::None
748        }
749    }
750
751    pub fn must_emit_unwind_tables(&self) -> bool {
752        // This is used to control the emission of the `uwtable` attribute on
753        // LLVM functions. The `uwtable` attribute according to LLVM is:
754        //
755        //     This attribute indicates that the ABI being targeted requires that an
756        //     unwind table entry be produced for this function even if we can show
757        //     that no exceptions passes by it. This is normally the case for the
758        //     ELF x86-64 abi, but it can be disabled for some compilation units.
759        //
760        // Typically when we're compiling with `-C panic=abort` we don't need
761        // `uwtable` because we can't generate any exceptions! But note that
762        // some targets require unwind tables to generate backtraces.
763        // Unwind tables are needed when compiling with `-C panic=unwind`, but
764        // LLVM won't omit unwind tables unless the function is also marked as
765        // `nounwind`, so users are allowed to disable `uwtable` emission.
766        // Historically rustc always emits `uwtable` attributes by default, so
767        // even they can be disabled, they're still emitted by default.
768        //
769        // On some targets (including windows), however, exceptions include
770        // other events such as illegal instructions, segfaults, etc. This means
771        // that on Windows we end up still needing unwind tables even if the `-C
772        // panic=abort` flag is passed.
773        //
774        // You can also find more info on why Windows needs unwind tables in:
775        //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
776        //
777        // If a target requires unwind tables, then they must be emitted.
778        // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
779        // value, if it is provided, or disable them, if not.
780        self.target.requires_uwtable
781            || self
782                .opts
783                .cg
784                .force_unwind_tables
785                .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
786    }
787
788    /// Returns the number of query threads that should be used for this
789    /// compilation
790    #[inline]
791    pub fn threads(&self) -> usize {
792        self.opts.unstable_opts.threads
793    }
794
795    /// Returns the number of codegen units that should be used for this
796    /// compilation
797    pub fn codegen_units(&self) -> CodegenUnits {
798        if let Some(n) = self.opts.cli_forced_codegen_units {
799            return CodegenUnits::User(n);
800        }
801        if let Some(n) = self.target.default_codegen_units {
802            return CodegenUnits::Default(n as usize);
803        }
804
805        // If incremental compilation is turned on, we default to a high number
806        // codegen units in order to reduce the "collateral damage" small
807        // changes cause.
808        if self.opts.incremental.is_some() {
809            return CodegenUnits::Default(256);
810        }
811
812        // Why is 16 codegen units the default all the time?
813        //
814        // The main reason for enabling multiple codegen units by default is to
815        // leverage the ability for the codegen backend to do codegen and
816        // optimization in parallel. This allows us, especially for large crates, to
817        // make good use of all available resources on the machine once we've
818        // hit that stage of compilation. Large crates especially then often
819        // take a long time in codegen/optimization and this helps us amortize that
820        // cost.
821        //
822        // Note that a high number here doesn't mean that we'll be spawning a
823        // large number of threads in parallel. The backend of rustc contains
824        // global rate limiting through the `jobserver` crate so we'll never
825        // overload the system with too much work, but rather we'll only be
826        // optimizing when we're otherwise cooperating with other instances of
827        // rustc.
828        //
829        // Rather a high number here means that we should be able to keep a lot
830        // of idle cpus busy. By ensuring that no codegen unit takes *too* long
831        // to build we'll be guaranteed that all cpus will finish pretty closely
832        // to one another and we should make relatively optimal use of system
833        // resources
834        //
835        // Note that the main cost of codegen units is that it prevents LLVM
836        // from inlining across codegen units. Users in general don't have a lot
837        // of control over how codegen units are split up so it's our job in the
838        // compiler to ensure that undue performance isn't lost when using
839        // codegen units (aka we can't require everyone to slap `#[inline]` on
840        // everything).
841        //
842        // If we're compiling at `-O0` then the number doesn't really matter too
843        // much because performance doesn't matter and inlining is ok to lose.
844        // In debug mode we just want to try to guarantee that no cpu is stuck
845        // doing work that could otherwise be farmed to others.
846        //
847        // In release mode, however (O1 and above) performance does indeed
848        // matter! To recover the loss in performance due to inlining we'll be
849        // enabling ThinLTO by default (the function for which is just below).
850        // This will ensure that we recover any inlining wins we otherwise lost
851        // through codegen unit partitioning.
852        //
853        // ---
854        //
855        // Ok that's a lot of words but the basic tl;dr; is that we want a high
856        // number here -- but not too high. Additionally we're "safe" to have it
857        // always at the same number at all optimization levels.
858        //
859        // As a result 16 was chosen here! Mostly because it was a power of 2
860        // and most benchmarks agreed it was roughly a local optimum. Not very
861        // scientific.
862        CodegenUnits::Default(16)
863    }
864
865    pub fn teach(&self, code: ErrCode) -> bool {
866        self.opts.unstable_opts.teach && self.dcx().must_teach(code)
867    }
868
869    pub fn edition(&self) -> Edition {
870        self.opts.edition
871    }
872
873    pub fn link_dead_code(&self) -> bool {
874        self.opts.cg.link_dead_code.unwrap_or(false)
875    }
876
877    pub fn filename_display_preference(
878        &self,
879        scope: RemapPathScopeComponents,
880    ) -> FileNameDisplayPreference {
881        assert!(
882            scope.bits().count_ones() == 1,
883            "one and only one scope should be passed to `Session::filename_display_preference`"
884        );
885        if self.opts.unstable_opts.remap_path_scope.contains(scope) {
886            FileNameDisplayPreference::Remapped
887        } else {
888            FileNameDisplayPreference::Local
889        }
890    }
891
892    /// Get the deployment target on Apple platforms based on the standard environment variables,
893    /// or fall back to the minimum version supported by `rustc`.
894    ///
895    /// This should be guarded behind `if sess.target.is_like_darwin`.
896    pub fn apple_deployment_target(&self) -> apple::OSVersion {
897        let min = apple::OSVersion::minimum_deployment_target(&self.target);
898        let env_var = apple::deployment_target_env_var(&self.target.os);
899
900        // FIXME(madsmtm): Track changes to this.
901        if let Ok(deployment_target) = env::var(env_var) {
902            match apple::OSVersion::from_str(&deployment_target) {
903                Ok(version) => {
904                    let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
905                    // It is common that the deployment target is set a bit too low, for example on
906                    // macOS Aarch64 to also target older x86_64. So we only want to warn when variable
907                    // is lower than the minimum OS supported by rustc, not when the variable is lower
908                    // than the minimum for a specific target.
909                    if version < os_min {
910                        self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
911                            env_var,
912                            version: version.fmt_pretty().to_string(),
913                            os_min: os_min.fmt_pretty().to_string(),
914                        });
915                    }
916
917                    // Raise the deployment target to the minimum supported.
918                    version.max(min)
919                }
920                Err(error) => {
921                    self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
922                    min
923                }
924            }
925        } else {
926            // If no deployment target variable is set, default to the minimum found above.
927            min
928        }
929    }
930}
931
932// JUSTIFICATION: part of session construction
933#[allow(rustc::bad_opt_access)]
934fn default_emitter(
935    sopts: &config::Options,
936    source_map: Arc<SourceMap>,
937    translator: Translator,
938) -> Box<DynEmitter> {
939    let macro_backtrace = sopts.unstable_opts.macro_backtrace;
940    let track_diagnostics = sopts.unstable_opts.track_diagnostics;
941    let terminal_url = match sopts.unstable_opts.terminal_urls {
942        TerminalUrl::Auto => {
943            match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
944                (Ok("truecolor"), Ok("xterm-256color"))
945                    if sopts.unstable_features.is_nightly_build() =>
946                {
947                    TerminalUrl::Yes
948                }
949                _ => TerminalUrl::No,
950            }
951        }
952        t => t,
953    };
954
955    let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
956
957    match sopts.error_format {
958        config::ErrorOutputType::HumanReadable { kind, color_config } => {
959            let short = kind.short();
960
961            if let HumanReadableErrorType::AnnotateSnippet = kind {
962                let emitter =
963                    AnnotateSnippetEmitter::new(source_map, translator, short, macro_backtrace);
964                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
965            } else {
966                let emitter = HumanEmitter::new(stderr_destination(color_config), translator)
967                    .sm(source_map)
968                    .short_message(short)
969                    .diagnostic_width(sopts.diagnostic_width)
970                    .macro_backtrace(macro_backtrace)
971                    .track_diagnostics(track_diagnostics)
972                    .terminal_url(terminal_url)
973                    .theme(if let HumanReadableErrorType::Unicode = kind {
974                        OutputTheme::Unicode
975                    } else {
976                        OutputTheme::Ascii
977                    })
978                    .ignored_directories_in_source_blocks(
979                        sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
980                    );
981                Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
982            }
983        }
984        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
985            JsonEmitter::new(
986                Box::new(io::BufWriter::new(io::stderr())),
987                source_map,
988                translator,
989                pretty,
990                json_rendered,
991                color_config,
992            )
993            .ui_testing(sopts.unstable_opts.ui_testing)
994            .ignored_directories_in_source_blocks(
995                sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
996            )
997            .diagnostic_width(sopts.diagnostic_width)
998            .macro_backtrace(macro_backtrace)
999            .track_diagnostics(track_diagnostics)
1000            .terminal_url(terminal_url),
1001        ),
1002    }
1003}
1004
1005// JUSTIFICATION: literally session construction
1006#[allow(rustc::bad_opt_access)]
1007#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
1008pub fn build_session(
1009    sopts: config::Options,
1010    io: CompilerIO,
1011    fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
1012    registry: rustc_errors::registry::Registry,
1013    fluent_resources: Vec<&'static str>,
1014    driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1015    target: Target,
1016    cfg_version: &'static str,
1017    ice_file: Option<PathBuf>,
1018    using_internal_features: &'static AtomicBool,
1019    expanded_args: Vec<String>,
1020) -> Session {
1021    // FIXME: This is not general enough to make the warning lint completely override
1022    // normal diagnostic warnings, since the warning lint can also be denied and changed
1023    // later via the source code.
1024    let warnings_allow = sopts
1025        .lint_opts
1026        .iter()
1027        .rfind(|&(key, _)| *key == "warnings")
1028        .is_some_and(|&(_, level)| level == lint::Allow);
1029    let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1030    let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1031
1032    let translator = Translator {
1033        fluent_bundle,
1034        fallback_fluent_bundle: fallback_fluent_bundle(
1035            fluent_resources,
1036            sopts.unstable_opts.translate_directionality_markers,
1037        ),
1038    };
1039    let source_map = rustc_span::source_map::get_source_map().unwrap();
1040    let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
1041
1042    let mut dcx = DiagCtxt::new(emitter)
1043        .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1044        .with_registry(registry);
1045    if let Some(ice_file) = ice_file {
1046        dcx = dcx.with_ice_file(ice_file);
1047    }
1048
1049    let host_triple = TargetTuple::from_tuple(config::host_tuple());
1050    let (host, target_warnings) = Target::search(&host_triple, sopts.sysroot.path())
1051        .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1052    for warning in target_warnings.warning_messages() {
1053        dcx.handle().warn(warning)
1054    }
1055
1056    let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1057    {
1058        let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1059
1060        let profiler = SelfProfiler::new(
1061            directory,
1062            sopts.crate_name.as_deref(),
1063            sopts.unstable_opts.self_profile_events.as_deref(),
1064            &sopts.unstable_opts.self_profile_counter,
1065        );
1066        match profiler {
1067            Ok(profiler) => Some(Arc::new(profiler)),
1068            Err(e) => {
1069                dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1070                None
1071            }
1072        }
1073    } else {
1074        None
1075    };
1076
1077    let mut psess = ParseSess::with_dcx(dcx, source_map);
1078    psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1079
1080    let host_triple = config::host_tuple();
1081    let target_triple = sopts.target_triple.tuple();
1082    // FIXME use host sysroot?
1083    let host_tlib_path =
1084        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1085    let target_tlib_path = if host_triple == target_triple {
1086        // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1087        // rescanning of the target lib path and an unnecessary allocation.
1088        Arc::clone(&host_tlib_path)
1089    } else {
1090        Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1091    };
1092
1093    let prof = SelfProfilerRef::new(
1094        self_profiler,
1095        sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1096    );
1097
1098    let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1099        Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1100        Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1101        _ => CtfeBacktrace::Disabled,
1102    });
1103
1104    let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1105    let target_filesearch =
1106        filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1107    let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1108
1109    let invocation_temp = sopts
1110        .incremental
1111        .as_ref()
1112        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1113
1114    let timings = TimingSectionHandler::new(sopts.json_timings);
1115
1116    let sess = Session {
1117        target,
1118        host,
1119        opts: sopts,
1120        target_tlib_path,
1121        psess,
1122        io,
1123        incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1124        prof,
1125        timings,
1126        code_stats: Default::default(),
1127        lint_store: None,
1128        driver_lint_caps,
1129        ctfe_backtrace,
1130        miri_unleashed_features: Lock::new(Default::default()),
1131        asm_arch,
1132        target_features: Default::default(),
1133        unstable_target_features: Default::default(),
1134        cfg_version,
1135        using_internal_features,
1136        expanded_args,
1137        target_filesearch,
1138        host_filesearch,
1139        invocation_temp,
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 == "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 != "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 sess.target.arch != "x86" && sess.target.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 sess.target.arch != "x86" && sess.target.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 != "x86" {
1366            sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1367        }
1368    }
1369    if sess.opts.unstable_opts.reg_struct_return {
1370        if sess.target.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.cg.soft_float {
1392        if sess.target.arch == "arm" {
1393            sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1394        } else {
1395            // All `use_softfp` does is the equivalent of `-mfloat-abi` in GCC/clang, which only exists on ARM targets.
1396            // We document this flag to only affect `*eabihf` targets, so let's show a warning for all other targets.
1397            sess.dcx().emit_warn(errors::SoftFloatIgnored);
1398        }
1399    }
1400}
1401
1402/// Holds data on the current incremental compilation session, if there is one.
1403#[derive(Debug)]
1404enum IncrCompSession {
1405    /// This is the state the session will be in until the incr. comp. dir is
1406    /// needed.
1407    NotInitialized,
1408    /// This is the state during which the session directory is private and can
1409    /// be modified. `_lock_file` is never directly used, but its presence
1410    /// alone has an effect, because the file will unlock when the session is
1411    /// dropped.
1412    Active { session_directory: PathBuf, _lock_file: flock::Lock },
1413    /// This is the state after the session directory has been finalized. In this
1414    /// state, the contents of the directory must not be modified any more.
1415    Finalized { session_directory: PathBuf },
1416    /// This is an error state that is reached when some compilation error has
1417    /// occurred. It indicates that the contents of the session directory must
1418    /// not be used, since they might be invalid.
1419    InvalidBecauseOfErrors { session_directory: PathBuf },
1420}
1421
1422/// A wrapper around an [`DiagCtxt`] that is used for early error emissions.
1423pub struct EarlyDiagCtxt {
1424    dcx: DiagCtxt,
1425}
1426
1427impl EarlyDiagCtxt {
1428    pub fn new(output: ErrorOutputType) -> Self {
1429        let emitter = mk_emitter(output);
1430        Self { dcx: DiagCtxt::new(emitter) }
1431    }
1432
1433    /// Swap out the underlying dcx once we acquire the user's preference on error emission
1434    /// format. If `early_err` was previously called this will panic.
1435    pub fn set_error_format(&mut self, output: ErrorOutputType) {
1436        assert!(self.dcx.handle().has_errors().is_none());
1437
1438        let emitter = mk_emitter(output);
1439        self.dcx = DiagCtxt::new(emitter);
1440    }
1441
1442    #[allow(rustc::untranslatable_diagnostic)]
1443    #[allow(rustc::diagnostic_outside_of_impl)]
1444    pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1445        self.dcx.handle().note(msg)
1446    }
1447
1448    #[allow(rustc::untranslatable_diagnostic)]
1449    #[allow(rustc::diagnostic_outside_of_impl)]
1450    pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1451        self.dcx.handle().struct_help(msg).emit()
1452    }
1453
1454    #[allow(rustc::untranslatable_diagnostic)]
1455    #[allow(rustc::diagnostic_outside_of_impl)]
1456    #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1457    pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1458        self.dcx.handle().err(msg)
1459    }
1460
1461    #[allow(rustc::untranslatable_diagnostic)]
1462    #[allow(rustc::diagnostic_outside_of_impl)]
1463    pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1464        self.dcx.handle().fatal(msg)
1465    }
1466
1467    #[allow(rustc::untranslatable_diagnostic)]
1468    #[allow(rustc::diagnostic_outside_of_impl)]
1469    pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1470        self.dcx.handle().struct_fatal(msg)
1471    }
1472
1473    #[allow(rustc::untranslatable_diagnostic)]
1474    #[allow(rustc::diagnostic_outside_of_impl)]
1475    pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1476        self.dcx.handle().warn(msg)
1477    }
1478
1479    #[allow(rustc::untranslatable_diagnostic)]
1480    #[allow(rustc::diagnostic_outside_of_impl)]
1481    pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1482        self.dcx.handle().struct_warn(msg)
1483    }
1484}
1485
1486fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1487    // FIXME(#100717): early errors aren't translated at the moment, so this is fine, but it will
1488    // need to reference every crate that might emit an early error for translation to work.
1489    let translator =
1490        Translator::with_fallback_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1491    let emitter: Box<DynEmitter> = match output {
1492        config::ErrorOutputType::HumanReadable { kind, color_config } => {
1493            let short = kind.short();
1494            Box::new(
1495                HumanEmitter::new(stderr_destination(color_config), translator)
1496                    .theme(if let HumanReadableErrorType::Unicode = kind {
1497                        OutputTheme::Unicode
1498                    } else {
1499                        OutputTheme::Ascii
1500                    })
1501                    .short_message(short),
1502            )
1503        }
1504        config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1505            Box::new(JsonEmitter::new(
1506                Box::new(io::BufWriter::new(io::stderr())),
1507                Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1508                translator,
1509                pretty,
1510                json_rendered,
1511                color_config,
1512            ))
1513        }
1514    };
1515    emitter
1516}
1517
1518pub trait RemapFileNameExt {
1519    type Output<'a>
1520    where
1521        Self: 'a;
1522
1523    /// Returns a possibly remapped filename based on the passed scope and remap cli options.
1524    ///
1525    /// One and only one scope should be passed to this method, it will panic otherwise.
1526    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1527}
1528
1529impl RemapFileNameExt for rustc_span::FileName {
1530    type Output<'a> = rustc_span::FileNameDisplay<'a>;
1531
1532    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1533        assert!(
1534            scope.bits().count_ones() == 1,
1535            "one and only one scope should be passed to for_scope"
1536        );
1537        if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1538            self.prefer_remapped_unconditionally()
1539        } else {
1540            self.prefer_local()
1541        }
1542    }
1543}
1544
1545impl RemapFileNameExt for rustc_span::RealFileName {
1546    type Output<'a> = &'a Path;
1547
1548    fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1549        assert!(
1550            scope.bits().count_ones() == 1,
1551            "one and only one scope should be passed to for_scope"
1552        );
1553        if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1554            self.remapped_path_if_available()
1555        } else {
1556            self.local_path_if_available()
1557        }
1558    }
1559}