rustc_session/
session.rs

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