]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/session.rs
Fix wrong argument in autoderef process
[rust.git] / src / librustc_session / session.rs
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, OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
5 use crate::filesearch;
6 use crate::lint;
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
9
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, Once, OneThread, Ordering, Ordering::SeqCst,
17 };
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::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported};
22 use rustc_span::edition::Edition;
23 use rustc_span::source_map::{self, FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
24 use rustc_span::SourceFileHashAlgorithm;
25 use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
26
27 use std::cell::{self, RefCell};
28 use std::env;
29 use std::io::Write;
30 use std::num::NonZeroU32;
31 use std::path::PathBuf;
32 use std::sync::Arc;
33 use std::time::Duration;
34
35 pub struct OptimizationFuel {
36     /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
37     remaining: u64,
38     /// We're rejecting all further optimizations.
39     out_of_fuel: bool,
40 }
41
42 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
43 #[derive(Clone, Copy)]
44 pub enum CtfeBacktrace {
45     /// Do nothing special, return the error as usual without a backtrace.
46     Disabled,
47     /// Capture a backtrace at the point the error is created and return it in the error
48     /// (to be printed later if/when the error ever actually gets shown to the user).
49     Capture,
50     /// Capture a backtrace at the point the error is created and immediately print it out.
51     Immediate,
52 }
53
54 /// Represents the data associated with a compilation
55 /// session for a single crate.
56 pub struct Session {
57     pub target: config::Config,
58     pub host: Target,
59     pub opts: config::Options,
60     pub host_tlib_path: SearchPath,
61     /// `None` if the host and target are the same.
62     pub target_tlib_path: Option<SearchPath>,
63     pub parse_sess: ParseSess,
64     pub sysroot: PathBuf,
65     /// The name of the root source file of the crate, in the local file system.
66     /// `None` means that there is no source file.
67     pub local_crate_source_file: Option<PathBuf>,
68     /// The directory the compiler has been executed in plus a flag indicating
69     /// if the value stored here has been affected by path remapping.
70     pub working_dir: (PathBuf, bool),
71
72     /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
73     /// (sub)diagnostics that have been set once, but should not be set again,
74     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
75     pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
76     pub crate_types: Once<Vec<config::CrateType>>,
77     /// The `crate_disambiguator` is constructed out of all the `-C metadata`
78     /// arguments passed to the compiler. Its value together with the crate-name
79     /// forms a unique global identifier for the crate. It is used to allow
80     /// multiple crates with the same name to coexist. See the
81     /// `rustc_codegen_llvm::back::symbol_names` module for more information.
82     pub crate_disambiguator: Once<CrateDisambiguator>,
83
84     features: Once<rustc_feature::Features>,
85
86     /// The maximum recursion limit for potentially infinitely recursive
87     /// operations such as auto-dereference and monomorphization.
88     pub recursion_limit: Once<usize>,
89
90     /// The maximum length of types during monomorphization.
91     pub type_length_limit: Once<usize>,
92
93     /// The maximum blocks a const expression can evaluate.
94     pub const_eval_limit: Once<usize>,
95
96     incr_comp_session: OneThread<RefCell<IncrCompSession>>,
97     /// Used for incremental compilation tests. Will only be populated if
98     /// `-Zquery-dep-graph` is specified.
99     pub cgu_reuse_tracker: CguReuseTracker,
100
101     /// Used by `-Z self-profile`.
102     pub prof: SelfProfilerRef,
103
104     /// Some measurements that are being gathered during compilation.
105     pub perf_stats: PerfStats,
106
107     /// Data about code being compiled, gathered during compilation.
108     pub code_stats: CodeStats,
109
110     /// If `-zfuel=crate=n` is specified, `Some(crate)`.
111     optimization_fuel_crate: Option<String>,
112
113     /// Tracks fuel info if `-zfuel=crate=n` is specified.
114     optimization_fuel: Lock<OptimizationFuel>,
115
116     // The next two are public because the driver needs to read them.
117     /// If `-zprint-fuel=crate`, `Some(crate)`.
118     pub print_fuel_crate: Option<String>,
119     /// Always set to zero and incremented so that we can print fuel expended by a crate.
120     pub print_fuel: AtomicU64,
121
122     /// Loaded up early on in the initialization of this `Session` to avoid
123     /// false positives about a job server in our environment.
124     pub jobserver: Client,
125
126     /// Cap lint level specified by a driver specifically.
127     pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
128
129     /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
130     pub trait_methods_not_found: Lock<FxHashSet<Span>>,
131
132     /// Mapping from ident span to path span for paths that don't exist as written, but that
133     /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
134     pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
135
136     /// Path for libraries that will take preference over libraries shipped by Rust.
137     /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
138     pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
139
140     /// Tracks the current behavior of the CTFE engine when an error occurs.
141     /// Options range from returning the error without a backtrace to returning an error
142     /// and immediately printing the backtrace to stderr.
143     pub ctfe_backtrace: Lock<CtfeBacktrace>,
144
145     /// Base directory containing the `src/` for the Rust standard library, and
146     /// potentially `rustc` as well, if we can can find it. Right now it's always
147     /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
148     ///
149     /// This directory is what the virtual `/rustc/$hash` is translated back to,
150     /// if Rust was built with path remapping to `/rustc/$hash` enabled
151     /// (the `rust.remap-debuginfo` option in `config.toml`).
152     pub real_rust_source_base_dir: Option<PathBuf>,
153 }
154
155 pub struct PerfStats {
156     /// The accumulated time spent on computing symbol hashes.
157     pub symbol_hash_time: Lock<Duration>,
158     /// The accumulated time spent decoding def path tables from metadata.
159     pub decode_def_path_tables_time: Lock<Duration>,
160     /// Total number of values canonicalized queries constructed.
161     pub queries_canonicalized: AtomicUsize,
162     /// Number of times this query is invoked.
163     pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
164     /// Number of times this query is invoked.
165     pub normalize_projection_ty: AtomicUsize,
166 }
167
168 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
169 enum DiagnosticBuilderMethod {
170     Note,
171     SpanNote,
172     SpanSuggestion(String), // suggestion
173                             // Add more variants as needed to support one-time diagnostics.
174 }
175
176 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
177 /// emitting the same message more than once.
178 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
179 pub enum DiagnosticMessageId {
180     ErrorId(u16), // EXXXX error code as integer
181     LintId(lint::LintId),
182     StabilityId(Option<NonZeroU32>), // issue number
183 }
184
185 impl From<&'static lint::Lint> for DiagnosticMessageId {
186     fn from(lint: &'static lint::Lint) -> Self {
187         DiagnosticMessageId::LintId(lint::LintId::of(lint))
188     }
189 }
190
191 impl Session {
192     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
193         *self.crate_disambiguator.get()
194     }
195
196     pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
197         self.diagnostic().struct_span_warn(sp, msg)
198     }
199     pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
200         &self,
201         sp: S,
202         msg: &str,
203         code: DiagnosticId,
204     ) -> DiagnosticBuilder<'_> {
205         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
206     }
207     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
208         self.diagnostic().struct_warn(msg)
209     }
210     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
211         self.diagnostic().struct_span_err(sp, msg)
212     }
213     pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
214         &self,
215         sp: S,
216         msg: &str,
217         code: DiagnosticId,
218     ) -> DiagnosticBuilder<'_> {
219         self.diagnostic().struct_span_err_with_code(sp, msg, code)
220     }
221     // FIXME: This method should be removed (every error should have an associated error code).
222     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
223         self.diagnostic().struct_err(msg)
224     }
225     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
226         self.diagnostic().struct_err_with_code(msg, code)
227     }
228     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
229         self.diagnostic().struct_span_fatal(sp, msg)
230     }
231     pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
232         &self,
233         sp: S,
234         msg: &str,
235         code: DiagnosticId,
236     ) -> DiagnosticBuilder<'_> {
237         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
238     }
239     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
240         self.diagnostic().struct_fatal(msg)
241     }
242
243     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
244         self.diagnostic().span_fatal(sp, msg).raise()
245     }
246     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
247         &self,
248         sp: S,
249         msg: &str,
250         code: DiagnosticId,
251     ) -> ! {
252         self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
253     }
254     pub fn fatal(&self, msg: &str) -> ! {
255         self.diagnostic().fatal(msg).raise()
256     }
257     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
258         if is_warning {
259             self.span_warn(sp, msg);
260         } else {
261             self.span_err(sp, msg);
262         }
263     }
264     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
265         self.diagnostic().span_err(sp, msg)
266     }
267     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
268         self.diagnostic().span_err_with_code(sp, &msg, code)
269     }
270     pub fn err(&self, msg: &str) {
271         self.diagnostic().err(msg)
272     }
273     pub fn err_count(&self) -> usize {
274         self.diagnostic().err_count()
275     }
276     pub fn has_errors(&self) -> bool {
277         self.diagnostic().has_errors()
278     }
279     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
280         self.diagnostic().has_errors_or_delayed_span_bugs()
281     }
282     pub fn abort_if_errors(&self) {
283         self.diagnostic().abort_if_errors();
284     }
285     pub fn compile_status(&self) -> Result<(), ErrorReported> {
286         if self.has_errors() {
287             self.diagnostic().emit_stashed_diagnostics();
288             Err(ErrorReported)
289         } else {
290             Ok(())
291         }
292     }
293     // FIXME(matthewjasper) Remove this method, it should never be needed.
294     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
295     where
296         F: FnOnce() -> T,
297     {
298         let old_count = self.err_count();
299         let result = f();
300         let errors = self.err_count() - old_count;
301         if errors == 0 { Ok(result) } else { Err(ErrorReported) }
302     }
303     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
304         self.diagnostic().span_warn(sp, msg)
305     }
306     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
307         self.diagnostic().span_warn_with_code(sp, msg, code)
308     }
309     pub fn warn(&self, msg: &str) {
310         self.diagnostic().warn(msg)
311     }
312     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
313         match opt_sp {
314             Some(sp) => self.span_warn(sp, msg),
315             None => self.warn(msg),
316         }
317     }
318     /// Delay a span_bug() call until abort_if_errors()
319     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
320         self.diagnostic().delay_span_bug(sp, msg)
321     }
322     pub fn note_without_error(&self, msg: &str) {
323         self.diagnostic().note_without_error(msg)
324     }
325     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
326         self.diagnostic().span_note_without_error(sp, msg)
327     }
328
329     pub fn diagnostic(&self) -> &rustc_errors::Handler {
330         &self.parse_sess.span_diagnostic
331     }
332
333     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
334     /// deduplicates on lint ID, span (if any), and message for this `Session`
335     fn diag_once<'a, 'b>(
336         &'a self,
337         diag_builder: &'b mut DiagnosticBuilder<'a>,
338         method: DiagnosticBuilderMethod,
339         msg_id: DiagnosticMessageId,
340         message: &str,
341         span_maybe: Option<Span>,
342     ) {
343         let id_span_message = (msg_id, span_maybe, message.to_owned());
344         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
345         if fresh {
346             match method {
347                 DiagnosticBuilderMethod::Note => {
348                     diag_builder.note(message);
349                 }
350                 DiagnosticBuilderMethod::SpanNote => {
351                     let span = span_maybe.expect("`span_note` needs a span");
352                     diag_builder.span_note(span, message);
353                 }
354                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
355                     let span = span_maybe.expect("`span_suggestion_*` needs a span");
356                     diag_builder.span_suggestion(
357                         span,
358                         message,
359                         suggestion,
360                         Applicability::Unspecified,
361                     );
362                 }
363             }
364         }
365     }
366
367     pub fn diag_span_note_once<'a, 'b>(
368         &'a self,
369         diag_builder: &'b mut DiagnosticBuilder<'a>,
370         msg_id: DiagnosticMessageId,
371         span: Span,
372         message: &str,
373     ) {
374         self.diag_once(
375             diag_builder,
376             DiagnosticBuilderMethod::SpanNote,
377             msg_id,
378             message,
379             Some(span),
380         );
381     }
382
383     pub fn diag_note_once<'a, 'b>(
384         &'a self,
385         diag_builder: &'b mut DiagnosticBuilder<'a>,
386         msg_id: DiagnosticMessageId,
387         message: &str,
388     ) {
389         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
390     }
391
392     pub fn diag_span_suggestion_once<'a, 'b>(
393         &'a self,
394         diag_builder: &'b mut DiagnosticBuilder<'a>,
395         msg_id: DiagnosticMessageId,
396         span: Span,
397         message: &str,
398         suggestion: String,
399     ) {
400         self.diag_once(
401             diag_builder,
402             DiagnosticBuilderMethod::SpanSuggestion(suggestion),
403             msg_id,
404             message,
405             Some(span),
406         );
407     }
408
409     #[inline]
410     pub fn source_map(&self) -> &source_map::SourceMap {
411         self.parse_sess.source_map()
412     }
413     pub fn verbose(&self) -> bool {
414         self.opts.debugging_opts.verbose
415     }
416     pub fn time_passes(&self) -> bool {
417         self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
418     }
419     pub fn instrument_mcount(&self) -> bool {
420         self.opts.debugging_opts.instrument_mcount
421     }
422     pub fn time_llvm_passes(&self) -> bool {
423         self.opts.debugging_opts.time_llvm_passes
424     }
425     pub fn meta_stats(&self) -> bool {
426         self.opts.debugging_opts.meta_stats
427     }
428     pub fn asm_comments(&self) -> bool {
429         self.opts.debugging_opts.asm_comments
430     }
431     pub fn verify_llvm_ir(&self) -> bool {
432         self.opts.debugging_opts.verify_llvm_ir || cfg!(always_verify_llvm_ir)
433     }
434     pub fn borrowck_stats(&self) -> bool {
435         self.opts.debugging_opts.borrowck_stats
436     }
437     pub fn print_llvm_passes(&self) -> bool {
438         self.opts.debugging_opts.print_llvm_passes
439     }
440     pub fn binary_dep_depinfo(&self) -> bool {
441         self.opts.debugging_opts.binary_dep_depinfo
442     }
443
444     /// Gets the features enabled for the current compilation session.
445     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
446     /// dependency tracking. Use tcx.features() instead.
447     #[inline]
448     pub fn features_untracked(&self) -> &rustc_feature::Features {
449         self.features.get()
450     }
451
452     pub fn init_features(&self, features: rustc_feature::Features) {
453         self.features.set(features);
454     }
455
456     /// Calculates the flavor of LTO to use for this compilation.
457     pub fn lto(&self) -> config::Lto {
458         // If our target has codegen requirements ignore the command line
459         if self.target.target.options.requires_lto {
460             return config::Lto::Fat;
461         }
462
463         // If the user specified something, return that. If they only said `-C
464         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
465         // then ensure we can't use a ThinLTO.
466         match self.opts.cg.lto {
467             config::LtoCli::Unspecified => {
468                 // The compiler was invoked without the `-Clto` flag. Fall
469                 // through to the default handling
470             }
471             config::LtoCli::No => {
472                 // The user explicitly opted out of any kind of LTO
473                 return config::Lto::No;
474             }
475             config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
476                 // All of these mean fat LTO
477                 return config::Lto::Fat;
478             }
479             config::LtoCli::Thin => {
480                 return if self.opts.cli_forced_thinlto_off {
481                     config::Lto::Fat
482                 } else {
483                     config::Lto::Thin
484                 };
485             }
486         }
487
488         // Ok at this point the target doesn't require anything and the user
489         // hasn't asked for anything. Our next decision is whether or not
490         // we enable "auto" ThinLTO where we use multiple codegen units and
491         // then do ThinLTO over those codegen units. The logic below will
492         // either return `No` or `ThinLocal`.
493
494         // If processing command line options determined that we're incompatible
495         // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
496         if self.opts.cli_forced_thinlto_off {
497             return config::Lto::No;
498         }
499
500         // If `-Z thinlto` specified process that, but note that this is mostly
501         // a deprecated option now that `-C lto=thin` exists.
502         if let Some(enabled) = self.opts.debugging_opts.thinlto {
503             if enabled {
504                 return config::Lto::ThinLocal;
505             } else {
506                 return config::Lto::No;
507             }
508         }
509
510         // If there's only one codegen unit and LTO isn't enabled then there's
511         // no need for ThinLTO so just return false.
512         if self.codegen_units() == 1 {
513             return config::Lto::No;
514         }
515
516         // Now we're in "defaults" territory. By default we enable ThinLTO for
517         // optimized compiles (anything greater than O0).
518         match self.opts.optimize {
519             config::OptLevel::No => config::Lto::No,
520             _ => config::Lto::ThinLocal,
521         }
522     }
523
524     /// Returns the panic strategy for this compile session. If the user explicitly selected one
525     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
526     pub fn panic_strategy(&self) -> PanicStrategy {
527         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
528     }
529     pub fn fewer_names(&self) -> bool {
530         let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
531             || self.opts.output_types.contains_key(&OutputType::Bitcode);
532
533         // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
534         let more_names = match self.opts.debugging_opts.sanitizer {
535             Some(Sanitizer::Address) => true,
536             Some(Sanitizer::Memory) => true,
537             _ => more_names,
538         };
539
540         self.opts.debugging_opts.fewer_names || !more_names
541     }
542
543     pub fn no_landing_pads(&self) -> bool {
544         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
545     }
546     pub fn unstable_options(&self) -> bool {
547         self.opts.debugging_opts.unstable_options
548     }
549     pub fn overflow_checks(&self) -> bool {
550         self.opts
551             .cg
552             .overflow_checks
553             .or(self.opts.debugging_opts.force_overflow_checks)
554             .unwrap_or(self.opts.debug_assertions)
555     }
556
557     /// Check whether this compile session and crate type use static crt.
558     pub fn crt_static(&self, crate_type: Option<config::CrateType>) -> bool {
559         // If the target does not opt in to crt-static support, use its default.
560         if self.target.target.options.crt_static_respected {
561             self.crt_static_feature(crate_type)
562         } else {
563             self.target.target.options.crt_static_default
564         }
565     }
566
567     /// Check whether this compile session and crate type use `crt-static` feature.
568     pub fn crt_static_feature(&self, crate_type: Option<config::CrateType>) -> bool {
569         let requested_features = self.opts.cg.target_feature.split(',');
570         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
571         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
572
573         if found_positive || found_negative {
574             found_positive
575         } else if crate_type == Some(config::CrateType::ProcMacro)
576             || crate_type == None && self.opts.crate_types.contains(&config::CrateType::ProcMacro)
577         {
578             // FIXME: When crate_type is not available,
579             // we use compiler options to determine the crate_type.
580             // We can't check `#![crate_type = "proc-macro"]` here.
581             false
582         } else {
583             self.target.target.options.crt_static_default
584         }
585     }
586
587     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
588         // "mcount" function relies on stack pointer.
589         // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
590         if self.instrument_mcount() {
591             true
592         } else if let Some(x) = self.opts.cg.force_frame_pointers {
593             x
594         } else {
595             !self.target.target.options.eliminate_frame_pointer
596         }
597     }
598
599     /// Returns the symbol name for the registrar function,
600     /// given the crate `Svh` and the function `DefIndex`.
601     pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
602         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
603     }
604
605     pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
606         format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
607     }
608
609     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
610         filesearch::FileSearch::new(
611             &self.sysroot,
612             self.opts.target_triple.triple(),
613             &self.opts.search_paths,
614             // `target_tlib_path == None` means it's the same as `host_tlib_path`.
615             self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
616             kind,
617         )
618     }
619     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
620         filesearch::FileSearch::new(
621             &self.sysroot,
622             config::host_triple(),
623             &self.opts.search_paths,
624             &self.host_tlib_path,
625             kind,
626         )
627     }
628
629     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
630         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
631
632         if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
633             *load_dep_graph = load;
634         }
635     }
636
637     pub fn incr_session_load_dep_graph(&self) -> bool {
638         let incr_comp_session = self.incr_comp_session.borrow();
639         match *incr_comp_session {
640             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
641             _ => false,
642         }
643     }
644
645     pub fn init_incr_comp_session(
646         &self,
647         session_dir: PathBuf,
648         lock_file: flock::Lock,
649         load_dep_graph: bool,
650     ) {
651         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
652
653         if let IncrCompSession::NotInitialized = *incr_comp_session {
654         } else {
655             panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
656         }
657
658         *incr_comp_session =
659             IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
660     }
661
662     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
663         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
664
665         if let IncrCompSession::Active { .. } = *incr_comp_session {
666         } else {
667             panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
668         }
669
670         // Note: this will also drop the lock file, thus unlocking the directory.
671         *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
672     }
673
674     pub fn mark_incr_comp_session_as_invalid(&self) {
675         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
676
677         let session_directory = match *incr_comp_session {
678             IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
679             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
680             _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
681         };
682
683         // Note: this will also drop the lock file, thus unlocking the directory.
684         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
685     }
686
687     pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
688         let incr_comp_session = self.incr_comp_session.borrow();
689         cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
690             IncrCompSession::NotInitialized => panic!(
691                 "trying to get session directory from `IncrCompSession`: {:?}",
692                 *incr_comp_session,
693             ),
694             IncrCompSession::Active { ref session_directory, .. }
695             | IncrCompSession::Finalized { ref session_directory }
696             | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
697                 session_directory
698             }
699         })
700     }
701
702     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
703         self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
704     }
705
706     pub fn print_perf_stats(&self) {
707         println!(
708             "Total time spent computing symbol hashes:      {}",
709             duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
710         );
711         println!(
712             "Total time spent decoding DefPath tables:      {}",
713             duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
714         );
715         println!(
716             "Total queries canonicalized:                   {}",
717             self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
718         );
719         println!(
720             "normalize_generic_arg_after_erasing_regions:   {}",
721             self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
722         );
723         println!(
724             "normalize_projection_ty:                       {}",
725             self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
726         );
727     }
728
729     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
730     /// This expends fuel if applicable, and records fuel if applicable.
731     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
732         let mut ret = true;
733         if let Some(ref c) = self.optimization_fuel_crate {
734             if c == crate_name {
735                 assert_eq!(self.threads(), 1);
736                 let mut fuel = self.optimization_fuel.lock();
737                 ret = fuel.remaining != 0;
738                 if fuel.remaining == 0 && !fuel.out_of_fuel {
739                     eprintln!("optimization-fuel-exhausted: {}", msg());
740                     fuel.out_of_fuel = true;
741                 } else if fuel.remaining > 0 {
742                     fuel.remaining -= 1;
743                 }
744             }
745         }
746         if let Some(ref c) = self.print_fuel_crate {
747             if c == crate_name {
748                 assert_eq!(self.threads(), 1);
749                 self.print_fuel.fetch_add(1, SeqCst);
750             }
751         }
752         ret
753     }
754
755     /// Returns the number of query threads that should be used for this
756     /// compilation
757     pub fn threads(&self) -> usize {
758         self.opts.debugging_opts.threads
759     }
760
761     /// Returns the number of codegen units that should be used for this
762     /// compilation
763     pub fn codegen_units(&self) -> usize {
764         if let Some(n) = self.opts.cli_forced_codegen_units {
765             return n;
766         }
767         if let Some(n) = self.target.target.options.default_codegen_units {
768             return n as usize;
769         }
770
771         // If incremental compilation is turned on, we default to a high number
772         // codegen units in order to reduce the "collateral damage" small
773         // changes cause.
774         if self.opts.incremental.is_some() {
775             return 256;
776         }
777
778         // Why is 16 codegen units the default all the time?
779         //
780         // The main reason for enabling multiple codegen units by default is to
781         // leverage the ability for the codegen backend to do codegen and
782         // optimization in parallel. This allows us, especially for large crates, to
783         // make good use of all available resources on the machine once we've
784         // hit that stage of compilation. Large crates especially then often
785         // take a long time in codegen/optimization and this helps us amortize that
786         // cost.
787         //
788         // Note that a high number here doesn't mean that we'll be spawning a
789         // large number of threads in parallel. The backend of rustc contains
790         // global rate limiting through the `jobserver` crate so we'll never
791         // overload the system with too much work, but rather we'll only be
792         // optimizing when we're otherwise cooperating with other instances of
793         // rustc.
794         //
795         // Rather a high number here means that we should be able to keep a lot
796         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
797         // to build we'll be guaranteed that all cpus will finish pretty closely
798         // to one another and we should make relatively optimal use of system
799         // resources
800         //
801         // Note that the main cost of codegen units is that it prevents LLVM
802         // from inlining across codegen units. Users in general don't have a lot
803         // of control over how codegen units are split up so it's our job in the
804         // compiler to ensure that undue performance isn't lost when using
805         // codegen units (aka we can't require everyone to slap `#[inline]` on
806         // everything).
807         //
808         // If we're compiling at `-O0` then the number doesn't really matter too
809         // much because performance doesn't matter and inlining is ok to lose.
810         // In debug mode we just want to try to guarantee that no cpu is stuck
811         // doing work that could otherwise be farmed to others.
812         //
813         // In release mode, however (O1 and above) performance does indeed
814         // matter! To recover the loss in performance due to inlining we'll be
815         // enabling ThinLTO by default (the function for which is just below).
816         // This will ensure that we recover any inlining wins we otherwise lost
817         // through codegen unit partitioning.
818         //
819         // ---
820         //
821         // Ok that's a lot of words but the basic tl;dr; is that we want a high
822         // number here -- but not too high. Additionally we're "safe" to have it
823         // always at the same number at all optimization levels.
824         //
825         // As a result 16 was chosen here! Mostly because it was a power of 2
826         // and most benchmarks agreed it was roughly a local optimum. Not very
827         // scientific.
828         16
829     }
830
831     pub fn teach(&self, code: &DiagnosticId) -> bool {
832         self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
833     }
834
835     pub fn rust_2015(&self) -> bool {
836         self.opts.edition == Edition::Edition2015
837     }
838
839     /// Are we allowed to use features from the Rust 2018 edition?
840     pub fn rust_2018(&self) -> bool {
841         self.opts.edition >= Edition::Edition2018
842     }
843
844     pub fn edition(&self) -> Edition {
845         self.opts.edition
846     }
847
848     /// Returns `true` if we cannot skip the PLT for shared library calls.
849     pub fn needs_plt(&self) -> bool {
850         // Check if the current target usually needs PLT to be enabled.
851         // The user can use the command line flag to override it.
852         let needs_plt = self.target.target.options.needs_plt;
853
854         let dbg_opts = &self.opts.debugging_opts;
855
856         let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
857
858         // Only enable this optimization by default if full relro is also enabled.
859         // In this case, lazy binding was already unavailable, so nothing is lost.
860         // This also ensures `-Wl,-z,now` is supported by the linker.
861         let full_relro = RelroLevel::Full == relro_level;
862
863         // If user didn't explicitly forced us to use / skip the PLT,
864         // then try to skip it where possible.
865         dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
866     }
867 }
868
869 pub fn build_session(
870     sopts: config::Options,
871     local_crate_source_file: Option<PathBuf>,
872     registry: rustc_errors::registry::Registry,
873 ) -> Session {
874     build_session_with_source_map(
875         sopts,
876         local_crate_source_file,
877         registry,
878         DiagnosticOutput::Default,
879         Default::default(),
880         None,
881     )
882     .0
883 }
884
885 fn default_emitter(
886     sopts: &config::Options,
887     registry: rustc_errors::registry::Registry,
888     source_map: &Lrc<source_map::SourceMap>,
889     emitter_dest: Option<Box<dyn Write + Send>>,
890 ) -> Box<dyn Emitter + sync::Send> {
891     let macro_backtrace = sopts.debugging_opts.macro_backtrace;
892     match (sopts.error_format, emitter_dest) {
893         (config::ErrorOutputType::HumanReadable(kind), dst) => {
894             let (short, color_config) = kind.unzip();
895
896             if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
897                 let emitter = AnnotateSnippetEmitterWriter::new(
898                     Some(source_map.clone()),
899                     short,
900                     macro_backtrace,
901                 );
902                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
903             } else {
904                 let emitter = match dst {
905                     None => EmitterWriter::stderr(
906                         color_config,
907                         Some(source_map.clone()),
908                         short,
909                         sopts.debugging_opts.teach,
910                         sopts.debugging_opts.terminal_width,
911                         macro_backtrace,
912                     ),
913                     Some(dst) => EmitterWriter::new(
914                         dst,
915                         Some(source_map.clone()),
916                         short,
917                         false, // no teach messages when writing to a buffer
918                         false, // no colors when writing to a buffer
919                         None,  // no terminal width
920                         macro_backtrace,
921                     ),
922                 };
923                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
924             }
925         }
926         (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
927             JsonEmitter::stderr(
928                 Some(registry),
929                 source_map.clone(),
930                 pretty,
931                 json_rendered,
932                 macro_backtrace,
933             )
934             .ui_testing(sopts.debugging_opts.ui_testing),
935         ),
936         (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
937             JsonEmitter::new(
938                 dst,
939                 Some(registry),
940                 source_map.clone(),
941                 pretty,
942                 json_rendered,
943                 macro_backtrace,
944             )
945             .ui_testing(sopts.debugging_opts.ui_testing),
946         ),
947     }
948 }
949
950 pub enum DiagnosticOutput {
951     Default,
952     Raw(Box<dyn Write + Send>),
953 }
954
955 pub fn build_session_with_source_map(
956     sopts: config::Options,
957     local_crate_source_file: Option<PathBuf>,
958     registry: rustc_errors::registry::Registry,
959     diagnostics_output: DiagnosticOutput,
960     driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
961     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
962 ) -> (Session, Lrc<SourceMap>) {
963     // FIXME: This is not general enough to make the warning lint completely override
964     // normal diagnostic warnings, since the warning lint can also be denied and changed
965     // later via the source code.
966     let warnings_allow = sopts
967         .lint_opts
968         .iter()
969         .filter(|&&(ref key, _)| *key == "warnings")
970         .map(|&(_, ref level)| *level == lint::Allow)
971         .last()
972         .unwrap_or(false);
973     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
974     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
975
976     let write_dest = match diagnostics_output {
977         DiagnosticOutput::Default => None,
978         DiagnosticOutput::Raw(write) => Some(write),
979     };
980
981     let target_cfg = config::build_target_config(&sopts, sopts.error_format);
982     let host_triple = TargetTriple::from_triple(config::host_triple());
983     let host = Target::search(&host_triple).unwrap_or_else(|e| {
984         early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
985     });
986
987     let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
988     let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
989         if target_cfg.target.options.is_like_msvc {
990             SourceFileHashAlgorithm::Sha1
991         } else {
992             SourceFileHashAlgorithm::Md5
993         }
994     });
995     let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
996         loader,
997         sopts.file_path_mapping(),
998         hash_kind,
999     ));
1000     let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
1001
1002     let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1003         emitter,
1004         sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1005     );
1006
1007     let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1008     {
1009         let directory =
1010             if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1011
1012         let profiler = SelfProfiler::new(
1013             directory,
1014             sopts.crate_name.as_ref().map(|s| &s[..]),
1015             &sopts.debugging_opts.self_profile_events,
1016         );
1017         match profiler {
1018             Ok(profiler) => Some(Arc::new(profiler)),
1019             Err(e) => {
1020                 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1021                 None
1022             }
1023         }
1024     } else {
1025         None
1026     };
1027
1028     let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map.clone());
1029     let sysroot = match &sopts.maybe_sysroot {
1030         Some(sysroot) => sysroot.clone(),
1031         None => filesearch::get_or_default_sysroot(),
1032     };
1033
1034     let host_triple = config::host_triple();
1035     let target_triple = sopts.target_triple.triple();
1036     let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1037     let target_tlib_path = if host_triple == target_triple {
1038         None
1039     } else {
1040         Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1041     };
1042
1043     let file_path_mapping = sopts.file_path_mapping();
1044
1045     let local_crate_source_file =
1046         local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1047
1048     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1049     let optimization_fuel = Lock::new(OptimizationFuel {
1050         remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1051         out_of_fuel: false,
1052     });
1053     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1054     let print_fuel = AtomicU64::new(0);
1055
1056     let working_dir = env::current_dir().unwrap_or_else(|e| {
1057         parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1058     });
1059     let working_dir = file_path_mapping.map_prefix(working_dir);
1060
1061     let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1062         CguReuseTracker::new()
1063     } else {
1064         CguReuseTracker::new_disabled()
1065     };
1066
1067     let prof = SelfProfilerRef::new(
1068         self_profiler,
1069         sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1070         sopts.debugging_opts.time_passes,
1071     );
1072
1073     let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1074         Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1075         Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1076         _ => CtfeBacktrace::Disabled,
1077     });
1078
1079     // Try to find a directory containing the Rust `src`, for more details see
1080     // the doc comment on the `real_rust_source_base_dir` field.
1081     let real_rust_source_base_dir = {
1082         // This is the location used by the `rust-src` `rustup` component.
1083         let mut candidate = sysroot.join("lib/rustlib/src/rust");
1084         if let Ok(metadata) = candidate.symlink_metadata() {
1085             // Replace the symlink rustbuild creates, with its destination.
1086             // We could try to use `fs::canonicalize` instead, but that might
1087             // produce unnecessarily verbose path.
1088             if metadata.file_type().is_symlink() {
1089                 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1090                     candidate = symlink_dest;
1091                 }
1092             }
1093         }
1094
1095         // Only use this directory if it has a file we can expect to always find.
1096         if candidate.join("src/libstd/lib.rs").is_file() { Some(candidate) } else { None }
1097     };
1098
1099     let sess = Session {
1100         target: target_cfg,
1101         host,
1102         opts: sopts,
1103         host_tlib_path,
1104         target_tlib_path,
1105         parse_sess,
1106         sysroot,
1107         local_crate_source_file,
1108         working_dir,
1109         one_time_diagnostics: Default::default(),
1110         crate_types: Once::new(),
1111         crate_disambiguator: Once::new(),
1112         features: Once::new(),
1113         recursion_limit: Once::new(),
1114         type_length_limit: Once::new(),
1115         const_eval_limit: Once::new(),
1116         incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1117         cgu_reuse_tracker,
1118         prof,
1119         perf_stats: PerfStats {
1120             symbol_hash_time: Lock::new(Duration::from_secs(0)),
1121             decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1122             queries_canonicalized: AtomicUsize::new(0),
1123             normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1124             normalize_projection_ty: AtomicUsize::new(0),
1125         },
1126         code_stats: Default::default(),
1127         optimization_fuel_crate,
1128         optimization_fuel,
1129         print_fuel_crate,
1130         print_fuel,
1131         jobserver: jobserver::client(),
1132         driver_lint_caps,
1133         trait_methods_not_found: Lock::new(Default::default()),
1134         confused_type_with_std_module: Lock::new(Default::default()),
1135         system_library_path: OneThread::new(RefCell::new(Default::default())),
1136         ctfe_backtrace,
1137         real_rust_source_base_dir,
1138     };
1139
1140     validate_commandline_args_with_session_available(&sess);
1141
1142     (sess, source_map)
1143 }
1144
1145 // If it is useful to have a Session available already for validating a
1146 // commandline argument, you can do so here.
1147 fn validate_commandline_args_with_session_available(sess: &Session) {
1148     // Since we don't know if code in an rlib will be linked to statically or
1149     // dynamically downstream, rustc generates `__imp_` symbols that help the
1150     // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1151     // these manually generated symbols confuse LLD when it tries to merge
1152     // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1153     // when compiling for LLD ThinLTO. This way we can validly just not generate
1154     // the `dllimport` attributes and `__imp_` symbols in that case.
1155     if sess.opts.cg.linker_plugin_lto.enabled()
1156         && sess.opts.cg.prefer_dynamic
1157         && sess.target.target.options.is_like_msvc
1158     {
1159         sess.err(
1160             "Linker plugin based LTO is not supported together with \
1161                   `-C prefer-dynamic` when targeting MSVC",
1162         );
1163     }
1164
1165     // Make sure that any given profiling data actually exists so LLVM can't
1166     // decide to silently skip PGO.
1167     if let Some(ref path) = sess.opts.cg.profile_use {
1168         if !path.exists() {
1169             sess.err(&format!(
1170                 "File `{}` passed to `-C profile-use` does not exist.",
1171                 path.display()
1172             ));
1173         }
1174     }
1175
1176     // PGO does not work reliably with panic=unwind on Windows. Let's make it
1177     // an error to combine the two for now. It always runs into an assertions
1178     // if LLVM is built with assertions, but without assertions it sometimes
1179     // does not crash and will probably generate a corrupted binary.
1180     // We should only display this error if we're actually going to run PGO.
1181     // If we're just supposed to print out some data, don't show the error (#61002).
1182     if sess.opts.cg.profile_generate.enabled()
1183         && sess.target.target.options.is_like_msvc
1184         && sess.panic_strategy() == PanicStrategy::Unwind
1185         && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1186     {
1187         sess.err(
1188             "Profile-guided optimization does not yet work in conjunction \
1189                   with `-Cpanic=unwind` on Windows when targeting MSVC. \
1190                   See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1191                   for more information.",
1192         );
1193     }
1194
1195     // Sanitizers can only be used on some tested platforms.
1196     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
1197         const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1198             "x86_64-unknown-linux-gnu",
1199             "x86_64-apple-darwin",
1200             "x86_64-fuchsia",
1201             "aarch64-fuchsia",
1202         ];
1203         const TSAN_SUPPORTED_TARGETS: &[&str] =
1204             &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1205         const LSAN_SUPPORTED_TARGETS: &[&str] =
1206             &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1207         const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
1208
1209         let supported_targets = match *sanitizer {
1210             Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
1211             Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
1212             Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
1213             Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
1214         };
1215
1216         if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1217             sess.err(&format!(
1218                 "{:?}Sanitizer only works with the `{}` target",
1219                 sanitizer,
1220                 supported_targets.join("` or `")
1221             ));
1222         }
1223     }
1224 }
1225
1226 /// Holds data on the current incremental compilation session, if there is one.
1227 #[derive(Debug)]
1228 pub enum IncrCompSession {
1229     /// This is the state the session will be in until the incr. comp. dir is
1230     /// needed.
1231     NotInitialized,
1232     /// This is the state during which the session directory is private and can
1233     /// be modified.
1234     Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1235     /// This is the state after the session directory has been finalized. In this
1236     /// state, the contents of the directory must not be modified any more.
1237     Finalized { session_directory: PathBuf },
1238     /// This is an error state that is reached when some compilation error has
1239     /// occurred. It indicates that the contents of the session directory must
1240     /// not be used, since they might be invalid.
1241     InvalidBecauseOfErrors { session_directory: PathBuf },
1242 }
1243
1244 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1245     let emitter: Box<dyn Emitter + sync::Send> = match output {
1246         config::ErrorOutputType::HumanReadable(kind) => {
1247             let (short, color_config) = kind.unzip();
1248             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1249         }
1250         config::ErrorOutputType::Json { pretty, json_rendered } => {
1251             Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1252         }
1253     };
1254     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1255     handler.struct_fatal(msg).emit();
1256     rustc_errors::FatalError.raise();
1257 }
1258
1259 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1260     let emitter: Box<dyn Emitter + sync::Send> = match output {
1261         config::ErrorOutputType::HumanReadable(kind) => {
1262             let (short, color_config) = kind.unzip();
1263             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1264         }
1265         config::ErrorOutputType::Json { pretty, json_rendered } => {
1266             Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1267         }
1268     };
1269     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1270     handler.struct_warn(msg).emit();
1271 }
1272
1273 pub type CompileResult = Result<(), ErrorReported>;