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, ProfileSampleUseFileDoesNotExist,
9 ProfileUseFileDoesNotExist, SanitizerCfiEnabled, SanitizerNotSupported, SanitizersNotSupported,
10 SkippingConstChecks, SplitDebugInfoUnstablePlatform, StackProtectorNotSupportedForTarget,
11 TargetRequiresUnwindTables, UnleashedFeatureHelp, UnstableVirtualFunctionElimination,
12 UnsupportedDwarfVersion,
14 use crate::parse::{add_feature_diagnostics, ParseSess};
15 use crate::search_paths::{PathKind, SearchPath};
16 use crate::{filesearch, lint};
18 pub use rustc_ast::attr::MarkedAttrs;
19 pub use rustc_ast::Attribute;
20 use rustc_data_structures::flock;
21 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
22 use rustc_data_structures::jobserver::{self, Client};
23 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
24 use rustc_data_structures::sync::{
25 self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
27 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
28 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
29 use rustc_errors::json::JsonEmitter;
30 use rustc_errors::registry::Registry;
32 error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage,
33 ErrorGuaranteed, FluentBundle, IntoDiagnostic, LazyFallbackBundle, MultiSpan, Noted,
35 use rustc_macros::HashStable_Generic;
36 pub use rustc_span::def_id::StableCrateId;
37 use rustc_span::edition::Edition;
38 use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMap, Span};
39 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
40 use rustc_target::asm::InlineAsmArch;
41 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
42 use rustc_target::spec::{
43 DebuginfoKind, SanitizerSet, SplitDebuginfo, StackProtector, Target, TargetTriple, TlsModel,
46 use std::cell::{self, RefCell};
49 use std::ops::{Div, Mul};
50 use std::path::{Path, PathBuf};
51 use std::str::FromStr;
53 use std::time::Duration;
55 pub struct OptimizationFuel {
56 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
58 /// We're rejecting all further optimizations.
62 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
63 #[derive(Clone, Copy)]
64 pub enum CtfeBacktrace {
65 /// Do nothing special, return the error as usual without a backtrace.
67 /// Capture a backtrace at the point the error is created and return it in the error
68 /// (to be printed later if/when the error ever actually gets shown to the user).
70 /// Capture a backtrace at the point the error is created and immediately print it out.
74 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
75 /// limits are consistent throughout the compiler.
76 #[derive(Clone, Copy, Debug, HashStable_Generic)]
77 pub struct Limit(pub usize);
80 /// Create a new limit from a `usize`.
81 pub fn new(value: usize) -> Self {
85 /// Check that `value` is within the limit. Ensures that the same comparisons are used
86 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
88 pub fn value_within_limit(&self, value: usize) -> bool {
93 impl From<usize> for Limit {
94 fn from(value: usize) -> Self {
99 impl fmt::Display for Limit {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 impl Div<usize> for Limit {
108 fn div(self, rhs: usize) -> Self::Output {
109 Limit::new(self.0 / rhs)
113 impl Mul<usize> for Limit {
116 fn mul(self, rhs: usize) -> Self::Output {
117 Limit::new(self.0 * rhs)
121 impl rustc_errors::IntoDiagnosticArg for Limit {
122 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
123 self.to_string().into_diagnostic_arg()
127 #[derive(Clone, Copy, Debug, HashStable_Generic)]
129 /// The maximum recursion limit for potentially infinitely recursive
130 /// operations such as auto-dereference and monomorphization.
131 pub recursion_limit: Limit,
132 /// The size at which the `large_assignments` lint starts
134 pub move_size_limit: Limit,
135 /// The maximum length of types during monomorphization.
136 pub type_length_limit: Limit,
137 /// The maximum blocks a const expression can evaluate.
138 pub const_eval_limit: Limit,
141 pub struct CompilerIO {
143 pub output_dir: Option<PathBuf>,
144 pub output_file: Option<PathBuf>,
145 pub temps_dir: Option<PathBuf>,
148 /// Represents the data associated with a compilation
149 /// session for a single crate.
153 pub opts: config::Options,
154 pub host_tlib_path: Lrc<SearchPath>,
155 pub target_tlib_path: Lrc<SearchPath>,
156 pub parse_sess: ParseSess,
157 pub sysroot: PathBuf,
158 /// Input, input file path and output file path to this compilation process.
161 crate_types: OnceCell<Vec<CrateType>>,
162 /// The `stable_crate_id` is constructed out of the crate name and all the
163 /// `-C metadata` arguments passed to the compiler. Its value forms a unique
164 /// global identifier for the crate. It is used to allow multiple crates
165 /// with the same name to coexist. See the
166 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
167 pub stable_crate_id: OnceCell<StableCrateId>,
169 features: OnceCell<rustc_feature::Features>,
171 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
172 /// Used for incremental compilation tests. Will only be populated if
173 /// `-Zquery-dep-graph` is specified.
174 pub cgu_reuse_tracker: CguReuseTracker,
176 /// Used by `-Z self-profile`.
177 pub prof: SelfProfilerRef,
179 /// Some measurements that are being gathered during compilation.
180 pub perf_stats: PerfStats,
182 /// Data about code being compiled, gathered during compilation.
183 pub code_stats: CodeStats,
185 /// Tracks fuel info if `-zfuel=crate=n` is specified.
186 optimization_fuel: Lock<OptimizationFuel>,
188 /// Always set to zero and incremented so that we can print fuel expended by a crate.
189 pub print_fuel: AtomicU64,
191 /// Loaded up early on in the initialization of this `Session` to avoid
192 /// false positives about a job server in our environment.
193 pub jobserver: Client,
195 /// Cap lint level specified by a driver specifically.
196 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
198 /// Tracks the current behavior of the CTFE engine when an error occurs.
199 /// Options range from returning the error without a backtrace to returning an error
200 /// and immediately printing the backtrace to stderr.
201 /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
202 /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
204 pub ctfe_backtrace: Lock<CtfeBacktrace>,
206 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
207 /// const check, optionally with the relevant feature gate. We use this to
208 /// warn about unleashing, but with a single diagnostic instead of dozens that
209 /// drown everything else in noise.
210 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
212 /// Architecture to use for interpreting asm!.
213 pub asm_arch: Option<InlineAsmArch>,
215 /// Set of enabled features for the current target.
216 pub target_features: FxHashSet<Symbol>,
218 /// Set of enabled features for the current target, including unstable ones.
219 pub unstable_target_features: FxHashSet<Symbol>,
222 pub struct PerfStats {
223 /// The accumulated time spent on computing symbol hashes.
224 pub symbol_hash_time: Lock<Duration>,
225 /// Total number of values canonicalized queries constructed.
226 pub queries_canonicalized: AtomicUsize,
227 /// Number of times this query is invoked.
228 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
229 /// Number of times this query is invoked.
230 pub normalize_projection_ty: AtomicUsize,
234 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
235 self.miri_unleashed_features.lock().push((span, feature_gate));
238 pub fn local_crate_source_file(&self) -> Option<PathBuf> {
239 let path = self.io.input.opt_path()?;
240 Some(self.opts.file_path_mapping().map_prefix(path).0.into_owned())
243 fn check_miri_unleashed_features(&self) {
244 let unleashed_features = self.miri_unleashed_features.lock();
245 if !unleashed_features.is_empty() {
246 let mut must_err = false;
247 // Create a diagnostic pointing at where things got unleashed.
248 self.emit_warning(SkippingConstChecks {
249 unleashed_features: unleashed_features
251 .map(|(span, gate)| {
254 UnleashedFeatureHelp::Named { span: *span, gate }
256 .unwrap_or(UnleashedFeatureHelp::Unnamed { span: *span })
261 // If we should err, make sure we did.
262 if must_err && self.has_errors().is_none() {
263 // We have skipped a feature gate, and not run into other errors... reject.
264 self.emit_err(NotCircumventFeature);
269 /// Invoked all the way at the end to finish off diagnostics printing.
270 pub fn finish_diagnostics(&self, registry: &Registry) {
271 self.check_miri_unleashed_features();
272 self.diagnostic().print_error_count(registry);
273 self.emit_future_breakage();
276 fn emit_future_breakage(&self) {
277 if !self.opts.json_future_incompat {
281 let diags = self.diagnostic().take_future_breakage_diagnostics();
282 if diags.is_empty() {
285 self.parse_sess.span_diagnostic.emit_future_breakage_report(diags);
288 pub fn local_stable_crate_id(&self) -> StableCrateId {
289 self.stable_crate_id.get().copied().unwrap()
292 pub fn crate_types(&self) -> &[CrateType] {
293 self.crate_types.get().unwrap().as_slice()
296 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
297 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
300 #[rustc_lint_diagnostics]
302 pub fn struct_span_warn<S: Into<MultiSpan>>(
305 msg: impl Into<DiagnosticMessage>,
306 ) -> DiagnosticBuilder<'_, ()> {
307 self.diagnostic().struct_span_warn(sp, msg)
309 #[rustc_lint_diagnostics]
311 pub fn struct_span_warn_with_expectation<S: Into<MultiSpan>>(
314 msg: impl Into<DiagnosticMessage>,
315 id: lint::LintExpectationId,
316 ) -> DiagnosticBuilder<'_, ()> {
317 self.diagnostic().struct_span_warn_with_expectation(sp, msg, id)
319 #[rustc_lint_diagnostics]
321 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
324 msg: impl Into<DiagnosticMessage>,
326 ) -> DiagnosticBuilder<'_, ()> {
327 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
329 #[rustc_lint_diagnostics]
331 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
332 self.diagnostic().struct_warn(msg)
334 #[rustc_lint_diagnostics]
336 pub fn struct_warn_with_expectation(
338 msg: impl Into<DiagnosticMessage>,
339 id: lint::LintExpectationId,
340 ) -> DiagnosticBuilder<'_, ()> {
341 self.diagnostic().struct_warn_with_expectation(msg, id)
343 #[rustc_lint_diagnostics]
345 pub fn struct_span_allow<S: Into<MultiSpan>>(
348 msg: impl Into<DiagnosticMessage>,
349 ) -> DiagnosticBuilder<'_, ()> {
350 self.diagnostic().struct_span_allow(sp, msg)
352 #[rustc_lint_diagnostics]
354 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
355 self.diagnostic().struct_allow(msg)
357 #[rustc_lint_diagnostics]
359 pub fn struct_expect(
361 msg: impl Into<DiagnosticMessage>,
362 id: lint::LintExpectationId,
363 ) -> DiagnosticBuilder<'_, ()> {
364 self.diagnostic().struct_expect(msg, id)
366 #[rustc_lint_diagnostics]
368 pub fn struct_span_err<S: Into<MultiSpan>>(
371 msg: impl Into<DiagnosticMessage>,
372 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
373 self.diagnostic().struct_span_err(sp, msg)
375 #[rustc_lint_diagnostics]
377 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
380 msg: impl Into<DiagnosticMessage>,
382 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
383 self.diagnostic().struct_span_err_with_code(sp, msg, code)
385 // FIXME: This method should be removed (every error should have an associated error code).
386 #[rustc_lint_diagnostics]
390 msg: impl Into<DiagnosticMessage>,
391 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
392 self.parse_sess.struct_err(msg)
395 #[rustc_lint_diagnostics]
396 pub fn struct_err_with_code(
398 msg: impl Into<DiagnosticMessage>,
400 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
401 self.diagnostic().struct_err_with_code(msg, code)
403 #[rustc_lint_diagnostics]
405 pub fn struct_warn_with_code(
407 msg: impl Into<DiagnosticMessage>,
409 ) -> DiagnosticBuilder<'_, ()> {
410 self.diagnostic().struct_warn_with_code(msg, code)
412 #[rustc_lint_diagnostics]
414 pub fn struct_span_fatal<S: Into<MultiSpan>>(
417 msg: impl Into<DiagnosticMessage>,
418 ) -> DiagnosticBuilder<'_, !> {
419 self.diagnostic().struct_span_fatal(sp, msg)
421 #[rustc_lint_diagnostics]
422 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
425 msg: impl Into<DiagnosticMessage>,
427 ) -> DiagnosticBuilder<'_, !> {
428 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
430 #[rustc_lint_diagnostics]
431 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
432 self.diagnostic().struct_fatal(msg)
435 #[rustc_lint_diagnostics]
437 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
438 self.diagnostic().span_fatal(sp, msg)
440 #[rustc_lint_diagnostics]
441 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
444 msg: impl Into<DiagnosticMessage>,
447 self.diagnostic().span_fatal_with_code(sp, msg, code)
449 #[rustc_lint_diagnostics]
450 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! {
451 self.diagnostic().fatal(msg).raise()
453 #[rustc_lint_diagnostics]
455 pub fn span_err_or_warn<S: Into<MultiSpan>>(
459 msg: impl Into<DiagnosticMessage>,
462 self.span_warn(sp, msg);
464 self.span_err(sp, msg);
467 #[rustc_lint_diagnostics]
469 pub fn span_err<S: Into<MultiSpan>>(
472 msg: impl Into<DiagnosticMessage>,
473 ) -> ErrorGuaranteed {
474 self.diagnostic().span_err(sp, msg)
476 #[rustc_lint_diagnostics]
477 pub fn span_err_with_code<S: Into<MultiSpan>>(
480 msg: impl Into<DiagnosticMessage>,
483 self.diagnostic().span_err_with_code(sp, msg, code)
485 #[rustc_lint_diagnostics]
486 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
487 self.diagnostic().err(msg)
490 pub fn create_err<'a>(
492 err: impl IntoDiagnostic<'a>,
493 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
494 self.parse_sess.create_err(err)
497 pub fn create_feature_err<'a>(
499 err: impl IntoDiagnostic<'a>,
501 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
502 let mut err = self.parse_sess.create_err(err);
503 if err.code.is_none() {
504 err.code = std::option::Option::Some(error_code!(E0658));
506 add_feature_diagnostics(&mut err, &self.parse_sess, feature);
510 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
511 self.parse_sess.emit_err(err)
514 pub fn create_warning<'a>(
516 err: impl IntoDiagnostic<'a, ()>,
517 ) -> DiagnosticBuilder<'a, ()> {
518 self.parse_sess.create_warning(err)
521 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
522 self.parse_sess.emit_warning(warning)
525 pub fn create_note<'a>(
527 note: impl IntoDiagnostic<'a, Noted>,
528 ) -> DiagnosticBuilder<'a, Noted> {
529 self.parse_sess.create_note(note)
532 pub fn emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted {
533 self.parse_sess.emit_note(note)
536 pub fn create_fatal<'a>(
538 fatal: impl IntoDiagnostic<'a, !>,
539 ) -> DiagnosticBuilder<'a, !> {
540 self.parse_sess.create_fatal(fatal)
543 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
544 self.parse_sess.emit_fatal(fatal)
547 pub fn err_count(&self) -> usize {
548 self.diagnostic().err_count()
550 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
551 self.diagnostic().has_errors()
553 pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> {
554 self.diagnostic().has_errors_or_delayed_span_bugs()
556 pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> {
557 self.diagnostic().is_compilation_going_to_fail()
559 pub fn abort_if_errors(&self) {
560 self.diagnostic().abort_if_errors();
562 pub fn compile_status(&self) -> Result<(), ErrorGuaranteed> {
563 if let Some(reported) = self.diagnostic().has_errors_or_lint_errors() {
564 let _ = self.diagnostic().emit_stashed_diagnostics();
570 // FIXME(matthewjasper) Remove this method, it should never be needed.
571 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorGuaranteed>
575 let old_count = self.err_count();
577 if self.err_count() == old_count {
580 Err(self.delay_span_bug(
581 rustc_span::DUMMY_SP,
582 "`self.err_count()` changed but an error was not emitted",
586 #[allow(rustc::untranslatable_diagnostic)]
587 #[allow(rustc::diagnostic_outside_of_impl)]
589 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
590 self.diagnostic().span_warn(sp, msg)
592 #[allow(rustc::untranslatable_diagnostic)]
593 #[allow(rustc::diagnostic_outside_of_impl)]
594 pub fn span_warn_with_code<S: Into<MultiSpan>>(
597 msg: impl Into<DiagnosticMessage>,
600 self.diagnostic().span_warn_with_code(sp, msg, code)
602 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
603 self.diagnostic().warn(msg)
606 /// Ensures that compilation cannot succeed.
608 /// If this function has been called but no errors have been emitted and
609 /// compilation succeeds, it will cause an internal compiler error (ICE).
611 /// This can be used in code paths that should never run on successful compilations.
612 /// For example, it can be used to create an [`ErrorGuaranteed`]
613 /// (but you should prefer threading through the [`ErrorGuaranteed`] from an error emission directly).
615 /// If no span is available, use [`DUMMY_SP`].
617 /// [`DUMMY_SP`]: rustc_span::DUMMY_SP
619 pub fn delay_span_bug<S: Into<MultiSpan>>(
622 msg: impl Into<DiagnosticMessage>,
623 ) -> ErrorGuaranteed {
624 self.diagnostic().delay_span_bug(sp, msg)
627 /// Used for code paths of expensive computations that should only take place when
628 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
629 /// it's likely a bug.
630 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
631 if self.opts.unstable_opts.print_type_sizes
632 || self.opts.unstable_opts.query_dep_graph
633 || self.opts.unstable_opts.dump_mir.is_some()
634 || self.opts.unstable_opts.unpretty.is_some()
635 || self.opts.output_types.contains_key(&OutputType::Mir)
636 || std::env::var_os("RUSTC_LOG").is_some()
641 self.diagnostic().delay_good_path_bug(msg)
644 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
645 self.diagnostic().note_without_error(msg)
649 pub fn span_note_without_error<S: Into<MultiSpan>>(
652 msg: impl Into<DiagnosticMessage>,
654 self.diagnostic().span_note_without_error(sp, msg)
656 #[allow(rustc::untranslatable_diagnostic)]
657 #[allow(rustc::diagnostic_outside_of_impl)]
658 pub fn struct_note_without_error(
660 msg: impl Into<DiagnosticMessage>,
661 ) -> DiagnosticBuilder<'_, ()> {
662 self.diagnostic().struct_note_without_error(msg)
666 pub fn diagnostic(&self) -> &rustc_errors::Handler {
667 &self.parse_sess.span_diagnostic
671 pub fn source_map(&self) -> &SourceMap {
672 self.parse_sess.source_map()
675 /// Returns `true` if internal lints should be added to the lint store - i.e. if
676 /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
677 /// to be emitted under rustdoc).
678 pub fn enable_internal_lints(&self) -> bool {
679 self.unstable_options() && !self.opts.actually_rustdoc
682 pub fn instrument_coverage(&self) -> bool {
683 self.opts.cg.instrument_coverage() != InstrumentCoverage::Off
686 pub fn instrument_coverage_except_unused_generics(&self) -> bool {
687 self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedGenerics
690 pub fn instrument_coverage_except_unused_functions(&self) -> bool {
691 self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedFunctions
694 /// Gets the features enabled for the current compilation session.
695 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
696 /// dependency tracking. Use tcx.features() instead.
698 pub fn features_untracked(&self) -> &rustc_feature::Features {
699 self.features.get().unwrap()
702 pub fn init_features(&self, features: rustc_feature::Features) {
703 match self.features.set(features) {
705 Err(_) => panic!("`features` was initialized twice"),
709 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
710 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
713 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
714 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
717 /// Check whether this compile session and crate type use static crt.
718 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
719 if !self.target.crt_static_respected {
720 // If the target does not opt in to crt-static support, use its default.
721 return self.target.crt_static_default;
724 let requested_features = self.opts.cg.target_feature.split(',');
725 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
726 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
728 // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
729 #[allow(rustc::bad_opt_access)]
730 if found_positive || found_negative {
732 } else if crate_type == Some(CrateType::ProcMacro)
733 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
735 // FIXME: When crate_type is not available,
736 // we use compiler options to determine the crate_type.
737 // We can't check `#![crate_type = "proc-macro"]` here.
740 self.target.crt_static_default
744 pub fn is_wasi_reactor(&self) -> bool {
745 self.target.options.os == "wasi"
747 self.opts.unstable_opts.wasi_exec_model,
748 Some(config::WasiExecModel::Reactor)
752 /// Returns `true` if the target can use the current split debuginfo configuration.
753 pub fn target_can_use_split_dwarf(&self) -> bool {
754 self.target.debuginfo_kind == DebuginfoKind::Dwarf
757 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
758 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.to_u64())
761 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
762 filesearch::FileSearch::new(
764 self.opts.target_triple.triple(),
765 &self.opts.search_paths,
766 &self.target_tlib_path,
770 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
771 filesearch::FileSearch::new(
773 config::host_triple(),
774 &self.opts.search_paths,
775 &self.host_tlib_path,
780 /// Returns a list of directories where target-specific tool binaries are located.
781 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
782 let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple());
783 let p = PathBuf::from_iter([
784 Path::new(&self.sysroot),
785 Path::new(&rustlib_path),
788 if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
791 pub fn init_incr_comp_session(
793 session_dir: PathBuf,
794 lock_file: flock::Lock,
795 load_dep_graph: bool,
797 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
799 if let IncrCompSession::NotInitialized = *incr_comp_session {
801 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
805 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
808 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
809 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
811 if let IncrCompSession::Active { .. } = *incr_comp_session {
813 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
816 // Note: this will also drop the lock file, thus unlocking the directory.
817 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
820 pub fn mark_incr_comp_session_as_invalid(&self) {
821 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
823 let session_directory = match *incr_comp_session {
824 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
825 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
826 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
829 // Note: this will also drop the lock file, thus unlocking the directory.
830 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
833 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
834 let incr_comp_session = self.incr_comp_session.borrow();
835 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
836 IncrCompSession::NotInitialized => panic!(
837 "trying to get session directory from `IncrCompSession`: {:?}",
840 IncrCompSession::Active { ref session_directory, .. }
841 | IncrCompSession::Finalized { ref session_directory }
842 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
848 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
849 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
852 pub fn print_perf_stats(&self) {
854 "Total time spent computing symbol hashes: {}",
855 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
858 "Total queries canonicalized: {}",
859 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
862 "normalize_generic_arg_after_erasing_regions: {}",
863 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
866 "normalize_projection_ty: {}",
867 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
871 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
872 /// This expends fuel if applicable, and records fuel if applicable.
873 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
875 if let Some((ref c, _)) = self.opts.unstable_opts.fuel {
877 assert_eq!(self.threads(), 1);
878 let mut fuel = self.optimization_fuel.lock();
879 ret = fuel.remaining != 0;
880 if fuel.remaining == 0 && !fuel.out_of_fuel {
881 if self.diagnostic().can_emit_warnings() {
882 // We only call `msg` in case we can actually emit warnings.
883 // Otherwise, this could cause a `delay_good_path_bug` to
884 // trigger (issue #79546).
885 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
887 fuel.out_of_fuel = true;
888 } else if fuel.remaining > 0 {
893 if let Some(ref c) = self.opts.unstable_opts.print_fuel {
895 assert_eq!(self.threads(), 1);
896 self.print_fuel.fetch_add(1, SeqCst);
902 pub fn rust_2015(&self) -> bool {
903 self.edition() == Edition::Edition2015
906 /// Are we allowed to use features from the Rust 2018 edition?
907 pub fn rust_2018(&self) -> bool {
908 self.edition() >= Edition::Edition2018
911 /// Are we allowed to use features from the Rust 2021 edition?
912 pub fn rust_2021(&self) -> bool {
913 self.edition() >= Edition::Edition2021
916 /// Are we allowed to use features from the Rust 2024 edition?
917 pub fn rust_2024(&self) -> bool {
918 self.edition() >= Edition::Edition2024
921 /// Returns `true` if we cannot skip the PLT for shared library calls.
922 pub fn needs_plt(&self) -> bool {
923 // Check if the current target usually needs PLT to be enabled.
924 // The user can use the command line flag to override it.
925 let needs_plt = self.target.needs_plt;
927 let dbg_opts = &self.opts.unstable_opts;
929 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
931 // Only enable this optimization by default if full relro is also enabled.
932 // In this case, lazy binding was already unavailable, so nothing is lost.
933 // This also ensures `-Wl,-z,now` is supported by the linker.
934 let full_relro = RelroLevel::Full == relro_level;
936 // If user didn't explicitly forced us to use / skip the PLT,
937 // then try to skip it where possible.
938 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
941 /// Checks if LLVM lifetime markers should be emitted.
942 pub fn emit_lifetime_markers(&self) -> bool {
943 self.opts.optimize != config::OptLevel::No
944 // AddressSanitizer uses lifetimes to detect use after scope bugs.
945 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
946 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
947 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
950 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
951 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
953 .any(|kind| attr.has_name(*kind))
956 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
957 attrs.iter().any(|item| item.has_name(name))
960 pub fn find_by_name<'a>(
962 attrs: &'a [Attribute],
964 ) -> Option<&'a Attribute> {
965 attrs.iter().find(|attr| attr.has_name(name))
968 pub fn filter_by_name<'a>(
970 attrs: &'a [Attribute],
972 ) -> impl Iterator<Item = &'a Attribute> {
973 attrs.iter().filter(move |attr| attr.has_name(name))
976 pub fn first_attr_value_str_by_name(
980 ) -> Option<Symbol> {
981 attrs.iter().find(|at| at.has_name(name)).and_then(|at| at.value_str())
984 pub fn diagnostic_width(&self) -> usize {
985 let default_column_width = 140;
986 if let Some(width) = self.opts.diagnostic_width {
988 } else if self.opts.unstable_opts.ui_testing {
991 termize::dimensions().map_or(default_column_width, |(w, _)| w)
996 // JUSTIFICATION: defn of the suggested wrapper fns
997 #[allow(rustc::bad_opt_access)]
999 pub fn verbose(&self) -> bool {
1000 self.opts.unstable_opts.verbose
1003 pub fn verify_llvm_ir(&self) -> bool {
1004 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
1007 pub fn binary_dep_depinfo(&self) -> bool {
1008 self.opts.unstable_opts.binary_dep_depinfo
1011 pub fn mir_opt_level(&self) -> usize {
1015 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
1018 /// Calculates the flavor of LTO to use for this compilation.
1019 pub fn lto(&self) -> config::Lto {
1020 // If our target has codegen requirements ignore the command line
1021 if self.target.requires_lto {
1022 return config::Lto::Fat;
1025 // If the user specified something, return that. If they only said `-C
1026 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
1027 // then ensure we can't use a ThinLTO.
1028 match self.opts.cg.lto {
1029 config::LtoCli::Unspecified => {
1030 // The compiler was invoked without the `-Clto` flag. Fall
1031 // through to the default handling
1033 config::LtoCli::No => {
1034 // The user explicitly opted out of any kind of LTO
1035 return config::Lto::No;
1037 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
1038 // All of these mean fat LTO
1039 return config::Lto::Fat;
1041 config::LtoCli::Thin => {
1042 // The user explicitly asked for ThinLTO
1043 return config::Lto::Thin;
1047 // Ok at this point the target doesn't require anything and the user
1048 // hasn't asked for anything. Our next decision is whether or not
1049 // we enable "auto" ThinLTO where we use multiple codegen units and
1050 // then do ThinLTO over those codegen units. The logic below will
1051 // either return `No` or `ThinLocal`.
1053 // If processing command line options determined that we're incompatible
1054 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
1055 if self.opts.cli_forced_local_thinlto_off {
1056 return config::Lto::No;
1059 // If `-Z thinlto` specified process that, but note that this is mostly
1060 // a deprecated option now that `-C lto=thin` exists.
1061 if let Some(enabled) = self.opts.unstable_opts.thinlto {
1063 return config::Lto::ThinLocal;
1065 return config::Lto::No;
1069 // If there's only one codegen unit and LTO isn't enabled then there's
1070 // no need for ThinLTO so just return false.
1071 if self.codegen_units() == 1 {
1072 return config::Lto::No;
1075 // Now we're in "defaults" territory. By default we enable ThinLTO for
1076 // optimized compiles (anything greater than O0).
1077 match self.opts.optimize {
1078 config::OptLevel::No => config::Lto::No,
1079 _ => config::Lto::ThinLocal,
1083 /// Returns the panic strategy for this compile session. If the user explicitly selected one
1084 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
1085 pub fn panic_strategy(&self) -> PanicStrategy {
1086 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
1089 pub fn fewer_names(&self) -> bool {
1090 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1093 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1094 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1095 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1096 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1101 pub fn unstable_options(&self) -> bool {
1102 self.opts.unstable_opts.unstable_options
1105 pub fn is_nightly_build(&self) -> bool {
1106 self.opts.unstable_features.is_nightly_build()
1109 pub fn overflow_checks(&self) -> bool {
1110 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1113 pub fn relocation_model(&self) -> RelocModel {
1114 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
1117 pub fn code_model(&self) -> Option<CodeModel> {
1118 self.opts.cg.code_model.or(self.target.code_model)
1121 pub fn tls_model(&self) -> TlsModel {
1122 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
1125 pub fn split_debuginfo(&self) -> SplitDebuginfo {
1126 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1129 pub fn stack_protector(&self) -> StackProtector {
1130 if self.target.options.supports_stack_protector {
1131 self.opts.unstable_opts.stack_protector
1133 StackProtector::None
1137 pub fn must_emit_unwind_tables(&self) -> bool {
1138 // This is used to control the emission of the `uwtable` attribute on
1141 // Unwind tables are needed when compiling with `-C panic=unwind`, but
1142 // LLVM won't omit unwind tables unless the function is also marked as
1143 // `nounwind`, so users are allowed to disable `uwtable` emission.
1144 // Historically rustc always emits `uwtable` attributes by default, so
1145 // even they can be disabled, they're still emitted by default.
1147 // On some targets (including windows), however, exceptions include
1148 // other events such as illegal instructions, segfaults, etc. This means
1149 // that on Windows we end up still needing unwind tables even if the `-C
1150 // panic=abort` flag is passed.
1152 // You can also find more info on why Windows needs unwind tables in:
1153 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1155 // If a target requires unwind tables, then they must be emitted.
1156 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1157 // value, if it is provided, or disable them, if not.
1158 self.target.requires_uwtable
1159 || self.opts.cg.force_unwind_tables.unwrap_or(
1160 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
1164 /// Returns the number of query threads that should be used for this
1166 pub fn threads(&self) -> usize {
1167 self.opts.unstable_opts.threads
1170 /// Returns the number of codegen units that should be used for this
1172 pub fn codegen_units(&self) -> usize {
1173 if let Some(n) = self.opts.cli_forced_codegen_units {
1176 if let Some(n) = self.target.default_codegen_units {
1180 // If incremental compilation is turned on, we default to a high number
1181 // codegen units in order to reduce the "collateral damage" small
1183 if self.opts.incremental.is_some() {
1187 // Why is 16 codegen units the default all the time?
1189 // The main reason for enabling multiple codegen units by default is to
1190 // leverage the ability for the codegen backend to do codegen and
1191 // optimization in parallel. This allows us, especially for large crates, to
1192 // make good use of all available resources on the machine once we've
1193 // hit that stage of compilation. Large crates especially then often
1194 // take a long time in codegen/optimization and this helps us amortize that
1197 // Note that a high number here doesn't mean that we'll be spawning a
1198 // large number of threads in parallel. The backend of rustc contains
1199 // global rate limiting through the `jobserver` crate so we'll never
1200 // overload the system with too much work, but rather we'll only be
1201 // optimizing when we're otherwise cooperating with other instances of
1204 // Rather a high number here means that we should be able to keep a lot
1205 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1206 // to build we'll be guaranteed that all cpus will finish pretty closely
1207 // to one another and we should make relatively optimal use of system
1210 // Note that the main cost of codegen units is that it prevents LLVM
1211 // from inlining across codegen units. Users in general don't have a lot
1212 // of control over how codegen units are split up so it's our job in the
1213 // compiler to ensure that undue performance isn't lost when using
1214 // codegen units (aka we can't require everyone to slap `#[inline]` on
1217 // If we're compiling at `-O0` then the number doesn't really matter too
1218 // much because performance doesn't matter and inlining is ok to lose.
1219 // In debug mode we just want to try to guarantee that no cpu is stuck
1220 // doing work that could otherwise be farmed to others.
1222 // In release mode, however (O1 and above) performance does indeed
1223 // matter! To recover the loss in performance due to inlining we'll be
1224 // enabling ThinLTO by default (the function for which is just below).
1225 // This will ensure that we recover any inlining wins we otherwise lost
1226 // through codegen unit partitioning.
1230 // Ok that's a lot of words but the basic tl;dr; is that we want a high
1231 // number here -- but not too high. Additionally we're "safe" to have it
1232 // always at the same number at all optimization levels.
1234 // As a result 16 was chosen here! Mostly because it was a power of 2
1235 // and most benchmarks agreed it was roughly a local optimum. Not very
1240 pub fn teach(&self, code: &DiagnosticId) -> bool {
1241 self.opts.unstable_opts.teach && self.diagnostic().must_teach(code)
1244 pub fn edition(&self) -> Edition {
1248 pub fn link_dead_code(&self) -> bool {
1249 self.opts.cg.link_dead_code.unwrap_or(false)
1253 // JUSTIFICATION: part of session construction
1254 #[allow(rustc::bad_opt_access)]
1256 sopts: &config::Options,
1257 registry: rustc_errors::registry::Registry,
1258 source_map: Lrc<SourceMap>,
1259 bundle: Option<Lrc<FluentBundle>>,
1260 fallback_bundle: LazyFallbackBundle,
1261 ) -> Box<dyn Emitter + sync::Send> {
1262 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1263 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
1264 match sopts.error_format {
1265 config::ErrorOutputType::HumanReadable(kind) => {
1266 let (short, color_config) = kind.unzip();
1268 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1269 let emitter = AnnotateSnippetEmitterWriter::new(
1276 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1278 let emitter = EmitterWriter::stderr(
1284 sopts.unstable_opts.teach,
1285 sopts.diagnostic_width,
1289 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1292 config::ErrorOutputType::Json { pretty, json_rendered } => Box::new(
1293 JsonEmitter::stderr(
1300 sopts.diagnostic_width,
1304 .ui_testing(sopts.unstable_opts.ui_testing),
1309 // JUSTIFICATION: literally session construction
1310 #[allow(rustc::bad_opt_access)]
1311 pub fn build_session(
1312 sopts: config::Options,
1314 bundle: Option<Lrc<rustc_errors::FluentBundle>>,
1315 registry: rustc_errors::registry::Registry,
1316 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1317 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1318 target_override: Option<Target>,
1320 // FIXME: This is not general enough to make the warning lint completely override
1321 // normal diagnostic warnings, since the warning lint can also be denied and changed
1322 // later via the source code.
1323 let warnings_allow = sopts
1326 .rfind(|&(key, _)| *key == "warnings")
1327 .map_or(false, |&(_, level)| level == lint::Allow);
1328 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1329 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1331 let sysroot = match &sopts.maybe_sysroot {
1332 Some(sysroot) => sysroot.clone(),
1333 None => filesearch::get_or_default_sysroot().expect("Failed finding sysroot"),
1336 let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
1337 let host_triple = TargetTriple::from_triple(config::host_triple());
1338 let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1339 early_error(sopts.error_format, &format!("Error loading host specification: {e}"))
1341 for warning in target_warnings.warning_messages() {
1342 early_warn(sopts.error_format, &warning)
1345 let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1346 let hash_kind = sopts.unstable_opts.src_hash_algorithm.unwrap_or_else(|| {
1347 if target_cfg.is_like_msvc {
1348 SourceFileHashAlgorithm::Sha1
1350 SourceFileHashAlgorithm::Md5
1353 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1355 sopts.file_path_mapping(),
1359 let fallback_bundle = fallback_fluent_bundle(
1360 rustc_errors::DEFAULT_LOCALE_RESOURCES,
1361 sopts.unstable_opts.translate_directionality_markers,
1363 let emitter = default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle);
1365 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1367 sopts.unstable_opts.diagnostic_handler_flags(can_emit_warnings),
1370 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1373 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1375 let profiler = SelfProfiler::new(
1377 sopts.crate_name.as_deref(),
1378 sopts.unstable_opts.self_profile_events.as_deref(),
1379 &sopts.unstable_opts.self_profile_counter,
1382 Ok(profiler) => Some(Arc::new(profiler)),
1384 early_warn(sopts.error_format, &format!("failed to create profiler: {e}"));
1392 let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1393 parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1395 let host_triple = config::host_triple();
1396 let target_triple = sopts.target_triple.triple();
1397 let host_tlib_path = Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1398 let target_tlib_path = if host_triple == target_triple {
1399 // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1400 // rescanning of the target lib path and an unnecessary allocation.
1401 host_tlib_path.clone()
1403 Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1406 let optimization_fuel = Lock::new(OptimizationFuel {
1407 remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |&(_, i)| i),
1410 let print_fuel = AtomicU64::new(0);
1412 let cgu_reuse_tracker = if sopts.unstable_opts.query_dep_graph {
1413 CguReuseTracker::new()
1415 CguReuseTracker::new_disabled()
1418 let prof = SelfProfilerRef::new(self_profiler, sopts.unstable_opts.time_passes);
1420 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1421 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1422 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1423 _ => CtfeBacktrace::Disabled,
1427 if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1429 let sess = Session {
1438 crate_types: OnceCell::new(),
1439 stable_crate_id: OnceCell::new(),
1440 features: OnceCell::new(),
1441 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1444 perf_stats: PerfStats {
1445 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1446 queries_canonicalized: AtomicUsize::new(0),
1447 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1448 normalize_projection_ty: AtomicUsize::new(0),
1450 code_stats: Default::default(),
1453 jobserver: jobserver::client(),
1456 miri_unleashed_features: Lock::new(Default::default()),
1458 target_features: FxHashSet::default(),
1459 unstable_target_features: FxHashSet::default(),
1462 validate_commandline_args_with_session_available(&sess);
1467 /// Validate command line arguments with a `Session`.
1469 /// If it is useful to have a Session available already for validating a commandline argument, you
1471 // JUSTIFICATION: needs to access args to validate them
1472 #[allow(rustc::bad_opt_access)]
1473 fn validate_commandline_args_with_session_available(sess: &Session) {
1474 // Since we don't know if code in an rlib will be linked to statically or
1475 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1476 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1477 // these manually generated symbols confuse LLD when it tries to merge
1478 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1479 // when compiling for LLD ThinLTO. This way we can validly just not generate
1480 // the `dllimport` attributes and `__imp_` symbols in that case.
1481 if sess.opts.cg.linker_plugin_lto.enabled()
1482 && sess.opts.cg.prefer_dynamic
1483 && sess.target.is_like_windows
1485 sess.emit_err(LinkerPluginToWindowsNotSupported);
1488 // Make sure that any given profiling data actually exists so LLVM can't
1489 // decide to silently skip PGO.
1490 if let Some(ref path) = sess.opts.cg.profile_use {
1492 sess.emit_err(ProfileUseFileDoesNotExist { path });
1496 // Do the same for sample profile data.
1497 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1499 sess.emit_err(ProfileSampleUseFileDoesNotExist { path });
1503 // Unwind tables cannot be disabled if the target requires them.
1504 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1505 if sess.target.requires_uwtable && !include_uwtables {
1506 sess.emit_err(TargetRequiresUnwindTables);
1510 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1511 let supported_sanitizers = sess.target.options.supported_sanitizers;
1512 let unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1513 match unsupported_sanitizers.into_iter().count() {
1516 sess.emit_err(SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1519 sess.emit_err(SanitizersNotSupported { us: unsupported_sanitizers.to_string() });
1522 // Cannot mix and match sanitizers.
1523 let mut sanitizer_iter = sess.opts.unstable_opts.sanitizer.into_iter();
1524 if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1525 sess.emit_err(CannotMixAndMatchSanitizers {
1526 first: first.to_string(),
1527 second: second.to_string(),
1531 // Cannot enable crt-static with sanitizers on Linux
1532 if sess.crt_static(None) && !sess.opts.unstable_opts.sanitizer.is_empty() {
1533 sess.emit_err(CannotEnableCrtStaticLinux);
1536 // LLVM CFI and VFE both require LTO.
1537 if sess.lto() != config::Lto::Fat {
1538 if sess.is_sanitizer_cfi_enabled() {
1539 sess.emit_err(SanitizerCfiEnabled);
1541 if sess.opts.unstable_opts.virtual_function_elimination {
1542 sess.emit_err(UnstableVirtualFunctionElimination);
1546 // LLVM CFI and KCFI are mutually exclusive
1547 if sess.is_sanitizer_cfi_enabled() && sess.is_sanitizer_kcfi_enabled() {
1548 sess.emit_err(CannotMixAndMatchSanitizers {
1549 first: "cfi".to_string(),
1550 second: "kcfi".to_string(),
1554 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1555 if !sess.target.options.supports_stack_protector {
1556 sess.emit_warning(StackProtectorNotSupportedForTarget {
1557 stack_protector: sess.opts.unstable_opts.stack_protector,
1558 target_triple: &sess.opts.target_triple,
1563 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1564 sess.emit_err(BranchProtectionRequiresAArch64);
1567 if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version {
1568 if dwarf_version > 5 {
1569 sess.emit_err(UnsupportedDwarfVersion { dwarf_version });
1573 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1574 && !sess.opts.unstable_opts.unstable_options
1576 sess.emit_err(SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1580 /// Holds data on the current incremental compilation session, if there is one.
1582 pub enum IncrCompSession {
1583 /// This is the state the session will be in until the incr. comp. dir is
1586 /// This is the state during which the session directory is private and can
1588 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1589 /// This is the state after the session directory has been finalized. In this
1590 /// state, the contents of the directory must not be modified any more.
1591 Finalized { session_directory: PathBuf },
1592 /// This is an error state that is reached when some compilation error has
1593 /// occurred. It indicates that the contents of the session directory must
1594 /// not be used, since they might be invalid.
1595 InvalidBecauseOfErrors { session_directory: PathBuf },
1598 fn early_error_handler(output: config::ErrorOutputType) -> rustc_errors::Handler {
1599 let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1600 let emitter: Box<dyn Emitter + sync::Send> = match output {
1601 config::ErrorOutputType::HumanReadable(kind) => {
1602 let (short, color_config) = kind.unzip();
1603 Box::new(EmitterWriter::stderr(
1615 config::ErrorOutputType::Json { pretty, json_rendered } => Box::new(JsonEmitter::basic(
1625 rustc_errors::Handler::with_emitter(true, None, emitter)
1628 #[allow(rustc::untranslatable_diagnostic)]
1629 #[allow(rustc::diagnostic_outside_of_impl)]
1630 pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) -> ErrorGuaranteed {
1631 early_error_handler(output).struct_err(msg).emit()
1634 #[allow(rustc::untranslatable_diagnostic)]
1635 #[allow(rustc::diagnostic_outside_of_impl)]
1636 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1637 early_error_handler(output).struct_fatal(msg).emit()
1640 #[allow(rustc::untranslatable_diagnostic)]
1641 #[allow(rustc::diagnostic_outside_of_impl)]
1642 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1643 early_error_handler(output).struct_warn(msg).emit()