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