1 use crate::cgu_reuse_tracker::CguReuseTracker;
2 use crate::code_stats::CodeStats;
3 pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, 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 /// Is this edition 2015?
922 pub fn rust_2015(&self) -> bool {
923 self.edition().rust_2015()
926 /// Are we allowed to use features from the Rust 2018 edition?
927 pub fn rust_2018(&self) -> bool {
928 self.edition().rust_2018()
931 /// Are we allowed to use features from the Rust 2021 edition?
932 pub fn rust_2021(&self) -> bool {
933 self.edition().rust_2021()
936 /// Are we allowed to use features from the Rust 2024 edition?
937 pub fn rust_2024(&self) -> bool {
938 self.edition().rust_2024()
941 /// Returns `true` if we cannot skip the PLT for shared library calls.
942 pub fn needs_plt(&self) -> bool {
943 // Check if the current target usually needs PLT to be enabled.
944 // The user can use the command line flag to override it.
945 let needs_plt = self.target.needs_plt;
947 let dbg_opts = &self.opts.unstable_opts;
949 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
951 // Only enable this optimization by default if full relro is also enabled.
952 // In this case, lazy binding was already unavailable, so nothing is lost.
953 // This also ensures `-Wl,-z,now` is supported by the linker.
954 let full_relro = RelroLevel::Full == relro_level;
956 // If user didn't explicitly forced us to use / skip the PLT,
957 // then try to skip it where possible.
958 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
961 /// Checks if LLVM lifetime markers should be emitted.
962 pub fn emit_lifetime_markers(&self) -> bool {
963 self.opts.optimize != config::OptLevel::No
964 // AddressSanitizer uses lifetimes to detect use after scope bugs.
965 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
966 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
967 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
970 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
971 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
973 .any(|kind| attr.has_name(*kind))
976 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
977 attrs.iter().any(|item| item.has_name(name))
980 pub fn find_by_name<'a>(
982 attrs: &'a [Attribute],
984 ) -> Option<&'a Attribute> {
985 attrs.iter().find(|attr| attr.has_name(name))
988 pub fn filter_by_name<'a>(
990 attrs: &'a [Attribute],
992 ) -> impl Iterator<Item = &'a Attribute> {
993 attrs.iter().filter(move |attr| attr.has_name(name))
996 pub fn first_attr_value_str_by_name(
1000 ) -> Option<Symbol> {
1001 attrs.iter().find(|at| at.has_name(name)).and_then(|at| at.value_str())
1004 pub fn diagnostic_width(&self) -> usize {
1005 let default_column_width = 140;
1006 if let Some(width) = self.opts.diagnostic_width {
1008 } else if self.opts.unstable_opts.ui_testing {
1009 default_column_width
1011 termize::dimensions().map_or(default_column_width, |(w, _)| w)
1016 // JUSTIFICATION: defn of the suggested wrapper fns
1017 #[allow(rustc::bad_opt_access)]
1019 pub fn verbose(&self) -> bool {
1020 self.opts.unstable_opts.verbose
1023 pub fn verify_llvm_ir(&self) -> bool {
1024 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
1027 pub fn binary_dep_depinfo(&self) -> bool {
1028 self.opts.unstable_opts.binary_dep_depinfo
1031 pub fn mir_opt_level(&self) -> usize {
1035 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
1038 /// Calculates the flavor of LTO to use for this compilation.
1039 pub fn lto(&self) -> config::Lto {
1040 // If our target has codegen requirements ignore the command line
1041 if self.target.requires_lto {
1042 return config::Lto::Fat;
1045 // If the user specified something, return that. If they only said `-C
1046 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
1047 // then ensure we can't use a ThinLTO.
1048 match self.opts.cg.lto {
1049 config::LtoCli::Unspecified => {
1050 // The compiler was invoked without the `-Clto` flag. Fall
1051 // through to the default handling
1053 config::LtoCli::No => {
1054 // The user explicitly opted out of any kind of LTO
1055 return config::Lto::No;
1057 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
1058 // All of these mean fat LTO
1059 return config::Lto::Fat;
1061 config::LtoCli::Thin => {
1062 // The user explicitly asked for ThinLTO
1063 return config::Lto::Thin;
1067 // Ok at this point the target doesn't require anything and the user
1068 // hasn't asked for anything. Our next decision is whether or not
1069 // we enable "auto" ThinLTO where we use multiple codegen units and
1070 // then do ThinLTO over those codegen units. The logic below will
1071 // either return `No` or `ThinLocal`.
1073 // If processing command line options determined that we're incompatible
1074 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
1075 if self.opts.cli_forced_local_thinlto_off {
1076 return config::Lto::No;
1079 // If `-Z thinlto` specified process that, but note that this is mostly
1080 // a deprecated option now that `-C lto=thin` exists.
1081 if let Some(enabled) = self.opts.unstable_opts.thinlto {
1083 return config::Lto::ThinLocal;
1085 return config::Lto::No;
1089 // If there's only one codegen unit and LTO isn't enabled then there's
1090 // no need for ThinLTO so just return false.
1091 if self.codegen_units() == 1 {
1092 return config::Lto::No;
1095 // Now we're in "defaults" territory. By default we enable ThinLTO for
1096 // optimized compiles (anything greater than O0).
1097 match self.opts.optimize {
1098 config::OptLevel::No => config::Lto::No,
1099 _ => config::Lto::ThinLocal,
1103 /// Returns the panic strategy for this compile session. If the user explicitly selected one
1104 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
1105 pub fn panic_strategy(&self) -> PanicStrategy {
1106 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
1109 pub fn fewer_names(&self) -> bool {
1110 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1113 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1114 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1115 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1116 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1121 pub fn unstable_options(&self) -> bool {
1122 self.opts.unstable_opts.unstable_options
1125 pub fn is_nightly_build(&self) -> bool {
1126 self.opts.unstable_features.is_nightly_build()
1129 pub fn overflow_checks(&self) -> bool {
1130 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1133 pub fn relocation_model(&self) -> RelocModel {
1134 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
1137 pub fn code_model(&self) -> Option<CodeModel> {
1138 self.opts.cg.code_model.or(self.target.code_model)
1141 pub fn tls_model(&self) -> TlsModel {
1142 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
1145 pub fn split_debuginfo(&self) -> SplitDebuginfo {
1146 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1149 pub fn stack_protector(&self) -> StackProtector {
1150 if self.target.options.supports_stack_protector {
1151 self.opts.unstable_opts.stack_protector
1153 StackProtector::None
1157 pub fn must_emit_unwind_tables(&self) -> bool {
1158 // This is used to control the emission of the `uwtable` attribute on
1161 // Unwind tables are needed when compiling with `-C panic=unwind`, but
1162 // LLVM won't omit unwind tables unless the function is also marked as
1163 // `nounwind`, so users are allowed to disable `uwtable` emission.
1164 // Historically rustc always emits `uwtable` attributes by default, so
1165 // even they can be disabled, they're still emitted by default.
1167 // On some targets (including windows), however, exceptions include
1168 // other events such as illegal instructions, segfaults, etc. This means
1169 // that on Windows we end up still needing unwind tables even if the `-C
1170 // panic=abort` flag is passed.
1172 // You can also find more info on why Windows needs unwind tables in:
1173 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1175 // If a target requires unwind tables, then they must be emitted.
1176 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1177 // value, if it is provided, or disable them, if not.
1178 self.target.requires_uwtable
1179 || self.opts.cg.force_unwind_tables.unwrap_or(
1180 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
1184 /// Returns the number of query threads that should be used for this
1186 pub fn threads(&self) -> usize {
1187 self.opts.unstable_opts.threads
1190 /// Returns the number of codegen units that should be used for this
1192 pub fn codegen_units(&self) -> usize {
1193 if let Some(n) = self.opts.cli_forced_codegen_units {
1196 if let Some(n) = self.target.default_codegen_units {
1200 // If incremental compilation is turned on, we default to a high number
1201 // codegen units in order to reduce the "collateral damage" small
1203 if self.opts.incremental.is_some() {
1207 // Why is 16 codegen units the default all the time?
1209 // The main reason for enabling multiple codegen units by default is to
1210 // leverage the ability for the codegen backend to do codegen and
1211 // optimization in parallel. This allows us, especially for large crates, to
1212 // make good use of all available resources on the machine once we've
1213 // hit that stage of compilation. Large crates especially then often
1214 // take a long time in codegen/optimization and this helps us amortize that
1217 // Note that a high number here doesn't mean that we'll be spawning a
1218 // large number of threads in parallel. The backend of rustc contains
1219 // global rate limiting through the `jobserver` crate so we'll never
1220 // overload the system with too much work, but rather we'll only be
1221 // optimizing when we're otherwise cooperating with other instances of
1224 // Rather a high number here means that we should be able to keep a lot
1225 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1226 // to build we'll be guaranteed that all cpus will finish pretty closely
1227 // to one another and we should make relatively optimal use of system
1230 // Note that the main cost of codegen units is that it prevents LLVM
1231 // from inlining across codegen units. Users in general don't have a lot
1232 // of control over how codegen units are split up so it's our job in the
1233 // compiler to ensure that undue performance isn't lost when using
1234 // codegen units (aka we can't require everyone to slap `#[inline]` on
1237 // If we're compiling at `-O0` then the number doesn't really matter too
1238 // much because performance doesn't matter and inlining is ok to lose.
1239 // In debug mode we just want to try to guarantee that no cpu is stuck
1240 // doing work that could otherwise be farmed to others.
1242 // In release mode, however (O1 and above) performance does indeed
1243 // matter! To recover the loss in performance due to inlining we'll be
1244 // enabling ThinLTO by default (the function for which is just below).
1245 // This will ensure that we recover any inlining wins we otherwise lost
1246 // through codegen unit partitioning.
1250 // Ok that's a lot of words but the basic tl;dr; is that we want a high
1251 // number here -- but not too high. Additionally we're "safe" to have it
1252 // always at the same number at all optimization levels.
1254 // As a result 16 was chosen here! Mostly because it was a power of 2
1255 // and most benchmarks agreed it was roughly a local optimum. Not very
1260 pub fn teach(&self, code: &DiagnosticId) -> bool {
1261 self.opts.unstable_opts.teach && self.diagnostic().must_teach(code)
1264 pub fn edition(&self) -> Edition {
1268 pub fn link_dead_code(&self) -> bool {
1269 self.opts.cg.link_dead_code.unwrap_or(false)
1273 // JUSTIFICATION: part of session construction
1274 #[allow(rustc::bad_opt_access)]
1276 sopts: &config::Options,
1277 registry: rustc_errors::registry::Registry,
1278 source_map: Lrc<SourceMap>,
1279 bundle: Option<Lrc<FluentBundle>>,
1280 fallback_bundle: LazyFallbackBundle,
1281 ) -> Box<dyn Emitter + sync::Send> {
1282 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1283 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1284 match sopts.error_format {
1285 config::ErrorOutputType::HumanReadable(kind) => {
1286 let (short, color_config) = kind.unzip();
1288 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1289 let emitter = AnnotateSnippetEmitterWriter::new(
1296 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1298 let emitter = EmitterWriter::stderr(
1304 sopts.unstable_opts.teach,
1305 sopts.diagnostic_width,
1309 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1312 config::ErrorOutputType::Json { pretty, json_rendered } => Box::new(
1313 JsonEmitter::stderr(
1320 sopts.diagnostic_width,
1324 .ui_testing(sopts.unstable_opts.ui_testing),
1329 // JUSTIFICATION: literally session construction
1330 #[allow(rustc::bad_opt_access)]
1331 pub fn build_session(
1332 sopts: config::Options,
1334 bundle: Option<Lrc<rustc_errors::FluentBundle>>,
1335 registry: rustc_errors::registry::Registry,
1336 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1337 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1338 target_override: Option<Target>,
1340 // FIXME: This is not general enough to make the warning lint completely override
1341 // normal diagnostic warnings, since the warning lint can also be denied and changed
1342 // later via the source code.
1343 let warnings_allow = sopts
1346 .rfind(|&(key, _)| *key == "warnings")
1347 .map_or(false, |&(_, level)| level == lint::Allow);
1348 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1349 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1351 let sysroot = match &sopts.maybe_sysroot {
1352 Some(sysroot) => sysroot.clone(),
1353 None => filesearch::get_or_default_sysroot().expect("Failed finding sysroot"),
1356 let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
1357 let host_triple = TargetTriple::from_triple(config::host_triple());
1358 let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1359 early_error(sopts.error_format, &format!("Error loading host specification: {e}"))
1361 for warning in target_warnings.warning_messages() {
1362 early_warn(sopts.error_format, &warning)
1365 let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1366 let hash_kind = sopts.unstable_opts.src_hash_algorithm.unwrap_or_else(|| {
1367 if target_cfg.is_like_msvc {
1368 SourceFileHashAlgorithm::Sha1
1370 SourceFileHashAlgorithm::Md5
1373 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1375 sopts.file_path_mapping(),
1379 let fallback_bundle = fallback_fluent_bundle(
1380 rustc_errors::DEFAULT_LOCALE_RESOURCES,
1381 sopts.unstable_opts.translate_directionality_markers,
1383 let emitter = default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle);
1385 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1387 sopts.unstable_opts.diagnostic_handler_flags(can_emit_warnings),
1390 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1393 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1395 let profiler = SelfProfiler::new(
1397 sopts.crate_name.as_deref(),
1398 sopts.unstable_opts.self_profile_events.as_deref(),
1399 &sopts.unstable_opts.self_profile_counter,
1402 Ok(profiler) => Some(Arc::new(profiler)),
1404 early_warn(sopts.error_format, &format!("failed to create profiler: {e}"));
1412 let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1413 parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1415 let host_triple = config::host_triple();
1416 let target_triple = sopts.target_triple.triple();
1417 let host_tlib_path = Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1418 let target_tlib_path = if host_triple == target_triple {
1419 // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1420 // rescanning of the target lib path and an unnecessary allocation.
1421 host_tlib_path.clone()
1423 Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1426 let optimization_fuel = Lock::new(OptimizationFuel {
1427 remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |&(_, i)| i),
1430 let print_fuel = AtomicU64::new(0);
1432 let cgu_reuse_tracker = if sopts.unstable_opts.query_dep_graph {
1433 CguReuseTracker::new()
1435 CguReuseTracker::new_disabled()
1438 let prof = SelfProfilerRef::new(self_profiler, sopts.unstable_opts.time_passes);
1440 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1441 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1442 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1443 _ => CtfeBacktrace::Disabled,
1447 if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1449 let sess = Session {
1458 crate_types: OnceCell::new(),
1459 stable_crate_id: OnceCell::new(),
1460 features: OnceCell::new(),
1461 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1464 perf_stats: PerfStats {
1465 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1466 queries_canonicalized: AtomicUsize::new(0),
1467 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1468 normalize_projection_ty: AtomicUsize::new(0),
1470 code_stats: Default::default(),
1473 jobserver: jobserver::client(),
1476 miri_unleashed_features: Lock::new(Default::default()),
1478 target_features: FxHashSet::default(),
1479 unstable_target_features: FxHashSet::default(),
1482 validate_commandline_args_with_session_available(&sess);
1487 /// Validate command line arguments with a `Session`.
1489 /// If it is useful to have a Session available already for validating a commandline argument, you
1491 // JUSTIFICATION: needs to access args to validate them
1492 #[allow(rustc::bad_opt_access)]
1493 fn validate_commandline_args_with_session_available(sess: &Session) {
1494 // Since we don't know if code in an rlib will be linked to statically or
1495 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1496 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1497 // these manually generated symbols confuse LLD when it tries to merge
1498 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1499 // when compiling for LLD ThinLTO. This way we can validly just not generate
1500 // the `dllimport` attributes and `__imp_` symbols in that case.
1501 if sess.opts.cg.linker_plugin_lto.enabled()
1502 && sess.opts.cg.prefer_dynamic
1503 && sess.target.is_like_windows
1505 sess.emit_err(LinkerPluginToWindowsNotSupported);
1508 // Make sure that any given profiling data actually exists so LLVM can't
1509 // decide to silently skip PGO.
1510 if let Some(ref path) = sess.opts.cg.profile_use {
1512 sess.emit_err(ProfileUseFileDoesNotExist { path });
1516 // Do the same for sample profile data.
1517 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1519 sess.emit_err(ProfileSampleUseFileDoesNotExist { path });
1523 // Unwind tables cannot be disabled if the target requires them.
1524 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1525 if sess.target.requires_uwtable && !include_uwtables {
1526 sess.emit_err(TargetRequiresUnwindTables);
1530 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1531 let supported_sanitizers = sess.target.options.supported_sanitizers;
1532 let unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1533 match unsupported_sanitizers.into_iter().count() {
1536 sess.emit_err(SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1539 sess.emit_err(SanitizersNotSupported { us: unsupported_sanitizers.to_string() });
1542 // Cannot mix and match sanitizers.
1543 let mut sanitizer_iter = sess.opts.unstable_opts.sanitizer.into_iter();
1544 if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1545 sess.emit_err(CannotMixAndMatchSanitizers {
1546 first: first.to_string(),
1547 second: second.to_string(),
1551 // Cannot enable crt-static with sanitizers on Linux
1552 if sess.crt_static(None) && !sess.opts.unstable_opts.sanitizer.is_empty() {
1553 sess.emit_err(CannotEnableCrtStaticLinux);
1556 // LLVM CFI and VFE both require LTO.
1557 if sess.lto() != config::Lto::Fat {
1558 if sess.is_sanitizer_cfi_enabled() {
1559 sess.emit_err(SanitizerCfiEnabled);
1561 if sess.opts.unstable_opts.virtual_function_elimination {
1562 sess.emit_err(UnstableVirtualFunctionElimination);
1566 // LLVM CFI and KCFI are mutually exclusive
1567 if sess.is_sanitizer_cfi_enabled() && sess.is_sanitizer_kcfi_enabled() {
1568 sess.emit_err(CannotMixAndMatchSanitizers {
1569 first: "cfi".to_string(),
1570 second: "kcfi".to_string(),
1574 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1575 if !sess.target.options.supports_stack_protector {
1576 sess.emit_warning(StackProtectorNotSupportedForTarget {
1577 stack_protector: sess.opts.unstable_opts.stack_protector,
1578 target_triple: &sess.opts.target_triple,
1583 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1584 sess.emit_err(BranchProtectionRequiresAArch64);
1587 if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version {
1588 if dwarf_version > 5 {
1589 sess.emit_err(UnsupportedDwarfVersion { dwarf_version });
1593 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1594 && !sess.opts.unstable_opts.unstable_options
1596 sess.emit_err(SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1600 /// Holds data on the current incremental compilation session, if there is one.
1602 pub enum IncrCompSession {
1603 /// This is the state the session will be in until the incr. comp. dir is
1606 /// This is the state during which the session directory is private and can
1608 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1609 /// This is the state after the session directory has been finalized. In this
1610 /// state, the contents of the directory must not be modified any more.
1611 Finalized { session_directory: PathBuf },
1612 /// This is an error state that is reached when some compilation error has
1613 /// occurred. It indicates that the contents of the session directory must
1614 /// not be used, since they might be invalid.
1615 InvalidBecauseOfErrors { session_directory: PathBuf },
1618 fn early_error_handler(output: config::ErrorOutputType) -> rustc_errors::Handler {
1619 let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1620 let emitter: Box<dyn Emitter + sync::Send> = match output {
1621 config::ErrorOutputType::HumanReadable(kind) => {
1622 let (short, color_config) = kind.unzip();
1623 Box::new(EmitterWriter::stderr(
1635 config::ErrorOutputType::Json { pretty, json_rendered } => Box::new(JsonEmitter::basic(
1645 rustc_errors::Handler::with_emitter(true, None, emitter)
1648 #[allow(rustc::untranslatable_diagnostic)]
1649 #[allow(rustc::diagnostic_outside_of_impl)]
1650 pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) -> ErrorGuaranteed {
1651 early_error_handler(output).struct_err(msg).emit()
1654 #[allow(rustc::untranslatable_diagnostic)]
1655 #[allow(rustc::diagnostic_outside_of_impl)]
1656 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1657 early_error_handler(output).struct_fatal(msg).emit()
1660 #[allow(rustc::untranslatable_diagnostic)]
1661 #[allow(rustc::diagnostic_outside_of_impl)]
1662 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1663 early_error_handler(output).struct_warn(msg).emit()