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, OutputType, PrintRequest, SanitizerSet, SwitchWithOptPath};
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
10 pub use rustc_ast::crate_disambiguator::CrateDisambiguator;
11 use rustc_data_structures::flock;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::jobserver::{self, Client};
14 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
15 use rustc_data_structures::sync::{
16 self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
18 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
19 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
20 use rustc_errors::json::JsonEmitter;
21 use rustc_errors::registry::Registry;
22 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported};
23 use rustc_span::edition::Edition;
24 use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
25 use rustc_span::{SourceFileHashAlgorithm, Symbol};
26 use rustc_target::asm::InlineAsmArch;
27 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
28 use rustc_target::spec::{Target, TargetTriple, TlsModel};
30 use std::cell::{self, RefCell};
34 use std::num::NonZeroU32;
35 use std::ops::{Div, Mul};
36 use std::path::PathBuf;
37 use std::str::FromStr;
39 use std::time::Duration;
41 pub struct OptimizationFuel {
42 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
44 /// We're rejecting all further optimizations.
48 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
49 #[derive(Clone, Copy)]
50 pub enum CtfeBacktrace {
51 /// Do nothing special, return the error as usual without a backtrace.
53 /// Capture a backtrace at the point the error is created and return it in the error
54 /// (to be printed later if/when the error ever actually gets shown to the user).
56 /// Capture a backtrace at the point the error is created and immediately print it out.
60 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
61 /// limits are consistent throughout the compiler.
62 #[derive(Clone, Copy, Debug)]
63 pub struct Limit(pub usize);
66 /// Create a new limit from a `usize`.
67 pub fn new(value: usize) -> Self {
71 /// Check that `value` is within the limit. Ensures that the same comparisons are used
72 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
73 pub fn value_within_limit(&self, value: usize) -> bool {
78 impl fmt::Display for Limit {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 write!(f, "{}", self.0)
84 impl Div<usize> for Limit {
87 fn div(self, rhs: usize) -> Self::Output {
88 Limit::new(self.0 / rhs)
92 impl Mul<usize> for Limit {
95 fn mul(self, rhs: usize) -> Self::Output {
96 Limit::new(self.0 * rhs)
100 /// Represents the data associated with a compilation
101 /// session for a single crate.
103 pub target: config::Config,
105 pub opts: config::Options,
106 pub host_tlib_path: SearchPath,
107 /// `None` if the host and target are the same.
108 pub target_tlib_path: Option<SearchPath>,
109 pub parse_sess: ParseSess,
110 pub sysroot: PathBuf,
111 /// The name of the root source file of the crate, in the local file system.
112 /// `None` means that there is no source file.
113 pub local_crate_source_file: Option<PathBuf>,
114 /// The directory the compiler has been executed in plus a flag indicating
115 /// if the value stored here has been affected by path remapping.
116 pub working_dir: (PathBuf, bool),
118 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
119 /// (sub)diagnostics that have been set once, but should not be set again,
120 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
121 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
122 crate_types: OnceCell<Vec<CrateType>>,
123 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
124 /// arguments passed to the compiler. Its value together with the crate-name
125 /// forms a unique global identifier for the crate. It is used to allow
126 /// multiple crates with the same name to coexist. See the
127 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
128 pub crate_disambiguator: OnceCell<CrateDisambiguator>,
130 features: OnceCell<rustc_feature::Features>,
132 /// The maximum recursion limit for potentially infinitely recursive
133 /// operations such as auto-dereference and monomorphization.
134 pub recursion_limit: OnceCell<Limit>,
136 /// The maximum length of types during monomorphization.
137 pub type_length_limit: OnceCell<Limit>,
139 /// The maximum blocks a const expression can evaluate.
140 pub const_eval_limit: OnceCell<Limit>,
142 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
143 /// Used for incremental compilation tests. Will only be populated if
144 /// `-Zquery-dep-graph` is specified.
145 pub cgu_reuse_tracker: CguReuseTracker,
147 /// Used by `-Z self-profile`.
148 pub prof: SelfProfilerRef,
150 /// Some measurements that are being gathered during compilation.
151 pub perf_stats: PerfStats,
153 /// Data about code being compiled, gathered during compilation.
154 pub code_stats: CodeStats,
156 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
157 optimization_fuel_crate: Option<String>,
159 /// Tracks fuel info if `-zfuel=crate=n` is specified.
160 optimization_fuel: Lock<OptimizationFuel>,
162 // The next two are public because the driver needs to read them.
163 /// If `-zprint-fuel=crate`, `Some(crate)`.
164 pub print_fuel_crate: Option<String>,
165 /// Always set to zero and incremented so that we can print fuel expended by a crate.
166 pub print_fuel: AtomicU64,
168 /// Loaded up early on in the initialization of this `Session` to avoid
169 /// false positives about a job server in our environment.
170 pub jobserver: Client,
172 /// Cap lint level specified by a driver specifically.
173 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
175 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
176 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
178 /// Mapping from ident span to path span for paths that don't exist as written, but that
179 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
180 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
182 /// Path for libraries that will take preference over libraries shipped by Rust.
183 /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
184 pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
186 /// Tracks the current behavior of the CTFE engine when an error occurs.
187 /// Options range from returning the error without a backtrace to returning an error
188 /// and immediately printing the backtrace to stderr.
189 pub ctfe_backtrace: Lock<CtfeBacktrace>,
191 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
192 /// const check, optionally with the relevant feature gate. We use this to
193 /// warn about unleashing, but with a single diagnostic instead of dozens that
194 /// drown everything else in noise.
195 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
197 /// Base directory containing the `src/` for the Rust standard library, and
198 /// potentially `rustc` as well, if we can can find it. Right now it's always
199 /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
201 /// This directory is what the virtual `/rustc/$hash` is translated back to,
202 /// if Rust was built with path remapping to `/rustc/$hash` enabled
203 /// (the `rust.remap-debuginfo` option in `config.toml`).
204 pub real_rust_source_base_dir: Option<PathBuf>,
206 /// Architecture to use for interpreting asm!.
207 pub asm_arch: Option<InlineAsmArch>,
209 /// Set of enabled features for the current target.
210 pub target_features: FxHashSet<Symbol>,
213 pub struct PerfStats {
214 /// The accumulated time spent on computing symbol hashes.
215 pub symbol_hash_time: Lock<Duration>,
216 /// The accumulated time spent decoding def path tables from metadata.
217 pub decode_def_path_tables_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,
226 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
227 enum DiagnosticBuilderMethod {
230 SpanSuggestion(String), // suggestion
231 // Add more variants as needed to support one-time diagnostics.
234 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
235 /// emitting the same message more than once.
236 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
237 pub enum DiagnosticMessageId {
238 ErrorId(u16), // EXXXX error code as integer
239 LintId(lint::LintId),
240 StabilityId(Option<NonZeroU32>), // issue number
243 impl From<&'static lint::Lint> for DiagnosticMessageId {
244 fn from(lint: &'static lint::Lint) -> Self {
245 DiagnosticMessageId::LintId(lint::LintId::of(lint))
250 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
251 self.miri_unleashed_features.lock().push((span, feature_gate));
254 fn check_miri_unleashed_features(&self) {
255 let unleashed_features = self.miri_unleashed_features.lock();
256 if !unleashed_features.is_empty() {
257 let mut must_err = false;
258 // Create a diagnostic pointing at where things got unleashed.
259 let mut diag = self.struct_warn("skipping const checks");
260 for &(span, feature_gate) in unleashed_features.iter() {
261 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
262 if let Some(feature_gate) = feature_gate {
263 diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate));
264 // The unleash flag must *not* be used to just "hack around" feature gates.
267 diag.span_help(span, "skipping check that does not even have a feature gate");
271 // If we should err, make sure we did.
272 if must_err && !self.has_errors() {
273 // We have skipped a feature gate, and not run into other errors... reject.
275 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
276 gates, except when testing error paths in the CTFE engine",
282 /// Invoked all the way at the end to finish off diagnostics printing.
283 pub fn finish_diagnostics(&self, registry: &Registry) {
284 self.check_miri_unleashed_features();
285 self.diagnostic().print_error_count(registry);
288 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
289 self.crate_disambiguator.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 pub fn recursion_limit(&self) -> Limit {
301 self.recursion_limit.get().copied().unwrap()
304 pub fn type_length_limit(&self) -> Limit {
305 self.type_length_limit.get().copied().unwrap()
308 pub fn const_eval_limit(&self) -> Limit {
309 self.const_eval_limit.get().copied().unwrap()
312 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
313 self.diagnostic().struct_span_warn(sp, msg)
315 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
320 ) -> DiagnosticBuilder<'_> {
321 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
323 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
324 self.diagnostic().struct_warn(msg)
326 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
327 self.diagnostic().struct_span_err(sp, msg)
329 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
334 ) -> DiagnosticBuilder<'_> {
335 self.diagnostic().struct_span_err_with_code(sp, msg, code)
337 // FIXME: This method should be removed (every error should have an associated error code).
338 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
339 self.diagnostic().struct_err(msg)
341 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
342 self.diagnostic().struct_err_with_code(msg, code)
344 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
345 self.diagnostic().struct_span_fatal(sp, msg)
347 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
352 ) -> DiagnosticBuilder<'_> {
353 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
355 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
356 self.diagnostic().struct_fatal(msg)
359 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
360 self.diagnostic().span_fatal(sp, msg).raise()
362 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
368 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
370 pub fn fatal(&self, msg: &str) -> ! {
371 self.diagnostic().fatal(msg).raise()
373 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
375 self.span_warn(sp, msg);
377 self.span_err(sp, msg);
380 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
381 self.diagnostic().span_err(sp, msg)
383 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
384 self.diagnostic().span_err_with_code(sp, &msg, code)
386 pub fn err(&self, msg: &str) {
387 self.diagnostic().err(msg)
389 pub fn err_count(&self) -> usize {
390 self.diagnostic().err_count()
392 pub fn has_errors(&self) -> bool {
393 self.diagnostic().has_errors()
395 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
396 self.diagnostic().has_errors_or_delayed_span_bugs()
398 pub fn abort_if_errors(&self) {
399 self.diagnostic().abort_if_errors();
401 pub fn compile_status(&self) -> Result<(), ErrorReported> {
402 if self.has_errors() {
403 self.diagnostic().emit_stashed_diagnostics();
409 // FIXME(matthewjasper) Remove this method, it should never be needed.
410 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
414 let old_count = self.err_count();
416 let errors = self.err_count() - old_count;
417 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
419 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
420 self.diagnostic().span_warn(sp, msg)
422 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
423 self.diagnostic().span_warn_with_code(sp, msg, code)
425 pub fn warn(&self, msg: &str) {
426 self.diagnostic().warn(msg)
428 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
430 Some(sp) => self.span_warn(sp, msg),
431 None => self.warn(msg),
434 /// Delay a span_bug() call until abort_if_errors()
435 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
436 self.diagnostic().delay_span_bug(sp, msg)
438 pub fn note_without_error(&self, msg: &str) {
439 self.diagnostic().note_without_error(msg)
441 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
442 self.diagnostic().span_note_without_error(sp, msg)
444 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
445 self.diagnostic().struct_note_without_error(msg)
448 pub fn diagnostic(&self) -> &rustc_errors::Handler {
449 &self.parse_sess.span_diagnostic
452 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
453 /// deduplicates on lint ID, span (if any), and message for this `Session`
454 fn diag_once<'a, 'b>(
456 diag_builder: &'b mut DiagnosticBuilder<'a>,
457 method: DiagnosticBuilderMethod,
458 msg_id: DiagnosticMessageId,
460 span_maybe: Option<Span>,
462 let id_span_message = (msg_id, span_maybe, message.to_owned());
463 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
466 DiagnosticBuilderMethod::Note => {
467 diag_builder.note(message);
469 DiagnosticBuilderMethod::SpanNote => {
470 let span = span_maybe.expect("`span_note` needs a span");
471 diag_builder.span_note(span, message);
473 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
474 let span = span_maybe.expect("`span_suggestion_*` needs a span");
475 diag_builder.span_suggestion(
479 Applicability::Unspecified,
486 pub fn diag_span_note_once<'a, 'b>(
488 diag_builder: &'b mut DiagnosticBuilder<'a>,
489 msg_id: DiagnosticMessageId,
495 DiagnosticBuilderMethod::SpanNote,
502 pub fn diag_note_once<'a, 'b>(
504 diag_builder: &'b mut DiagnosticBuilder<'a>,
505 msg_id: DiagnosticMessageId,
508 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
511 pub fn diag_span_suggestion_once<'a, 'b>(
513 diag_builder: &'b mut DiagnosticBuilder<'a>,
514 msg_id: DiagnosticMessageId,
521 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
529 pub fn source_map(&self) -> &SourceMap {
530 self.parse_sess.source_map()
532 pub fn verbose(&self) -> bool {
533 self.opts.debugging_opts.verbose
535 pub fn time_passes(&self) -> bool {
536 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
538 pub fn instrument_mcount(&self) -> bool {
539 self.opts.debugging_opts.instrument_mcount
541 pub fn time_llvm_passes(&self) -> bool {
542 self.opts.debugging_opts.time_llvm_passes
544 pub fn meta_stats(&self) -> bool {
545 self.opts.debugging_opts.meta_stats
547 pub fn asm_comments(&self) -> bool {
548 self.opts.debugging_opts.asm_comments
550 pub fn verify_llvm_ir(&self) -> bool {
551 self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
553 pub fn borrowck_stats(&self) -> bool {
554 self.opts.debugging_opts.borrowck_stats
556 pub fn print_llvm_passes(&self) -> bool {
557 self.opts.debugging_opts.print_llvm_passes
559 pub fn binary_dep_depinfo(&self) -> bool {
560 self.opts.debugging_opts.binary_dep_depinfo
563 /// Gets the features enabled for the current compilation session.
564 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
565 /// dependency tracking. Use tcx.features() instead.
567 pub fn features_untracked(&self) -> &rustc_feature::Features {
568 self.features.get().unwrap()
571 pub fn init_features(&self, features: rustc_feature::Features) {
572 match self.features.set(features) {
574 Err(_) => panic!("`features` was initialized twice"),
578 /// Calculates the flavor of LTO to use for this compilation.
579 pub fn lto(&self) -> config::Lto {
580 // If our target has codegen requirements ignore the command line
581 if self.target.target.options.requires_lto {
582 return config::Lto::Fat;
585 // If the user specified something, return that. If they only said `-C
586 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
587 // then ensure we can't use a ThinLTO.
588 match self.opts.cg.lto {
589 config::LtoCli::Unspecified => {
590 // The compiler was invoked without the `-Clto` flag. Fall
591 // through to the default handling
593 config::LtoCli::No => {
594 // The user explicitly opted out of any kind of LTO
595 return config::Lto::No;
597 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
598 // All of these mean fat LTO
599 return config::Lto::Fat;
601 config::LtoCli::Thin => {
602 return if self.opts.cli_forced_thinlto_off {
610 // Ok at this point the target doesn't require anything and the user
611 // hasn't asked for anything. Our next decision is whether or not
612 // we enable "auto" ThinLTO where we use multiple codegen units and
613 // then do ThinLTO over those codegen units. The logic below will
614 // either return `No` or `ThinLocal`.
616 // If processing command line options determined that we're incompatible
617 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
618 if self.opts.cli_forced_thinlto_off {
619 return config::Lto::No;
622 // If `-Z thinlto` specified process that, but note that this is mostly
623 // a deprecated option now that `-C lto=thin` exists.
624 if let Some(enabled) = self.opts.debugging_opts.thinlto {
626 return config::Lto::ThinLocal;
628 return config::Lto::No;
632 // If there's only one codegen unit and LTO isn't enabled then there's
633 // no need for ThinLTO so just return false.
634 if self.codegen_units() == 1 {
635 return config::Lto::No;
638 // Now we're in "defaults" territory. By default we enable ThinLTO for
639 // optimized compiles (anything greater than O0).
640 match self.opts.optimize {
641 config::OptLevel::No => config::Lto::No,
642 _ => config::Lto::ThinLocal,
646 /// Returns the panic strategy for this compile session. If the user explicitly selected one
647 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
648 pub fn panic_strategy(&self) -> PanicStrategy {
649 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
651 pub fn fewer_names(&self) -> bool {
652 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
653 || self.opts.output_types.contains_key(&OutputType::Bitcode)
654 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
655 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
657 self.opts.debugging_opts.fewer_names || !more_names
660 pub fn unstable_options(&self) -> bool {
661 self.opts.debugging_opts.unstable_options
663 pub fn overflow_checks(&self) -> bool {
667 .or(self.opts.debugging_opts.force_overflow_checks)
668 .unwrap_or(self.opts.debug_assertions)
671 /// Check whether this compile session and crate type use static crt.
672 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
673 if !self.target.target.options.crt_static_respected {
674 // If the target does not opt in to crt-static support, use its default.
675 return self.target.target.options.crt_static_default;
678 let requested_features = self.opts.cg.target_feature.split(',');
679 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
680 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
682 if found_positive || found_negative {
684 } else if crate_type == Some(CrateType::ProcMacro)
685 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
687 // FIXME: When crate_type is not available,
688 // we use compiler options to determine the crate_type.
689 // We can't check `#![crate_type = "proc-macro"]` here.
692 self.target.target.options.crt_static_default
696 pub fn relocation_model(&self) -> RelocModel {
697 self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
700 pub fn code_model(&self) -> Option<CodeModel> {
701 self.opts.cg.code_model.or(self.target.target.options.code_model)
704 pub fn tls_model(&self) -> TlsModel {
705 self.opts.debugging_opts.tls_model.unwrap_or(self.target.target.options.tls_model)
708 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
709 // "mcount" function relies on stack pointer.
710 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
711 if self.instrument_mcount() {
713 } else if let Some(x) = self.opts.cg.force_frame_pointers {
716 !self.target.target.options.eliminate_frame_pointer
720 pub fn must_emit_unwind_tables(&self) -> bool {
721 // This is used to control the emission of the `uwtable` attribute on
724 // At the very least, unwind tables are needed when compiling with
725 // `-C panic=unwind`.
727 // On some targets (including windows), however, exceptions include
728 // other events such as illegal instructions, segfaults, etc. This means
729 // that on Windows we end up still needing unwind tables even if the `-C
730 // panic=abort` flag is passed.
732 // You can also find more info on why Windows needs unwind tables in:
733 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
735 // If a target requires unwind tables, then they must be emitted.
736 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
737 // value, if it is provided, or disable them, if not.
738 if self.panic_strategy() == PanicStrategy::Unwind {
740 } else if self.target.target.options.requires_uwtable {
743 self.opts.cg.force_unwind_tables.unwrap_or(false)
747 /// Returns the symbol name for the registrar function,
748 /// given the crate `Svh` and the function `DefIndex`.
749 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
750 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
753 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
754 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
757 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
758 filesearch::FileSearch::new(
760 self.opts.target_triple.triple(),
761 &self.opts.search_paths,
762 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
763 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
767 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
768 filesearch::FileSearch::new(
770 config::host_triple(),
771 &self.opts.search_paths,
772 &self.host_tlib_path,
777 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
778 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
780 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
781 *load_dep_graph = load;
785 pub fn incr_session_load_dep_graph(&self) -> bool {
786 let incr_comp_session = self.incr_comp_session.borrow();
787 match *incr_comp_session {
788 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
793 pub fn init_incr_comp_session(
795 session_dir: PathBuf,
796 lock_file: flock::Lock,
797 load_dep_graph: bool,
799 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
801 if let IncrCompSession::NotInitialized = *incr_comp_session {
803 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
807 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
810 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
811 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
813 if let IncrCompSession::Active { .. } = *incr_comp_session {
815 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
818 // Note: this will also drop the lock file, thus unlocking the directory.
819 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
822 pub fn mark_incr_comp_session_as_invalid(&self) {
823 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
825 let session_directory = match *incr_comp_session {
826 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
827 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
828 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
831 // Note: this will also drop the lock file, thus unlocking the directory.
832 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
835 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
836 let incr_comp_session = self.incr_comp_session.borrow();
837 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
838 IncrCompSession::NotInitialized => panic!(
839 "trying to get session directory from `IncrCompSession`: {:?}",
842 IncrCompSession::Active { ref session_directory, .. }
843 | IncrCompSession::Finalized { ref session_directory }
844 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
850 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
851 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
854 pub fn print_perf_stats(&self) {
856 "Total time spent computing symbol hashes: {}",
857 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
860 "Total time spent decoding DefPath tables: {}",
861 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
864 "Total queries canonicalized: {}",
865 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
868 "normalize_generic_arg_after_erasing_regions: {}",
869 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
872 "normalize_projection_ty: {}",
873 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
877 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
878 /// This expends fuel if applicable, and records fuel if applicable.
879 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
881 if let Some(ref c) = self.optimization_fuel_crate {
883 assert_eq!(self.threads(), 1);
884 let mut fuel = self.optimization_fuel.lock();
885 ret = fuel.remaining != 0;
886 if fuel.remaining == 0 && !fuel.out_of_fuel {
887 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
888 fuel.out_of_fuel = true;
889 } else if fuel.remaining > 0 {
894 if let Some(ref c) = self.print_fuel_crate {
896 assert_eq!(self.threads(), 1);
897 self.print_fuel.fetch_add(1, SeqCst);
903 /// Returns the number of query threads that should be used for this
905 pub fn threads(&self) -> usize {
906 self.opts.debugging_opts.threads
909 /// Returns the number of codegen units that should be used for this
911 pub fn codegen_units(&self) -> usize {
912 if let Some(n) = self.opts.cli_forced_codegen_units {
915 if let Some(n) = self.target.target.options.default_codegen_units {
919 // If incremental compilation is turned on, we default to a high number
920 // codegen units in order to reduce the "collateral damage" small
922 if self.opts.incremental.is_some() {
926 // Why is 16 codegen units the default all the time?
928 // The main reason for enabling multiple codegen units by default is to
929 // leverage the ability for the codegen backend to do codegen and
930 // optimization in parallel. This allows us, especially for large crates, to
931 // make good use of all available resources on the machine once we've
932 // hit that stage of compilation. Large crates especially then often
933 // take a long time in codegen/optimization and this helps us amortize that
936 // Note that a high number here doesn't mean that we'll be spawning a
937 // large number of threads in parallel. The backend of rustc contains
938 // global rate limiting through the `jobserver` crate so we'll never
939 // overload the system with too much work, but rather we'll only be
940 // optimizing when we're otherwise cooperating with other instances of
943 // Rather a high number here means that we should be able to keep a lot
944 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
945 // to build we'll be guaranteed that all cpus will finish pretty closely
946 // to one another and we should make relatively optimal use of system
949 // Note that the main cost of codegen units is that it prevents LLVM
950 // from inlining across codegen units. Users in general don't have a lot
951 // of control over how codegen units are split up so it's our job in the
952 // compiler to ensure that undue performance isn't lost when using
953 // codegen units (aka we can't require everyone to slap `#[inline]` on
956 // If we're compiling at `-O0` then the number doesn't really matter too
957 // much because performance doesn't matter and inlining is ok to lose.
958 // In debug mode we just want to try to guarantee that no cpu is stuck
959 // doing work that could otherwise be farmed to others.
961 // In release mode, however (O1 and above) performance does indeed
962 // matter! To recover the loss in performance due to inlining we'll be
963 // enabling ThinLTO by default (the function for which is just below).
964 // This will ensure that we recover any inlining wins we otherwise lost
965 // through codegen unit partitioning.
969 // Ok that's a lot of words but the basic tl;dr; is that we want a high
970 // number here -- but not too high. Additionally we're "safe" to have it
971 // always at the same number at all optimization levels.
973 // As a result 16 was chosen here! Mostly because it was a power of 2
974 // and most benchmarks agreed it was roughly a local optimum. Not very
979 pub fn teach(&self, code: &DiagnosticId) -> bool {
980 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
983 pub fn rust_2015(&self) -> bool {
984 self.opts.edition == Edition::Edition2015
987 /// Are we allowed to use features from the Rust 2018 edition?
988 pub fn rust_2018(&self) -> bool {
989 self.opts.edition >= Edition::Edition2018
992 pub fn edition(&self) -> Edition {
996 /// Returns `true` if we cannot skip the PLT for shared library calls.
997 pub fn needs_plt(&self) -> bool {
998 // Check if the current target usually needs PLT to be enabled.
999 // The user can use the command line flag to override it.
1000 let needs_plt = self.target.target.options.needs_plt;
1002 let dbg_opts = &self.opts.debugging_opts;
1004 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
1006 // Only enable this optimization by default if full relro is also enabled.
1007 // In this case, lazy binding was already unavailable, so nothing is lost.
1008 // This also ensures `-Wl,-z,now` is supported by the linker.
1009 let full_relro = RelroLevel::Full == relro_level;
1011 // If user didn't explicitly forced us to use / skip the PLT,
1012 // then try to skip it where possible.
1013 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1016 /// Checks if LLVM lifetime markers should be emitted.
1017 pub fn emit_lifetime_markers(&self) -> bool {
1018 self.opts.optimize != config::OptLevel::No
1019 // AddressSanitizer uses lifetimes to detect use after scope bugs.
1020 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1021 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY)
1026 sopts: &config::Options,
1027 registry: rustc_errors::registry::Registry,
1028 source_map: Lrc<SourceMap>,
1029 emitter_dest: Option<Box<dyn Write + Send>>,
1030 ) -> Box<dyn Emitter + sync::Send> {
1031 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1032 match (sopts.error_format, emitter_dest) {
1033 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1034 let (short, color_config) = kind.unzip();
1036 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1038 AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1039 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1041 let emitter = match dst {
1042 None => EmitterWriter::stderr(
1046 sopts.debugging_opts.teach,
1047 sopts.debugging_opts.terminal_width,
1050 Some(dst) => EmitterWriter::new(
1054 false, // no teach messages when writing to a buffer
1055 false, // no colors when writing to a buffer
1056 None, // no terminal width
1060 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1063 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1064 JsonEmitter::stderr(
1069 sopts.debugging_opts.terminal_width,
1072 .ui_testing(sopts.debugging_opts.ui_testing),
1074 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1081 sopts.debugging_opts.terminal_width,
1084 .ui_testing(sopts.debugging_opts.ui_testing),
1089 pub enum DiagnosticOutput {
1091 Raw(Box<dyn Write + Send>),
1094 pub fn build_session(
1095 sopts: config::Options,
1096 local_crate_source_file: Option<PathBuf>,
1097 registry: rustc_errors::registry::Registry,
1098 diagnostics_output: DiagnosticOutput,
1099 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1100 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1102 // FIXME: This is not general enough to make the warning lint completely override
1103 // normal diagnostic warnings, since the warning lint can also be denied and changed
1104 // later via the source code.
1105 let warnings_allow = sopts
1108 .filter(|&&(ref key, _)| *key == "warnings")
1109 .map(|&(_, ref level)| *level == lint::Allow)
1112 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1113 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1115 let write_dest = match diagnostics_output {
1116 DiagnosticOutput::Default => None,
1117 DiagnosticOutput::Raw(write) => Some(write),
1120 let target_cfg = config::build_target_config(&sopts, sopts.error_format);
1121 let host_triple = TargetTriple::from_triple(config::host_triple());
1122 let host = Target::search(&host_triple).unwrap_or_else(|e| {
1123 early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1126 let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
1127 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1128 if target_cfg.target.options.is_like_msvc {
1129 SourceFileHashAlgorithm::Sha1
1131 SourceFileHashAlgorithm::Md5
1134 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1136 sopts.file_path_mapping(),
1139 let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1141 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1143 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1146 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1149 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1151 let profiler = SelfProfiler::new(
1153 sopts.crate_name.as_ref().map(|s| &s[..]),
1154 &sopts.debugging_opts.self_profile_events,
1157 Ok(profiler) => Some(Arc::new(profiler)),
1159 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1167 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1168 let sysroot = match &sopts.maybe_sysroot {
1169 Some(sysroot) => sysroot.clone(),
1170 None => filesearch::get_or_default_sysroot(),
1173 let host_triple = config::host_triple();
1174 let target_triple = sopts.target_triple.triple();
1175 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1176 let target_tlib_path = if host_triple == target_triple {
1179 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1182 let file_path_mapping = sopts.file_path_mapping();
1184 let local_crate_source_file =
1185 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1187 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1188 let optimization_fuel = Lock::new(OptimizationFuel {
1189 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1192 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1193 let print_fuel = AtomicU64::new(0);
1195 let working_dir = env::current_dir().unwrap_or_else(|e| {
1196 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1198 let working_dir = file_path_mapping.map_prefix(working_dir);
1200 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1201 CguReuseTracker::new()
1203 CguReuseTracker::new_disabled()
1206 let prof = SelfProfilerRef::new(
1208 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1209 sopts.debugging_opts.time_passes,
1212 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1213 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1214 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1215 _ => CtfeBacktrace::Disabled,
1218 // Try to find a directory containing the Rust `src`, for more details see
1219 // the doc comment on the `real_rust_source_base_dir` field.
1220 let real_rust_source_base_dir = {
1221 // This is the location used by the `rust-src` `rustup` component.
1222 let mut candidate = sysroot.join("lib/rustlib/src/rust");
1223 if let Ok(metadata) = candidate.symlink_metadata() {
1224 // Replace the symlink rustbuild creates, with its destination.
1225 // We could try to use `fs::canonicalize` instead, but that might
1226 // produce unnecessarily verbose path.
1227 if metadata.file_type().is_symlink() {
1228 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1229 candidate = symlink_dest;
1234 // Only use this directory if it has a file we can expect to always find.
1235 if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None }
1238 let asm_arch = if target_cfg.target.options.allow_asm {
1239 InlineAsmArch::from_str(&target_cfg.target.arch).ok()
1244 let sess = Session {
1252 local_crate_source_file,
1254 one_time_diagnostics: Default::default(),
1255 crate_types: OnceCell::new(),
1256 crate_disambiguator: OnceCell::new(),
1257 features: OnceCell::new(),
1258 recursion_limit: OnceCell::new(),
1259 type_length_limit: OnceCell::new(),
1260 const_eval_limit: OnceCell::new(),
1261 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1264 perf_stats: PerfStats {
1265 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1266 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1267 queries_canonicalized: AtomicUsize::new(0),
1268 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1269 normalize_projection_ty: AtomicUsize::new(0),
1271 code_stats: Default::default(),
1272 optimization_fuel_crate,
1276 jobserver: jobserver::client(),
1278 trait_methods_not_found: Lock::new(Default::default()),
1279 confused_type_with_std_module: Lock::new(Default::default()),
1280 system_library_path: OneThread::new(RefCell::new(Default::default())),
1282 miri_unleashed_features: Lock::new(Default::default()),
1283 real_rust_source_base_dir,
1285 target_features: FxHashSet::default(),
1288 validate_commandline_args_with_session_available(&sess);
1293 // If it is useful to have a Session available already for validating a
1294 // commandline argument, you can do so here.
1295 fn validate_commandline_args_with_session_available(sess: &Session) {
1296 // Since we don't know if code in an rlib will be linked to statically or
1297 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1298 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1299 // these manually generated symbols confuse LLD when it tries to merge
1300 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1301 // when compiling for LLD ThinLTO. This way we can validly just not generate
1302 // the `dllimport` attributes and `__imp_` symbols in that case.
1303 if sess.opts.cg.linker_plugin_lto.enabled()
1304 && sess.opts.cg.prefer_dynamic
1305 && sess.target.target.options.is_like_windows
1308 "Linker plugin based LTO is not supported together with \
1309 `-C prefer-dynamic` when targeting Windows-like targets",
1313 // Make sure that any given profiling data actually exists so LLVM can't
1314 // decide to silently skip PGO.
1315 if let Some(ref path) = sess.opts.cg.profile_use {
1318 "File `{}` passed to `-C profile-use` does not exist.",
1324 // Unwind tables cannot be disabled if the target requires them.
1325 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1326 if sess.panic_strategy() == PanicStrategy::Unwind && !include_uwtables {
1328 "panic=unwind requires unwind tables, they cannot be disabled \
1329 with `-C force-unwind-tables=no`.",
1333 if sess.target.target.options.requires_uwtable && !include_uwtables {
1335 "target requires unwind tables, they cannot be disabled with \
1336 `-C force-unwind-tables=no`.",
1341 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1342 // an error to combine the two for now. It always runs into an assertions
1343 // if LLVM is built with assertions, but without assertions it sometimes
1344 // does not crash and will probably generate a corrupted binary.
1345 // We should only display this error if we're actually going to run PGO.
1346 // If we're just supposed to print out some data, don't show the error (#61002).
1347 if sess.opts.cg.profile_generate.enabled()
1348 && sess.target.target.options.is_like_msvc
1349 && sess.panic_strategy() == PanicStrategy::Unwind
1350 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1353 "Profile-guided optimization does not yet work in conjunction \
1354 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1355 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1356 for more information.",
1360 // FIXME(richkadel): See `src/test/run-make-fulldeps/instrument-coverage/Makefile`. After
1361 // compiling with `-Zinstrument-coverage`, the resulting binary generates a segfault during
1362 // the program's exit process (likely while attempting to generate the coverage stats in
1363 // the "*.profraw" file). An investigation to resolve the problem on Windows is ongoing,
1364 // but until this is resolved, the option is disabled on Windows, and the test is skipped
1365 // when targeting `MSVC`.
1366 if sess.opts.debugging_opts.instrument_coverage && sess.target.target.options.is_like_msvc {
1368 "Rust source-based code coverage instrumentation (with `-Z instrument-coverage`) \
1369 is not yet supported on Windows when targeting MSVC. The resulting binaries will \
1370 still be instrumented for experimentation purposes, but may not execute correctly.",
1374 const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1376 "aarch64-unknown-linux-gnu",
1377 "x86_64-apple-darwin",
1379 "x86_64-unknown-linux-gnu",
1381 const LSAN_SUPPORTED_TARGETS: &[&str] =
1382 &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1383 const MSAN_SUPPORTED_TARGETS: &[&str] =
1384 &["aarch64-unknown-linux-gnu", "x86_64-unknown-linux-gnu"];
1385 const TSAN_SUPPORTED_TARGETS: &[&str] =
1386 &["aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"];
1388 // Sanitizers can only be used on some tested platforms.
1389 for s in sess.opts.debugging_opts.sanitizer {
1390 let supported_targets = match s {
1391 SanitizerSet::ADDRESS => ASAN_SUPPORTED_TARGETS,
1392 SanitizerSet::LEAK => LSAN_SUPPORTED_TARGETS,
1393 SanitizerSet::MEMORY => MSAN_SUPPORTED_TARGETS,
1394 SanitizerSet::THREAD => TSAN_SUPPORTED_TARGETS,
1395 _ => panic!("unrecognized sanitizer {}", s),
1397 if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1399 "`-Zsanitizer={}` only works with targets: {}",
1401 supported_targets.join(", ")
1404 let conflicting = sess.opts.debugging_opts.sanitizer - s;
1405 if !conflicting.is_empty() {
1407 "`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`",
1410 // Don't report additional errors.
1416 /// Holds data on the current incremental compilation session, if there is one.
1418 pub enum IncrCompSession {
1419 /// This is the state the session will be in until the incr. comp. dir is
1422 /// This is the state during which the session directory is private and can
1424 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1425 /// This is the state after the session directory has been finalized. In this
1426 /// state, the contents of the directory must not be modified any more.
1427 Finalized { session_directory: PathBuf },
1428 /// This is an error state that is reached when some compilation error has
1429 /// occurred. It indicates that the contents of the session directory must
1430 /// not be used, since they might be invalid.
1431 InvalidBecauseOfErrors { session_directory: PathBuf },
1434 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1435 let emitter: Box<dyn Emitter + sync::Send> = match output {
1436 config::ErrorOutputType::HumanReadable(kind) => {
1437 let (short, color_config) = kind.unzip();
1438 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1440 config::ErrorOutputType::Json { pretty, json_rendered } => {
1441 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1444 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1445 handler.struct_fatal(msg).emit();
1446 rustc_errors::FatalError.raise();
1449 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1450 let emitter: Box<dyn Emitter + sync::Send> = match output {
1451 config::ErrorOutputType::HumanReadable(kind) => {
1452 let (short, color_config) = kind.unzip();
1453 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1455 config::ErrorOutputType::Json { pretty, json_rendered } => {
1456 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1459 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1460 handler.struct_warn(msg).emit();
1463 pub type CompileResult = Result<(), ErrorReported>;