1 use crate::code_stats::CodeStats;
2 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::cgu_reuse_tracker::CguReuseTracker;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use crate::config::{self, OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
11 use crate::search_paths::{PathKind, SearchPath};
12 use crate::utils::duration_to_secs_str;
13 use rustc_errors::ErrorReported;
15 use rustc_data_structures::base_n;
16 use rustc_data_structures::impl_stable_hash_via_hash;
17 use rustc_data_structures::sync::{
18 self, AtomicU64, AtomicUsize, Lock, Lrc, Once, OneThread, Ordering, Ordering::SeqCst,
21 use crate::parse::ParseSess;
22 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
23 use rustc_errors::emitter::HumanReadableErrorType;
24 use rustc_errors::emitter::{Emitter, EmitterWriter};
25 use rustc_errors::json::JsonEmitter;
26 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId};
27 use rustc_span::edition::Edition;
28 use rustc_span::source_map;
29 use rustc_span::{MultiSpan, Span};
31 use rustc_data_structures::flock;
32 use rustc_data_structures::jobserver::{self, Client};
33 use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
34 use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
37 use std::cell::{self, RefCell};
41 use std::num::NonZeroU32;
42 use std::path::PathBuf;
44 use std::time::Duration;
46 pub struct OptimizationFuel {
47 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
49 /// We're rejecting all further optimizations.
53 /// Represents the data associated with a compilation
54 /// session for a single crate.
56 pub target: config::Config,
58 pub opts: config::Options,
59 pub host_tlib_path: SearchPath,
60 /// `None` if the host and target are the same.
61 pub target_tlib_path: Option<SearchPath>,
62 pub parse_sess: ParseSess,
64 /// The name of the root source file of the crate, in the local file system.
65 /// `None` means that there is no source file.
66 pub local_crate_source_file: Option<PathBuf>,
67 /// The directory the compiler has been executed in plus a flag indicating
68 /// if the value stored here has been affected by path remapping.
69 pub working_dir: (PathBuf, bool),
71 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
72 /// (sub)diagnostics that have been set once, but should not be set again,
73 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
74 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
75 pub crate_types: Once<Vec<config::CrateType>>,
76 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
77 /// arguments passed to the compiler. Its value together with the crate-name
78 /// forms a unique global identifier for the crate. It is used to allow
79 /// multiple crates with the same name to coexist. See the
80 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
81 pub crate_disambiguator: Once<CrateDisambiguator>,
83 features: Once<rustc_feature::Features>,
85 /// The maximum recursion limit for potentially infinitely recursive
86 /// operations such as auto-dereference and monomorphization.
87 pub recursion_limit: Once<usize>,
89 /// The maximum length of types during monomorphization.
90 pub type_length_limit: Once<usize>,
92 /// Map from imported macro spans (which consist of
93 /// the localized span for the macro body) to the
94 /// macro name and definition span in the source crate.
95 pub imported_macro_spans: OneThread<RefCell<FxHashMap<Span, (String, Span)>>>,
97 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
98 /// Used for incremental compilation tests. Will only be populated if
99 /// `-Zquery-dep-graph` is specified.
100 pub cgu_reuse_tracker: CguReuseTracker,
102 /// Used by `-Z self-profile`.
103 pub prof: SelfProfilerRef,
105 /// Some measurements that are being gathered during compilation.
106 pub perf_stats: PerfStats,
108 /// Data about code being compiled, gathered during compilation.
109 pub code_stats: CodeStats,
111 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
112 optimization_fuel_crate: Option<String>,
114 /// Tracks fuel info if `-zfuel=crate=n` is specified.
115 optimization_fuel: Lock<OptimizationFuel>,
117 // The next two are public because the driver needs to read them.
118 /// If `-zprint-fuel=crate`, `Some(crate)`.
119 pub print_fuel_crate: Option<String>,
120 /// Always set to zero and incremented so that we can print fuel expended by a crate.
121 pub print_fuel: AtomicU64,
123 /// Loaded up early on in the initialization of this `Session` to avoid
124 /// false positives about a job server in our environment.
125 pub jobserver: Client,
127 /// Cap lint level specified by a driver specifically.
128 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
130 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
131 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
133 /// Mapping from ident span to path span for paths that don't exist as written, but that
134 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
135 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
138 pub struct PerfStats {
139 /// The accumulated time spent on computing symbol hashes.
140 pub symbol_hash_time: Lock<Duration>,
141 /// The accumulated time spent decoding def path tables from metadata.
142 pub decode_def_path_tables_time: Lock<Duration>,
143 /// Total number of values canonicalized queries constructed.
144 pub queries_canonicalized: AtomicUsize,
145 /// Number of times this query is invoked.
146 pub normalize_ty_after_erasing_regions: AtomicUsize,
147 /// Number of times this query is invoked.
148 pub normalize_projection_ty: AtomicUsize,
151 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
152 enum DiagnosticBuilderMethod {
155 SpanSuggestion(String), // suggestion
156 // Add more variants as needed to support one-time diagnostics.
159 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
160 /// emitting the same message more than once.
161 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
162 pub enum DiagnosticMessageId {
163 ErrorId(u16), // EXXXX error code as integer
164 LintId(lint::LintId),
165 StabilityId(Option<NonZeroU32>), // issue number
168 impl From<&'static lint::Lint> for DiagnosticMessageId {
169 fn from(lint: &'static lint::Lint) -> Self {
170 DiagnosticMessageId::LintId(lint::LintId::of(lint))
175 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
176 *self.crate_disambiguator.get()
179 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
180 self.diagnostic().struct_span_warn(sp, msg)
182 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
187 ) -> DiagnosticBuilder<'_> {
188 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
190 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
191 self.diagnostic().struct_warn(msg)
193 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
194 self.diagnostic().struct_span_err(sp, msg)
196 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
201 ) -> DiagnosticBuilder<'_> {
202 self.diagnostic().struct_span_err_with_code(sp, msg, code)
204 // FIXME: This method should be removed (every error should have an associated error code).
205 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
206 self.diagnostic().struct_err(msg)
208 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
209 self.diagnostic().struct_err_with_code(msg, code)
211 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
212 self.diagnostic().struct_span_fatal(sp, msg)
214 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
219 ) -> DiagnosticBuilder<'_> {
220 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
222 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
223 self.diagnostic().struct_fatal(msg)
226 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
227 self.diagnostic().span_fatal(sp, msg).raise()
229 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
235 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
237 pub fn fatal(&self, msg: &str) -> ! {
238 self.diagnostic().fatal(msg).raise()
240 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
242 self.span_warn(sp, msg);
244 self.span_err(sp, msg);
247 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
248 self.diagnostic().span_err(sp, msg)
250 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
251 self.diagnostic().span_err_with_code(sp, &msg, code)
253 pub fn err(&self, msg: &str) {
254 self.diagnostic().err(msg)
256 pub fn err_count(&self) -> usize {
257 self.diagnostic().err_count()
259 pub fn has_errors(&self) -> bool {
260 self.diagnostic().has_errors()
262 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
263 self.diagnostic().has_errors_or_delayed_span_bugs()
265 pub fn abort_if_errors(&self) {
266 self.diagnostic().abort_if_errors();
268 pub fn compile_status(&self) -> Result<(), ErrorReported> {
269 if self.has_errors() {
270 self.diagnostic().emit_stashed_diagnostics();
276 // FIXME(matthewjasper) Remove this method, it should never be needed.
277 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
281 let old_count = self.err_count();
283 let errors = self.err_count() - old_count;
284 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
286 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
287 self.diagnostic().span_warn(sp, msg)
289 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
290 self.diagnostic().span_warn_with_code(sp, msg, code)
292 pub fn warn(&self, msg: &str) {
293 self.diagnostic().warn(msg)
295 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
297 Some(sp) => self.span_warn(sp, msg),
298 None => self.warn(msg),
301 /// Delay a span_bug() call until abort_if_errors()
302 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
303 self.diagnostic().delay_span_bug(sp, msg)
305 pub fn note_without_error(&self, msg: &str) {
306 self.diagnostic().note_without_error(msg)
308 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
309 self.diagnostic().span_note_without_error(sp, msg)
312 pub fn diagnostic(&self) -> &rustc_errors::Handler {
313 &self.parse_sess.span_diagnostic
316 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
317 /// deduplicates on lint ID, span (if any), and message for this `Session`
318 fn diag_once<'a, 'b>(
320 diag_builder: &'b mut DiagnosticBuilder<'a>,
321 method: DiagnosticBuilderMethod,
322 msg_id: DiagnosticMessageId,
324 span_maybe: Option<Span>,
326 let id_span_message = (msg_id, span_maybe, message.to_owned());
327 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
330 DiagnosticBuilderMethod::Note => {
331 diag_builder.note(message);
333 DiagnosticBuilderMethod::SpanNote => {
334 let span = span_maybe.expect("`span_note` needs a span");
335 diag_builder.span_note(span, message);
337 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
338 let span = span_maybe.expect("`span_suggestion_*` needs a span");
339 diag_builder.span_suggestion(
343 Applicability::Unspecified,
350 pub fn diag_span_note_once<'a, 'b>(
352 diag_builder: &'b mut DiagnosticBuilder<'a>,
353 msg_id: DiagnosticMessageId,
359 DiagnosticBuilderMethod::SpanNote,
366 pub fn diag_note_once<'a, 'b>(
368 diag_builder: &'b mut DiagnosticBuilder<'a>,
369 msg_id: DiagnosticMessageId,
372 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
375 pub fn diag_span_suggestion_once<'a, 'b>(
377 diag_builder: &'b mut DiagnosticBuilder<'a>,
378 msg_id: DiagnosticMessageId,
385 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
392 pub fn source_map(&self) -> &source_map::SourceMap {
393 self.parse_sess.source_map()
395 pub fn verbose(&self) -> bool {
396 self.opts.debugging_opts.verbose
398 pub fn time_passes(&self) -> bool {
399 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
401 pub fn time_extended(&self) -> bool {
402 self.opts.debugging_opts.time_passes
404 pub fn instrument_mcount(&self) -> bool {
405 self.opts.debugging_opts.instrument_mcount
407 pub fn time_llvm_passes(&self) -> bool {
408 self.opts.debugging_opts.time_llvm_passes
410 pub fn meta_stats(&self) -> bool {
411 self.opts.debugging_opts.meta_stats
413 pub fn asm_comments(&self) -> bool {
414 self.opts.debugging_opts.asm_comments
416 pub fn verify_llvm_ir(&self) -> bool {
417 self.opts.debugging_opts.verify_llvm_ir || cfg!(always_verify_llvm_ir)
419 pub fn borrowck_stats(&self) -> bool {
420 self.opts.debugging_opts.borrowck_stats
422 pub fn print_llvm_passes(&self) -> bool {
423 self.opts.debugging_opts.print_llvm_passes
425 pub fn binary_dep_depinfo(&self) -> bool {
426 self.opts.debugging_opts.binary_dep_depinfo
429 /// Gets the features enabled for the current compilation session.
430 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
431 /// dependency tracking. Use tcx.features() instead.
433 pub fn features_untracked(&self) -> &rustc_feature::Features {
437 pub fn init_features(&self, features: rustc_feature::Features) {
438 self.features.set(features);
441 /// Calculates the flavor of LTO to use for this compilation.
442 pub fn lto(&self) -> config::Lto {
443 // If our target has codegen requirements ignore the command line
444 if self.target.target.options.requires_lto {
445 return config::Lto::Fat;
448 // If the user specified something, return that. If they only said `-C
449 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
450 // then ensure we can't use a ThinLTO.
451 match self.opts.cg.lto {
452 config::LtoCli::Unspecified => {
453 // The compiler was invoked without the `-Clto` flag. Fall
454 // through to the default handling
456 config::LtoCli::No => {
457 // The user explicitly opted out of any kind of LTO
458 return config::Lto::No;
460 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
461 // All of these mean fat LTO
462 return config::Lto::Fat;
464 config::LtoCli::Thin => {
465 return if self.opts.cli_forced_thinlto_off {
473 // Ok at this point the target doesn't require anything and the user
474 // hasn't asked for anything. Our next decision is whether or not
475 // we enable "auto" ThinLTO where we use multiple codegen units and
476 // then do ThinLTO over those codegen units. The logic below will
477 // either return `No` or `ThinLocal`.
479 // If processing command line options determined that we're incompatible
480 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
481 if self.opts.cli_forced_thinlto_off {
482 return config::Lto::No;
485 // If `-Z thinlto` specified process that, but note that this is mostly
486 // a deprecated option now that `-C lto=thin` exists.
487 if let Some(enabled) = self.opts.debugging_opts.thinlto {
489 return config::Lto::ThinLocal;
491 return config::Lto::No;
495 // If there's only one codegen unit and LTO isn't enabled then there's
496 // no need for ThinLTO so just return false.
497 if self.codegen_units() == 1 {
498 return config::Lto::No;
501 // Now we're in "defaults" territory. By default we enable ThinLTO for
502 // optimized compiles (anything greater than O0).
503 match self.opts.optimize {
504 config::OptLevel::No => config::Lto::No,
505 _ => config::Lto::ThinLocal,
509 /// Returns the panic strategy for this compile session. If the user explicitly selected one
510 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
511 pub fn panic_strategy(&self) -> PanicStrategy {
512 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
514 pub fn fewer_names(&self) -> bool {
515 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
516 || self.opts.output_types.contains_key(&OutputType::Bitcode);
518 // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
519 let more_names = match self.opts.debugging_opts.sanitizer {
520 Some(Sanitizer::Address) => true,
521 Some(Sanitizer::Memory) => true,
525 self.opts.debugging_opts.fewer_names || !more_names
528 pub fn no_landing_pads(&self) -> bool {
529 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
531 pub fn unstable_options(&self) -> bool {
532 self.opts.debugging_opts.unstable_options
534 pub fn overflow_checks(&self) -> bool {
538 .or(self.opts.debugging_opts.force_overflow_checks)
539 .unwrap_or(self.opts.debug_assertions)
542 pub fn crt_static(&self) -> bool {
543 // If the target does not opt in to crt-static support, use its default.
544 if self.target.target.options.crt_static_respected {
545 self.crt_static_feature()
547 self.target.target.options.crt_static_default
551 pub fn crt_static_feature(&self) -> bool {
552 let requested_features = self.opts.cg.target_feature.split(',');
553 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
554 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
556 // If the target we're compiling for requests a static crt by default,
557 // then see if the `-crt-static` feature was passed to disable that.
558 // Otherwise if we don't have a static crt by default then see if the
559 // `+crt-static` feature was passed.
560 if self.target.target.options.crt_static_default { !found_negative } else { found_positive }
563 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
564 // "mcount" function relies on stack pointer.
565 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
566 if self.instrument_mcount() {
568 } else if let Some(x) = self.opts.cg.force_frame_pointers {
571 !self.target.target.options.eliminate_frame_pointer
575 /// Returns the symbol name for the registrar function,
576 /// given the crate `Svh` and the function `DefIndex`.
577 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
578 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
581 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
582 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
585 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
586 filesearch::FileSearch::new(
588 self.opts.target_triple.triple(),
589 &self.opts.search_paths,
590 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
591 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
595 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
596 filesearch::FileSearch::new(
598 config::host_triple(),
599 &self.opts.search_paths,
600 &self.host_tlib_path,
605 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
606 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
608 if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
609 *load_dep_graph = load;
613 pub fn incr_session_load_dep_graph(&self) -> bool {
614 let incr_comp_session = self.incr_comp_session.borrow();
615 match *incr_comp_session {
616 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
621 pub fn init_incr_comp_session(
623 session_dir: PathBuf,
624 lock_file: flock::Lock,
625 load_dep_graph: bool,
627 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
629 if let IncrCompSession::NotInitialized = *incr_comp_session {
631 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
635 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
638 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
639 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
641 if let IncrCompSession::Active { .. } = *incr_comp_session {
643 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
646 // Note: this will also drop the lock file, thus unlocking the directory.
647 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
650 pub fn mark_incr_comp_session_as_invalid(&self) {
651 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
653 let session_directory = match *incr_comp_session {
654 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
655 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
656 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
659 // Note: this will also drop the lock file, thus unlocking the directory.
660 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
663 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
664 let incr_comp_session = self.incr_comp_session.borrow();
665 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
666 IncrCompSession::NotInitialized => panic!(
667 "trying to get session directory from `IncrCompSession`: {:?}",
670 IncrCompSession::Active { ref session_directory, .. }
671 | IncrCompSession::Finalized { ref session_directory }
672 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
678 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
679 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
682 pub fn print_perf_stats(&self) {
684 "Total time spent computing symbol hashes: {}",
685 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
688 "Total time spent decoding DefPath tables: {}",
689 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
692 "Total queries canonicalized: {}",
693 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
696 "normalize_ty_after_erasing_regions: {}",
697 self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed)
700 "normalize_projection_ty: {}",
701 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
705 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
706 /// This expends fuel if applicable, and records fuel if applicable.
707 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
709 if let Some(ref c) = self.optimization_fuel_crate {
711 assert_eq!(self.threads(), 1);
712 let mut fuel = self.optimization_fuel.lock();
713 ret = fuel.remaining != 0;
714 if fuel.remaining == 0 && !fuel.out_of_fuel {
715 eprintln!("optimization-fuel-exhausted: {}", msg());
716 fuel.out_of_fuel = true;
717 } else if fuel.remaining > 0 {
722 if let Some(ref c) = self.print_fuel_crate {
724 assert_eq!(self.threads(), 1);
725 self.print_fuel.fetch_add(1, SeqCst);
731 /// Returns the number of query threads that should be used for this
733 pub fn threads(&self) -> usize {
734 self.opts.debugging_opts.threads
737 /// Returns the number of codegen units that should be used for this
739 pub fn codegen_units(&self) -> usize {
740 if let Some(n) = self.opts.cli_forced_codegen_units {
743 if let Some(n) = self.target.target.options.default_codegen_units {
747 // Why is 16 codegen units the default all the time?
749 // The main reason for enabling multiple codegen units by default is to
750 // leverage the ability for the codegen backend to do codegen and
751 // optimization in parallel. This allows us, especially for large crates, to
752 // make good use of all available resources on the machine once we've
753 // hit that stage of compilation. Large crates especially then often
754 // take a long time in codegen/optimization and this helps us amortize that
757 // Note that a high number here doesn't mean that we'll be spawning a
758 // large number of threads in parallel. The backend of rustc contains
759 // global rate limiting through the `jobserver` crate so we'll never
760 // overload the system with too much work, but rather we'll only be
761 // optimizing when we're otherwise cooperating with other instances of
764 // Rather a high number here means that we should be able to keep a lot
765 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
766 // to build we'll be guaranteed that all cpus will finish pretty closely
767 // to one another and we should make relatively optimal use of system
770 // Note that the main cost of codegen units is that it prevents LLVM
771 // from inlining across codegen units. Users in general don't have a lot
772 // of control over how codegen units are split up so it's our job in the
773 // compiler to ensure that undue performance isn't lost when using
774 // codegen units (aka we can't require everyone to slap `#[inline]` on
777 // If we're compiling at `-O0` then the number doesn't really matter too
778 // much because performance doesn't matter and inlining is ok to lose.
779 // In debug mode we just want to try to guarantee that no cpu is stuck
780 // doing work that could otherwise be farmed to others.
782 // In release mode, however (O1 and above) performance does indeed
783 // matter! To recover the loss in performance due to inlining we'll be
784 // enabling ThinLTO by default (the function for which is just below).
785 // This will ensure that we recover any inlining wins we otherwise lost
786 // through codegen unit partitioning.
790 // Ok that's a lot of words but the basic tl;dr; is that we want a high
791 // number here -- but not too high. Additionally we're "safe" to have it
792 // always at the same number at all optimization levels.
794 // As a result 16 was chosen here! Mostly because it was a power of 2
795 // and most benchmarks agreed it was roughly a local optimum. Not very
800 pub fn teach(&self, code: &DiagnosticId) -> bool {
801 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
804 pub fn rust_2015(&self) -> bool {
805 self.opts.edition == Edition::Edition2015
808 /// Are we allowed to use features from the Rust 2018 edition?
809 pub fn rust_2018(&self) -> bool {
810 self.opts.edition >= Edition::Edition2018
813 pub fn edition(&self) -> Edition {
817 /// Returns `true` if we cannot skip the PLT for shared library calls.
818 pub fn needs_plt(&self) -> bool {
819 // Check if the current target usually needs PLT to be enabled.
820 // The user can use the command line flag to override it.
821 let needs_plt = self.target.target.options.needs_plt;
823 let dbg_opts = &self.opts.debugging_opts;
825 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
827 // Only enable this optimization by default if full relro is also enabled.
828 // In this case, lazy binding was already unavailable, so nothing is lost.
829 // This also ensures `-Wl,-z,now` is supported by the linker.
830 let full_relro = RelroLevel::Full == relro_level;
832 // If user didn't explicitly forced us to use / skip the PLT,
833 // then try to skip it where possible.
834 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
838 pub fn build_session(
839 sopts: config::Options,
840 local_crate_source_file: Option<PathBuf>,
841 registry: rustc_errors::registry::Registry,
843 let file_path_mapping = sopts.file_path_mapping();
845 build_session_with_source_map(
847 local_crate_source_file,
849 Lrc::new(source_map::SourceMap::new(file_path_mapping)),
850 DiagnosticOutput::Default,
856 sopts: &config::Options,
857 registry: rustc_errors::registry::Registry,
858 source_map: &Lrc<source_map::SourceMap>,
859 emitter_dest: Option<Box<dyn Write + Send>>,
860 ) -> Box<dyn Emitter + sync::Send> {
861 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
862 match (sopts.error_format, emitter_dest) {
863 (config::ErrorOutputType::HumanReadable(kind), dst) => {
864 let (short, color_config) = kind.unzip();
866 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
867 let emitter = AnnotateSnippetEmitterWriter::new(
868 Some(source_map.clone()),
870 external_macro_backtrace,
872 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing()))
874 let emitter = match dst {
875 None => EmitterWriter::stderr(
877 Some(source_map.clone()),
879 sopts.debugging_opts.teach,
880 sopts.debugging_opts.terminal_width,
881 external_macro_backtrace,
883 Some(dst) => EmitterWriter::new(
885 Some(source_map.clone()),
887 false, // no teach messages when writing to a buffer
888 false, // no colors when writing to a buffer
889 None, // no terminal width
890 external_macro_backtrace,
893 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing()))
896 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
902 external_macro_backtrace,
904 .ui_testing(sopts.debugging_opts.ui_testing()),
906 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
913 external_macro_backtrace,
915 .ui_testing(sopts.debugging_opts.ui_testing()),
920 pub enum DiagnosticOutput {
922 Raw(Box<dyn Write + Send>),
925 pub fn build_session_with_source_map(
926 sopts: config::Options,
927 local_crate_source_file: Option<PathBuf>,
928 registry: rustc_errors::registry::Registry,
929 source_map: Lrc<source_map::SourceMap>,
930 diagnostics_output: DiagnosticOutput,
931 lint_caps: FxHashMap<lint::LintId, lint::Level>,
933 // FIXME: This is not general enough to make the warning lint completely override
934 // normal diagnostic warnings, since the warning lint can also be denied and changed
935 // later via the source code.
936 let warnings_allow = sopts
939 .filter(|&&(ref key, _)| *key == "warnings")
940 .map(|&(_, ref level)| *level == lint::Allow)
943 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
944 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
946 let write_dest = match diagnostics_output {
947 DiagnosticOutput::Default => None,
948 DiagnosticOutput::Raw(write) => Some(write),
950 let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
952 let diagnostic_handler = rustc_errors::Handler::with_emitter_and_flags(
954 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
957 build_session_(sopts, local_crate_source_file, diagnostic_handler, source_map, lint_caps)
961 sopts: config::Options,
962 local_crate_source_file: Option<PathBuf>,
963 span_diagnostic: rustc_errors::Handler,
964 source_map: Lrc<source_map::SourceMap>,
965 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
967 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
970 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
972 let profiler = SelfProfiler::new(
974 sopts.crate_name.as_ref().map(|s| &s[..]),
975 &sopts.debugging_opts.self_profile_events,
978 Ok(profiler) => Some(Arc::new(profiler)),
980 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
988 let host_triple = TargetTriple::from_triple(config::host_triple());
989 let host = Target::search(&host_triple).unwrap_or_else(|e| {
990 span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise()
992 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
994 let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
995 let sysroot = match &sopts.maybe_sysroot {
996 Some(sysroot) => sysroot.clone(),
997 None => filesearch::get_or_default_sysroot(),
1000 let host_triple = config::host_triple();
1001 let target_triple = sopts.target_triple.triple();
1002 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1003 let target_tlib_path = if host_triple == target_triple {
1006 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1009 let file_path_mapping = sopts.file_path_mapping();
1011 let local_crate_source_file =
1012 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1014 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1015 let optimization_fuel = Lock::new(OptimizationFuel {
1016 remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1019 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1020 let print_fuel = AtomicU64::new(0);
1022 let working_dir = env::current_dir().unwrap_or_else(|e| {
1023 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1025 let working_dir = file_path_mapping.map_prefix(working_dir);
1027 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1028 CguReuseTracker::new()
1030 CguReuseTracker::new_disabled()
1033 let sess = Session {
1041 local_crate_source_file,
1043 one_time_diagnostics: Default::default(),
1044 crate_types: Once::new(),
1045 crate_disambiguator: Once::new(),
1046 features: Once::new(),
1047 recursion_limit: Once::new(),
1048 type_length_limit: Once::new(),
1049 imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())),
1050 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1052 prof: SelfProfilerRef::new(self_profiler),
1053 perf_stats: PerfStats {
1054 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1055 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1056 queries_canonicalized: AtomicUsize::new(0),
1057 normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1058 normalize_projection_ty: AtomicUsize::new(0),
1060 code_stats: Default::default(),
1061 optimization_fuel_crate,
1065 jobserver: jobserver::client(),
1067 trait_methods_not_found: Lock::new(Default::default()),
1068 confused_type_with_std_module: Lock::new(Default::default()),
1071 validate_commandline_args_with_session_available(&sess);
1076 // If it is useful to have a Session available already for validating a
1077 // commandline argument, you can do so here.
1078 fn validate_commandline_args_with_session_available(sess: &Session) {
1079 // Since we don't know if code in an rlib will be linked to statically or
1080 // dynamically downstream, rustc generates `__imp_` symbols that help the
1081 // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1082 // these manually generated symbols confuse LLD when it tries to merge
1083 // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1084 // when compiling for LLD ThinLTO. This way we can validly just not generate
1085 // the `dllimport` attributes and `__imp_` symbols in that case.
1086 if sess.opts.cg.linker_plugin_lto.enabled()
1087 && sess.opts.cg.prefer_dynamic
1088 && sess.target.target.options.is_like_msvc
1091 "Linker plugin based LTO is not supported together with \
1092 `-C prefer-dynamic` when targeting MSVC",
1096 // Make sure that any given profiling data actually exists so LLVM can't
1097 // decide to silently skip PGO.
1098 if let Some(ref path) = sess.opts.cg.profile_use {
1101 "File `{}` passed to `-C profile-use` does not exist.",
1107 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1108 // an error to combine the two for now. It always runs into an assertions
1109 // if LLVM is built with assertions, but without assertions it sometimes
1110 // does not crash and will probably generate a corrupted binary.
1111 // We should only display this error if we're actually going to run PGO.
1112 // If we're just supposed to print out some data, don't show the error (#61002).
1113 if sess.opts.cg.profile_generate.enabled()
1114 && sess.target.target.options.is_like_msvc
1115 && sess.panic_strategy() == PanicStrategy::Unwind
1116 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1119 "Profile-guided optimization does not yet work in conjunction \
1120 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1121 See https://github.com/rust-lang/rust/issues/61002 for details.",
1126 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1127 /// compiler. Together with the crate-name forms a unique global identifier for
1129 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1130 pub struct CrateDisambiguator(Fingerprint);
1132 impl CrateDisambiguator {
1133 pub fn to_fingerprint(self) -> Fingerprint {
1138 impl fmt::Display for CrateDisambiguator {
1139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1140 let (a, b) = self.0.as_value();
1141 let as_u128 = a as u128 | ((b as u128) << 64);
1142 f.write_str(&base_n::encode(as_u128, base_n::CASE_INSENSITIVE))
1146 impl From<Fingerprint> for CrateDisambiguator {
1147 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1148 CrateDisambiguator(fingerprint)
1152 impl_stable_hash_via_hash!(CrateDisambiguator);
1154 /// Holds data on the current incremental compilation session, if there is one.
1156 pub enum IncrCompSession {
1157 /// This is the state the session will be in until the incr. comp. dir is
1160 /// This is the state during which the session directory is private and can
1162 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1163 /// This is the state after the session directory has been finalized. In this
1164 /// state, the contents of the directory must not be modified any more.
1165 Finalized { session_directory: PathBuf },
1166 /// This is an error state that is reached when some compilation error has
1167 /// occurred. It indicates that the contents of the session directory must
1168 /// not be used, since they might be invalid.
1169 InvalidBecauseOfErrors { session_directory: PathBuf },
1172 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1173 let emitter: Box<dyn Emitter + sync::Send> = match output {
1174 config::ErrorOutputType::HumanReadable(kind) => {
1175 let (short, color_config) = kind.unzip();
1176 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1178 config::ErrorOutputType::Json { pretty, json_rendered } => {
1179 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1182 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1183 handler.struct_fatal(msg).emit();
1184 rustc_errors::FatalError.raise();
1187 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1188 let emitter: Box<dyn Emitter + sync::Send> = match output {
1189 config::ErrorOutputType::HumanReadable(kind) => {
1190 let (short, color_config) = kind.unzip();
1191 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1193 config::ErrorOutputType::Json { pretty, json_rendered } => {
1194 Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1197 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1198 handler.struct_warn(msg).emit();
1201 pub type CompileResult = Result<(), ErrorReported>;