1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
12 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
14 use hir::def_id::CrateNum;
19 use lint::builtin::BuiltinLintDiagnostics;
20 use middle::allocator::AllocatorKind;
21 use middle::dependency_format;
22 use session::search_paths::PathKind;
23 use session::config::{OutputType};
25 use util::nodemap::{FxHashMap, FxHashSet};
26 use util::common::{duration_to_secs_str, ErrorReported};
27 use util::common::ProfileQueriesMsg;
29 use rustc_data_structures::sync::{self, Lrc, Lock, LockCell, OneThread, Once, RwLock};
31 use syntax::ast::NodeId;
32 use errors::{self, DiagnosticBuilder, DiagnosticId};
33 use errors::emitter::{Emitter, EmitterWriter};
34 use syntax::edition::Edition;
35 use syntax::json::JsonEmitter;
36 use syntax::feature_gate;
37 use syntax::symbol::Symbol;
39 use syntax::parse::ParseSess;
40 use syntax::{ast, codemap};
41 use syntax::feature_gate::AttributeType;
42 use syntax_pos::{MultiSpan, Span};
43 use util::profiling::SelfProfiler;
45 use rustc_target::spec::{LinkerFlavor, PanicStrategy};
46 use rustc_target::spec::{Target, TargetTriple};
47 use rustc_data_structures::flock;
48 use jobserver::Client;
51 use std::cell::{self, Cell, RefCell};
52 use std::collections::HashMap;
56 use std::path::{Path, PathBuf};
57 use std::time::Duration;
59 use std::sync::atomic::{AtomicUsize, Ordering};
66 /// Represents the data associated with a compilation
67 /// session for a single crate.
69 pub target: config::Config,
71 pub opts: config::Options,
72 pub parse_sess: ParseSess,
73 /// For a library crate, this is always none
74 pub entry_fn: Once<Option<(NodeId, Span, config::EntryFnType)>>,
75 pub plugin_registrar_fn: Once<Option<ast::NodeId>>,
76 pub derive_registrar_fn: Once<Option<ast::NodeId>>,
77 pub default_sysroot: Option<PathBuf>,
78 /// The name of the root source file of the crate, in the local file system.
79 /// `None` means that there is no source file.
80 pub local_crate_source_file: Option<PathBuf>,
81 /// The directory the compiler has been executed in plus a flag indicating
82 /// if the value stored here has been affected by path remapping.
83 pub working_dir: (PathBuf, bool),
85 // FIXME: lint_store and buffered_lints are not thread-safe,
86 // but are only used in a single thread
87 pub lint_store: RwLock<lint::LintStore>,
88 pub buffered_lints: Lock<Option<lint::LintBuffer>>,
90 /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
91 /// (sub)diagnostics that have been set once, but should not be set again,
92 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
93 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
94 pub plugin_llvm_passes: OneThread<RefCell<Vec<String>>>,
95 pub plugin_attributes: OneThread<RefCell<Vec<(String, AttributeType)>>>,
96 pub crate_types: Once<Vec<config::CrateType>>,
97 pub dependency_formats: Once<dependency_format::Dependencies>,
98 /// The crate_disambiguator is constructed out of all the `-C metadata`
99 /// arguments passed to the compiler. Its value together with the crate-name
100 /// forms a unique global identifier for the crate. It is used to allow
101 /// multiple crates with the same name to coexist. See the
102 /// rustc_codegen_llvm::back::symbol_names module for more information.
103 pub crate_disambiguator: Once<CrateDisambiguator>,
105 features: Once<feature_gate::Features>,
107 /// The maximum recursion limit for potentially infinitely recursive
108 /// operations such as auto-dereference and monomorphization.
109 pub recursion_limit: Once<usize>,
111 /// The maximum length of types during monomorphization.
112 pub type_length_limit: Once<usize>,
114 /// The maximum number of stackframes allowed in const eval
115 pub const_eval_stack_frame_limit: usize,
117 /// The metadata::creader module may inject an allocator/panic_runtime
118 /// dependency if it didn't already find one, and this tracks what was
120 pub injected_allocator: Once<Option<CrateNum>>,
121 pub allocator_kind: Once<Option<AllocatorKind>>,
122 pub injected_panic_runtime: Once<Option<CrateNum>>,
124 /// Map from imported macro spans (which consist of
125 /// the localized span for the macro body) to the
126 /// macro name and definition span in the source crate.
127 pub imported_macro_spans: OneThread<RefCell<HashMap<Span, (String, Span)>>>,
129 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
131 /// A cache of attributes ignored by StableHashingContext
132 pub ignored_attr_names: FxHashSet<Symbol>,
134 /// Used by -Z profile-queries in util::common
135 pub profile_channel: Lock<Option<mpsc::Sender<ProfileQueriesMsg>>>,
137 /// Used by -Z self-profile
138 pub self_profiling: Lock<SelfProfiler>,
140 /// Some measurements that are being gathered during compilation.
141 pub perf_stats: PerfStats,
143 /// Data about code being compiled, gathered during compilation.
144 pub code_stats: Lock<CodeStats>,
146 next_node_id: OneThread<Cell<ast::NodeId>>,
148 /// If -zfuel=crate=n is specified, Some(crate).
149 optimization_fuel_crate: Option<String>,
150 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
151 optimization_fuel_limit: LockCell<u64>,
152 /// We're rejecting all further optimizations.
153 out_of_fuel: LockCell<bool>,
155 // The next two are public because the driver needs to read them.
156 /// If -zprint-fuel=crate, Some(crate).
157 pub print_fuel_crate: Option<String>,
158 /// Always set to zero and incremented so that we can print fuel expended by a crate.
159 pub print_fuel: LockCell<u64>,
161 /// Loaded up early on in the initialization of this `Session` to avoid
162 /// false positives about a job server in our environment.
163 pub jobserver: Client,
165 /// Metadata about the allocators for the current crate being compiled
166 pub has_global_allocator: Once<bool>,
168 /// Cap lint level specified by a driver specifically.
169 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
172 pub struct PerfStats {
173 /// The accumulated time spent on computing symbol hashes
174 pub symbol_hash_time: Lock<Duration>,
175 /// The accumulated time spent decoding def path tables from metadata
176 pub decode_def_path_tables_time: Lock<Duration>,
177 /// Total number of values canonicalized queries constructed.
178 pub queries_canonicalized: AtomicUsize,
179 /// Number of times this query is invoked.
180 pub normalize_ty_after_erasing_regions: AtomicUsize,
181 /// Number of times this query is invoked.
182 pub normalize_projection_ty: AtomicUsize,
185 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
186 enum DiagnosticBuilderMethod {
189 SpanSuggestion(String), // suggestion
190 // add more variants as needed to support one-time diagnostics
193 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
194 /// emitting the same message more than once
195 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
196 pub enum DiagnosticMessageId {
197 ErrorId(u16), // EXXXX error code as integer
198 LintId(lint::LintId),
199 StabilityId(u32), // issue number
202 impl From<&'static lint::Lint> for DiagnosticMessageId {
203 fn from(lint: &'static lint::Lint) -> Self {
204 DiagnosticMessageId::LintId(lint::LintId::of(lint))
209 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
210 *self.crate_disambiguator.get()
213 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(
217 ) -> DiagnosticBuilder<'a> {
218 self.diagnostic().struct_span_warn(sp, msg)
220 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(
225 ) -> DiagnosticBuilder<'a> {
226 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
228 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
229 self.diagnostic().struct_warn(msg)
231 pub fn struct_span_err<'a, S: Into<MultiSpan>>(
235 ) -> DiagnosticBuilder<'a> {
236 self.diagnostic().struct_span_err(sp, msg)
238 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(
243 ) -> DiagnosticBuilder<'a> {
244 self.diagnostic().struct_span_err_with_code(sp, msg, code)
246 // FIXME: This method should be removed (every error should have an associated error code).
247 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
248 self.diagnostic().struct_err(msg)
250 pub fn struct_err_with_code<'a>(
254 ) -> DiagnosticBuilder<'a> {
255 self.diagnostic().struct_err_with_code(msg, code)
257 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(
261 ) -> DiagnosticBuilder<'a> {
262 self.diagnostic().struct_span_fatal(sp, msg)
264 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(
269 ) -> DiagnosticBuilder<'a> {
270 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
272 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
273 self.diagnostic().struct_fatal(msg)
276 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
277 self.diagnostic().span_fatal(sp, msg).raise()
279 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
286 .span_fatal_with_code(sp, msg, code)
289 pub fn fatal(&self, msg: &str) -> ! {
290 self.diagnostic().fatal(msg).raise()
292 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
294 self.span_warn(sp, msg);
296 self.span_err(sp, msg);
299 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
300 self.diagnostic().span_err(sp, msg)
302 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
303 self.diagnostic().span_err_with_code(sp, &msg, code)
305 pub fn err(&self, msg: &str) {
306 self.diagnostic().err(msg)
308 pub fn err_count(&self) -> usize {
309 self.diagnostic().err_count()
311 pub fn has_errors(&self) -> bool {
312 self.diagnostic().has_errors()
314 pub fn abort_if_errors(&self) {
315 self.diagnostic().abort_if_errors();
317 pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
318 compile_result_from_err_count(self.err_count())
320 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
324 let old_count = self.err_count();
326 let errors = self.err_count() - old_count;
333 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
334 self.diagnostic().span_warn(sp, msg)
336 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
337 self.diagnostic().span_warn_with_code(sp, msg, code)
339 pub fn warn(&self, msg: &str) {
340 self.diagnostic().warn(msg)
342 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
344 Some(sp) => self.span_warn(sp, msg),
345 None => self.warn(msg),
348 /// Delay a span_bug() call until abort_if_errors()
349 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
350 self.diagnostic().delay_span_bug(sp, msg)
352 pub fn note_without_error(&self, msg: &str) {
353 self.diagnostic().note_without_error(msg)
355 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
356 self.diagnostic().span_note_without_error(sp, msg)
358 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
359 self.diagnostic().span_unimpl(sp, msg)
361 pub fn unimpl(&self, msg: &str) -> ! {
362 self.diagnostic().unimpl(msg)
365 pub fn buffer_lint<S: Into<MultiSpan>>(
367 lint: &'static lint::Lint,
372 match *self.buffered_lints.borrow_mut() {
373 Some(ref mut buffer) => {
374 buffer.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
376 None => bug!("can't buffer lints after HIR lowering"),
380 pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(
382 lint: &'static lint::Lint,
386 diagnostic: BuiltinLintDiagnostics,
388 match *self.buffered_lints.borrow_mut() {
389 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg, diagnostic),
390 None => bug!("can't buffer lints after HIR lowering"),
394 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
395 let id = self.next_node_id.get();
397 match id.as_usize().checked_add(count) {
399 self.next_node_id.set(ast::NodeId::new(next));
401 None => bug!("Input too large, ran out of node ids!"),
406 pub fn next_node_id(&self) -> NodeId {
407 self.reserve_node_ids(1)
409 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
410 &self.parse_sess.span_diagnostic
413 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
414 /// deduplicates on lint ID, span (if any), and message for this `Session`
415 fn diag_once<'a, 'b>(
417 diag_builder: &'b mut DiagnosticBuilder<'a>,
418 method: DiagnosticBuilderMethod,
419 msg_id: DiagnosticMessageId,
421 span_maybe: Option<Span>,
423 let id_span_message = (msg_id, span_maybe, message.to_owned());
424 let fresh = self.one_time_diagnostics
426 .insert(id_span_message);
429 DiagnosticBuilderMethod::Note => {
430 diag_builder.note(message);
432 DiagnosticBuilderMethod::SpanNote => {
433 let span = span_maybe.expect("span_note needs a span");
434 diag_builder.span_note(span, message);
436 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
437 let span = span_maybe.expect("span_suggestion needs a span");
438 diag_builder.span_suggestion(span, message, suggestion);
444 pub fn diag_span_note_once<'a, 'b>(
446 diag_builder: &'b mut DiagnosticBuilder<'a>,
447 msg_id: DiagnosticMessageId,
453 DiagnosticBuilderMethod::SpanNote,
460 pub fn diag_note_once<'a, 'b>(
462 diag_builder: &'b mut DiagnosticBuilder<'a>,
463 msg_id: DiagnosticMessageId,
468 DiagnosticBuilderMethod::Note,
475 pub fn diag_span_suggestion_once<'a, 'b>(
477 diag_builder: &'b mut DiagnosticBuilder<'a>,
478 msg_id: DiagnosticMessageId,
485 DiagnosticBuilderMethod::SpanSuggestion(suggestion),
492 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
493 self.parse_sess.codemap()
495 pub fn verbose(&self) -> bool {
496 self.opts.debugging_opts.verbose
498 pub fn time_passes(&self) -> bool {
499 self.opts.debugging_opts.time_passes
501 pub fn profile_queries(&self) -> bool {
502 self.opts.debugging_opts.profile_queries
503 || self.opts.debugging_opts.profile_queries_and_keys
505 pub fn profile_queries_and_keys(&self) -> bool {
506 self.opts.debugging_opts.profile_queries_and_keys
508 pub fn count_llvm_insns(&self) -> bool {
509 self.opts.debugging_opts.count_llvm_insns
511 pub fn time_llvm_passes(&self) -> bool {
512 self.opts.debugging_opts.time_llvm_passes
514 pub fn codegen_stats(&self) -> bool {
515 self.opts.debugging_opts.codegen_stats
517 pub fn meta_stats(&self) -> bool {
518 self.opts.debugging_opts.meta_stats
520 pub fn asm_comments(&self) -> bool {
521 self.opts.debugging_opts.asm_comments
523 pub fn verify_llvm_ir(&self) -> bool {
524 self.opts.debugging_opts.verify_llvm_ir
526 pub fn borrowck_stats(&self) -> bool {
527 self.opts.debugging_opts.borrowck_stats
529 pub fn print_llvm_passes(&self) -> bool {
530 self.opts.debugging_opts.print_llvm_passes
533 /// Get the features enabled for the current compilation session.
534 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
535 /// dependency tracking. Use tcx.features() instead.
537 pub fn features_untracked(&self) -> &feature_gate::Features {
541 pub fn init_features(&self, features: feature_gate::Features) {
542 self.features.set(features);
545 /// Calculates the flavor of LTO to use for this compilation.
546 pub fn lto(&self) -> config::Lto {
547 // If our target has codegen requirements ignore the command line
548 if self.target.target.options.requires_lto {
549 return config::Lto::Fat;
552 // If the user specified something, return that. If they only said `-C
553 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
554 // then ensure we can't use a ThinLTO.
555 match self.opts.cg.lto {
556 config::Lto::No => {}
557 config::Lto::Yes if self.opts.cli_forced_thinlto_off => return config::Lto::Fat,
558 other => return other,
561 // Ok at this point the target doesn't require anything and the user
562 // hasn't asked for anything. Our next decision is whether or not
563 // we enable "auto" ThinLTO where we use multiple codegen units and
564 // then do ThinLTO over those codegen units. The logic below will
565 // either return `No` or `ThinLocal`.
567 // If processing command line options determined that we're incompatible
568 // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
569 if self.opts.cli_forced_thinlto_off {
570 return config::Lto::No;
573 // If `-Z thinlto` specified process that, but note that this is mostly
574 // a deprecated option now that `-C lto=thin` exists.
575 if let Some(enabled) = self.opts.debugging_opts.thinlto {
577 return config::Lto::ThinLocal;
579 return config::Lto::No;
583 // If there's only one codegen unit and LTO isn't enabled then there's
584 // no need for ThinLTO so just return false.
585 if self.codegen_units() == 1 {
586 return config::Lto::No;
589 // Right now ThinLTO isn't compatible with incremental compilation.
590 if self.opts.incremental.is_some() {
591 return config::Lto::No;
594 // Now we're in "defaults" territory. By default we enable ThinLTO for
595 // optimized compiles (anything greater than O0).
596 match self.opts.optimize {
597 config::OptLevel::No => config::Lto::No,
598 _ => config::Lto::ThinLocal,
602 /// Returns the panic strategy for this compile session. If the user explicitly selected one
603 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
604 pub fn panic_strategy(&self) -> PanicStrategy {
608 .unwrap_or(self.target.target.options.panic_strategy)
610 pub fn linker_flavor(&self) -> LinkerFlavor {
614 .unwrap_or(self.target.target.linker_flavor)
617 pub fn fewer_names(&self) -> bool {
618 let more_names = self.opts
620 .contains_key(&OutputType::LlvmAssembly)
621 || self.opts.output_types.contains_key(&OutputType::Bitcode);
622 self.opts.debugging_opts.fewer_names || !more_names
625 pub fn no_landing_pads(&self) -> bool {
626 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
628 pub fn unstable_options(&self) -> bool {
629 self.opts.debugging_opts.unstable_options
631 pub fn overflow_checks(&self) -> bool {
635 .or(self.opts.debugging_opts.force_overflow_checks)
636 .unwrap_or(self.opts.debug_assertions)
639 pub fn crt_static(&self) -> bool {
640 // If the target does not opt in to crt-static support, use its default.
641 if self.target.target.options.crt_static_respected {
642 self.crt_static_feature()
644 self.target.target.options.crt_static_default
648 pub fn crt_static_feature(&self) -> bool {
649 let requested_features = self.opts.cg.target_feature.split(',');
650 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
651 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
653 // If the target we're compiling for requests a static crt by default,
654 // then see if the `-crt-static` feature was passed to disable that.
655 // Otherwise if we don't have a static crt by default then see if the
656 // `+crt-static` feature was passed.
657 if self.target.target.options.crt_static_default {
664 pub fn target_cpu(&self) -> &str {
665 match self.opts.cg.target_cpu {
667 None => &*self.target.target.options.cpu
671 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
672 if let Some(x) = self.opts.cg.force_frame_pointers {
675 !self.target.target.options.eliminate_frame_pointer
679 /// Returns the symbol name for the registrar function,
680 /// given the crate Svh and the function DefIndex.
681 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
683 "__rustc_plugin_registrar_{}__",
684 disambiguator.to_fingerprint().to_hex()
688 pub fn generate_derive_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
690 "__rustc_derive_registrar_{}__",
691 disambiguator.to_fingerprint().to_hex()
695 pub fn sysroot<'a>(&'a self) -> &'a Path {
696 match self.opts.maybe_sysroot {
697 Some(ref sysroot) => sysroot,
698 None => self.default_sysroot
700 .expect("missing sysroot and default_sysroot in Session"),
703 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
704 filesearch::FileSearch::new(
706 self.opts.target_triple.triple(),
707 &self.opts.search_paths,
711 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
712 filesearch::FileSearch::new(
714 config::host_triple(),
715 &self.opts.search_paths,
720 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
721 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
723 match *incr_comp_session {
724 IncrCompSession::Active {
725 ref mut load_dep_graph,
728 *load_dep_graph = load;
734 pub fn incr_session_load_dep_graph(&self) -> bool {
735 let incr_comp_session = self.incr_comp_session.borrow();
736 match *incr_comp_session {
737 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
742 pub fn init_incr_comp_session(
744 session_dir: PathBuf,
745 lock_file: flock::Lock,
746 load_dep_graph: bool,
748 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
750 if let IncrCompSession::NotInitialized = *incr_comp_session {
753 "Trying to initialize IncrCompSession `{:?}`",
758 *incr_comp_session = IncrCompSession::Active {
759 session_directory: session_dir,
765 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
766 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
768 if let IncrCompSession::Active { .. } = *incr_comp_session {
771 "Trying to finalize IncrCompSession `{:?}`",
776 // Note: This will also drop the lock file, thus unlocking the directory
777 *incr_comp_session = IncrCompSession::Finalized {
778 session_directory: new_directory_path,
782 pub fn mark_incr_comp_session_as_invalid(&self) {
783 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
785 let session_directory = match *incr_comp_session {
786 IncrCompSession::Active {
787 ref session_directory,
789 } => session_directory.clone(),
790 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
792 "Trying to invalidate IncrCompSession `{:?}`",
797 // Note: This will also drop the lock file, thus unlocking the directory
798 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
801 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
802 let incr_comp_session = self.incr_comp_session.borrow();
805 |incr_comp_session| match *incr_comp_session {
806 IncrCompSession::NotInitialized => bug!(
807 "Trying to get session directory from IncrCompSession `{:?}`",
810 IncrCompSession::Active {
811 ref session_directory,
814 | IncrCompSession::Finalized {
815 ref session_directory,
817 | IncrCompSession::InvalidBecauseOfErrors {
818 ref session_directory,
819 } => session_directory,
824 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
825 if self.opts.incremental.is_some() {
826 Some(self.incr_comp_session_dir())
832 pub fn profiler<F: FnOnce(&mut SelfProfiler) -> ()>(&self, f: F) {
833 let mut profiler = self.self_profiling.borrow_mut();
837 pub fn print_profiler_results(&self) {
838 let mut profiler = self.self_profiling.borrow_mut();
839 profiler.print_results(&self.opts);
842 pub fn print_perf_stats(&self) {
844 "Total time spent computing symbol hashes: {}",
845 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
848 "Total time spent decoding DefPath tables: {}",
849 duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
851 println!("Total queries canonicalized: {}",
852 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed));
853 println!("normalize_ty_after_erasing_regions: {}",
854 self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed));
855 println!("normalize_projection_ty: {}",
856 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed));
859 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
860 /// This expends fuel if applicable, and records fuel if applicable.
861 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
863 match self.optimization_fuel_crate {
864 Some(ref c) if c == crate_name => {
865 assert!(self.query_threads() == 1);
866 let fuel = self.optimization_fuel_limit.get();
868 if fuel == 0 && !self.out_of_fuel.get() {
869 println!("optimization-fuel-exhausted: {}", msg());
870 self.out_of_fuel.set(true);
872 self.optimization_fuel_limit.set(fuel - 1);
877 match self.print_fuel_crate {
878 Some(ref c) if c == crate_name => {
879 assert!(self.query_threads() == 1);
880 self.print_fuel.set(self.print_fuel.get() + 1);
887 /// Returns the number of query threads that should be used for this
889 pub fn query_threads_from_opts(opts: &config::Options) -> usize {
890 opts.debugging_opts.query_threads.unwrap_or(1)
893 /// Returns the number of query threads that should be used for this
895 pub fn query_threads(&self) -> usize {
896 Self::query_threads_from_opts(&self.opts)
899 /// Returns the number of codegen units that should be used for this
901 pub fn codegen_units(&self) -> usize {
902 if let Some(n) = self.opts.cli_forced_codegen_units {
905 if let Some(n) = self.target.target.options.default_codegen_units {
909 // Why is 16 codegen units the default all the time?
911 // The main reason for enabling multiple codegen units by default is to
912 // leverage the ability for the codegen backend to do codegen and
913 // optimization in parallel. This allows us, especially for large crates, to
914 // make good use of all available resources on the machine once we've
915 // hit that stage of compilation. Large crates especially then often
916 // take a long time in codegen/optimization and this helps us amortize that
919 // Note that a high number here doesn't mean that we'll be spawning a
920 // large number of threads in parallel. The backend of rustc contains
921 // global rate limiting through the `jobserver` crate so we'll never
922 // overload the system with too much work, but rather we'll only be
923 // optimizing when we're otherwise cooperating with other instances of
926 // Rather a high number here means that we should be able to keep a lot
927 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
928 // to build we'll be guaranteed that all cpus will finish pretty closely
929 // to one another and we should make relatively optimal use of system
932 // Note that the main cost of codegen units is that it prevents LLVM
933 // from inlining across codegen units. Users in general don't have a lot
934 // of control over how codegen units are split up so it's our job in the
935 // compiler to ensure that undue performance isn't lost when using
936 // codegen units (aka we can't require everyone to slap `#[inline]` on
939 // If we're compiling at `-O0` then the number doesn't really matter too
940 // much because performance doesn't matter and inlining is ok to lose.
941 // In debug mode we just want to try to guarantee that no cpu is stuck
942 // doing work that could otherwise be farmed to others.
944 // In release mode, however (O1 and above) performance does indeed
945 // matter! To recover the loss in performance due to inlining we'll be
946 // enabling ThinLTO by default (the function for which is just below).
947 // This will ensure that we recover any inlining wins we otherwise lost
948 // through codegen unit partitioning.
952 // Ok that's a lot of words but the basic tl;dr; is that we want a high
953 // number here -- but not too high. Additionally we're "safe" to have it
954 // always at the same number at all optimization levels.
956 // As a result 16 was chosen here! Mostly because it was a power of 2
957 // and most benchmarks agreed it was roughly a local optimum. Not very
962 pub fn teach(&self, code: &DiagnosticId) -> bool {
963 self.opts.debugging_opts.teach && self.parse_sess.span_diagnostic.must_teach(code)
966 /// Are we allowed to use features from the Rust 2018 edition?
967 pub fn rust_2018(&self) -> bool {
968 self.opts.edition >= Edition::Edition2018
971 pub fn edition(&self) -> Edition {
976 pub fn build_session(
977 sopts: config::Options,
978 local_crate_source_file: Option<PathBuf>,
979 registry: errors::registry::Registry,
981 let file_path_mapping = sopts.file_path_mapping();
983 build_session_with_codemap(
985 local_crate_source_file,
987 Lrc::new(codemap::CodeMap::new(file_path_mapping)),
992 pub fn build_session_with_codemap(
993 sopts: config::Options,
994 local_crate_source_file: Option<PathBuf>,
995 registry: errors::registry::Registry,
996 codemap: Lrc<codemap::CodeMap>,
997 emitter_dest: Option<Box<dyn Write + Send>>,
999 // FIXME: This is not general enough to make the warning lint completely override
1000 // normal diagnostic warnings, since the warning lint can also be denied and changed
1001 // later via the source code.
1002 let warnings_allow = sopts
1005 .filter(|&&(ref key, _)| *key == "warnings")
1006 .map(|&(_, ref level)| *level == lint::Allow)
1009 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1011 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1013 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
1014 let report_delayed_bugs = sopts.debugging_opts.report_delayed_bugs;
1016 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
1018 let emitter: Box<dyn Emitter + sync::Send> =
1019 match (sopts.error_format, emitter_dest) {
1020 (config::ErrorOutputType::HumanReadable(color_config), None) => Box::new(
1021 EmitterWriter::stderr(
1023 Some(codemap.clone()),
1025 sopts.debugging_opts.teach,
1026 ).ui_testing(sopts.debugging_opts.ui_testing),
1028 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => Box::new(
1029 EmitterWriter::new(dst, Some(codemap.clone()), false, false)
1030 .ui_testing(sopts.debugging_opts.ui_testing),
1032 (config::ErrorOutputType::Json(pretty), None) => Box::new(
1033 JsonEmitter::stderr(
1037 ).ui_testing(sopts.debugging_opts.ui_testing),
1039 (config::ErrorOutputType::Json(pretty), Some(dst)) => Box::new(
1045 ).ui_testing(sopts.debugging_opts.ui_testing),
1047 (config::ErrorOutputType::Short(color_config), None) => Box::new(
1048 EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false),
1050 (config::ErrorOutputType::Short(_), Some(dst)) => {
1051 Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
1055 let diagnostic_handler = errors::Handler::with_emitter_and_flags(
1057 errors::HandlerFlags {
1060 report_delayed_bugs,
1061 external_macro_backtrace,
1062 ..Default::default()
1066 build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap)
1069 pub fn build_session_(
1070 sopts: config::Options,
1071 local_crate_source_file: Option<PathBuf>,
1072 span_diagnostic: errors::Handler,
1073 codemap: Lrc<codemap::CodeMap>,
1075 let host_triple = TargetTriple::from_triple(config::host_triple());
1076 let host = match Target::search(&host_triple) {
1080 .fatal(&format!("Error loading host specification: {}", e))
1084 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
1086 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
1087 let default_sysroot = match sopts.maybe_sysroot {
1089 None => Some(filesearch::get_or_default_sysroot()),
1092 let file_path_mapping = sopts.file_path_mapping();
1094 let local_crate_source_file =
1095 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1097 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1098 let optimization_fuel_limit =
1099 LockCell::new(sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0));
1100 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1101 let print_fuel = LockCell::new(0);
1103 let working_dir = match env::current_dir() {
1105 Err(e) => p_s.span_diagnostic
1106 .fatal(&format!("Current directory is invalid: {}", e))
1109 let working_dir = file_path_mapping.map_prefix(working_dir);
1111 let sess = Session {
1116 // For a library crate, this is always none
1117 entry_fn: Once::new(),
1118 plugin_registrar_fn: Once::new(),
1119 derive_registrar_fn: Once::new(),
1121 local_crate_source_file,
1123 lint_store: RwLock::new(lint::LintStore::new()),
1124 buffered_lints: Lock::new(Some(lint::LintBuffer::new())),
1125 one_time_diagnostics: Lock::new(FxHashSet()),
1126 plugin_llvm_passes: OneThread::new(RefCell::new(Vec::new())),
1127 plugin_attributes: OneThread::new(RefCell::new(Vec::new())),
1128 crate_types: Once::new(),
1129 dependency_formats: Once::new(),
1130 crate_disambiguator: Once::new(),
1131 features: Once::new(),
1132 recursion_limit: Once::new(),
1133 type_length_limit: Once::new(),
1134 const_eval_stack_frame_limit: 100,
1135 next_node_id: OneThread::new(Cell::new(NodeId::new(1))),
1136 injected_allocator: Once::new(),
1137 allocator_kind: Once::new(),
1138 injected_panic_runtime: Once::new(),
1139 imported_macro_spans: OneThread::new(RefCell::new(HashMap::new())),
1140 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1141 ignored_attr_names: ich::compute_ignored_attr_names(),
1142 self_profiling: Lock::new(SelfProfiler::new()),
1143 profile_channel: Lock::new(None),
1144 perf_stats: PerfStats {
1145 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1146 decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1147 queries_canonicalized: AtomicUsize::new(0),
1148 normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1149 normalize_projection_ty: AtomicUsize::new(0),
1151 code_stats: Lock::new(CodeStats::new()),
1152 optimization_fuel_crate,
1153 optimization_fuel_limit,
1156 out_of_fuel: LockCell::new(false),
1157 // Note that this is unsafe because it may misinterpret file descriptors
1158 // on Unix as jobserver file descriptors. We hopefully execute this near
1159 // the beginning of the process though to ensure we don't get false
1160 // positives, or in other words we try to execute this before we open
1161 // any file descriptors ourselves.
1163 // Pick a "reasonable maximum" if we don't otherwise have
1164 // a jobserver in our environment, capping out at 32 so we
1165 // don't take everything down by hogging the process run queue.
1166 // The fixed number is used to have deterministic compilation
1169 // Also note that we stick this in a global because there could be
1170 // multiple `Session` instances in this process, and the jobserver is
1173 static mut GLOBAL_JOBSERVER: *mut Client = 0 as *mut _;
1174 static INIT: std::sync::Once = std::sync::ONCE_INIT;
1176 let client = Client::from_env().unwrap_or_else(|| {
1177 Client::new(32).expect("failed to create jobserver")
1179 GLOBAL_JOBSERVER = Box::into_raw(Box::new(client));
1181 (*GLOBAL_JOBSERVER).clone()
1183 has_global_allocator: Once::new(),
1184 driver_lint_caps: FxHashMap(),
1190 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1191 /// compiler. Together with the crate-name forms a unique global identifier for
1193 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1194 pub struct CrateDisambiguator(Fingerprint);
1196 impl CrateDisambiguator {
1197 pub fn to_fingerprint(self) -> Fingerprint {
1202 impl From<Fingerprint> for CrateDisambiguator {
1203 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1204 CrateDisambiguator(fingerprint)
1208 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1210 /// Holds data on the current incremental compilation session, if there is one.
1212 pub enum IncrCompSession {
1213 /// This is the state the session will be in until the incr. comp. dir is
1216 /// This is the state during which the session directory is private and can
1219 session_directory: PathBuf,
1220 lock_file: flock::Lock,
1221 load_dep_graph: bool,
1223 /// This is the state after the session directory has been finalized. In this
1224 /// state, the contents of the directory must not be modified any more.
1225 Finalized { session_directory: PathBuf },
1226 /// This is an error state that is reached when some compilation error has
1227 /// occurred. It indicates that the contents of the session directory must
1228 /// not be used, since they might be invalid.
1229 InvalidBecauseOfErrors { session_directory: PathBuf },
1232 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1233 let emitter: Box<dyn Emitter + sync::Send> = match output {
1234 config::ErrorOutputType::HumanReadable(color_config) => {
1235 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1237 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1238 config::ErrorOutputType::Short(color_config) => {
1239 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1242 let handler = errors::Handler::with_emitter(true, false, emitter);
1243 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1244 errors::FatalError.raise();
1247 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1248 let emitter: Box<dyn Emitter + sync::Send> = match output {
1249 config::ErrorOutputType::HumanReadable(color_config) => {
1250 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1252 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1253 config::ErrorOutputType::Short(color_config) => {
1254 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1257 let handler = errors::Handler::with_emitter(true, false, emitter);
1258 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1261 #[derive(Copy, Clone, Debug)]
1262 pub enum CompileIncomplete {
1264 Errored(ErrorReported),
1266 impl From<ErrorReported> for CompileIncomplete {
1267 fn from(err: ErrorReported) -> CompileIncomplete {
1268 CompileIncomplete::Errored(err)
1271 pub type CompileResult = Result<(), CompileIncomplete>;
1273 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1277 Err(CompileIncomplete::Errored(ErrorReported))
1283 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1284 // this wrapper mostly exists so I don't have to write a fully
1285 // qualified path of None::<Span> inside the bug!() macro definition
1286 opt_span_bug_fmt(file, line, None::<Span>, args);
1291 pub fn span_bug_fmt<S: Into<MultiSpan>>(
1295 args: fmt::Arguments,
1297 opt_span_bug_fmt(file, line, Some(span), args);
1300 fn opt_span_bug_fmt<S: Into<MultiSpan>>(
1304 args: fmt::Arguments,
1306 tls::with_opt(move |tcx| {
1307 let msg = format!("{}:{}: {}", file, line, args);
1309 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1310 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1311 (None, _) => panic!(msg),