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::{BorrowckMode, DebugInfoLevel, OutputType, Epoch};
25 use util::nodemap::{FxHashMap, FxHashSet};
26 use util::common::{duration_to_secs_str, ErrorReported};
28 use rustc_data_structures::sync::Lrc;
30 use syntax::ast::NodeId;
31 use errors::{self, DiagnosticBuilder, DiagnosticId};
32 use errors::emitter::{Emitter, EmitterWriter};
33 use syntax::json::JsonEmitter;
34 use syntax::feature_gate;
35 use syntax::symbol::Symbol;
37 use syntax::parse::ParseSess;
38 use syntax::{ast, codemap};
39 use syntax::feature_gate::AttributeType;
40 use syntax_pos::{Span, MultiSpan};
42 use rustc_back::{LinkerFlavor, PanicStrategy};
43 use rustc_back::target::Target;
44 use rustc_data_structures::flock;
45 use jobserver::Client;
47 use std::cell::{self, Cell, RefCell};
48 use std::collections::HashMap;
52 use std::path::{Path, PathBuf};
53 use std::sync::{Once, ONCE_INIT};
54 use std::time::Duration;
61 /// Represents the data associated with a compilation
62 /// session for a single crate.
64 pub target: config::Config,
66 pub opts: config::Options,
67 pub parse_sess: ParseSess,
68 /// For a library crate, this is always none
69 pub entry_fn: RefCell<Option<(NodeId, Span)>>,
70 pub entry_type: Cell<Option<config::EntryFnType>>,
71 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
72 pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
73 pub default_sysroot: Option<PathBuf>,
74 /// The name of the root source file of the crate, in the local file system.
75 /// `None` means that there is no source file.
76 pub local_crate_source_file: Option<PathBuf>,
77 /// The directory the compiler has been executed in plus a flag indicating
78 /// if the value stored here has been affected by path remapping.
79 pub working_dir: (PathBuf, bool),
80 pub lint_store: RefCell<lint::LintStore>,
81 pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
82 /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
83 /// (sub)diagnostics that have been set once, but should not be set again,
84 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
85 pub one_time_diagnostics: RefCell<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
86 pub plugin_llvm_passes: RefCell<Vec<String>>,
87 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
88 pub crate_types: RefCell<Vec<config::CrateType>>,
89 pub dependency_formats: RefCell<dependency_format::Dependencies>,
90 /// The crate_disambiguator is constructed out of all the `-C metadata`
91 /// arguments passed to the compiler. Its value together with the crate-name
92 /// forms a unique global identifier for the crate. It is used to allow
93 /// multiple crates with the same name to coexist. See the
94 /// trans::back::symbol_names module for more information.
95 pub crate_disambiguator: RefCell<Option<CrateDisambiguator>>,
96 pub features: RefCell<feature_gate::Features>,
98 /// The maximum recursion limit for potentially infinitely recursive
99 /// operations such as auto-dereference and monomorphization.
100 pub recursion_limit: Cell<usize>,
102 /// The maximum length of types during monomorphization.
103 pub type_length_limit: Cell<usize>,
105 /// The metadata::creader module may inject an allocator/panic_runtime
106 /// dependency if it didn't already find one, and this tracks what was
108 pub injected_allocator: Cell<Option<CrateNum>>,
109 pub allocator_kind: Cell<Option<AllocatorKind>>,
110 pub injected_panic_runtime: Cell<Option<CrateNum>>,
112 /// Map from imported macro spans (which consist of
113 /// the localized span for the macro body) to the
114 /// macro name and definition span in the source crate.
115 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
117 incr_comp_session: RefCell<IncrCompSession>,
119 /// A cache of attributes ignored by StableHashingContext
120 pub ignored_attr_names: FxHashSet<Symbol>,
122 /// Some measurements that are being gathered during compilation.
123 pub perf_stats: PerfStats,
125 /// Data about code being compiled, gathered during compilation.
126 pub code_stats: RefCell<CodeStats>,
128 next_node_id: Cell<ast::NodeId>,
130 /// If -zfuel=crate=n is specified, Some(crate).
131 optimization_fuel_crate: Option<String>,
132 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
133 optimization_fuel_limit: Cell<u64>,
134 /// We're rejecting all further optimizations.
135 out_of_fuel: Cell<bool>,
137 // The next two are public because the driver needs to read them.
139 /// If -zprint-fuel=crate, Some(crate).
140 pub print_fuel_crate: Option<String>,
141 /// Always set to zero and incremented so that we can print fuel expended by a crate.
142 pub print_fuel: Cell<u64>,
144 /// Loaded up early on in the initialization of this `Session` to avoid
145 /// false positives about a job server in our environment.
146 pub jobserver_from_env: Option<Client>,
148 /// Metadata about the allocators for the current crate being compiled
149 pub has_global_allocator: Cell<bool>,
152 pub struct PerfStats {
153 /// The accumulated time needed for computing the SVH of the crate
154 pub svh_time: Cell<Duration>,
155 /// The accumulated time spent on computing incr. comp. hashes
156 pub incr_comp_hashes_time: Cell<Duration>,
157 /// The number of incr. comp. hash computations performed
158 pub incr_comp_hashes_count: Cell<u64>,
159 /// The number of bytes hashed when computing ICH values
160 pub incr_comp_bytes_hashed: Cell<u64>,
161 /// The accumulated time spent on computing symbol hashes
162 pub symbol_hash_time: Cell<Duration>,
163 /// The accumulated time spent decoding def path tables from metadata
164 pub decode_def_path_tables_time: Cell<Duration>,
167 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
168 enum DiagnosticBuilderMethod {
171 SpanSuggestion(String), // suggestion
172 // add more variants as needed to support one-time diagnostics
175 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
176 /// emitting the same message more than once
177 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
178 pub enum DiagnosticMessageId {
179 ErrorId(u16), // EXXXX error code as integer
180 LintId(lint::LintId),
181 StabilityId(u32) // issue number
184 impl From<&'static lint::Lint> for DiagnosticMessageId {
185 fn from(lint: &'static lint::Lint) -> Self {
186 DiagnosticMessageId::LintId(lint::LintId::of(lint))
191 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
192 match *self.crate_disambiguator.borrow() {
193 Some(value) => value,
194 None => bug!("accessing disambiguator before initialization"),
197 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
200 -> DiagnosticBuilder<'a> {
201 self.diagnostic().struct_span_warn(sp, msg)
203 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
207 -> DiagnosticBuilder<'a> {
208 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
210 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
211 self.diagnostic().struct_warn(msg)
213 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
216 -> DiagnosticBuilder<'a> {
217 self.diagnostic().struct_span_err(sp, msg)
219 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
223 -> DiagnosticBuilder<'a> {
224 self.diagnostic().struct_span_err_with_code(sp, msg, code)
226 // FIXME: This method should be removed (every error should have an associated error code).
227 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
228 self.diagnostic().struct_err(msg)
230 pub fn struct_err_with_code<'a>(
234 ) -> DiagnosticBuilder<'a> {
235 self.diagnostic().struct_err_with_code(msg, code)
237 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
240 -> DiagnosticBuilder<'a> {
241 self.diagnostic().struct_span_fatal(sp, msg)
243 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
247 -> DiagnosticBuilder<'a> {
248 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
250 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
251 self.diagnostic().struct_fatal(msg)
254 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
255 self.diagnostic().span_fatal(sp, msg).raise()
257 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
263 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
265 pub fn fatal(&self, msg: &str) -> ! {
266 self.diagnostic().fatal(msg).raise()
268 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
270 self.span_warn(sp, msg);
272 self.span_err(sp, msg);
275 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
276 self.diagnostic().span_err(sp, msg)
278 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
279 self.diagnostic().span_err_with_code(sp, &msg, code)
281 pub fn err(&self, msg: &str) {
282 self.diagnostic().err(msg)
284 pub fn err_count(&self) -> usize {
285 self.diagnostic().err_count()
287 pub fn has_errors(&self) -> bool {
288 self.diagnostic().has_errors()
290 pub fn abort_if_errors(&self) {
291 self.diagnostic().abort_if_errors();
293 pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
294 compile_result_from_err_count(self.err_count())
296 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
297 where F: FnOnce() -> T
299 let old_count = self.err_count();
301 let errors = self.err_count() - old_count;
308 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
309 self.diagnostic().span_warn(sp, msg)
311 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
312 self.diagnostic().span_warn_with_code(sp, msg, code)
314 pub fn warn(&self, msg: &str) {
315 self.diagnostic().warn(msg)
317 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
319 Some(sp) => self.span_warn(sp, msg),
320 None => self.warn(msg),
323 /// Delay a span_bug() call until abort_if_errors()
324 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
325 self.diagnostic().delay_span_bug(sp, msg)
327 pub fn note_without_error(&self, msg: &str) {
328 self.diagnostic().note_without_error(msg)
330 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
331 self.diagnostic().span_note_without_error(sp, msg)
333 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
334 self.diagnostic().span_unimpl(sp, msg)
336 pub fn unimpl(&self, msg: &str) -> ! {
337 self.diagnostic().unimpl(msg)
340 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
341 lint: &'static lint::Lint,
345 match *self.buffered_lints.borrow_mut() {
346 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
347 msg, BuiltinLintDiagnostics::Normal),
348 None => bug!("can't buffer lints after HIR lowering"),
352 pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(&self,
353 lint: &'static lint::Lint, id: ast::NodeId, sp: S,
354 msg: &str, diagnostic: BuiltinLintDiagnostics) {
355 match *self.buffered_lints.borrow_mut() {
356 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
358 None => bug!("can't buffer lints after HIR lowering"),
362 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
363 let id = self.next_node_id.get();
365 match id.as_usize().checked_add(count) {
367 self.next_node_id.set(ast::NodeId::new(next));
369 None => bug!("Input too large, ran out of node ids!")
374 pub fn next_node_id(&self) -> NodeId {
375 self.reserve_node_ids(1)
377 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
378 &self.parse_sess.span_diagnostic
381 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
382 /// deduplicates on lint ID, span (if any), and message for this `Session`
383 fn diag_once<'a, 'b>(&'a self,
384 diag_builder: &'b mut DiagnosticBuilder<'a>,
385 method: DiagnosticBuilderMethod,
386 msg_id: DiagnosticMessageId,
388 span_maybe: Option<Span>) {
390 let id_span_message = (msg_id, span_maybe, message.to_owned());
391 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
394 DiagnosticBuilderMethod::Note => {
395 diag_builder.note(message);
397 DiagnosticBuilderMethod::SpanNote => {
398 let span = span_maybe.expect("span_note needs a span");
399 diag_builder.span_note(span, message);
401 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
402 let span = span_maybe.expect("span_suggestion needs a span");
403 diag_builder.span_suggestion(span, message, suggestion);
409 pub fn diag_span_note_once<'a, 'b>(&'a self,
410 diag_builder: &'b mut DiagnosticBuilder<'a>,
411 msg_id: DiagnosticMessageId, span: Span, message: &str) {
412 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote,
413 msg_id, message, Some(span));
416 pub fn diag_note_once<'a, 'b>(&'a self,
417 diag_builder: &'b mut DiagnosticBuilder<'a>,
418 msg_id: DiagnosticMessageId, message: &str) {
419 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
422 pub fn diag_span_suggestion_once<'a, 'b>(&'a self,
423 diag_builder: &'b mut DiagnosticBuilder<'a>,
424 msg_id: DiagnosticMessageId,
427 suggestion: String) {
428 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanSuggestion(suggestion),
429 msg_id, message, Some(span));
432 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
433 self.parse_sess.codemap()
435 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
436 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
437 pub fn profile_queries(&self) -> bool {
438 self.opts.debugging_opts.profile_queries ||
439 self.opts.debugging_opts.profile_queries_and_keys
441 pub fn profile_queries_and_keys(&self) -> bool {
442 self.opts.debugging_opts.profile_queries_and_keys
444 pub fn count_llvm_insns(&self) -> bool {
445 self.opts.debugging_opts.count_llvm_insns
447 pub fn time_llvm_passes(&self) -> bool {
448 self.opts.debugging_opts.time_llvm_passes
450 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
451 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
452 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
453 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
454 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
455 pub fn print_llvm_passes(&self) -> bool {
456 self.opts.debugging_opts.print_llvm_passes
459 /// If true, we should use NLL-style region checking instead of
461 pub fn nll(&self) -> bool {
462 self.features.borrow().nll || self.opts.debugging_opts.nll
465 /// If true, we should use the MIR-based borrowck (we may *also* use
466 /// the AST-based borrowck).
467 pub fn use_mir(&self) -> bool {
468 self.borrowck_mode().use_mir()
471 /// If true, we should gather causal information during NLL
472 /// checking. This will eventually be the normal thing, but right
473 /// now it is too unoptimized.
474 pub fn nll_dump_cause(&self) -> bool {
475 self.opts.debugging_opts.nll_dump_cause
478 /// If true, we should enable two-phase borrows checks. This is
479 /// done with either `-Ztwo-phase-borrows` or with
480 /// `#![feature(nll)]`.
481 pub fn two_phase_borrows(&self) -> bool {
482 self.features.borrow().nll || self.opts.debugging_opts.two_phase_borrows
485 /// What mode(s) of borrowck should we run? AST? MIR? both?
486 /// (Also considers the `#![feature(nll)]` setting.)
487 pub fn borrowck_mode(&self) -> BorrowckMode {
488 match self.opts.borrowck_mode {
489 mode @ BorrowckMode::Mir |
490 mode @ BorrowckMode::Compare => mode,
492 mode @ BorrowckMode::Ast => {
503 /// Should we emit EndRegion MIR statements? These are consumed by
504 /// MIR borrowck, but not when NLL is used. They are also consumed
505 /// by the validation stuff.
506 pub fn emit_end_regions(&self) -> bool {
507 // FIXME(#46875) -- we should not emit end regions when NLL is enabled,
508 // but for now we can't stop doing so because it causes false positives
509 self.opts.debugging_opts.emit_end_regions ||
510 self.opts.debugging_opts.mir_emit_validate > 0 ||
514 /// Calculates the flavor of LTO to use for this compilation.
515 pub fn lto(&self) -> config::Lto {
516 // If our target has codegen requirements ignore the command line
517 if self.target.target.options.requires_lto {
518 return config::Lto::Fat
521 // If the user specified something, return that. If they only said `-C
522 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
523 // then ensure we can't use a ThinLTO.
524 match self.opts.cg.lto {
525 config::Lto::No => {}
526 config::Lto::Yes if self.opts.cli_forced_thinlto_off => {
527 return config::Lto::Fat
529 other => return other,
532 // Ok at this point the target doesn't require anything and the user
533 // hasn't asked for anything. Our next decision is whether or not
534 // we enable "auto" ThinLTO where we use multiple codegen units and
535 // then do ThinLTO over those codegen units. The logic below will
536 // either return `No` or `ThinLocal`.
538 // If processing command line options determined that we're incompatible
539 // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
540 if self.opts.cli_forced_thinlto_off {
541 return config::Lto::No
544 // If `-Z thinlto` specified process that, but note that this is mostly
545 // a deprecated option now that `-C lto=thin` exists.
546 if let Some(enabled) = self.opts.debugging_opts.thinlto {
548 return config::Lto::ThinLocal
550 return config::Lto::No
554 // If there's only one codegen unit and LTO isn't enabled then there's
555 // no need for ThinLTO so just return false.
556 if self.codegen_units() == 1 {
557 return config::Lto::No
560 // Right now ThinLTO isn't compatible with incremental compilation.
561 if self.opts.incremental.is_some() {
562 return config::Lto::No
565 // Now we're in "defaults" territory. By default we enable ThinLTO for
566 // optimized compiles (anything greater than O0).
567 match self.opts.optimize {
568 config::OptLevel::No => config::Lto::No,
569 _ => config::Lto::ThinLocal,
573 /// Returns the panic strategy for this compile session. If the user explicitly selected one
574 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
575 pub fn panic_strategy(&self) -> PanicStrategy {
576 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
578 pub fn linker_flavor(&self) -> LinkerFlavor {
579 self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
582 pub fn fewer_names(&self) -> bool {
583 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly) ||
584 self.opts.output_types.contains_key(&OutputType::Bitcode);
585 self.opts.debugging_opts.fewer_names || !more_names
588 pub fn no_landing_pads(&self) -> bool {
589 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
591 pub fn unstable_options(&self) -> bool {
592 self.opts.debugging_opts.unstable_options
594 pub fn nonzeroing_move_hints(&self) -> bool {
595 self.opts.debugging_opts.enable_nonzeroing_move_hints
597 pub fn overflow_checks(&self) -> bool {
598 self.opts.cg.overflow_checks
599 .or(self.opts.debugging_opts.force_overflow_checks)
600 .unwrap_or(self.opts.debug_assertions)
603 pub fn crt_static(&self) -> bool {
604 // If the target does not opt in to crt-static support, use its default.
605 if self.target.target.options.crt_static_respected {
606 self.crt_static_feature()
608 self.target.target.options.crt_static_default
612 pub fn crt_static_feature(&self) -> bool {
613 let requested_features = self.opts.cg.target_feature.split(',');
614 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
615 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
617 // If the target we're compiling for requests a static crt by default,
618 // then see if the `-crt-static` feature was passed to disable that.
619 // Otherwise if we don't have a static crt by default then see if the
620 // `+crt-static` feature was passed.
621 if self.target.target.options.crt_static_default {
628 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
629 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
630 !self.target.target.options.eliminate_frame_pointer
633 /// Returns the symbol name for the registrar function,
634 /// given the crate Svh and the function DefIndex.
635 pub fn generate_plugin_registrar_symbol(&self,
636 disambiguator: CrateDisambiguator)
638 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
641 pub fn generate_derive_registrar_symbol(&self,
642 disambiguator: CrateDisambiguator)
644 format!("__rustc_derive_registrar_{}__", disambiguator.to_fingerprint().to_hex())
647 pub fn sysroot<'a>(&'a self) -> &'a Path {
648 match self.opts.maybe_sysroot {
649 Some (ref sysroot) => sysroot,
650 None => self.default_sysroot.as_ref()
651 .expect("missing sysroot and default_sysroot in Session")
654 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
655 filesearch::FileSearch::new(self.sysroot(),
656 &self.opts.target_triple,
657 &self.opts.search_paths,
660 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
661 filesearch::FileSearch::new(
663 config::host_triple(),
664 &self.opts.search_paths,
668 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
669 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
671 match *incr_comp_session {
672 IncrCompSession::Active { ref mut load_dep_graph, .. } => {
673 *load_dep_graph = load;
679 pub fn incr_session_load_dep_graph(&self) -> bool {
680 let incr_comp_session = self.incr_comp_session.borrow();
681 match *incr_comp_session {
682 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
687 pub fn init_incr_comp_session(&self,
688 session_dir: PathBuf,
689 lock_file: flock::Lock,
690 load_dep_graph: bool) {
691 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
693 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
694 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
697 *incr_comp_session = IncrCompSession::Active {
698 session_directory: session_dir,
704 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
705 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
707 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
708 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
711 // Note: This will also drop the lock file, thus unlocking the directory
712 *incr_comp_session = IncrCompSession::Finalized {
713 session_directory: new_directory_path,
717 pub fn mark_incr_comp_session_as_invalid(&self) {
718 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
720 let session_directory = match *incr_comp_session {
721 IncrCompSession::Active { ref session_directory, .. } => {
722 session_directory.clone()
724 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
725 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
729 // Note: This will also drop the lock file, thus unlocking the directory
730 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
735 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
736 let incr_comp_session = self.incr_comp_session.borrow();
737 cell::Ref::map(incr_comp_session, |incr_comp_session| {
738 match *incr_comp_session {
739 IncrCompSession::NotInitialized => {
740 bug!("Trying to get session directory from IncrCompSession `{:?}`",
743 IncrCompSession::Active { ref session_directory, .. } |
744 IncrCompSession::Finalized { ref session_directory } |
745 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
752 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
753 if self.opts.incremental.is_some() {
754 Some(self.incr_comp_session_dir())
760 pub fn print_perf_stats(&self) {
761 println!("Total time spent computing SVHs: {}",
762 duration_to_secs_str(self.perf_stats.svh_time.get()));
763 println!("Total time spent computing incr. comp. hashes: {}",
764 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
765 println!("Total number of incr. comp. hashes computed: {}",
766 self.perf_stats.incr_comp_hashes_count.get());
767 println!("Total number of bytes hashed for incr. comp.: {}",
768 self.perf_stats.incr_comp_bytes_hashed.get());
769 if self.perf_stats.incr_comp_hashes_count.get() != 0 {
770 println!("Average bytes hashed per incr. comp. HIR node: {}",
771 self.perf_stats.incr_comp_bytes_hashed.get() /
772 self.perf_stats.incr_comp_hashes_count.get());
774 println!("Average bytes hashed per incr. comp. HIR node: N/A");
776 println!("Total time spent computing symbol hashes: {}",
777 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
778 println!("Total time spent decoding DefPath tables: {}",
779 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
782 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
783 /// This expends fuel if applicable, and records fuel if applicable.
784 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
786 match self.optimization_fuel_crate {
787 Some(ref c) if c == crate_name => {
788 let fuel = self.optimization_fuel_limit.get();
790 if fuel == 0 && !self.out_of_fuel.get() {
791 println!("optimization-fuel-exhausted: {}", msg());
792 self.out_of_fuel.set(true);
794 self.optimization_fuel_limit.set(fuel-1);
799 match self.print_fuel_crate {
800 Some(ref c) if c == crate_name=> {
801 self.print_fuel.set(self.print_fuel.get()+1);
808 /// Returns the number of query threads that should be used for this
810 pub fn query_threads(&self) -> usize {
811 self.opts.debugging_opts.query_threads.unwrap_or(1)
814 /// Returns the number of codegen units that should be used for this
816 pub fn codegen_units(&self) -> usize {
817 if let Some(n) = self.opts.cli_forced_codegen_units {
820 if let Some(n) = self.target.target.options.default_codegen_units {
824 // Why is 16 codegen units the default all the time?
826 // The main reason for enabling multiple codegen units by default is to
827 // leverage the ability for the trans backend to do translation and
828 // codegen in parallel. This allows us, especially for large crates, to
829 // make good use of all available resources on the machine once we've
830 // hit that stage of compilation. Large crates especially then often
831 // take a long time in trans/codegen and this helps us amortize that
834 // Note that a high number here doesn't mean that we'll be spawning a
835 // large number of threads in parallel. The backend of rustc contains
836 // global rate limiting through the `jobserver` crate so we'll never
837 // overload the system with too much work, but rather we'll only be
838 // optimizing when we're otherwise cooperating with other instances of
841 // Rather a high number here means that we should be able to keep a lot
842 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
843 // to build we'll be guaranteed that all cpus will finish pretty closely
844 // to one another and we should make relatively optimal use of system
847 // Note that the main cost of codegen units is that it prevents LLVM
848 // from inlining across codegen units. Users in general don't have a lot
849 // of control over how codegen units are split up so it's our job in the
850 // compiler to ensure that undue performance isn't lost when using
851 // codegen units (aka we can't require everyone to slap `#[inline]` on
854 // If we're compiling at `-O0` then the number doesn't really matter too
855 // much because performance doesn't matter and inlining is ok to lose.
856 // In debug mode we just want to try to guarantee that no cpu is stuck
857 // doing work that could otherwise be farmed to others.
859 // In release mode, however (O1 and above) performance does indeed
860 // matter! To recover the loss in performance due to inlining we'll be
861 // enabling ThinLTO by default (the function for which is just below).
862 // This will ensure that we recover any inlining wins we otherwise lost
863 // through codegen unit partitioning.
867 // Ok that's a lot of words but the basic tl;dr; is that we want a high
868 // number here -- but not too high. Additionally we're "safe" to have it
869 // always at the same number at all optimization levels.
871 // As a result 16 was chosen here! Mostly because it was a power of 2
872 // and most benchmarks agreed it was roughly a local optimum. Not very
877 pub fn teach(&self, code: &DiagnosticId) -> bool {
878 self.opts.debugging_opts.teach && !self.parse_sess.span_diagnostic.code_emitted(code)
881 /// Are we allowed to use features from the Rust 2018 epoch?
882 pub fn rust_2018(&self) -> bool {
883 self.opts.debugging_opts.epoch >= Epoch::Epoch2018
886 pub fn epoch(&self) -> Epoch {
887 self.opts.debugging_opts.epoch
891 pub fn build_session(sopts: config::Options,
892 local_crate_source_file: Option<PathBuf>,
893 registry: errors::registry::Registry)
895 let file_path_mapping = sopts.file_path_mapping();
897 build_session_with_codemap(sopts,
898 local_crate_source_file,
900 Lrc::new(codemap::CodeMap::new(file_path_mapping)),
904 pub fn build_session_with_codemap(sopts: config::Options,
905 local_crate_source_file: Option<PathBuf>,
906 registry: errors::registry::Registry,
907 codemap: Lrc<codemap::CodeMap>,
908 emitter_dest: Option<Box<dyn Write + Send>>)
910 // FIXME: This is not general enough to make the warning lint completely override
911 // normal diagnostic warnings, since the warning lint can also be denied and changed
912 // later via the source code.
913 let warnings_allow = sopts.lint_opts
915 .filter(|&&(ref key, _)| *key == "warnings")
916 .map(|&(_, ref level)| *level == lint::Allow)
919 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
921 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
923 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
925 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
927 let emitter: Box<dyn Emitter> = match (sopts.error_format, emitter_dest) {
928 (config::ErrorOutputType::HumanReadable(color_config), None) => {
929 Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()),
930 false, sopts.debugging_opts.teach)
931 .ui_testing(sopts.debugging_opts.ui_testing))
933 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
934 Box::new(EmitterWriter::new(dst, Some(codemap.clone()),
936 .ui_testing(sopts.debugging_opts.ui_testing))
938 (config::ErrorOutputType::Json(pretty), None) => {
939 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone(),
940 pretty, sopts.debugging_opts.approximate_suggestions)
941 .ui_testing(sopts.debugging_opts.ui_testing))
943 (config::ErrorOutputType::Json(pretty), Some(dst)) => {
944 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone(),
945 pretty, sopts.debugging_opts.approximate_suggestions)
946 .ui_testing(sopts.debugging_opts.ui_testing))
948 (config::ErrorOutputType::Short(color_config), None) => {
949 Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false))
951 (config::ErrorOutputType::Short(_), Some(dst)) => {
952 Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
956 let diagnostic_handler =
957 errors::Handler::with_emitter_and_flags(
959 errors::HandlerFlags {
962 external_macro_backtrace,
963 .. Default::default()
966 build_session_(sopts,
967 local_crate_source_file,
972 pub fn build_session_(sopts: config::Options,
973 local_crate_source_file: Option<PathBuf>,
974 span_diagnostic: errors::Handler,
975 codemap: Lrc<codemap::CodeMap>)
977 let host = match Target::search(config::host_triple()) {
980 span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise();
983 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
985 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
986 let default_sysroot = match sopts.maybe_sysroot {
988 None => Some(filesearch::get_or_default_sysroot())
991 let file_path_mapping = sopts.file_path_mapping();
993 let local_crate_source_file = local_crate_source_file.map(|path| {
994 file_path_mapping.map_prefix(path).0
997 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
998 let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
999 .map(|i| i.1).unwrap_or(0));
1000 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1001 let print_fuel = Cell::new(0);
1003 let working_dir = match env::current_dir() {
1006 p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1009 let working_dir = file_path_mapping.map_prefix(working_dir);
1011 let sess = Session {
1016 // For a library crate, this is always none
1017 entry_fn: RefCell::new(None),
1018 entry_type: Cell::new(None),
1019 plugin_registrar_fn: Cell::new(None),
1020 derive_registrar_fn: Cell::new(None),
1022 local_crate_source_file,
1024 lint_store: RefCell::new(lint::LintStore::new()),
1025 buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
1026 one_time_diagnostics: RefCell::new(FxHashSet()),
1027 plugin_llvm_passes: RefCell::new(Vec::new()),
1028 plugin_attributes: RefCell::new(Vec::new()),
1029 crate_types: RefCell::new(Vec::new()),
1030 dependency_formats: RefCell::new(FxHashMap()),
1031 crate_disambiguator: RefCell::new(None),
1032 features: RefCell::new(feature_gate::Features::new()),
1033 recursion_limit: Cell::new(64),
1034 type_length_limit: Cell::new(1048576),
1035 next_node_id: Cell::new(NodeId::new(1)),
1036 injected_allocator: Cell::new(None),
1037 allocator_kind: Cell::new(None),
1038 injected_panic_runtime: Cell::new(None),
1039 imported_macro_spans: RefCell::new(HashMap::new()),
1040 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
1041 ignored_attr_names: ich::compute_ignored_attr_names(),
1042 perf_stats: PerfStats {
1043 svh_time: Cell::new(Duration::from_secs(0)),
1044 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
1045 incr_comp_hashes_count: Cell::new(0),
1046 incr_comp_bytes_hashed: Cell::new(0),
1047 symbol_hash_time: Cell::new(Duration::from_secs(0)),
1048 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
1050 code_stats: RefCell::new(CodeStats::new()),
1051 optimization_fuel_crate,
1052 optimization_fuel_limit,
1055 out_of_fuel: Cell::new(false),
1056 // Note that this is unsafe because it may misinterpret file descriptors
1057 // on Unix as jobserver file descriptors. We hopefully execute this near
1058 // the beginning of the process though to ensure we don't get false
1059 // positives, or in other words we try to execute this before we open
1060 // any file descriptors ourselves.
1062 // Also note that we stick this in a global because there could be
1063 // multiple `Session` instances in this process, and the jobserver is
1065 jobserver_from_env: unsafe {
1066 static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
1067 static INIT: Once = ONCE_INIT;
1069 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
1071 (*GLOBAL_JOBSERVER).clone()
1073 has_global_allocator: Cell::new(false),
1079 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1080 /// compiler. Together with the crate-name forms a unique global identifier for
1082 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1083 pub struct CrateDisambiguator(Fingerprint);
1085 impl CrateDisambiguator {
1086 pub fn to_fingerprint(self) -> Fingerprint {
1091 impl From<Fingerprint> for CrateDisambiguator {
1092 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1093 CrateDisambiguator(fingerprint)
1097 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1099 /// Holds data on the current incremental compilation session, if there is one.
1101 pub enum IncrCompSession {
1102 /// This is the state the session will be in until the incr. comp. dir is
1105 /// This is the state during which the session directory is private and can
1108 session_directory: PathBuf,
1109 lock_file: flock::Lock,
1110 load_dep_graph: bool,
1112 /// This is the state after the session directory has been finalized. In this
1113 /// state, the contents of the directory must not be modified any more.
1115 session_directory: PathBuf,
1117 /// This is an error state that is reached when some compilation error has
1118 /// occurred. It indicates that the contents of the session directory must
1119 /// not be used, since they might be invalid.
1120 InvalidBecauseOfErrors {
1121 session_directory: PathBuf,
1125 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1126 let emitter: Box<dyn Emitter> = match output {
1127 config::ErrorOutputType::HumanReadable(color_config) => {
1128 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1130 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1131 config::ErrorOutputType::Short(color_config) => {
1132 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1135 let handler = errors::Handler::with_emitter(true, false, emitter);
1136 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1137 errors::FatalError.raise();
1140 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1141 let emitter: Box<dyn Emitter> = match output {
1142 config::ErrorOutputType::HumanReadable(color_config) => {
1143 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1145 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1146 config::ErrorOutputType::Short(color_config) => {
1147 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1150 let handler = errors::Handler::with_emitter(true, false, emitter);
1151 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1154 #[derive(Copy, Clone, Debug)]
1155 pub enum CompileIncomplete {
1157 Errored(ErrorReported)
1159 impl From<ErrorReported> for CompileIncomplete {
1160 fn from(err: ErrorReported) -> CompileIncomplete {
1161 CompileIncomplete::Errored(err)
1164 pub type CompileResult = Result<(), CompileIncomplete>;
1166 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1170 Err(CompileIncomplete::Errored(ErrorReported))
1176 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1177 // this wrapper mostly exists so I don't have to write a fully
1178 // qualified path of None::<Span> inside the bug!() macro definition
1179 opt_span_bug_fmt(file, line, None::<Span>, args);
1184 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1187 args: fmt::Arguments) -> ! {
1188 opt_span_bug_fmt(file, line, Some(span), args);
1191 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1194 args: fmt::Arguments) -> ! {
1195 tls::with_opt(move |tcx| {
1196 let msg = format!("{}:{}: {}", file, line, args);
1198 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1199 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1200 (None, _) => panic!(msg)