1 use crate::cgu_reuse_tracker::CguReuseTracker;
2 use crate::code_stats::CodeStats;
3 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::config::Input;
5 use crate::config::{self, CrateType, InstrumentCoverage, OptLevel, OutputType, SwitchWithOptPath};
7 BranchProtectionRequiresAArch64, CannotEnableCrtStaticLinux, CannotMixAndMatchSanitizers,
8 LinkerPluginToWindowsNotSupported, NotCircumventFeature, OptimisationFuelExhausted,
9 ProfileSampleUseFileDoesNotExist, ProfileUseFileDoesNotExist, SanitizerCfiEnabled,
10 SanitizerNotSupported, SanitizersNotSupported, SkippingConstChecks,
11 SplitDebugInfoUnstablePlatform, StackProtectorNotSupportedForTarget,
12 TargetRequiresUnwindTables, UnleashedFeatureHelp, UnstableVirtualFunctionElimination,
13 UnsupportedDwarfVersion,
15 use crate::parse::{add_feature_diagnostics, ParseSess};
16 use crate::search_paths::{PathKind, SearchPath};
17 use crate::{filesearch, lint};
19 pub use rustc_ast::attr::MarkedAttrs;
20 pub use rustc_ast::Attribute;
21 use rustc_data_structures::flock;
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_data_structures::jobserver::{self, Client};
24 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
25 use rustc_data_structures::sync::{
26 self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
28 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
29 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
30 use rustc_errors::json::JsonEmitter;
31 use rustc_errors::registry::Registry;
33 error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage,
34 ErrorGuaranteed, FluentBundle, IntoDiagnostic, LazyFallbackBundle, MultiSpan, Noted,
36 use rustc_macros::HashStable_Generic;
37 pub use rustc_span::def_id::StableCrateId;
38 use rustc_span::edition::Edition;
39 use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMap, Span};
40 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
41 use rustc_target::asm::InlineAsmArch;
42 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
43 use rustc_target::spec::{
44 DebuginfoKind, SanitizerSet, SplitDebuginfo, StackProtector, Target, TargetTriple, TlsModel,
47 use std::cell::{self, RefCell};
50 use std::ops::{Div, Mul};
51 use std::path::{Path, PathBuf};
52 use std::str::FromStr;
54 use std::time::Duration;
56 pub struct OptimizationFuel {
57 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
59 /// We're rejecting all further optimizations.
63 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
64 #[derive(Clone, Copy)]
65 pub enum CtfeBacktrace {
66 /// Do nothing special, return the error as usual without a backtrace.
68 /// Capture a backtrace at the point the error is created and return it in the error
69 /// (to be printed later if/when the error ever actually gets shown to the user).
71 /// Capture a backtrace at the point the error is created and immediately print it out.
75 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
76 /// limits are consistent throughout the compiler.
77 #[derive(Clone, Copy, Debug, HashStable_Generic)]
78 pub struct Limit(pub usize);
81 /// Create a new limit from a `usize`.
82 pub fn new(value: usize) -> Self {
86 /// Check that `value` is within the limit. Ensures that the same comparisons are used
87 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
89 pub fn value_within_limit(&self, value: usize) -> bool {
94 impl From<usize> for Limit {
95 fn from(value: usize) -> Self {
100 impl fmt::Display for Limit {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 impl Div<usize> for Limit {
109 fn div(self, rhs: usize) -> Self::Output {
110 Limit::new(self.0 / rhs)
114 impl Mul<usize> for Limit {
117 fn mul(self, rhs: usize) -> Self::Output {
118 Limit::new(self.0 * rhs)
122 impl rustc_errors::IntoDiagnosticArg for Limit {
123 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
124 self.to_string().into_diagnostic_arg()
128 #[derive(Clone, Copy, Debug, HashStable_Generic)]
130 /// The maximum recursion limit for potentially infinitely recursive
131 /// operations such as auto-dereference and monomorphization.
132 pub recursion_limit: Limit,
133 /// The size at which the `large_assignments` lint starts
135 pub move_size_limit: Limit,
136 /// The maximum length of types during monomorphization.
137 pub type_length_limit: Limit,
138 /// The maximum blocks a const expression can evaluate.
139 pub const_eval_limit: Limit,
142 pub struct CompilerIO {
144 pub output_dir: Option<PathBuf>,
145 pub output_file: Option<PathBuf>,
146 pub temps_dir: Option<PathBuf>,
149 /// Represents the data associated with a compilation
150 /// session for a single crate.
154 pub opts: config::Options,
155 pub host_tlib_path: Lrc<SearchPath>,
156 pub target_tlib_path: Lrc<SearchPath>,
157 pub parse_sess: ParseSess,
158 pub sysroot: PathBuf,
159 /// Input, input file path and output file path to this compilation process.
162 crate_types: OnceCell<Vec<CrateType>>,
163 /// The `stable_crate_id` is constructed out of the crate name and all the
164 /// `-C metadata` arguments passed to the compiler. Its value forms a unique
165 /// global identifier for the crate. It is used to allow multiple crates
166 /// with the same name to coexist. See the
167 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
168 pub stable_crate_id: OnceCell<StableCrateId>,
170 features: OnceCell<rustc_feature::Features>,
172 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
173 /// Used for incremental compilation tests. Will only be populated if
174 /// `-Zquery-dep-graph` is specified.
175 pub cgu_reuse_tracker: CguReuseTracker,
177 /// Used by `-Z self-profile`.
178 pub prof: SelfProfilerRef,
180 /// Some measurements that are being gathered during compilation.
181 pub perf_stats: PerfStats,
183 /// Data about code being compiled, gathered during compilation.
184 pub code_stats: CodeStats,
186 /// Tracks fuel info if `-zfuel=crate=n` is specified.
187 optimization_fuel: Lock<OptimizationFuel>,
189 /// Always set to zero and incremented so that we can print fuel expended by a crate.
190 pub print_fuel: AtomicU64,
192 /// Loaded up early on in the initialization of this `Session` to avoid
193 /// false positives about a job server in our environment.
194 pub jobserver: Client,
196 /// Cap lint level specified by a driver specifically.
197 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
199 /// Tracks the current behavior of the CTFE engine when an error occurs.
200 /// Options range from returning the error without a backtrace to returning an error
201 /// and immediately printing the backtrace to stderr.
202 /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
203 /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
205 pub ctfe_backtrace: Lock<CtfeBacktrace>,
207 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
208 /// const check, optionally with the relevant feature gate. We use this to
209 /// warn about unleashing, but with a single diagnostic instead of dozens that
210 /// drown everything else in noise.
211 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
213 /// Architecture to use for interpreting asm!.
214 pub asm_arch: Option<InlineAsmArch>,
216 /// Set of enabled features for the current target.
217 pub target_features: FxHashSet<Symbol>,
219 /// Set of enabled features for the current target, including unstable ones.
220 pub unstable_target_features: FxHashSet<Symbol>,
223 pub struct PerfStats {
224 /// The accumulated time spent on computing symbol hashes.
225 pub symbol_hash_time: Lock<Duration>,
226 /// Total number of values canonicalized queries constructed.
227 pub queries_canonicalized: AtomicUsize,
228 /// Number of times this query is invoked.
229 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
230 /// Number of times this query is invoked.
231 pub normalize_projection_ty: AtomicUsize,
235 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
236 self.miri_unleashed_features.lock().push((span, feature_gate));
239 pub fn local_crate_source_file(&self) -> Option<PathBuf> {
240 let path = self.io.input.opt_path()?;
241 Some(self.opts.file_path_mapping().map_prefix(path).0.into_owned())
244 fn check_miri_unleashed_features(&self) {
245 let unleashed_features = self.miri_unleashed_features.lock();
246 if !unleashed_features.is_empty() {
247 let mut must_err = false;
248 // Create a diagnostic pointing at where things got unleashed.
249 self.emit_warning(SkippingConstChecks {
250 unleashed_features: unleashed_features
252 .map(|(span, gate)| {
255 UnleashedFeatureHelp::Named { span: *span, gate }
257 .unwrap_or(UnleashedFeatureHelp::Unnamed { span: *span })
262 // If we should err, make sure we did.
263 if must_err && self.has_errors().is_none() {
264 // We have skipped a feature gate, and not run into other errors... reject.
265 self.emit_err(NotCircumventFeature);
270 /// Invoked all the way at the end to finish off diagnostics printing.
271 pub fn finish_diagnostics(&self, registry: &Registry) {
272 self.check_miri_unleashed_features();
273 self.diagnostic().print_error_count(registry);
274 self.emit_future_breakage();
277 fn emit_future_breakage(&self) {
278 if !self.opts.json_future_incompat {
282 let diags = self.diagnostic().take_future_breakage_diagnostics();
283 if diags.is_empty() {
286 self.parse_sess.span_diagnostic.emit_future_breakage_report(diags);
289 pub fn local_stable_crate_id(&self) -> StableCrateId {
290 self.stable_crate_id.get().copied().unwrap()
293 pub fn crate_types(&self) -> &[CrateType] {
294 self.crate_types.get().unwrap().as_slice()
297 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
298 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
301 #[rustc_lint_diagnostics]
303 pub fn struct_span_warn<S: Into<MultiSpan>>(
306 msg: impl Into<DiagnosticMessage>,
307 ) -> DiagnosticBuilder<'_, ()> {
308 self.diagnostic().struct_span_warn(sp, msg)
310 #[rustc_lint_diagnostics]
312 pub fn struct_span_warn_with_expectation<S: Into<MultiSpan>>(
315 msg: impl Into<DiagnosticMessage>,
316 id: lint::LintExpectationId,
317 ) -> DiagnosticBuilder<'_, ()> {
318 self.diagnostic().struct_span_warn_with_expectation(sp, msg, id)
320 #[rustc_lint_diagnostics]
322 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
325 msg: impl Into<DiagnosticMessage>,
327 ) -> DiagnosticBuilder<'_, ()> {
328 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
330 #[rustc_lint_diagnostics]
332 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
333 self.diagnostic().struct_warn(msg)
335 #[rustc_lint_diagnostics]
337 pub fn struct_warn_with_expectation(
339 msg: impl Into<DiagnosticMessage>,
340 id: lint::LintExpectationId,
341 ) -> DiagnosticBuilder<'_, ()> {
342 self.diagnostic().struct_warn_with_expectation(msg, id)
344 #[rustc_lint_diagnostics]
346 pub fn struct_span_allow<S: Into<MultiSpan>>(
349 msg: impl Into<DiagnosticMessage>,
350 ) -> DiagnosticBuilder<'_, ()> {
351 self.diagnostic().struct_span_allow(sp, msg)
353 #[rustc_lint_diagnostics]
355 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
356 self.diagnostic().struct_allow(msg)
358 #[rustc_lint_diagnostics]
360 pub fn struct_expect(
362 msg: impl Into<DiagnosticMessage>,
363 id: lint::LintExpectationId,
364 ) -> DiagnosticBuilder<'_, ()> {
365 self.diagnostic().struct_expect(msg, id)
367 #[rustc_lint_diagnostics]
369 pub fn struct_span_err<S: Into<MultiSpan>>(
372 msg: impl Into<DiagnosticMessage>,
373 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
374 self.diagnostic().struct_span_err(sp, msg)
376 #[rustc_lint_diagnostics]
378 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
381 msg: impl Into<DiagnosticMessage>,
383 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
384 self.diagnostic().struct_span_err_with_code(sp, msg, code)
386 // FIXME: This method should be removed (every error should have an associated error code).
387 #[rustc_lint_diagnostics]
391 msg: impl Into<DiagnosticMessage>,
392 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
393 self.parse_sess.struct_err(msg)
396 #[rustc_lint_diagnostics]
397 pub fn struct_err_with_code(
399 msg: impl Into<DiagnosticMessage>,
401 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
402 self.diagnostic().struct_err_with_code(msg, code)
404 #[rustc_lint_diagnostics]
406 pub fn struct_warn_with_code(
408 msg: impl Into<DiagnosticMessage>,
410 ) -> DiagnosticBuilder<'_, ()> {
411 self.diagnostic().struct_warn_with_code(msg, code)
413 #[rustc_lint_diagnostics]
415 pub fn struct_span_fatal<S: Into<MultiSpan>>(
418 msg: impl Into<DiagnosticMessage>,
419 ) -> DiagnosticBuilder<'_, !> {
420 self.diagnostic().struct_span_fatal(sp, msg)
422 #[rustc_lint_diagnostics]
423 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
426 msg: impl Into<DiagnosticMessage>,
428 ) -> DiagnosticBuilder<'_, !> {
429 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
431 #[rustc_lint_diagnostics]
432 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
433 self.diagnostic().struct_fatal(msg)
436 #[rustc_lint_diagnostics]
438 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
439 self.diagnostic().span_fatal(sp, msg)
441 #[rustc_lint_diagnostics]
442 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
445 msg: impl Into<DiagnosticMessage>,
448 self.diagnostic().span_fatal_with_code(sp, msg, code)
450 #[rustc_lint_diagnostics]
451 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! {
452 self.diagnostic().fatal(msg).raise()
454 #[rustc_lint_diagnostics]
456 pub fn span_err_or_warn<S: Into<MultiSpan>>(
460 msg: impl Into<DiagnosticMessage>,
463 self.span_warn(sp, msg);
465 self.span_err(sp, msg);
468 #[rustc_lint_diagnostics]
470 pub fn span_err<S: Into<MultiSpan>>(
473 msg: impl Into<DiagnosticMessage>,
474 ) -> ErrorGuaranteed {
475 self.diagnostic().span_err(sp, msg)
477 #[rustc_lint_diagnostics]
478 pub fn span_err_with_code<S: Into<MultiSpan>>(
481 msg: impl Into<DiagnosticMessage>,
484 self.diagnostic().span_err_with_code(sp, msg, code)
486 #[rustc_lint_diagnostics]
487 #[allow(rustc::untranslatable_diagnostic)]
488 #[allow(rustc::diagnostic_outside_of_impl)]
489 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
490 self.diagnostic().err(msg)
493 pub fn create_err<'a>(
495 err: impl IntoDiagnostic<'a>,
496 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
497 self.parse_sess.create_err(err)
500 pub fn create_feature_err<'a>(
502 err: impl IntoDiagnostic<'a>,
504 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
505 let mut err = self.parse_sess.create_err(err);
506 if err.code.is_none() {
507 err.code = std::option::Option::Some(error_code!(E0658));
509 add_feature_diagnostics(&mut err, &self.parse_sess, feature);
513 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
514 self.parse_sess.emit_err(err)
517 pub fn create_warning<'a>(
519 err: impl IntoDiagnostic<'a, ()>,
520 ) -> DiagnosticBuilder<'a, ()> {
521 self.parse_sess.create_warning(err)
524 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
525 self.parse_sess.emit_warning(warning)
528 pub fn create_note<'a>(
530 note: impl IntoDiagnostic<'a, Noted>,
531 ) -> DiagnosticBuilder<'a, Noted> {
532 self.parse_sess.create_note(note)
535 pub fn emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted {
536 self.parse_sess.emit_note(note)
539 pub fn create_fatal<'a>(
541 fatal: impl IntoDiagnostic<'a, !>,
542 ) -> DiagnosticBuilder<'a, !> {
543 self.parse_sess.create_fatal(fatal)
546 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
547 self.parse_sess.emit_fatal(fatal)
550 pub fn err_count(&self) -> usize {
551 self.diagnostic().err_count()
553 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
554 self.diagnostic().has_errors()
556 pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> {
557 self.diagnostic().has_errors_or_delayed_span_bugs()
559 pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> {
560 self.diagnostic().is_compilation_going_to_fail()
562 pub fn abort_if_errors(&self) {
563 self.diagnostic().abort_if_errors();
565 pub fn compile_status(&self) -> Result<(), ErrorGuaranteed> {
566 if let Some(reported) = self.diagnostic().has_errors_or_lint_errors() {
567 let _ = self.diagnostic().emit_stashed_diagnostics();
573 // FIXME(matthewjasper) Remove this method, it should never be needed.
574 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorGuaranteed>
578 let old_count = self.err_count();
580 if self.err_count() == old_count {
583 Err(self.delay_span_bug(
584 rustc_span::DUMMY_SP,
585 "`self.err_count()` changed but an error was not emitted",
590 #[rustc_lint_diagnostics]
591 #[allow(rustc::untranslatable_diagnostic)]
592 #[allow(rustc::diagnostic_outside_of_impl)]
594 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
595 self.diagnostic().span_warn(sp, msg)
598 #[rustc_lint_diagnostics]
599 #[allow(rustc::untranslatable_diagnostic)]
600 #[allow(rustc::diagnostic_outside_of_impl)]
601 pub fn span_warn_with_code<S: Into<MultiSpan>>(
604 msg: impl Into<DiagnosticMessage>,
607 self.diagnostic().span_warn_with_code(sp, msg, code)
610 #[rustc_lint_diagnostics]
611 #[allow(rustc::untranslatable_diagnostic)]
612 #[allow(rustc::diagnostic_outside_of_impl)]
613 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
614 self.diagnostic().warn(msg)
617 /// Ensures that compilation cannot succeed.
619 /// If this function has been called but no errors have been emitted and
620 /// compilation succeeds, it will cause an internal compiler error (ICE).
622 /// This can be used in code paths that should never run on successful compilations.
623 /// For example, it can be used to create an [`ErrorGuaranteed`]
624 /// (but you should prefer threading through the [`ErrorGuaranteed`] from an error emission directly).
626 /// If no span is available, use [`DUMMY_SP`].
628 /// [`DUMMY_SP`]: rustc_span::DUMMY_SP
630 pub fn delay_span_bug<S: Into<MultiSpan>>(
633 msg: impl Into<DiagnosticMessage>,
634 ) -> ErrorGuaranteed {
635 self.diagnostic().delay_span_bug(sp, msg)
638 /// Used for code paths of expensive computations that should only take place when
639 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
640 /// it's likely a bug.
641 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
642 if self.opts.unstable_opts.print_type_sizes
643 || self.opts.unstable_opts.query_dep_graph
644 || self.opts.unstable_opts.dump_mir.is_some()
645 || self.opts.unstable_opts.unpretty.is_some()
646 || self.opts.output_types.contains_key(&OutputType::Mir)
647 || std::env::var_os("RUSTC_LOG").is_some()
652 self.diagnostic().delay_good_path_bug(msg)
655 #[rustc_lint_diagnostics]
656 #[allow(rustc::untranslatable_diagnostic)]
657 #[allow(rustc::diagnostic_outside_of_impl)]
658 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
659 self.diagnostic().note_without_error(msg)
663 #[rustc_lint_diagnostics]
664 #[allow(rustc::untranslatable_diagnostic)]
665 #[allow(rustc::diagnostic_outside_of_impl)]
666 pub fn span_note_without_error<S: Into<MultiSpan>>(
669 msg: impl Into<DiagnosticMessage>,
671 self.diagnostic().span_note_without_error(sp, msg)
674 #[rustc_lint_diagnostics]
675 #[allow(rustc::untranslatable_diagnostic)]
676 #[allow(rustc::diagnostic_outside_of_impl)]
677 pub fn struct_note_without_error(
679 msg: impl Into<DiagnosticMessage>,
680 ) -> DiagnosticBuilder<'_, ()> {
681 self.diagnostic().struct_note_without_error(msg)
685 pub fn diagnostic(&self) -> &rustc_errors::Handler {
686 &self.parse_sess.span_diagnostic
690 pub fn source_map(&self) -> &SourceMap {
691 self.parse_sess.source_map()
694 /// Returns `true` if internal lints should be added to the lint store - i.e. if
695 /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
696 /// to be emitted under rustdoc).
697 pub fn enable_internal_lints(&self) -> bool {
698 self.unstable_options() && !self.opts.actually_rustdoc
701 pub fn instrument_coverage(&self) -> bool {
702 self.opts.cg.instrument_coverage() != InstrumentCoverage::Off
705 pub fn instrument_coverage_except_unused_generics(&self) -> bool {
706 self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedGenerics
709 pub fn instrument_coverage_except_unused_functions(&self) -> bool {
710 self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedFunctions
713 /// Gets the features enabled for the current compilation session.
714 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
715 /// dependency tracking. Use tcx.features() instead.
717 pub fn features_untracked(&self) -> &rustc_feature::Features {
718 self.features.get().unwrap()
721 pub fn init_features(&self, features: rustc_feature::Features) {
722 match self.features.set(features) {
724 Err(_) => panic!("`features` was initialized twice"),
728 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
729 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
732 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
733 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
736 /// Check whether this compile session and crate type use static crt.
737 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
738 if !self.target.crt_static_respected {
739 // If the target does not opt in to crt-static support, use its default.
740 return self.target.crt_static_default;
743 let requested_features = self.opts.cg.target_feature.split(',');
744 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
745 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
747 // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
748 #[allow(rustc::bad_opt_access)]
749 if found_positive || found_negative {
751 } else if crate_type == Some(CrateType::ProcMacro)
752 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
754 // FIXME: When crate_type is not available,
755 // we use compiler options to determine the crate_type.
756 // We can't check `#![crate_type = "proc-macro"]` here.
759 self.target.crt_static_default
763 pub fn is_wasi_reactor(&self) -> bool {
764 self.target.options.os == "wasi"
766 self.opts.unstable_opts.wasi_exec_model,
767 Some(config::WasiExecModel::Reactor)
771 /// Returns `true` if the target can use the current split debuginfo configuration.
772 pub fn target_can_use_split_dwarf(&self) -> bool {
773 self.target.debuginfo_kind == DebuginfoKind::Dwarf
776 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
777 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.to_u64())
780 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
781 filesearch::FileSearch::new(
783 self.opts.target_triple.triple(),
784 &self.opts.search_paths,
785 &self.target_tlib_path,
789 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
790 filesearch::FileSearch::new(
792 config::host_triple(),
793 &self.opts.search_paths,
794 &self.host_tlib_path,
799 /// Returns a list of directories where target-specific tool binaries are located.
800 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
801 let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple());
802 let p = PathBuf::from_iter([
803 Path::new(&self.sysroot),
804 Path::new(&rustlib_path),
807 if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
810 pub fn init_incr_comp_session(
812 session_dir: PathBuf,
813 lock_file: flock::Lock,
814 load_dep_graph: bool,
816 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
818 if let IncrCompSession::NotInitialized = *incr_comp_session {
820 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
824 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
827 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
828 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
830 if let IncrCompSession::Active { .. } = *incr_comp_session {
832 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
835 // Note: this will also drop the lock file, thus unlocking the directory.
836 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
839 pub fn mark_incr_comp_session_as_invalid(&self) {
840 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
842 let session_directory = match *incr_comp_session {
843 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
844 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
845 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
848 // Note: this will also drop the lock file, thus unlocking the directory.
849 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
852 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
853 let incr_comp_session = self.incr_comp_session.borrow();
854 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
855 IncrCompSession::NotInitialized => panic!(
856 "trying to get session directory from `IncrCompSession`: {:?}",
859 IncrCompSession::Active { ref session_directory, .. }
860 | IncrCompSession::Finalized { ref session_directory }
861 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
867 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
868 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
871 pub fn print_perf_stats(&self) {
873 "Total time spent computing symbol hashes: {}",
874 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
877 "Total queries canonicalized: {}",
878 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
881 "normalize_generic_arg_after_erasing_regions: {}",
882 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
885 "normalize_projection_ty: {}",
886 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
890 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
891 /// This expends fuel if applicable, and records fuel if applicable.
892 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
894 if let Some((ref c, _)) = self.opts.unstable_opts.fuel {
896 assert_eq!(self.threads(), 1);
897 let mut fuel = self.optimization_fuel.lock();
898 ret = fuel.remaining != 0;
899 if fuel.remaining == 0 && !fuel.out_of_fuel {
900 if self.diagnostic().can_emit_warnings() {
901 // We only call `msg` in case we can actually emit warnings.
902 // Otherwise, this could cause a `delay_good_path_bug` to
903 // trigger (issue #79546).
904 self.emit_warning(OptimisationFuelExhausted { msg: msg() });
906 fuel.out_of_fuel = true;
907 } else if fuel.remaining > 0 {
912 if let Some(ref c) = self.opts.unstable_opts.print_fuel {
914 assert_eq!(self.threads(), 1);
915 self.print_fuel.fetch_add(1, SeqCst);
921 pub fn rust_2015(&self) -> bool {
922 self.edition() == Edition::Edition2015
925 /// Are we allowed to use features from the Rust 2018 edition?
926 pub fn rust_2018(&self) -> bool {
927 self.edition() >= Edition::Edition2018
930 /// Are we allowed to use features from the Rust 2021 edition?
931 pub fn rust_2021(&self) -> bool {
932 self.edition() >= Edition::Edition2021
935 /// Are we allowed to use features from the Rust 2024 edition?
936 pub fn rust_2024(&self) -> bool {
937 self.edition() >= Edition::Edition2024
940 /// Returns `true` if we cannot skip the PLT for shared library calls.
941 pub fn needs_plt(&self) -> bool {
942 // Check if the current target usually needs PLT to be enabled.
943 // The user can use the command line flag to override it.
944 let needs_plt = self.target.needs_plt;
946 let dbg_opts = &self.opts.unstable_opts;
948 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
950 // Only enable this optimization by default if full relro is also enabled.
951 // In this case, lazy binding was already unavailable, so nothing is lost.
952 // This also ensures `-Wl,-z,now` is supported by the linker.
953 let full_relro = RelroLevel::Full == relro_level;
955 // If user didn't explicitly forced us to use / skip the PLT,
956 // then try to skip it where possible.
957 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
960 /// Checks if LLVM lifetime markers should be emitted.
961 pub fn emit_lifetime_markers(&self) -> bool {
962 self.opts.optimize != config::OptLevel::No
963 // AddressSanitizer uses lifetimes to detect use after scope bugs.
964 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
965 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
966 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
969 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
970 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
972 .any(|kind| attr.has_name(*kind))
975 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
976 attrs.iter().any(|item| item.has_name(name))
979 pub fn find_by_name<'a>(
981 attrs: &'a [Attribute],
983 ) -> Option<&'a Attribute> {
984 attrs.iter().find(|attr| attr.has_name(name))
987 pub fn filter_by_name<'a>(
989 attrs: &'a [Attribute],
991 ) -> impl Iterator<Item = &'a Attribute> {
992 attrs.iter().filter(move |attr| attr.has_name(name))
995 pub fn first_attr_value_str_by_name(
999 ) -> Option<Symbol> {
1000 attrs.iter().find(|at| at.has_name(name)).and_then(|at| at.value_str())
1003 pub fn diagnostic_width(&self) -> usize {
1004 let default_column_width = 140;
1005 if let Some(width) = self.opts.diagnostic_width {
1007 } else if self.opts.unstable_opts.ui_testing {
1008 default_column_width
1010 termize::dimensions().map_or(default_column_width, |(w, _)| w)
1015 // JUSTIFICATION: defn of the suggested wrapper fns
1016 #[allow(rustc::bad_opt_access)]
1018 pub fn verbose(&self) -> bool {
1019 self.opts.unstable_opts.verbose
1022 pub fn verify_llvm_ir(&self) -> bool {
1023 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
1026 pub fn binary_dep_depinfo(&self) -> bool {
1027 self.opts.unstable_opts.binary_dep_depinfo
1030 pub fn mir_opt_level(&self) -> usize {
1034 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
1037 /// Calculates the flavor of LTO to use for this compilation.
1038 pub fn lto(&self) -> config::Lto {
1039 // If our target has codegen requirements ignore the command line
1040 if self.target.requires_lto {
1041 return config::Lto::Fat;
1044 // If the user specified something, return that. If they only said `-C
1045 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
1046 // then ensure we can't use a ThinLTO.
1047 match self.opts.cg.lto {
1048 config::LtoCli::Unspecified => {
1049 // The compiler was invoked without the `-Clto` flag. Fall
1050 // through to the default handling
1052 config::LtoCli::No => {
1053 // The user explicitly opted out of any kind of LTO
1054 return config::Lto::No;
1056 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
1057 // All of these mean fat LTO
1058 return config::Lto::Fat;
1060 config::LtoCli::Thin => {
1061 // The user explicitly asked for ThinLTO
1062 return config::Lto::Thin;
1066 // Ok at this point the target doesn't require anything and the user
1067 // hasn't asked for anything. Our next decision is whether or not
1068 // we enable "auto" ThinLTO where we use multiple codegen units and
1069 // then do ThinLTO over those codegen units. The logic below will
1070 // either return `No` or `ThinLocal`.
1072 // If processing command line options determined that we're incompatible
1073 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
1074 if self.opts.cli_forced_local_thinlto_off {
1075 return config::Lto::No;
1078 // If `-Z thinlto` specified process that, but note that this is mostly
1079 // a deprecated option now that `-C lto=thin` exists.
1080 if let Some(enabled) = self.opts.unstable_opts.thinlto {
1082 return config::Lto::ThinLocal;
1084 return config::Lto::No;
1088 // If there's only one codegen unit and LTO isn't enabled then there's
1089 // no need for ThinLTO so just return false.
1090 if self.codegen_units() == 1 {
1091 return config::Lto::No;
1094 // Now we're in "defaults" territory. By default we enable ThinLTO for
1095 // optimized compiles (anything greater than O0).
1096 match self.opts.optimize {
1097 config::OptLevel::No => config::Lto::No,
1098 _ => config::Lto::ThinLocal,
1102 /// Returns the panic strategy for this compile session. If the user explicitly selected one
1103 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
1104 pub fn panic_strategy(&self) -> PanicStrategy {
1105 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
1108 pub fn fewer_names(&self) -> bool {
1109 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1112 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1113 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1114 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1115 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1120 pub fn unstable_options(&self) -> bool {
1121 self.opts.unstable_opts.unstable_options
1124 pub fn is_nightly_build(&self) -> bool {
1125 self.opts.unstable_features.is_nightly_build()
1128 pub fn overflow_checks(&self) -> bool {
1129 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1132 pub fn relocation_model(&self) -> RelocModel {
1133 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
1136 pub fn code_model(&self) -> Option<CodeModel> {
1137 self.opts.cg.code_model.or(self.target.code_model)
1140 pub fn tls_model(&self) -> TlsModel {
1141 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
1144 pub fn split_debuginfo(&self) -> SplitDebuginfo {
1145 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1148 pub fn stack_protector(&self) -> StackProtector {
1149 if self.target.options.supports_stack_protector {
1150 self.opts.unstable_opts.stack_protector
1152 StackProtector::None
1156 pub fn must_emit_unwind_tables(&self) -> bool {
1157 // This is used to control the emission of the `uwtable` attribute on
1160 // Unwind tables are needed when compiling with `-C panic=unwind`, but
1161 // LLVM won't omit unwind tables unless the function is also marked as
1162 // `nounwind`, so users are allowed to disable `uwtable` emission.
1163 // Historically rustc always emits `uwtable` attributes by default, so
1164 // even they can be disabled, they're still emitted by default.
1166 // On some targets (including windows), however, exceptions include
1167 // other events such as illegal instructions, segfaults, etc. This means
1168 // that on Windows we end up still needing unwind tables even if the `-C
1169 // panic=abort` flag is passed.
1171 // You can also find more info on why Windows needs unwind tables in:
1172 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1174 // If a target requires unwind tables, then they must be emitted.
1175 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1176 // value, if it is provided, or disable them, if not.
1177 self.target.requires_uwtable
1178 || self.opts.cg.force_unwind_tables.unwrap_or(
1179 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
1183 /// Returns the number of query threads that should be used for this
1185 pub fn threads(&self) -> usize {
1186 self.opts.unstable_opts.threads
1189 /// Returns the number of codegen units that should be used for this
1191 pub fn codegen_units(&self) -> usize {
1192 if let Some(n) = self.opts.cli_forced_codegen_units {
1195 if let Some(n) = self.target.default_codegen_units {
1199 // If incremental compilation is turned on, we default to a high number
1200 // codegen units in order to reduce the "collateral damage" small
1202 if self.opts.incremental.is_some() {
1206 // Why is 16 codegen units the default all the time?
1208 // The main reason for enabling multiple codegen units by default is to
1209 // leverage the ability for the codegen backend to do codegen and
1210 // optimization in parallel. This allows us, especially for large crates, to
1211 // make good use of all available resources on the machine once we've
1212 // hit that stage of compilation. Large crates especially then often
1213 // take a long time in codegen/optimization and this helps us amortize that
1216 // Note that a high number here doesn't mean that we'll be spawning a
1217 // large number of threads in parallel. The backend of rustc contains
1218 // global rate limiting through the `jobserver` crate so we'll never
1219 // overload the system with too much work, but rather we'll only be
1220 // optimizing when we're otherwise cooperating with other instances of
1223 // Rather a high number here means that we should be able to keep a lot
1224 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1225 // to build we'll be guaranteed that all cpus will finish pretty closely
1226 // to one another and we should make relatively optimal use of system
1229 // Note that the main cost of codegen units is that it prevents LLVM
1230 // from inlining across codegen units. Users in general don't have a lot
1231 // of control over how codegen units are split up so it's our job in the
1232 // compiler to ensure that undue performance isn't lost when using
1233 // codegen units (aka we can't require everyone to slap `#[inline]` on
1236 // If we're compiling at `-O0` then the number doesn't really matter too
1237 // much because performance doesn't matter and inlining is ok to lose.
1238 // In debug mode we just want to try to guarantee that no cpu is stuck
1239 // doing work that could otherwise be farmed to others.
1241 // In release mode, however (O1 and above) performance does indeed
1242 // matter! To recover the loss in performance due to inlining we'll be
1243 // enabling ThinLTO by default (the function for which is just below).
1244 // This will ensure that we recover any inlining wins we otherwise lost
1245 // through codegen unit partitioning.
1249 // Ok that's a lot of words but the basic tl;dr; is that we want a high
1250 // number here -- but not too high. Additionally we're "safe" to have it
1251 // always at the same number at all optimization levels.
1253 // As a result 16 was chosen here! Mostly because it was a power of 2
1254 // and most benchmarks agreed it was roughly a local optimum. Not very
1259 pub fn teach(&self, code: &DiagnosticId) -> bool {
1260 self.opts.unstable_opts.teach && self.diagnostic().must_teach(code)
1263 pub fn edition(&self) -> Edition {
1267 pub fn link_dead_code(&self) -> bool {
1268 self.opts.cg.link_dead_code.unwrap_or(false)
1272 // JUSTIFICATION: part of session construction
1273 #[allow(rustc::bad_opt_access)]
1275 sopts: &config::Options,
1276 registry: rustc_errors::registry::Registry,
1277 source_map: Lrc<SourceMap>,
1278 bundle: Option<Lrc<FluentBundle>>,
1279 fallback_bundle: LazyFallbackBundle,
1280 ) -> Box<dyn Emitter + sync::Send> {
1281 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1282 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1283 match sopts.error_format {
1284 config::ErrorOutputType::HumanReadable(kind) => {
1285 let (short, color_config) = kind.unzip();
1287 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1288 let emitter = AnnotateSnippetEmitterWriter::new(
1295 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1297 let emitter = EmitterWriter::stderr(
1303 sopts.unstable_opts.teach,
1304 sopts.diagnostic_width,
1308 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1311 config::ErrorOutputType::Json { pretty, json_rendered } => Box::new(
1312 JsonEmitter::stderr(
1319 sopts.diagnostic_width,
1323 .ui_testing(sopts.unstable_opts.ui_testing),
1328 // JUSTIFICATION: literally session construction
1329 #[allow(rustc::bad_opt_access)]
1330 pub fn build_session(
1331 sopts: config::Options,
1333 bundle: Option<Lrc<rustc_errors::FluentBundle>>,
1334 registry: rustc_errors::registry::Registry,
1335 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1336 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1337 target_override: Option<Target>,
1339 // FIXME: This is not general enough to make the warning lint completely override
1340 // normal diagnostic warnings, since the warning lint can also be denied and changed
1341 // later via the source code.
1342 let warnings_allow = sopts
1345 .rfind(|&(key, _)| *key == "warnings")
1346 .map_or(false, |&(_, level)| level == lint::Allow);
1347 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1348 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1350 let sysroot = match &sopts.maybe_sysroot {
1351 Some(sysroot) => sysroot.clone(),
1352 None => filesearch::get_or_default_sysroot().expect("Failed finding sysroot"),
1355 let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
1356 let host_triple = TargetTriple::from_triple(config::host_triple());
1357 let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1358 early_error(sopts.error_format, &format!("Error loading host specification: {e}"))
1360 for warning in target_warnings.warning_messages() {
1361 early_warn(sopts.error_format, &warning)
1364 let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1365 let hash_kind = sopts.unstable_opts.src_hash_algorithm.unwrap_or_else(|| {
1366 if target_cfg.is_like_msvc {
1367 SourceFileHashAlgorithm::Sha1
1369 SourceFileHashAlgorithm::Md5
1372 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1374 sopts.file_path_mapping(),
1378 let fallback_bundle = fallback_fluent_bundle(
1379 rustc_errors::DEFAULT_LOCALE_RESOURCES,
1380 sopts.unstable_opts.translate_directionality_markers,
1382 let emitter = default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle);
1384 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1386 sopts.unstable_opts.diagnostic_handler_flags(can_emit_warnings),
1389 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1392 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1394 let profiler = SelfProfiler::new(
1396 sopts.crate_name.as_deref(),
1397 sopts.unstable_opts.self_profile_events.as_deref(),
1398 &sopts.unstable_opts.self_profile_counter,
1401 Ok(profiler) => Some(Arc::new(profiler)),
1403 early_warn(sopts.error_format, &format!("failed to create profiler: {e}"));
1411 let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1412 parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1414 let host_triple = config::host_triple();
1415 let target_triple = sopts.target_triple.triple();
1416 let host_tlib_path = Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1417 let target_tlib_path = if host_triple == target_triple {
1418 // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1419 // rescanning of the target lib path and an unnecessary allocation.
1420 host_tlib_path.clone()
1422 Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1425 let optimization_fuel = Lock::new(OptimizationFuel {
1426 remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |&(_, i)| i),
1429 let print_fuel = AtomicU64::new(0);
1431 let cgu_reuse_tracker = if sopts.unstable_opts.query_dep_graph {
1432 CguReuseTracker::new()
1434 CguReuseTracker::new_disabled()
1437 let prof = SelfProfilerRef::new(self_profiler, sopts.unstable_opts.time_passes);
1439 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1440 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1441 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1442 _ => CtfeBacktrace::Disabled,
1446 if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1448 let sess = Session {
1457 crate_types: OnceCell::new(),
1458 stable_crate_id: OnceCell::new(),
1459 features: OnceCell::new(),
1460 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1463 perf_stats: PerfStats {
1464 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1465 queries_canonicalized: AtomicUsize::new(0),
1466 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1467 normalize_projection_ty: AtomicUsize::new(0),
1469 code_stats: Default::default(),
1472 jobserver: jobserver::client(),
1475 miri_unleashed_features: Lock::new(Default::default()),
1477 target_features: FxHashSet::default(),
1478 unstable_target_features: FxHashSet::default(),
1481 validate_commandline_args_with_session_available(&sess);
1486 /// Validate command line arguments with a `Session`.
1488 /// If it is useful to have a Session available already for validating a commandline argument, you
1490 // JUSTIFICATION: needs to access args to validate them
1491 #[allow(rustc::bad_opt_access)]
1492 fn validate_commandline_args_with_session_available(sess: &Session) {
1493 // Since we don't know if code in an rlib will be linked to statically or
1494 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1495 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1496 // these manually generated symbols confuse LLD when it tries to merge
1497 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1498 // when compiling for LLD ThinLTO. This way we can validly just not generate
1499 // the `dllimport` attributes and `__imp_` symbols in that case.
1500 if sess.opts.cg.linker_plugin_lto.enabled()
1501 && sess.opts.cg.prefer_dynamic
1502 && sess.target.is_like_windows
1504 sess.emit_err(LinkerPluginToWindowsNotSupported);
1507 // Make sure that any given profiling data actually exists so LLVM can't
1508 // decide to silently skip PGO.
1509 if let Some(ref path) = sess.opts.cg.profile_use {
1511 sess.emit_err(ProfileUseFileDoesNotExist { path });
1515 // Do the same for sample profile data.
1516 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1518 sess.emit_err(ProfileSampleUseFileDoesNotExist { path });
1522 // Unwind tables cannot be disabled if the target requires them.
1523 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1524 if sess.target.requires_uwtable && !include_uwtables {
1525 sess.emit_err(TargetRequiresUnwindTables);
1529 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1530 let supported_sanitizers = sess.target.options.supported_sanitizers;
1531 let unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1532 match unsupported_sanitizers.into_iter().count() {
1535 sess.emit_err(SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1538 sess.emit_err(SanitizersNotSupported { us: unsupported_sanitizers.to_string() });
1541 // Cannot mix and match sanitizers.
1542 let mut sanitizer_iter = sess.opts.unstable_opts.sanitizer.into_iter();
1543 if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1544 sess.emit_err(CannotMixAndMatchSanitizers {
1545 first: first.to_string(),
1546 second: second.to_string(),
1550 // Cannot enable crt-static with sanitizers on Linux
1551 if sess.crt_static(None) && !sess.opts.unstable_opts.sanitizer.is_empty() {
1552 sess.emit_err(CannotEnableCrtStaticLinux);
1555 // LLVM CFI and VFE both require LTO.
1556 if sess.lto() != config::Lto::Fat {
1557 if sess.is_sanitizer_cfi_enabled() {
1558 sess.emit_err(SanitizerCfiEnabled);
1560 if sess.opts.unstable_opts.virtual_function_elimination {
1561 sess.emit_err(UnstableVirtualFunctionElimination);
1565 // LLVM CFI and KCFI are mutually exclusive
1566 if sess.is_sanitizer_cfi_enabled() && sess.is_sanitizer_kcfi_enabled() {
1567 sess.emit_err(CannotMixAndMatchSanitizers {
1568 first: "cfi".to_string(),
1569 second: "kcfi".to_string(),
1573 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1574 if !sess.target.options.supports_stack_protector {
1575 sess.emit_warning(StackProtectorNotSupportedForTarget {
1576 stack_protector: sess.opts.unstable_opts.stack_protector,
1577 target_triple: &sess.opts.target_triple,
1582 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1583 sess.emit_err(BranchProtectionRequiresAArch64);
1586 if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version {
1587 if dwarf_version > 5 {
1588 sess.emit_err(UnsupportedDwarfVersion { dwarf_version });
1592 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1593 && !sess.opts.unstable_opts.unstable_options
1595 sess.emit_err(SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1599 /// Holds data on the current incremental compilation session, if there is one.
1601 pub enum IncrCompSession {
1602 /// This is the state the session will be in until the incr. comp. dir is
1605 /// This is the state during which the session directory is private and can
1607 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1608 /// This is the state after the session directory has been finalized. In this
1609 /// state, the contents of the directory must not be modified any more.
1610 Finalized { session_directory: PathBuf },
1611 /// This is an error state that is reached when some compilation error has
1612 /// occurred. It indicates that the contents of the session directory must
1613 /// not be used, since they might be invalid.
1614 InvalidBecauseOfErrors { session_directory: PathBuf },
1617 fn early_error_handler(output: config::ErrorOutputType) -> rustc_errors::Handler {
1618 let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1619 let emitter: Box<dyn Emitter + sync::Send> = match output {
1620 config::ErrorOutputType::HumanReadable(kind) => {
1621 let (short, color_config) = kind.unzip();
1622 Box::new(EmitterWriter::stderr(
1634 config::ErrorOutputType::Json { pretty, json_rendered } => Box::new(JsonEmitter::basic(
1644 rustc_errors::Handler::with_emitter(true, None, emitter)
1647 #[allow(rustc::untranslatable_diagnostic)]
1648 #[allow(rustc::diagnostic_outside_of_impl)]
1649 pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) -> ErrorGuaranteed {
1650 early_error_handler(output).struct_err(msg).emit()
1653 #[allow(rustc::untranslatable_diagnostic)]
1654 #[allow(rustc::diagnostic_outside_of_impl)]
1655 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1656 early_error_handler(output).struct_fatal(msg).emit()
1659 #[allow(rustc::untranslatable_diagnostic)]
1660 #[allow(rustc::diagnostic_outside_of_impl)]
1661 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1662 early_error_handler(output).struct_warn(msg).emit()