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::{self, CrateType, InstrumentCoverage, OptLevel, OutputType, SwitchWithOptPath};
6 CannotEnableCrtStaticLinux, CannotMixAndMatchSanitizers, LinkerPluginToWindowsNotSupported,
7 NotCircumventFeature, ProfileSampleUseFileDoesNotExist, ProfileUseFileDoesNotExist,
8 SanitizerCfiEnabled, SanitizerNotSupported, SanitizersNotSupported,
9 SplitDebugInfoUnstablePlatform, StackProtectorNotSupportedForTarget,
10 TargetRequiresUnwindTables, UnstableVirtualFunctionElimination, UnsupportedDwarfVersion,
12 use crate::parse::{add_feature_diagnostics, ParseSess};
13 use crate::search_paths::{PathKind, SearchPath};
14 use crate::{filesearch, lint};
16 pub use rustc_ast::attr::MarkedAttrs;
17 pub use rustc_ast::Attribute;
18 use rustc_data_structures::flock;
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20 use rustc_data_structures::jobserver::{self, Client};
21 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
22 use rustc_data_structures::sync::{
23 self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
25 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
26 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
27 use rustc_errors::json::JsonEmitter;
28 use rustc_errors::registry::Registry;
30 error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage,
31 ErrorGuaranteed, FluentBundle, IntoDiagnostic, LazyFallbackBundle, MultiSpan, Noted,
33 use rustc_macros::HashStable_Generic;
34 pub use rustc_span::def_id::StableCrateId;
35 use rustc_span::edition::Edition;
36 use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMap, Span};
37 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
38 use rustc_target::asm::InlineAsmArch;
39 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
40 use rustc_target::spec::{
41 DebuginfoKind, SanitizerSet, SplitDebuginfo, StackProtector, Target, TargetTriple, TlsModel,
44 use std::cell::{self, RefCell};
48 use std::ops::{Div, Mul};
49 use std::path::{Path, PathBuf};
50 use std::str::FromStr;
52 use std::time::Duration;
54 pub struct OptimizationFuel {
55 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
57 /// We're rejecting all further optimizations.
61 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
62 #[derive(Clone, Copy)]
63 pub enum CtfeBacktrace {
64 /// Do nothing special, return the error as usual without a backtrace.
66 /// Capture a backtrace at the point the error is created and return it in the error
67 /// (to be printed later if/when the error ever actually gets shown to the user).
69 /// Capture a backtrace at the point the error is created and immediately print it out.
73 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
74 /// limits are consistent throughout the compiler.
75 #[derive(Clone, Copy, Debug, HashStable_Generic)]
76 pub struct Limit(pub usize);
79 /// Create a new limit from a `usize`.
80 pub fn new(value: usize) -> Self {
84 /// Check that `value` is within the limit. Ensures that the same comparisons are used
85 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
87 pub fn value_within_limit(&self, value: usize) -> bool {
92 impl From<usize> for Limit {
93 fn from(value: usize) -> Self {
98 impl fmt::Display for Limit {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 impl Div<usize> for Limit {
107 fn div(self, rhs: usize) -> Self::Output {
108 Limit::new(self.0 / rhs)
112 impl Mul<usize> for Limit {
115 fn mul(self, rhs: usize) -> Self::Output {
116 Limit::new(self.0 * rhs)
120 impl rustc_errors::IntoDiagnosticArg for Limit {
121 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
122 self.to_string().into_diagnostic_arg()
126 #[derive(Clone, Copy, Debug, HashStable_Generic)]
128 /// The maximum recursion limit for potentially infinitely recursive
129 /// operations such as auto-dereference and monomorphization.
130 pub recursion_limit: Limit,
131 /// The size at which the `large_assignments` lint starts
133 pub move_size_limit: Limit,
134 /// The maximum length of types during monomorphization.
135 pub type_length_limit: Limit,
136 /// The maximum blocks a const expression can evaluate.
137 pub const_eval_limit: Limit,
140 /// Represents the data associated with a compilation
141 /// session for a single crate.
145 pub opts: config::Options,
146 pub host_tlib_path: Lrc<SearchPath>,
147 pub target_tlib_path: Lrc<SearchPath>,
148 pub parse_sess: ParseSess,
149 pub sysroot: PathBuf,
150 /// The name of the root source file of the crate, in the local file system.
151 /// `None` means that there is no source file.
152 pub local_crate_source_file: Option<PathBuf>,
154 crate_types: OnceCell<Vec<CrateType>>,
155 /// The `stable_crate_id` is constructed out of the crate name and all the
156 /// `-C metadata` arguments passed to the compiler. Its value forms a unique
157 /// global identifier for the crate. It is used to allow multiple crates
158 /// with the same name to coexist. See the
159 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
160 pub stable_crate_id: OnceCell<StableCrateId>,
162 features: OnceCell<rustc_feature::Features>,
164 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
165 /// Used for incremental compilation tests. Will only be populated if
166 /// `-Zquery-dep-graph` is specified.
167 pub cgu_reuse_tracker: CguReuseTracker,
169 /// Used by `-Z self-profile`.
170 pub prof: SelfProfilerRef,
172 /// Some measurements that are being gathered during compilation.
173 pub perf_stats: PerfStats,
175 /// Data about code being compiled, gathered during compilation.
176 pub code_stats: CodeStats,
178 /// Tracks fuel info if `-zfuel=crate=n` is specified.
179 optimization_fuel: Lock<OptimizationFuel>,
181 /// Always set to zero and incremented so that we can print fuel expended by a crate.
182 pub print_fuel: AtomicU64,
184 /// Loaded up early on in the initialization of this `Session` to avoid
185 /// false positives about a job server in our environment.
186 pub jobserver: Client,
188 /// Cap lint level specified by a driver specifically.
189 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
191 /// Tracks the current behavior of the CTFE engine when an error occurs.
192 /// Options range from returning the error without a backtrace to returning an error
193 /// and immediately printing the backtrace to stderr.
194 /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
195 /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
197 pub ctfe_backtrace: Lock<CtfeBacktrace>,
199 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
200 /// const check, optionally with the relevant feature gate. We use this to
201 /// warn about unleashing, but with a single diagnostic instead of dozens that
202 /// drown everything else in noise.
203 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
205 /// Architecture to use for interpreting asm!.
206 pub asm_arch: Option<InlineAsmArch>,
208 /// Set of enabled features for the current target.
209 pub target_features: FxHashSet<Symbol>,
211 /// Set of enabled features for the current target, including unstable ones.
212 pub unstable_target_features: FxHashSet<Symbol>,
215 pub struct PerfStats {
216 /// The accumulated time spent on computing symbol hashes.
217 pub symbol_hash_time: Lock<Duration>,
218 /// Total number of values canonicalized queries constructed.
219 pub queries_canonicalized: AtomicUsize,
220 /// Number of times this query is invoked.
221 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
222 /// Number of times this query is invoked.
223 pub normalize_projection_ty: AtomicUsize,
227 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
228 self.miri_unleashed_features.lock().push((span, feature_gate));
231 fn check_miri_unleashed_features(&self) {
232 let unleashed_features = self.miri_unleashed_features.lock();
233 if !unleashed_features.is_empty() {
234 let mut must_err = false;
235 // Create a diagnostic pointing at where things got unleashed.
236 // FIXME(#100717): needs eager translation/lists
237 #[allow(rustc::untranslatable_diagnostic)]
238 #[allow(rustc::diagnostic_outside_of_impl)]
239 let mut diag = self.struct_warn("skipping const checks");
240 for &(span, feature_gate) in unleashed_features.iter() {
241 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
242 if let Some(gate) = feature_gate {
243 diag.span_help(span, &format!("skipping check for `{gate}` feature"));
244 // The unleash flag must *not* be used to just "hack around" feature gates.
247 diag.span_help(span, "skipping check that does not even have a feature gate");
251 // If we should err, make sure we did.
252 if must_err && self.has_errors().is_none() {
253 // We have skipped a feature gate, and not run into other errors... reject.
254 self.emit_err(NotCircumventFeature);
259 /// Invoked all the way at the end to finish off diagnostics printing.
260 pub fn finish_diagnostics(&self, registry: &Registry) {
261 self.check_miri_unleashed_features();
262 self.diagnostic().print_error_count(registry);
263 self.emit_future_breakage();
266 fn emit_future_breakage(&self) {
267 if !self.opts.json_future_incompat {
271 let diags = self.diagnostic().take_future_breakage_diagnostics();
272 if diags.is_empty() {
275 self.parse_sess.span_diagnostic.emit_future_breakage_report(diags);
278 pub fn local_stable_crate_id(&self) -> StableCrateId {
279 self.stable_crate_id.get().copied().unwrap()
282 pub fn crate_types(&self) -> &[CrateType] {
283 self.crate_types.get().unwrap().as_slice()
286 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
287 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
290 #[rustc_lint_diagnostics]
291 pub fn struct_span_warn<S: Into<MultiSpan>>(
294 msg: impl Into<DiagnosticMessage>,
295 ) -> DiagnosticBuilder<'_, ()> {
296 self.diagnostic().struct_span_warn(sp, msg)
298 #[rustc_lint_diagnostics]
299 pub fn struct_span_warn_with_expectation<S: Into<MultiSpan>>(
302 msg: impl Into<DiagnosticMessage>,
303 id: lint::LintExpectationId,
304 ) -> DiagnosticBuilder<'_, ()> {
305 self.diagnostic().struct_span_warn_with_expectation(sp, msg, id)
307 #[rustc_lint_diagnostics]
308 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
311 msg: impl Into<DiagnosticMessage>,
313 ) -> DiagnosticBuilder<'_, ()> {
314 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
316 #[rustc_lint_diagnostics]
317 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
318 self.diagnostic().struct_warn(msg)
320 #[rustc_lint_diagnostics]
321 pub fn struct_warn_with_expectation(
323 msg: impl Into<DiagnosticMessage>,
324 id: lint::LintExpectationId,
325 ) -> DiagnosticBuilder<'_, ()> {
326 self.diagnostic().struct_warn_with_expectation(msg, id)
328 #[rustc_lint_diagnostics]
329 pub fn struct_span_allow<S: Into<MultiSpan>>(
332 msg: impl Into<DiagnosticMessage>,
333 ) -> DiagnosticBuilder<'_, ()> {
334 self.diagnostic().struct_span_allow(sp, msg)
336 #[rustc_lint_diagnostics]
337 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
338 self.diagnostic().struct_allow(msg)
340 #[rustc_lint_diagnostics]
341 pub fn struct_expect(
343 msg: impl Into<DiagnosticMessage>,
344 id: lint::LintExpectationId,
345 ) -> DiagnosticBuilder<'_, ()> {
346 self.diagnostic().struct_expect(msg, id)
348 #[rustc_lint_diagnostics]
349 pub fn struct_span_err<S: Into<MultiSpan>>(
352 msg: impl Into<DiagnosticMessage>,
353 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
354 self.diagnostic().struct_span_err(sp, msg)
356 #[rustc_lint_diagnostics]
357 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
360 msg: impl Into<DiagnosticMessage>,
362 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
363 self.diagnostic().struct_span_err_with_code(sp, msg, code)
365 // FIXME: This method should be removed (every error should have an associated error code).
366 #[rustc_lint_diagnostics]
369 msg: impl Into<DiagnosticMessage>,
370 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
371 self.parse_sess.struct_err(msg)
373 #[rustc_lint_diagnostics]
374 pub fn struct_err_with_code(
376 msg: impl Into<DiagnosticMessage>,
378 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
379 self.diagnostic().struct_err_with_code(msg, code)
381 #[rustc_lint_diagnostics]
382 pub fn struct_warn_with_code(
384 msg: impl Into<DiagnosticMessage>,
386 ) -> DiagnosticBuilder<'_, ()> {
387 self.diagnostic().struct_warn_with_code(msg, code)
389 #[rustc_lint_diagnostics]
390 pub fn struct_span_fatal<S: Into<MultiSpan>>(
393 msg: impl Into<DiagnosticMessage>,
394 ) -> DiagnosticBuilder<'_, !> {
395 self.diagnostic().struct_span_fatal(sp, msg)
397 #[rustc_lint_diagnostics]
398 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
401 msg: impl Into<DiagnosticMessage>,
403 ) -> DiagnosticBuilder<'_, !> {
404 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
406 #[rustc_lint_diagnostics]
407 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
408 self.diagnostic().struct_fatal(msg)
411 #[rustc_lint_diagnostics]
412 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
413 self.diagnostic().span_fatal(sp, msg)
415 #[rustc_lint_diagnostics]
416 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
419 msg: impl Into<DiagnosticMessage>,
422 self.diagnostic().span_fatal_with_code(sp, msg, code)
424 #[rustc_lint_diagnostics]
425 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! {
426 self.diagnostic().fatal(msg).raise()
428 #[rustc_lint_diagnostics]
429 pub fn span_err_or_warn<S: Into<MultiSpan>>(
433 msg: impl Into<DiagnosticMessage>,
436 self.span_warn(sp, msg);
438 self.span_err(sp, msg);
441 #[rustc_lint_diagnostics]
442 pub fn span_err<S: Into<MultiSpan>>(
445 msg: impl Into<DiagnosticMessage>,
446 ) -> ErrorGuaranteed {
447 self.diagnostic().span_err(sp, msg)
449 #[rustc_lint_diagnostics]
450 pub fn span_err_with_code<S: Into<MultiSpan>>(
453 msg: impl Into<DiagnosticMessage>,
456 self.diagnostic().span_err_with_code(sp, msg, code)
458 #[rustc_lint_diagnostics]
459 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
460 self.diagnostic().err(msg)
462 pub fn create_err<'a>(
464 err: impl IntoDiagnostic<'a>,
465 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
466 self.parse_sess.create_err(err)
468 pub fn create_feature_err<'a>(
470 err: impl IntoDiagnostic<'a>,
472 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
473 let mut err = self.parse_sess.create_err(err);
474 if err.code.is_none() {
475 err.code = std::option::Option::Some(error_code!(E0658));
477 add_feature_diagnostics(&mut err, &self.parse_sess, feature);
480 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
481 self.parse_sess.emit_err(err)
483 pub fn create_warning<'a>(
485 err: impl IntoDiagnostic<'a, ()>,
486 ) -> DiagnosticBuilder<'a, ()> {
487 self.parse_sess.create_warning(err)
489 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
490 self.parse_sess.emit_warning(warning)
492 pub fn create_note<'a>(
494 note: impl IntoDiagnostic<'a, Noted>,
495 ) -> DiagnosticBuilder<'a, Noted> {
496 self.parse_sess.create_note(note)
498 pub fn emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted {
499 self.parse_sess.emit_note(note)
501 pub fn create_fatal<'a>(
503 fatal: impl IntoDiagnostic<'a, !>,
504 ) -> DiagnosticBuilder<'a, !> {
505 self.parse_sess.create_fatal(fatal)
507 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
508 self.parse_sess.emit_fatal(fatal)
511 pub fn err_count(&self) -> usize {
512 self.diagnostic().err_count()
514 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
515 self.diagnostic().has_errors()
517 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
518 self.diagnostic().has_errors_or_delayed_span_bugs()
520 pub fn abort_if_errors(&self) {
521 self.diagnostic().abort_if_errors();
523 pub fn compile_status(&self) -> Result<(), ErrorGuaranteed> {
524 if let Some(reported) = self.diagnostic().has_errors_or_lint_errors() {
525 let _ = self.diagnostic().emit_stashed_diagnostics();
531 // FIXME(matthewjasper) Remove this method, it should never be needed.
532 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorGuaranteed>
536 let old_count = self.err_count();
538 if self.err_count() == old_count {
541 Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
544 #[allow(rustc::untranslatable_diagnostic)]
545 #[allow(rustc::diagnostic_outside_of_impl)]
546 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
547 self.diagnostic().span_warn(sp, msg)
549 #[allow(rustc::untranslatable_diagnostic)]
550 #[allow(rustc::diagnostic_outside_of_impl)]
551 pub fn span_warn_with_code<S: Into<MultiSpan>>(
554 msg: impl Into<DiagnosticMessage>,
557 self.diagnostic().span_warn_with_code(sp, msg, code)
559 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
560 self.diagnostic().warn(msg)
562 /// Delay a span_bug() call until abort_if_errors()
564 pub fn delay_span_bug<S: Into<MultiSpan>>(
567 msg: impl Into<DiagnosticMessage>,
568 ) -> ErrorGuaranteed {
569 self.diagnostic().delay_span_bug(sp, msg)
572 /// Used for code paths of expensive computations that should only take place when
573 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
574 /// it's likely a bug.
575 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
576 if self.opts.unstable_opts.print_type_sizes
577 || self.opts.unstable_opts.query_dep_graph
578 || self.opts.unstable_opts.dump_mir.is_some()
579 || self.opts.unstable_opts.unpretty.is_some()
580 || self.opts.output_types.contains_key(&OutputType::Mir)
581 || std::env::var_os("RUSTC_LOG").is_some()
586 self.diagnostic().delay_good_path_bug(msg)
589 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
590 self.diagnostic().note_without_error(msg)
592 pub fn span_note_without_error<S: Into<MultiSpan>>(
595 msg: impl Into<DiagnosticMessage>,
597 self.diagnostic().span_note_without_error(sp, msg)
599 #[allow(rustc::untranslatable_diagnostic)]
600 #[allow(rustc::diagnostic_outside_of_impl)]
601 pub fn struct_note_without_error(
603 msg: impl Into<DiagnosticMessage>,
604 ) -> DiagnosticBuilder<'_, ()> {
605 self.diagnostic().struct_note_without_error(msg)
609 pub fn diagnostic(&self) -> &rustc_errors::Handler {
610 &self.parse_sess.span_diagnostic
614 pub fn source_map(&self) -> &SourceMap {
615 self.parse_sess.source_map()
618 /// Returns `true` if internal lints should be added to the lint store - i.e. if
619 /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
620 /// to be emitted under rustdoc).
621 pub fn enable_internal_lints(&self) -> bool {
622 self.unstable_options() && !self.opts.actually_rustdoc
625 pub fn instrument_coverage(&self) -> bool {
626 self.opts.cg.instrument_coverage() != InstrumentCoverage::Off
629 pub fn instrument_coverage_except_unused_generics(&self) -> bool {
630 self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedGenerics
633 pub fn instrument_coverage_except_unused_functions(&self) -> bool {
634 self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedFunctions
637 /// Gets the features enabled for the current compilation session.
638 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
639 /// dependency tracking. Use tcx.features() instead.
641 pub fn features_untracked(&self) -> &rustc_feature::Features {
642 self.features.get().unwrap()
645 pub fn init_features(&self, features: rustc_feature::Features) {
646 match self.features.set(features) {
648 Err(_) => panic!("`features` was initialized twice"),
652 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
653 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
656 /// Check whether this compile session and crate type use static crt.
657 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
658 if !self.target.crt_static_respected {
659 // If the target does not opt in to crt-static support, use its default.
660 return self.target.crt_static_default;
663 let requested_features = self.opts.cg.target_feature.split(',');
664 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
665 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
667 // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
668 #[allow(rustc::bad_opt_access)]
669 if found_positive || found_negative {
671 } else if crate_type == Some(CrateType::ProcMacro)
672 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
674 // FIXME: When crate_type is not available,
675 // we use compiler options to determine the crate_type.
676 // We can't check `#![crate_type = "proc-macro"]` here.
679 self.target.crt_static_default
683 pub fn is_wasi_reactor(&self) -> bool {
684 self.target.options.os == "wasi"
686 self.opts.unstable_opts.wasi_exec_model,
687 Some(config::WasiExecModel::Reactor)
691 /// Returns `true` if the target can use the current split debuginfo configuration.
692 pub fn target_can_use_split_dwarf(&self) -> bool {
693 self.target.debuginfo_kind == DebuginfoKind::Dwarf
696 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
697 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.to_u64())
700 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
701 filesearch::FileSearch::new(
703 self.opts.target_triple.triple(),
704 &self.opts.search_paths,
705 &self.target_tlib_path,
709 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
710 filesearch::FileSearch::new(
712 config::host_triple(),
713 &self.opts.search_paths,
714 &self.host_tlib_path,
719 /// Returns a list of directories where target-specific tool binaries are located.
720 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
721 let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple());
722 let p = PathBuf::from_iter([
723 Path::new(&self.sysroot),
724 Path::new(&rustlib_path),
727 if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
730 pub fn init_incr_comp_session(
732 session_dir: PathBuf,
733 lock_file: flock::Lock,
734 load_dep_graph: bool,
736 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
738 if let IncrCompSession::NotInitialized = *incr_comp_session {
740 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
744 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
747 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
748 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
750 if let IncrCompSession::Active { .. } = *incr_comp_session {
752 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
755 // Note: this will also drop the lock file, thus unlocking the directory.
756 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
759 pub fn mark_incr_comp_session_as_invalid(&self) {
760 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
762 let session_directory = match *incr_comp_session {
763 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
764 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
765 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
768 // Note: this will also drop the lock file, thus unlocking the directory.
769 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
772 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
773 let incr_comp_session = self.incr_comp_session.borrow();
774 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
775 IncrCompSession::NotInitialized => panic!(
776 "trying to get session directory from `IncrCompSession`: {:?}",
779 IncrCompSession::Active { ref session_directory, .. }
780 | IncrCompSession::Finalized { ref session_directory }
781 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
787 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
788 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
791 pub fn print_perf_stats(&self) {
793 "Total time spent computing symbol hashes: {}",
794 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
797 "Total queries canonicalized: {}",
798 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
801 "normalize_generic_arg_after_erasing_regions: {}",
802 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
805 "normalize_projection_ty: {}",
806 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
810 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
811 /// This expends fuel if applicable, and records fuel if applicable.
812 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
814 if let Some((ref c, _)) = self.opts.unstable_opts.fuel {
816 assert_eq!(self.threads(), 1);
817 let mut fuel = self.optimization_fuel.lock();
818 ret = fuel.remaining != 0;
819 if fuel.remaining == 0 && !fuel.out_of_fuel {
820 if self.diagnostic().can_emit_warnings() {
821 // We only call `msg` in case we can actually emit warnings.
822 // Otherwise, this could cause a `delay_good_path_bug` to
823 // trigger (issue #79546).
824 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
826 fuel.out_of_fuel = true;
827 } else if fuel.remaining > 0 {
832 if let Some(ref c) = self.opts.unstable_opts.print_fuel {
834 assert_eq!(self.threads(), 1);
835 self.print_fuel.fetch_add(1, SeqCst);
841 pub fn rust_2015(&self) -> bool {
842 self.edition() == Edition::Edition2015
845 /// Are we allowed to use features from the Rust 2018 edition?
846 pub fn rust_2018(&self) -> bool {
847 self.edition() >= Edition::Edition2018
850 /// Are we allowed to use features from the Rust 2021 edition?
851 pub fn rust_2021(&self) -> bool {
852 self.edition() >= Edition::Edition2021
855 /// Are we allowed to use features from the Rust 2024 edition?
856 pub fn rust_2024(&self) -> bool {
857 self.edition() >= Edition::Edition2024
860 /// Returns `true` if we cannot skip the PLT for shared library calls.
861 pub fn needs_plt(&self) -> bool {
862 // Check if the current target usually needs PLT to be enabled.
863 // The user can use the command line flag to override it.
864 let needs_plt = self.target.needs_plt;
866 let dbg_opts = &self.opts.unstable_opts;
868 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
870 // Only enable this optimization by default if full relro is also enabled.
871 // In this case, lazy binding was already unavailable, so nothing is lost.
872 // This also ensures `-Wl,-z,now` is supported by the linker.
873 let full_relro = RelroLevel::Full == relro_level;
875 // If user didn't explicitly forced us to use / skip the PLT,
876 // then try to skip it where possible.
877 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
880 /// Checks if LLVM lifetime markers should be emitted.
881 pub fn emit_lifetime_markers(&self) -> bool {
882 self.opts.optimize != config::OptLevel::No
883 // AddressSanitizer uses lifetimes to detect use after scope bugs.
884 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
885 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
886 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
889 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
890 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
892 .any(|kind| attr.has_name(*kind))
895 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
896 attrs.iter().any(|item| item.has_name(name))
899 pub fn find_by_name<'a>(
901 attrs: &'a [Attribute],
903 ) -> Option<&'a Attribute> {
904 attrs.iter().find(|attr| attr.has_name(name))
907 pub fn filter_by_name<'a>(
909 attrs: &'a [Attribute],
911 ) -> impl Iterator<Item = &'a Attribute> {
912 attrs.iter().filter(move |attr| attr.has_name(name))
915 pub fn first_attr_value_str_by_name(
919 ) -> Option<Symbol> {
920 attrs.iter().find(|at| at.has_name(name)).and_then(|at| at.value_str())
924 // JUSTIFICATION: defn of the suggested wrapper fns
925 #[allow(rustc::bad_opt_access)]
927 pub fn verbose(&self) -> bool {
928 self.opts.unstable_opts.verbose
931 pub fn instrument_mcount(&self) -> bool {
932 self.opts.unstable_opts.instrument_mcount
935 pub fn time_passes(&self) -> bool {
936 self.opts.unstable_opts.time_passes
939 pub fn time_llvm_passes(&self) -> bool {
940 self.opts.unstable_opts.time_llvm_passes
943 pub fn meta_stats(&self) -> bool {
944 self.opts.unstable_opts.meta_stats
947 pub fn asm_comments(&self) -> bool {
948 self.opts.unstable_opts.asm_comments
951 pub fn verify_llvm_ir(&self) -> bool {
952 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
955 pub fn print_llvm_passes(&self) -> bool {
956 self.opts.unstable_opts.print_llvm_passes
959 pub fn binary_dep_depinfo(&self) -> bool {
960 self.opts.unstable_opts.binary_dep_depinfo
963 pub fn mir_opt_level(&self) -> usize {
967 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
970 /// Calculates the flavor of LTO to use for this compilation.
971 pub fn lto(&self) -> config::Lto {
972 // If our target has codegen requirements ignore the command line
973 if self.target.requires_lto {
974 return config::Lto::Fat;
977 // If the user specified something, return that. If they only said `-C
978 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
979 // then ensure we can't use a ThinLTO.
980 match self.opts.cg.lto {
981 config::LtoCli::Unspecified => {
982 // The compiler was invoked without the `-Clto` flag. Fall
983 // through to the default handling
985 config::LtoCli::No => {
986 // The user explicitly opted out of any kind of LTO
987 return config::Lto::No;
989 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
990 // All of these mean fat LTO
991 return config::Lto::Fat;
993 config::LtoCli::Thin => {
994 return if self.opts.cli_forced_thinlto_off {
1002 // Ok at this point the target doesn't require anything and the user
1003 // hasn't asked for anything. Our next decision is whether or not
1004 // we enable "auto" ThinLTO where we use multiple codegen units and
1005 // then do ThinLTO over those codegen units. The logic below will
1006 // either return `No` or `ThinLocal`.
1008 // If processing command line options determined that we're incompatible
1009 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
1010 if self.opts.cli_forced_thinlto_off {
1011 return config::Lto::No;
1014 // If `-Z thinlto` specified process that, but note that this is mostly
1015 // a deprecated option now that `-C lto=thin` exists.
1016 if let Some(enabled) = self.opts.unstable_opts.thinlto {
1018 return config::Lto::ThinLocal;
1020 return config::Lto::No;
1024 // If there's only one codegen unit and LTO isn't enabled then there's
1025 // no need for ThinLTO so just return false.
1026 if self.codegen_units() == 1 {
1027 return config::Lto::No;
1030 // Now we're in "defaults" territory. By default we enable ThinLTO for
1031 // optimized compiles (anything greater than O0).
1032 match self.opts.optimize {
1033 config::OptLevel::No => config::Lto::No,
1034 _ => config::Lto::ThinLocal,
1038 /// Returns the panic strategy for this compile session. If the user explicitly selected one
1039 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
1040 pub fn panic_strategy(&self) -> PanicStrategy {
1041 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
1044 pub fn fewer_names(&self) -> bool {
1045 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1048 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1049 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1050 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1051 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1056 pub fn unstable_options(&self) -> bool {
1057 self.opts.unstable_opts.unstable_options
1060 pub fn is_nightly_build(&self) -> bool {
1061 self.opts.unstable_features.is_nightly_build()
1064 pub fn overflow_checks(&self) -> bool {
1065 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1068 pub fn relocation_model(&self) -> RelocModel {
1069 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
1072 pub fn code_model(&self) -> Option<CodeModel> {
1073 self.opts.cg.code_model.or(self.target.code_model)
1076 pub fn tls_model(&self) -> TlsModel {
1077 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
1080 pub fn split_debuginfo(&self) -> SplitDebuginfo {
1081 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1084 pub fn stack_protector(&self) -> StackProtector {
1085 if self.target.options.supports_stack_protector {
1086 self.opts.unstable_opts.stack_protector
1088 StackProtector::None
1092 pub fn must_emit_unwind_tables(&self) -> bool {
1093 // This is used to control the emission of the `uwtable` attribute on
1096 // Unwind tables are needed when compiling with `-C panic=unwind`, but
1097 // LLVM won't omit unwind tables unless the function is also marked as
1098 // `nounwind`, so users are allowed to disable `uwtable` emission.
1099 // Historically rustc always emits `uwtable` attributes by default, so
1100 // even they can be disabled, they're still emitted by default.
1102 // On some targets (including windows), however, exceptions include
1103 // other events such as illegal instructions, segfaults, etc. This means
1104 // that on Windows we end up still needing unwind tables even if the `-C
1105 // panic=abort` flag is passed.
1107 // You can also find more info on why Windows needs unwind tables in:
1108 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1110 // If a target requires unwind tables, then they must be emitted.
1111 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1112 // value, if it is provided, or disable them, if not.
1113 self.target.requires_uwtable
1114 || self.opts.cg.force_unwind_tables.unwrap_or(
1115 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
1119 /// Returns the number of query threads that should be used for this
1121 pub fn threads(&self) -> usize {
1122 self.opts.unstable_opts.threads
1125 /// Returns the number of codegen units that should be used for this
1127 pub fn codegen_units(&self) -> usize {
1128 if let Some(n) = self.opts.cli_forced_codegen_units {
1131 if let Some(n) = self.target.default_codegen_units {
1135 // If incremental compilation is turned on, we default to a high number
1136 // codegen units in order to reduce the "collateral damage" small
1138 if self.opts.incremental.is_some() {
1142 // Why is 16 codegen units the default all the time?
1144 // The main reason for enabling multiple codegen units by default is to
1145 // leverage the ability for the codegen backend to do codegen and
1146 // optimization in parallel. This allows us, especially for large crates, to
1147 // make good use of all available resources on the machine once we've
1148 // hit that stage of compilation. Large crates especially then often
1149 // take a long time in codegen/optimization and this helps us amortize that
1152 // Note that a high number here doesn't mean that we'll be spawning a
1153 // large number of threads in parallel. The backend of rustc contains
1154 // global rate limiting through the `jobserver` crate so we'll never
1155 // overload the system with too much work, but rather we'll only be
1156 // optimizing when we're otherwise cooperating with other instances of
1159 // Rather a high number here means that we should be able to keep a lot
1160 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1161 // to build we'll be guaranteed that all cpus will finish pretty closely
1162 // to one another and we should make relatively optimal use of system
1165 // Note that the main cost of codegen units is that it prevents LLVM
1166 // from inlining across codegen units. Users in general don't have a lot
1167 // of control over how codegen units are split up so it's our job in the
1168 // compiler to ensure that undue performance isn't lost when using
1169 // codegen units (aka we can't require everyone to slap `#[inline]` on
1172 // If we're compiling at `-O0` then the number doesn't really matter too
1173 // much because performance doesn't matter and inlining is ok to lose.
1174 // In debug mode we just want to try to guarantee that no cpu is stuck
1175 // doing work that could otherwise be farmed to others.
1177 // In release mode, however (O1 and above) performance does indeed
1178 // matter! To recover the loss in performance due to inlining we'll be
1179 // enabling ThinLTO by default (the function for which is just below).
1180 // This will ensure that we recover any inlining wins we otherwise lost
1181 // through codegen unit partitioning.
1185 // Ok that's a lot of words but the basic tl;dr; is that we want a high
1186 // number here -- but not too high. Additionally we're "safe" to have it
1187 // always at the same number at all optimization levels.
1189 // As a result 16 was chosen here! Mostly because it was a power of 2
1190 // and most benchmarks agreed it was roughly a local optimum. Not very
1195 pub fn teach(&self, code: &DiagnosticId) -> bool {
1196 self.opts.unstable_opts.teach && self.diagnostic().must_teach(code)
1199 pub fn edition(&self) -> Edition {
1203 pub fn link_dead_code(&self) -> bool {
1204 self.opts.cg.link_dead_code.unwrap_or(false)
1208 // JUSTIFICATION: part of session construction
1209 #[allow(rustc::bad_opt_access)]
1211 sopts: &config::Options,
1212 registry: rustc_errors::registry::Registry,
1213 source_map: Lrc<SourceMap>,
1214 bundle: Option<Lrc<FluentBundle>>,
1215 fallback_bundle: LazyFallbackBundle,
1216 emitter_dest: Option<Box<dyn Write + Send>>,
1217 ) -> Box<dyn Emitter + sync::Send> {
1218 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1219 match (sopts.error_format, emitter_dest) {
1220 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1221 let (short, color_config) = kind.unzip();
1223 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1224 let emitter = AnnotateSnippetEmitterWriter::new(
1231 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1233 let emitter = match dst {
1234 None => EmitterWriter::stderr(
1240 sopts.unstable_opts.teach,
1241 sopts.diagnostic_width,
1244 Some(dst) => EmitterWriter::new(
1250 false, // no teach messages when writing to a buffer
1251 false, // no colors when writing to a buffer
1252 None, // no diagnostic width
1256 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1259 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1260 JsonEmitter::stderr(
1267 sopts.diagnostic_width,
1270 .ui_testing(sopts.unstable_opts.ui_testing),
1272 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1281 sopts.diagnostic_width,
1284 .ui_testing(sopts.unstable_opts.ui_testing),
1289 pub enum DiagnosticOutput {
1291 Raw(Box<dyn Write + Send>),
1294 // JUSTIFICATION: literally session construction
1295 #[allow(rustc::bad_opt_access)]
1296 pub fn build_session(
1297 sopts: config::Options,
1298 local_crate_source_file: Option<PathBuf>,
1299 bundle: Option<Lrc<rustc_errors::FluentBundle>>,
1300 registry: rustc_errors::registry::Registry,
1301 diagnostics_output: DiagnosticOutput,
1302 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1303 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1304 target_override: Option<Target>,
1306 // FIXME: This is not general enough to make the warning lint completely override
1307 // normal diagnostic warnings, since the warning lint can also be denied and changed
1308 // later via the source code.
1309 let warnings_allow = sopts
1312 .rfind(|&&(ref key, _)| *key == "warnings")
1313 .map_or(false, |&(_, level)| level == lint::Allow);
1314 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1315 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1317 let write_dest = match diagnostics_output {
1318 DiagnosticOutput::Default => None,
1319 DiagnosticOutput::Raw(write) => Some(write),
1322 let sysroot = match &sopts.maybe_sysroot {
1323 Some(sysroot) => sysroot.clone(),
1324 None => filesearch::get_or_default_sysroot(),
1327 let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
1328 let host_triple = TargetTriple::from_triple(config::host_triple());
1329 let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1330 early_error(sopts.error_format, &format!("Error loading host specification: {e}"))
1332 for warning in target_warnings.warning_messages() {
1333 early_warn(sopts.error_format, &warning)
1336 let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1337 let hash_kind = sopts.unstable_opts.src_hash_algorithm.unwrap_or_else(|| {
1338 if target_cfg.is_like_msvc {
1339 SourceFileHashAlgorithm::Sha1
1341 SourceFileHashAlgorithm::Md5
1344 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1346 sopts.file_path_mapping(),
1350 let fallback_bundle = fallback_fluent_bundle(
1351 rustc_errors::DEFAULT_LOCALE_RESOURCES,
1352 sopts.unstable_opts.translate_directionality_markers,
1355 default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle, write_dest);
1357 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1359 sopts.unstable_opts.diagnostic_handler_flags(can_emit_warnings),
1362 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1365 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1367 let profiler = SelfProfiler::new(
1369 sopts.crate_name.as_deref(),
1370 sopts.unstable_opts.self_profile_events.as_ref().map(|xs| &xs[..]),
1371 &sopts.unstable_opts.self_profile_counter,
1374 Ok(profiler) => Some(Arc::new(profiler)),
1376 early_warn(sopts.error_format, &format!("failed to create profiler: {e}"));
1384 let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1385 parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1387 let host_triple = config::host_triple();
1388 let target_triple = sopts.target_triple.triple();
1389 let host_tlib_path = Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1390 let target_tlib_path = if host_triple == target_triple {
1391 // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1392 // rescanning of the target lib path and an unnecessary allocation.
1393 host_tlib_path.clone()
1395 Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1398 let file_path_mapping = sopts.file_path_mapping();
1400 let local_crate_source_file =
1401 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1403 let optimization_fuel = Lock::new(OptimizationFuel {
1404 remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |i| i.1),
1407 let print_fuel = AtomicU64::new(0);
1409 let cgu_reuse_tracker = if sopts.unstable_opts.query_dep_graph {
1410 CguReuseTracker::new()
1412 CguReuseTracker::new_disabled()
1415 let prof = SelfProfilerRef::new(self_profiler, sopts.unstable_opts.time_passes);
1417 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1418 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1419 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1420 _ => CtfeBacktrace::Disabled,
1424 if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1426 let sess = Session {
1434 local_crate_source_file,
1435 crate_types: OnceCell::new(),
1436 stable_crate_id: OnceCell::new(),
1437 features: OnceCell::new(),
1438 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1441 perf_stats: PerfStats {
1442 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1443 queries_canonicalized: AtomicUsize::new(0),
1444 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1445 normalize_projection_ty: AtomicUsize::new(0),
1447 code_stats: Default::default(),
1450 jobserver: jobserver::client(),
1453 miri_unleashed_features: Lock::new(Default::default()),
1455 target_features: FxHashSet::default(),
1456 unstable_target_features: FxHashSet::default(),
1459 validate_commandline_args_with_session_available(&sess);
1464 /// Validate command line arguments with a `Session`.
1466 /// If it is useful to have a Session available already for validating a commandline argument, you
1468 // JUSTIFICATION: needs to access args to validate them
1469 #[allow(rustc::bad_opt_access)]
1470 fn validate_commandline_args_with_session_available(sess: &Session) {
1471 // Since we don't know if code in an rlib will be linked to statically or
1472 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1473 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1474 // these manually generated symbols confuse LLD when it tries to merge
1475 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1476 // when compiling for LLD ThinLTO. This way we can validly just not generate
1477 // the `dllimport` attributes and `__imp_` symbols in that case.
1478 if sess.opts.cg.linker_plugin_lto.enabled()
1479 && sess.opts.cg.prefer_dynamic
1480 && sess.target.is_like_windows
1482 sess.emit_err(LinkerPluginToWindowsNotSupported);
1485 // Make sure that any given profiling data actually exists so LLVM can't
1486 // decide to silently skip PGO.
1487 if let Some(ref path) = sess.opts.cg.profile_use {
1489 sess.emit_err(ProfileUseFileDoesNotExist { path });
1493 // Do the same for sample profile data.
1494 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1496 sess.emit_err(ProfileSampleUseFileDoesNotExist { path });
1500 // Unwind tables cannot be disabled if the target requires them.
1501 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1502 if sess.target.requires_uwtable && !include_uwtables {
1503 sess.emit_err(TargetRequiresUnwindTables);
1507 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1508 let supported_sanitizers = sess.target.options.supported_sanitizers;
1509 let unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1510 match unsupported_sanitizers.into_iter().count() {
1513 sess.emit_err(SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1516 sess.emit_err(SanitizersNotSupported { us: unsupported_sanitizers.to_string() });
1519 // Cannot mix and match sanitizers.
1520 let mut sanitizer_iter = sess.opts.unstable_opts.sanitizer.into_iter();
1521 if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1522 sess.emit_err(CannotMixAndMatchSanitizers {
1523 first: first.to_string(),
1524 second: second.to_string(),
1528 // Cannot enable crt-static with sanitizers on Linux
1529 if sess.crt_static(None) && !sess.opts.unstable_opts.sanitizer.is_empty() {
1530 sess.emit_err(CannotEnableCrtStaticLinux);
1533 // LLVM CFI and VFE both require LTO.
1534 if sess.lto() != config::Lto::Fat {
1535 if sess.is_sanitizer_cfi_enabled() {
1536 sess.emit_err(SanitizerCfiEnabled);
1538 if sess.opts.unstable_opts.virtual_function_elimination {
1539 sess.emit_err(UnstableVirtualFunctionElimination);
1543 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1544 if !sess.target.options.supports_stack_protector {
1545 sess.emit_warning(StackProtectorNotSupportedForTarget {
1546 stack_protector: sess.opts.unstable_opts.stack_protector,
1547 target_triple: &sess.opts.target_triple,
1552 if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version {
1553 if dwarf_version > 5 {
1554 sess.emit_err(UnsupportedDwarfVersion { dwarf_version });
1558 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1559 && !sess.opts.unstable_opts.unstable_options
1561 sess.emit_err(SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1565 /// Holds data on the current incremental compilation session, if there is one.
1567 pub enum IncrCompSession {
1568 /// This is the state the session will be in until the incr. comp. dir is
1571 /// This is the state during which the session directory is private and can
1573 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1574 /// This is the state after the session directory has been finalized. In this
1575 /// state, the contents of the directory must not be modified any more.
1576 Finalized { session_directory: PathBuf },
1577 /// This is an error state that is reached when some compilation error has
1578 /// occurred. It indicates that the contents of the session directory must
1579 /// not be used, since they might be invalid.
1580 InvalidBecauseOfErrors { session_directory: PathBuf },
1583 fn early_error_handler(output: config::ErrorOutputType) -> rustc_errors::Handler {
1584 let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1585 let emitter: Box<dyn Emitter + sync::Send> = match output {
1586 config::ErrorOutputType::HumanReadable(kind) => {
1587 let (short, color_config) = kind.unzip();
1588 Box::new(EmitterWriter::stderr(
1599 config::ErrorOutputType::Json { pretty, json_rendered } => {
1600 Box::new(JsonEmitter::basic(pretty, json_rendered, None, fallback_bundle, None, false))
1603 rustc_errors::Handler::with_emitter(true, None, emitter)
1606 #[allow(rustc::untranslatable_diagnostic)]
1607 #[allow(rustc::diagnostic_outside_of_impl)]
1608 pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) -> ErrorGuaranteed {
1609 early_error_handler(output).struct_err(msg).emit()
1612 #[allow(rustc::untranslatable_diagnostic)]
1613 #[allow(rustc::diagnostic_outside_of_impl)]
1614 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1615 early_error_handler(output).struct_fatal(msg).emit()
1618 #[allow(rustc::untranslatable_diagnostic)]
1619 #[allow(rustc::diagnostic_outside_of_impl)]
1620 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1621 early_error_handler(output).struct_warn(msg).emit()