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 syntax::ast::NodeId;
29 use errors::{self, DiagnosticBuilder, DiagnosticId};
30 use errors::emitter::{Emitter, EmitterWriter};
31 use syntax::json::JsonEmitter;
32 use syntax::feature_gate;
33 use syntax::symbol::Symbol;
35 use syntax::parse::ParseSess;
36 use syntax::{ast, codemap};
37 use syntax::feature_gate::AttributeType;
38 use syntax_pos::{Span, MultiSpan};
40 use rustc_back::{LinkerFlavor, PanicStrategy};
41 use rustc_back::target::Target;
42 use rustc_data_structures::flock;
43 use jobserver::Client;
45 use std::cell::{self, Cell, RefCell};
46 use std::collections::HashMap;
50 use std::path::{Path, PathBuf};
52 use std::sync::{Once, ONCE_INIT};
53 use std::time::Duration;
60 /// Represents the data associated with a compilation
61 /// session for a single crate.
63 pub target: config::Config,
65 pub opts: config::Options,
66 pub parse_sess: ParseSess,
67 /// For a library crate, this is always none
68 pub entry_fn: RefCell<Option<(NodeId, Span)>>,
69 pub entry_type: Cell<Option<config::EntryFnType>>,
70 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
71 pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
72 pub default_sysroot: Option<PathBuf>,
73 /// The name of the root source file of the crate, in the local file system.
74 /// `None` means that there is no source file.
75 pub local_crate_source_file: Option<PathBuf>,
76 /// The directory the compiler has been executed in plus a flag indicating
77 /// if the value stored here has been affected by path remapping.
78 pub working_dir: (PathBuf, bool),
79 pub lint_store: RefCell<lint::LintStore>,
80 pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
81 /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
82 /// (sub)diagnostics that have been set once, but should not be set again,
83 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
84 pub one_time_diagnostics: RefCell<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
85 pub plugin_llvm_passes: RefCell<Vec<String>>,
86 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
87 pub crate_types: RefCell<Vec<config::CrateType>>,
88 pub dependency_formats: RefCell<dependency_format::Dependencies>,
89 /// The crate_disambiguator is constructed out of all the `-C metadata`
90 /// arguments passed to the compiler. Its value together with the crate-name
91 /// forms a unique global identifier for the crate. It is used to allow
92 /// multiple crates with the same name to coexist. See the
93 /// trans::back::symbol_names module for more information.
94 pub crate_disambiguator: RefCell<Option<CrateDisambiguator>>,
95 pub features: RefCell<feature_gate::Features>,
97 /// The maximum recursion limit for potentially infinitely recursive
98 /// operations such as auto-dereference and monomorphization.
99 pub recursion_limit: Cell<usize>,
101 /// The maximum length of types during monomorphization.
102 pub type_length_limit: Cell<usize>,
104 /// The metadata::creader module may inject an allocator/panic_runtime
105 /// dependency if it didn't already find one, and this tracks what was
107 pub injected_allocator: Cell<Option<CrateNum>>,
108 pub allocator_kind: Cell<Option<AllocatorKind>>,
109 pub injected_panic_runtime: Cell<Option<CrateNum>>,
111 /// Map from imported macro spans (which consist of
112 /// the localized span for the macro body) to the
113 /// macro name and definition span in the source crate.
114 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
116 incr_comp_session: RefCell<IncrCompSession>,
118 /// A cache of attributes ignored by StableHashingContext
119 pub ignored_attr_names: FxHashSet<Symbol>,
121 /// Some measurements that are being gathered during compilation.
122 pub perf_stats: PerfStats,
124 /// Data about code being compiled, gathered during compilation.
125 pub code_stats: RefCell<CodeStats>,
127 next_node_id: Cell<ast::NodeId>,
129 /// If -zfuel=crate=n is specified, Some(crate).
130 optimization_fuel_crate: Option<String>,
131 /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
132 optimization_fuel_limit: Cell<u64>,
133 /// We're rejecting all further optimizations.
134 out_of_fuel: Cell<bool>,
136 // The next two are public because the driver needs to read them.
138 /// If -zprint-fuel=crate, Some(crate).
139 pub print_fuel_crate: Option<String>,
140 /// Always set to zero and incremented so that we can print fuel expended by a crate.
141 pub print_fuel: Cell<u64>,
143 /// Loaded up early on in the initialization of this `Session` to avoid
144 /// false positives about a job server in our environment.
145 pub jobserver_from_env: Option<Client>,
147 /// Metadata about the allocators for the current crate being compiled
148 pub has_global_allocator: Cell<bool>,
151 pub struct PerfStats {
152 /// The accumulated time needed for computing the SVH of the crate
153 pub svh_time: Cell<Duration>,
154 /// The accumulated time spent on computing incr. comp. hashes
155 pub incr_comp_hashes_time: Cell<Duration>,
156 /// The number of incr. comp. hash computations performed
157 pub incr_comp_hashes_count: Cell<u64>,
158 /// The number of bytes hashed when computing ICH values
159 pub incr_comp_bytes_hashed: Cell<u64>,
160 /// The accumulated time spent on computing symbol hashes
161 pub symbol_hash_time: Cell<Duration>,
162 /// The accumulated time spent decoding def path tables from metadata
163 pub decode_def_path_tables_time: Cell<Duration>,
166 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
167 enum DiagnosticBuilderMethod {
170 SpanSuggestion(String), // suggestion
171 // add more variants as needed to support one-time diagnostics
174 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
175 /// emitting the same message more than once
176 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
177 pub enum DiagnosticMessageId {
178 ErrorId(u16), // EXXXX error code as integer
179 LintId(lint::LintId),
180 StabilityId(u32) // issue number
183 impl From<&'static lint::Lint> for DiagnosticMessageId {
184 fn from(lint: &'static lint::Lint) -> Self {
185 DiagnosticMessageId::LintId(lint::LintId::of(lint))
190 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
191 match *self.crate_disambiguator.borrow() {
192 Some(value) => value,
193 None => bug!("accessing disambiguator before initialization"),
196 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
199 -> DiagnosticBuilder<'a> {
200 self.diagnostic().struct_span_warn(sp, msg)
202 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
206 -> DiagnosticBuilder<'a> {
207 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
209 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
210 self.diagnostic().struct_warn(msg)
212 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
215 -> DiagnosticBuilder<'a> {
216 self.diagnostic().struct_span_err(sp, msg)
218 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
222 -> DiagnosticBuilder<'a> {
223 self.diagnostic().struct_span_err_with_code(sp, msg, code)
225 // FIXME: This method should be removed (every error should have an associated error code).
226 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
227 self.diagnostic().struct_err(msg)
229 pub fn struct_err_with_code<'a>(
233 ) -> DiagnosticBuilder<'a> {
234 self.diagnostic().struct_err_with_code(msg, code)
236 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
239 -> DiagnosticBuilder<'a> {
240 self.diagnostic().struct_span_fatal(sp, msg)
242 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
246 -> DiagnosticBuilder<'a> {
247 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
249 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
250 self.diagnostic().struct_fatal(msg)
253 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
254 self.diagnostic().span_fatal(sp, msg).raise()
256 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
262 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
264 pub fn fatal(&self, msg: &str) -> ! {
265 self.diagnostic().fatal(msg).raise()
267 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
269 self.span_warn(sp, msg);
271 self.span_err(sp, msg);
274 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
275 self.diagnostic().span_err(sp, msg)
277 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
278 self.diagnostic().span_err_with_code(sp, &msg, code)
280 pub fn err(&self, msg: &str) {
281 self.diagnostic().err(msg)
283 pub fn err_count(&self) -> usize {
284 self.diagnostic().err_count()
286 pub fn has_errors(&self) -> bool {
287 self.diagnostic().has_errors()
289 pub fn abort_if_errors(&self) {
290 self.diagnostic().abort_if_errors();
292 pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
293 compile_result_from_err_count(self.err_count())
295 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
296 where F: FnOnce() -> T
298 let old_count = self.err_count();
300 let errors = self.err_count() - old_count;
307 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
308 self.diagnostic().span_warn(sp, msg)
310 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
311 self.diagnostic().span_warn_with_code(sp, msg, code)
313 pub fn warn(&self, msg: &str) {
314 self.diagnostic().warn(msg)
316 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
318 Some(sp) => self.span_warn(sp, msg),
319 None => self.warn(msg),
322 /// Delay a span_bug() call until abort_if_errors()
323 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
324 self.diagnostic().delay_span_bug(sp, msg)
326 pub fn note_without_error(&self, msg: &str) {
327 self.diagnostic().note_without_error(msg)
329 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
330 self.diagnostic().span_note_without_error(sp, msg)
332 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
333 self.diagnostic().span_unimpl(sp, msg)
335 pub fn unimpl(&self, msg: &str) -> ! {
336 self.diagnostic().unimpl(msg)
339 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
340 lint: &'static lint::Lint,
344 match *self.buffered_lints.borrow_mut() {
345 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
346 msg, BuiltinLintDiagnostics::Normal),
347 None => bug!("can't buffer lints after HIR lowering"),
351 pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(&self,
352 lint: &'static lint::Lint, id: ast::NodeId, sp: S,
353 msg: &str, diagnostic: BuiltinLintDiagnostics) {
354 match *self.buffered_lints.borrow_mut() {
355 Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
357 None => bug!("can't buffer lints after HIR lowering"),
361 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
362 let id = self.next_node_id.get();
364 match id.as_usize().checked_add(count) {
366 self.next_node_id.set(ast::NodeId::new(next));
368 None => bug!("Input too large, ran out of node ids!")
373 pub fn next_node_id(&self) -> NodeId {
374 self.reserve_node_ids(1)
376 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
377 &self.parse_sess.span_diagnostic
380 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
381 /// deduplicates on lint ID, span (if any), and message for this `Session`
382 fn diag_once<'a, 'b>(&'a self,
383 diag_builder: &'b mut DiagnosticBuilder<'a>,
384 method: DiagnosticBuilderMethod,
385 msg_id: DiagnosticMessageId,
387 span_maybe: Option<Span>) {
389 let id_span_message = (msg_id, span_maybe, message.to_owned());
390 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
393 DiagnosticBuilderMethod::Note => {
394 diag_builder.note(message);
396 DiagnosticBuilderMethod::SpanNote => {
397 let span = span_maybe.expect("span_note needs a span");
398 diag_builder.span_note(span, message);
400 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
401 let span = span_maybe.expect("span_suggestion needs a span");
402 diag_builder.span_suggestion(span, message, suggestion);
408 pub fn diag_span_note_once<'a, 'b>(&'a self,
409 diag_builder: &'b mut DiagnosticBuilder<'a>,
410 msg_id: DiagnosticMessageId, span: Span, message: &str) {
411 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote,
412 msg_id, message, Some(span));
415 pub fn diag_note_once<'a, 'b>(&'a self,
416 diag_builder: &'b mut DiagnosticBuilder<'a>,
417 msg_id: DiagnosticMessageId, message: &str) {
418 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
421 pub fn diag_span_suggestion_once<'a, 'b>(&'a self,
422 diag_builder: &'b mut DiagnosticBuilder<'a>,
423 msg_id: DiagnosticMessageId,
426 suggestion: String) {
427 self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanSuggestion(suggestion),
428 msg_id, message, Some(span));
431 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
432 self.parse_sess.codemap()
434 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
435 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
436 pub fn profile_queries(&self) -> bool {
437 self.opts.debugging_opts.profile_queries ||
438 self.opts.debugging_opts.profile_queries_and_keys
440 pub fn profile_queries_and_keys(&self) -> bool {
441 self.opts.debugging_opts.profile_queries_and_keys
443 pub fn count_llvm_insns(&self) -> bool {
444 self.opts.debugging_opts.count_llvm_insns
446 pub fn time_llvm_passes(&self) -> bool {
447 self.opts.debugging_opts.time_llvm_passes
449 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
450 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
451 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
452 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
453 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
454 pub fn print_llvm_passes(&self) -> bool {
455 self.opts.debugging_opts.print_llvm_passes
458 /// If true, we should use NLL-style region checking instead of
460 pub fn nll(&self) -> bool {
461 self.features.borrow().nll || self.opts.debugging_opts.nll
464 /// If true, we should use the MIR-based borrowck (we may *also* use
465 /// the AST-based borrowck).
466 pub fn use_mir(&self) -> bool {
467 self.borrowck_mode().use_mir()
470 /// If true, we should gather causal information during NLL
471 /// checking. This will eventually be the normal thing, but right
472 /// now it is too unoptimized.
473 pub fn nll_dump_cause(&self) -> bool {
474 self.opts.debugging_opts.nll_dump_cause
477 /// If true, we should enable two-phase borrows checks. This is
478 /// done with either `-Ztwo-phase-borrows` or with
479 /// `#![feature(nll)]`.
480 pub fn two_phase_borrows(&self) -> bool {
481 self.features.borrow().nll || self.opts.debugging_opts.two_phase_borrows
484 /// What mode(s) of borrowck should we run? AST? MIR? both?
485 /// (Also considers the `#![feature(nll)]` setting.)
486 pub fn borrowck_mode(&self) -> BorrowckMode {
487 match self.opts.borrowck_mode {
488 mode @ BorrowckMode::Mir |
489 mode @ BorrowckMode::Compare => mode,
491 mode @ BorrowckMode::Ast => {
502 /// Should we emit EndRegion MIR statements? These are consumed by
503 /// MIR borrowck, but not when NLL is used. They are also consumed
504 /// by the validation stuff.
505 pub fn emit_end_regions(&self) -> bool {
506 // FIXME(#46875) -- we should not emit end regions when NLL is enabled,
507 // but for now we can't stop doing so because it causes false positives
508 self.opts.debugging_opts.emit_end_regions ||
509 self.opts.debugging_opts.mir_emit_validate > 0 ||
513 /// Calculates the flavor of LTO to use for this compilation.
514 pub fn lto(&self) -> config::Lto {
515 // If our target has codegen requirements ignore the command line
516 if self.target.target.options.requires_lto {
517 return config::Lto::Fat
520 // If the user specified something, return that. If they only said `-C
521 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
522 // then ensure we can't use a ThinLTO.
523 match self.opts.cg.lto {
524 config::Lto::No => {}
525 config::Lto::Yes if self.opts.cli_forced_thinlto_off => {
526 return config::Lto::Fat
528 other => return other,
531 // Ok at this point the target doesn't require anything and the user
532 // hasn't asked for anything. Our next decision is whether or not
533 // we enable "auto" ThinLTO where we use multiple codegen units and
534 // then do ThinLTO over those codegen units. The logic below will
535 // either return `No` or `ThinLocal`.
537 // If processing command line options determined that we're incompatible
538 // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
539 if self.opts.cli_forced_thinlto_off {
540 return config::Lto::No
543 // If `-Z thinlto` specified process that, but note that this is mostly
544 // a deprecated option now that `-C lto=thin` exists.
545 if let Some(enabled) = self.opts.debugging_opts.thinlto {
547 return config::Lto::ThinLocal
549 return config::Lto::No
553 // If there's only one codegen unit and LTO isn't enabled then there's
554 // no need for ThinLTO so just return false.
555 if self.codegen_units() == 1 {
556 return config::Lto::No
559 // Right now ThinLTO isn't compatible with incremental compilation.
560 if self.opts.incremental.is_some() {
561 return config::Lto::No
564 // Now we're in "defaults" territory. By default we enable ThinLTO for
565 // optimized compiles (anything greater than O0).
566 match self.opts.optimize {
567 config::OptLevel::No => config::Lto::No,
568 _ => config::Lto::ThinLocal,
572 /// Returns the panic strategy for this compile session. If the user explicitly selected one
573 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
574 pub fn panic_strategy(&self) -> PanicStrategy {
575 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
577 pub fn linker_flavor(&self) -> LinkerFlavor {
578 self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
581 pub fn fewer_names(&self) -> bool {
582 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly) ||
583 self.opts.output_types.contains_key(&OutputType::Bitcode);
584 self.opts.debugging_opts.fewer_names || !more_names
587 pub fn no_landing_pads(&self) -> bool {
588 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
590 pub fn unstable_options(&self) -> bool {
591 self.opts.debugging_opts.unstable_options
593 pub fn nonzeroing_move_hints(&self) -> bool {
594 self.opts.debugging_opts.enable_nonzeroing_move_hints
596 pub fn overflow_checks(&self) -> bool {
597 self.opts.cg.overflow_checks
598 .or(self.opts.debugging_opts.force_overflow_checks)
599 .unwrap_or(self.opts.debug_assertions)
602 pub fn crt_static(&self) -> bool {
603 // If the target does not opt in to crt-static support, use its default.
604 if self.target.target.options.crt_static_respected {
605 self.crt_static_feature()
607 self.target.target.options.crt_static_default
611 pub fn crt_static_feature(&self) -> bool {
612 let requested_features = self.opts.cg.target_feature.split(',');
613 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
614 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
616 // If the target we're compiling for requests a static crt by default,
617 // then see if the `-crt-static` feature was passed to disable that.
618 // Otherwise if we don't have a static crt by default then see if the
619 // `+crt-static` feature was passed.
620 if self.target.target.options.crt_static_default {
627 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
628 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
629 !self.target.target.options.eliminate_frame_pointer
632 /// Returns the symbol name for the registrar function,
633 /// given the crate Svh and the function DefIndex.
634 pub fn generate_plugin_registrar_symbol(&self,
635 disambiguator: CrateDisambiguator)
637 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
640 pub fn generate_derive_registrar_symbol(&self,
641 disambiguator: CrateDisambiguator)
643 format!("__rustc_derive_registrar_{}__", disambiguator.to_fingerprint().to_hex())
646 pub fn sysroot<'a>(&'a self) -> &'a Path {
647 match self.opts.maybe_sysroot {
648 Some (ref sysroot) => sysroot,
649 None => self.default_sysroot.as_ref()
650 .expect("missing sysroot and default_sysroot in Session")
653 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
654 filesearch::FileSearch::new(self.sysroot(),
655 &self.opts.target_triple,
656 &self.opts.search_paths,
659 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
660 filesearch::FileSearch::new(
662 config::host_triple(),
663 &self.opts.search_paths,
667 pub fn set_incr_session_load_dep_graph(&self, load: bool) {
668 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
670 match *incr_comp_session {
671 IncrCompSession::Active { ref mut load_dep_graph, .. } => {
672 *load_dep_graph = load;
678 pub fn incr_session_load_dep_graph(&self) -> bool {
679 let incr_comp_session = self.incr_comp_session.borrow();
680 match *incr_comp_session {
681 IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
686 pub fn init_incr_comp_session(&self,
687 session_dir: PathBuf,
688 lock_file: flock::Lock,
689 load_dep_graph: bool) {
690 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
692 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
693 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
696 *incr_comp_session = IncrCompSession::Active {
697 session_directory: session_dir,
703 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
704 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
706 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
707 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
710 // Note: This will also drop the lock file, thus unlocking the directory
711 *incr_comp_session = IncrCompSession::Finalized {
712 session_directory: new_directory_path,
716 pub fn mark_incr_comp_session_as_invalid(&self) {
717 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
719 let session_directory = match *incr_comp_session {
720 IncrCompSession::Active { ref session_directory, .. } => {
721 session_directory.clone()
723 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
724 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
728 // Note: This will also drop the lock file, thus unlocking the directory
729 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
734 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
735 let incr_comp_session = self.incr_comp_session.borrow();
736 cell::Ref::map(incr_comp_session, |incr_comp_session| {
737 match *incr_comp_session {
738 IncrCompSession::NotInitialized => {
739 bug!("Trying to get session directory from IncrCompSession `{:?}`",
742 IncrCompSession::Active { ref session_directory, .. } |
743 IncrCompSession::Finalized { ref session_directory } |
744 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
751 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
752 if self.opts.incremental.is_some() {
753 Some(self.incr_comp_session_dir())
759 pub fn print_perf_stats(&self) {
760 println!("Total time spent computing SVHs: {}",
761 duration_to_secs_str(self.perf_stats.svh_time.get()));
762 println!("Total time spent computing incr. comp. hashes: {}",
763 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
764 println!("Total number of incr. comp. hashes computed: {}",
765 self.perf_stats.incr_comp_hashes_count.get());
766 println!("Total number of bytes hashed for incr. comp.: {}",
767 self.perf_stats.incr_comp_bytes_hashed.get());
768 if self.perf_stats.incr_comp_hashes_count.get() != 0 {
769 println!("Average bytes hashed per incr. comp. HIR node: {}",
770 self.perf_stats.incr_comp_bytes_hashed.get() /
771 self.perf_stats.incr_comp_hashes_count.get());
773 println!("Average bytes hashed per incr. comp. HIR node: N/A");
775 println!("Total time spent computing symbol hashes: {}",
776 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
777 println!("Total time spent decoding DefPath tables: {}",
778 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
781 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
782 /// This expends fuel if applicable, and records fuel if applicable.
783 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
785 match self.optimization_fuel_crate {
786 Some(ref c) if c == crate_name => {
787 let fuel = self.optimization_fuel_limit.get();
789 if fuel == 0 && !self.out_of_fuel.get() {
790 println!("optimization-fuel-exhausted: {}", msg());
791 self.out_of_fuel.set(true);
793 self.optimization_fuel_limit.set(fuel-1);
798 match self.print_fuel_crate {
799 Some(ref c) if c == crate_name=> {
800 self.print_fuel.set(self.print_fuel.get()+1);
807 /// Returns the number of query threads that should be used for this
809 pub fn query_threads(&self) -> usize {
810 self.opts.debugging_opts.query_threads.unwrap_or(1)
813 /// Returns the number of codegen units that should be used for this
815 pub fn codegen_units(&self) -> usize {
816 if let Some(n) = self.opts.cli_forced_codegen_units {
819 if let Some(n) = self.target.target.options.default_codegen_units {
823 // Why is 16 codegen units the default all the time?
825 // The main reason for enabling multiple codegen units by default is to
826 // leverage the ability for the trans backend to do translation and
827 // codegen in parallel. This allows us, especially for large crates, to
828 // make good use of all available resources on the machine once we've
829 // hit that stage of compilation. Large crates especially then often
830 // take a long time in trans/codegen and this helps us amortize that
833 // Note that a high number here doesn't mean that we'll be spawning a
834 // large number of threads in parallel. The backend of rustc contains
835 // global rate limiting through the `jobserver` crate so we'll never
836 // overload the system with too much work, but rather we'll only be
837 // optimizing when we're otherwise cooperating with other instances of
840 // Rather a high number here means that we should be able to keep a lot
841 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
842 // to build we'll be guaranteed that all cpus will finish pretty closely
843 // to one another and we should make relatively optimal use of system
846 // Note that the main cost of codegen units is that it prevents LLVM
847 // from inlining across codegen units. Users in general don't have a lot
848 // of control over how codegen units are split up so it's our job in the
849 // compiler to ensure that undue performance isn't lost when using
850 // codegen units (aka we can't require everyone to slap `#[inline]` on
853 // If we're compiling at `-O0` then the number doesn't really matter too
854 // much because performance doesn't matter and inlining is ok to lose.
855 // In debug mode we just want to try to guarantee that no cpu is stuck
856 // doing work that could otherwise be farmed to others.
858 // In release mode, however (O1 and above) performance does indeed
859 // matter! To recover the loss in performance due to inlining we'll be
860 // enabling ThinLTO by default (the function for which is just below).
861 // This will ensure that we recover any inlining wins we otherwise lost
862 // through codegen unit partitioning.
866 // Ok that's a lot of words but the basic tl;dr; is that we want a high
867 // number here -- but not too high. Additionally we're "safe" to have it
868 // always at the same number at all optimization levels.
870 // As a result 16 was chosen here! Mostly because it was a power of 2
871 // and most benchmarks agreed it was roughly a local optimum. Not very
876 pub fn teach(&self, code: &DiagnosticId) -> bool {
877 self.opts.debugging_opts.teach && !self.parse_sess.span_diagnostic.code_emitted(code)
880 /// Are we allowed to use features from the Rust 2018 epoch?
881 pub fn rust_2018(&self) -> bool {
882 self.opts.debugging_opts.epoch >= Epoch::Epoch2018
885 pub fn epoch(&self) -> Epoch {
886 self.opts.debugging_opts.epoch
890 pub fn build_session(sopts: config::Options,
891 local_crate_source_file: Option<PathBuf>,
892 registry: errors::registry::Registry)
894 let file_path_mapping = sopts.file_path_mapping();
896 build_session_with_codemap(sopts,
897 local_crate_source_file,
899 Rc::new(codemap::CodeMap::new(file_path_mapping)),
903 pub fn build_session_with_codemap(sopts: config::Options,
904 local_crate_source_file: Option<PathBuf>,
905 registry: errors::registry::Registry,
906 codemap: Rc<codemap::CodeMap>,
907 emitter_dest: Option<Box<Write + Send>>)
909 // FIXME: This is not general enough to make the warning lint completely override
910 // normal diagnostic warnings, since the warning lint can also be denied and changed
911 // later via the source code.
912 let warnings_allow = sopts.lint_opts
914 .filter(|&&(ref key, _)| *key == "warnings")
915 .map(|&(_, ref level)| *level == lint::Allow)
918 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
920 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
922 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
924 let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
926 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
927 (config::ErrorOutputType::HumanReadable(color_config), None) => {
928 Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()),
929 false, sopts.debugging_opts.teach)
930 .ui_testing(sopts.debugging_opts.ui_testing))
932 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
933 Box::new(EmitterWriter::new(dst, Some(codemap.clone()),
935 .ui_testing(sopts.debugging_opts.ui_testing))
937 (config::ErrorOutputType::Json(pretty), None) => {
938 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone(),
939 pretty, sopts.debugging_opts.approximate_suggestions)
940 .ui_testing(sopts.debugging_opts.ui_testing))
942 (config::ErrorOutputType::Json(pretty), Some(dst)) => {
943 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone(),
944 pretty, sopts.debugging_opts.approximate_suggestions)
945 .ui_testing(sopts.debugging_opts.ui_testing))
947 (config::ErrorOutputType::Short(color_config), None) => {
948 Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false))
950 (config::ErrorOutputType::Short(_), Some(dst)) => {
951 Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
955 let diagnostic_handler =
956 errors::Handler::with_emitter_and_flags(
958 errors::HandlerFlags {
961 external_macro_backtrace,
962 .. Default::default()
965 build_session_(sopts,
966 local_crate_source_file,
971 pub fn build_session_(sopts: config::Options,
972 local_crate_source_file: Option<PathBuf>,
973 span_diagnostic: errors::Handler,
974 codemap: Rc<codemap::CodeMap>)
976 let host = match Target::search(config::host_triple()) {
979 span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise();
982 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
984 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
985 let default_sysroot = match sopts.maybe_sysroot {
987 None => Some(filesearch::get_or_default_sysroot())
990 let file_path_mapping = sopts.file_path_mapping();
992 let local_crate_source_file = local_crate_source_file.map(|path| {
993 file_path_mapping.map_prefix(path).0
996 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
997 let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
998 .map(|i| i.1).unwrap_or(0));
999 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1000 let print_fuel = Cell::new(0);
1002 let working_dir = match env::current_dir() {
1005 p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1008 let working_dir = file_path_mapping.map_prefix(working_dir);
1010 let sess = Session {
1015 // For a library crate, this is always none
1016 entry_fn: RefCell::new(None),
1017 entry_type: Cell::new(None),
1018 plugin_registrar_fn: Cell::new(None),
1019 derive_registrar_fn: Cell::new(None),
1021 local_crate_source_file,
1023 lint_store: RefCell::new(lint::LintStore::new()),
1024 buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
1025 one_time_diagnostics: RefCell::new(FxHashSet()),
1026 plugin_llvm_passes: RefCell::new(Vec::new()),
1027 plugin_attributes: RefCell::new(Vec::new()),
1028 crate_types: RefCell::new(Vec::new()),
1029 dependency_formats: RefCell::new(FxHashMap()),
1030 crate_disambiguator: RefCell::new(None),
1031 features: RefCell::new(feature_gate::Features::new()),
1032 recursion_limit: Cell::new(64),
1033 type_length_limit: Cell::new(1048576),
1034 next_node_id: Cell::new(NodeId::new(1)),
1035 injected_allocator: Cell::new(None),
1036 allocator_kind: Cell::new(None),
1037 injected_panic_runtime: Cell::new(None),
1038 imported_macro_spans: RefCell::new(HashMap::new()),
1039 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
1040 ignored_attr_names: ich::compute_ignored_attr_names(),
1041 perf_stats: PerfStats {
1042 svh_time: Cell::new(Duration::from_secs(0)),
1043 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
1044 incr_comp_hashes_count: Cell::new(0),
1045 incr_comp_bytes_hashed: Cell::new(0),
1046 symbol_hash_time: Cell::new(Duration::from_secs(0)),
1047 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
1049 code_stats: RefCell::new(CodeStats::new()),
1050 optimization_fuel_crate,
1051 optimization_fuel_limit,
1054 out_of_fuel: Cell::new(false),
1055 // Note that this is unsafe because it may misinterpret file descriptors
1056 // on Unix as jobserver file descriptors. We hopefully execute this near
1057 // the beginning of the process though to ensure we don't get false
1058 // positives, or in other words we try to execute this before we open
1059 // any file descriptors ourselves.
1061 // Also note that we stick this in a global because there could be
1062 // multiple `Session` instances in this process, and the jobserver is
1064 jobserver_from_env: unsafe {
1065 static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
1066 static INIT: Once = ONCE_INIT;
1068 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
1070 (*GLOBAL_JOBSERVER).clone()
1072 has_global_allocator: Cell::new(false),
1078 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1079 /// compiler. Together with the crate-name forms a unique global identifier for
1081 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1082 pub struct CrateDisambiguator(Fingerprint);
1084 impl CrateDisambiguator {
1085 pub fn to_fingerprint(self) -> Fingerprint {
1090 impl From<Fingerprint> for CrateDisambiguator {
1091 fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1092 CrateDisambiguator(fingerprint)
1096 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1098 /// Holds data on the current incremental compilation session, if there is one.
1100 pub enum IncrCompSession {
1101 /// This is the state the session will be in until the incr. comp. dir is
1104 /// This is the state during which the session directory is private and can
1107 session_directory: PathBuf,
1108 lock_file: flock::Lock,
1109 load_dep_graph: bool,
1111 /// This is the state after the session directory has been finalized. In this
1112 /// state, the contents of the directory must not be modified any more.
1114 session_directory: PathBuf,
1116 /// This is an error state that is reached when some compilation error has
1117 /// occurred. It indicates that the contents of the session directory must
1118 /// not be used, since they might be invalid.
1119 InvalidBecauseOfErrors {
1120 session_directory: PathBuf,
1124 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1125 let emitter: Box<Emitter> = match output {
1126 config::ErrorOutputType::HumanReadable(color_config) => {
1127 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1129 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1130 config::ErrorOutputType::Short(color_config) => {
1131 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1134 let handler = errors::Handler::with_emitter(true, false, emitter);
1135 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1136 errors::FatalError.raise();
1139 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1140 let emitter: Box<Emitter> = match output {
1141 config::ErrorOutputType::HumanReadable(color_config) => {
1142 Box::new(EmitterWriter::stderr(color_config, None, false, false))
1144 config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1145 config::ErrorOutputType::Short(color_config) => {
1146 Box::new(EmitterWriter::stderr(color_config, None, true, false))
1149 let handler = errors::Handler::with_emitter(true, false, emitter);
1150 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1153 #[derive(Copy, Clone, Debug)]
1154 pub enum CompileIncomplete {
1156 Errored(ErrorReported)
1158 impl From<ErrorReported> for CompileIncomplete {
1159 fn from(err: ErrorReported) -> CompileIncomplete {
1160 CompileIncomplete::Errored(err)
1163 pub type CompileResult = Result<(), CompileIncomplete>;
1165 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1169 Err(CompileIncomplete::Errored(ErrorReported))
1175 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1176 // this wrapper mostly exists so I don't have to write a fully
1177 // qualified path of None::<Span> inside the bug!() macro definition
1178 opt_span_bug_fmt(file, line, None::<Span>, args);
1183 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1186 args: fmt::Arguments) -> ! {
1187 opt_span_bug_fmt(file, line, Some(span), args);
1190 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1193 args: fmt::Arguments) -> ! {
1194 tls::with_opt(move |tcx| {
1195 let msg = format!("{}:{}: {}", file, line, args);
1197 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1198 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1199 (None, _) => panic!(msg)