]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
Rollup merge of #48618 - scottmcm:elaborate-exitcode, r=alexcrichton
[rust.git] / src / librustc / session / mod.rs
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.
4 //
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.
10
11 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
12 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
13
14 use hir::def_id::CrateNum;
15 use ich::Fingerprint;
16
17 use ich;
18 use lint;
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::{DebugInfoLevel, OutputType, Epoch};
24 use ty::tls;
25 use util::nodemap::{FxHashMap, FxHashSet};
26 use util::common::{duration_to_secs_str, ErrorReported};
27
28 use rustc_data_structures::sync::Lrc;
29
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;
36 use syntax::parse;
37 use syntax::parse::ParseSess;
38 use syntax::{ast, codemap};
39 use syntax::feature_gate::AttributeType;
40 use syntax_pos::{Span, MultiSpan};
41
42 use rustc_back::{LinkerFlavor, PanicStrategy};
43 use rustc_back::target::Target;
44 use rustc_data_structures::flock;
45 use jobserver::Client;
46
47 use std::cell::{self, Cell, RefCell};
48 use std::collections::HashMap;
49 use std::env;
50 use std::fmt;
51 use std::io::Write;
52 use std::path::{Path, PathBuf};
53 use std::sync::{Once, ONCE_INIT};
54 use std::time::Duration;
55
56 mod code_stats;
57 pub mod config;
58 pub mod filesearch;
59 pub mod search_paths;
60
61 /// Represents the data associated with a compilation
62 /// session for a single crate.
63 pub struct Session {
64     pub target: config::Config,
65     pub host: Target,
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
97     features: RefCell<Option<feature_gate::Features>>,
98
99     /// The maximum recursion limit for potentially infinitely recursive
100     /// operations such as auto-dereference and monomorphization.
101     pub recursion_limit: Cell<usize>,
102
103     /// The maximum length of types during monomorphization.
104     pub type_length_limit: Cell<usize>,
105
106     /// The metadata::creader module may inject an allocator/panic_runtime
107     /// dependency if it didn't already find one, and this tracks what was
108     /// injected.
109     pub injected_allocator: Cell<Option<CrateNum>>,
110     pub allocator_kind: Cell<Option<AllocatorKind>>,
111     pub injected_panic_runtime: Cell<Option<CrateNum>>,
112
113     /// Map from imported macro spans (which consist of
114     /// the localized span for the macro body) to the
115     /// macro name and definition span in the source crate.
116     pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
117
118     incr_comp_session: RefCell<IncrCompSession>,
119
120     /// A cache of attributes ignored by StableHashingContext
121     pub ignored_attr_names: FxHashSet<Symbol>,
122
123     /// Some measurements that are being gathered during compilation.
124     pub perf_stats: PerfStats,
125
126     /// Data about code being compiled, gathered during compilation.
127     pub code_stats: RefCell<CodeStats>,
128
129     next_node_id: Cell<ast::NodeId>,
130
131     /// If -zfuel=crate=n is specified, Some(crate).
132     optimization_fuel_crate: Option<String>,
133     /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
134     optimization_fuel_limit: Cell<u64>,
135     /// We're rejecting all further optimizations.
136     out_of_fuel: Cell<bool>,
137
138     // The next two are public because the driver needs to read them.
139
140     /// If -zprint-fuel=crate, Some(crate).
141     pub print_fuel_crate: Option<String>,
142     /// Always set to zero and incremented so that we can print fuel expended by a crate.
143     pub print_fuel: Cell<u64>,
144
145     /// Loaded up early on in the initialization of this `Session` to avoid
146     /// false positives about a job server in our environment.
147     pub jobserver_from_env: Option<Client>,
148
149     /// Metadata about the allocators for the current crate being compiled
150     pub has_global_allocator: Cell<bool>,
151 }
152
153 pub struct PerfStats {
154     /// The accumulated time needed for computing the SVH of the crate
155     pub svh_time: Cell<Duration>,
156     /// The accumulated time spent on computing incr. comp. hashes
157     pub incr_comp_hashes_time: Cell<Duration>,
158     /// The number of incr. comp. hash computations performed
159     pub incr_comp_hashes_count: Cell<u64>,
160     /// The number of bytes hashed when computing ICH values
161     pub incr_comp_bytes_hashed: Cell<u64>,
162     /// The accumulated time spent on computing symbol hashes
163     pub symbol_hash_time: Cell<Duration>,
164     /// The accumulated time spent decoding def path tables from metadata
165     pub decode_def_path_tables_time: Cell<Duration>,
166 }
167
168 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
169 enum DiagnosticBuilderMethod {
170     Note,
171     SpanNote,
172     SpanSuggestion(String), // suggestion
173     // add more variants as needed to support one-time diagnostics
174 }
175
176 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
177 /// emitting the same message more than once
178 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
179 pub enum DiagnosticMessageId {
180     ErrorId(u16), // EXXXX error code as integer
181     LintId(lint::LintId),
182     StabilityId(u32) // issue number
183 }
184
185 impl From<&'static lint::Lint> for DiagnosticMessageId {
186     fn from(lint: &'static lint::Lint) -> Self {
187         DiagnosticMessageId::LintId(lint::LintId::of(lint))
188     }
189 }
190
191 impl Session {
192     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
193         match *self.crate_disambiguator.borrow() {
194             Some(value) => value,
195             None => bug!("accessing disambiguator before initialization"),
196         }
197     }
198
199     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
200                                                     sp: S,
201                                                     msg: &str)
202                                                     -> DiagnosticBuilder<'a> {
203         self.diagnostic().struct_span_warn(sp, msg)
204     }
205     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
206                                                               sp: S,
207                                                               msg: &str,
208                                                               code: DiagnosticId)
209                                                               -> DiagnosticBuilder<'a> {
210         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
211     }
212     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
213         self.diagnostic().struct_warn(msg)
214     }
215     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
216                                                    sp: S,
217                                                    msg: &str)
218                                                    -> DiagnosticBuilder<'a> {
219         self.diagnostic().struct_span_err(sp, msg)
220     }
221     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
222                                                              sp: S,
223                                                              msg: &str,
224                                                              code: DiagnosticId)
225                                                              -> DiagnosticBuilder<'a> {
226         self.diagnostic().struct_span_err_with_code(sp, msg, code)
227     }
228     // FIXME: This method should be removed (every error should have an associated error code).
229     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
230         self.diagnostic().struct_err(msg)
231     }
232     pub fn struct_err_with_code<'a>(
233         &'a self,
234         msg: &str,
235         code: DiagnosticId,
236     ) -> DiagnosticBuilder<'a> {
237         self.diagnostic().struct_err_with_code(msg, code)
238     }
239     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
240                                                      sp: S,
241                                                      msg: &str)
242                                                      -> DiagnosticBuilder<'a> {
243         self.diagnostic().struct_span_fatal(sp, msg)
244     }
245     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
246                                                                sp: S,
247                                                                msg: &str,
248                                                                code: DiagnosticId)
249                                                                -> DiagnosticBuilder<'a> {
250         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
251     }
252     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
253         self.diagnostic().struct_fatal(msg)
254     }
255
256     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
257         self.diagnostic().span_fatal(sp, msg).raise()
258     }
259     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
260         &self,
261         sp: S,
262         msg: &str,
263         code: DiagnosticId,
264     ) -> ! {
265         self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
266     }
267     pub fn fatal(&self, msg: &str) -> ! {
268         self.diagnostic().fatal(msg).raise()
269     }
270     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
271         if is_warning {
272             self.span_warn(sp, msg);
273         } else {
274             self.span_err(sp, msg);
275         }
276     }
277     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
278         self.diagnostic().span_err(sp, msg)
279     }
280     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
281         self.diagnostic().span_err_with_code(sp, &msg, code)
282     }
283     pub fn err(&self, msg: &str) {
284         self.diagnostic().err(msg)
285     }
286     pub fn err_count(&self) -> usize {
287         self.diagnostic().err_count()
288     }
289     pub fn has_errors(&self) -> bool {
290         self.diagnostic().has_errors()
291     }
292     pub fn abort_if_errors(&self) {
293         self.diagnostic().abort_if_errors();
294     }
295     pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
296         compile_result_from_err_count(self.err_count())
297     }
298     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
299         where F: FnOnce() -> T
300     {
301         let old_count = self.err_count();
302         let result = f();
303         let errors = self.err_count() - old_count;
304         if errors == 0 {
305             Ok(result)
306         } else {
307             Err(ErrorReported)
308         }
309     }
310     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
311         self.diagnostic().span_warn(sp, msg)
312     }
313     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
314         self.diagnostic().span_warn_with_code(sp, msg, code)
315     }
316     pub fn warn(&self, msg: &str) {
317         self.diagnostic().warn(msg)
318     }
319     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
320         match opt_sp {
321             Some(sp) => self.span_warn(sp, msg),
322             None => self.warn(msg),
323         }
324     }
325     /// Delay a span_bug() call until abort_if_errors()
326     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
327         self.diagnostic().delay_span_bug(sp, msg)
328     }
329     pub fn note_without_error(&self, msg: &str) {
330         self.diagnostic().note_without_error(msg)
331     }
332     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
333         self.diagnostic().span_note_without_error(sp, msg)
334     }
335     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
336         self.diagnostic().span_unimpl(sp, msg)
337     }
338     pub fn unimpl(&self, msg: &str) -> ! {
339         self.diagnostic().unimpl(msg)
340     }
341
342     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
343                                            lint: &'static lint::Lint,
344                                            id: ast::NodeId,
345                                            sp: S,
346                                            msg: &str) {
347         match *self.buffered_lints.borrow_mut() {
348             Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
349                                                     msg, BuiltinLintDiagnostics::Normal),
350             None => bug!("can't buffer lints after HIR lowering"),
351         }
352     }
353
354     pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(&self,
355         lint: &'static lint::Lint, id: ast::NodeId, sp: S,
356         msg: &str, diagnostic: BuiltinLintDiagnostics) {
357         match *self.buffered_lints.borrow_mut() {
358             Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
359                                                     msg, diagnostic),
360             None => bug!("can't buffer lints after HIR lowering"),
361         }
362     }
363
364     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
365         let id = self.next_node_id.get();
366
367         match id.as_usize().checked_add(count) {
368             Some(next) => {
369                 self.next_node_id.set(ast::NodeId::new(next));
370             }
371             None => bug!("Input too large, ran out of node ids!")
372         }
373
374         id
375     }
376     pub fn next_node_id(&self) -> NodeId {
377         self.reserve_node_ids(1)
378     }
379     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
380         &self.parse_sess.span_diagnostic
381     }
382
383     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
384     /// deduplicates on lint ID, span (if any), and message for this `Session`
385     fn diag_once<'a, 'b>(&'a self,
386                          diag_builder: &'b mut DiagnosticBuilder<'a>,
387                          method: DiagnosticBuilderMethod,
388                          msg_id: DiagnosticMessageId,
389                          message: &str,
390                          span_maybe: Option<Span>) {
391
392         let id_span_message = (msg_id, span_maybe, message.to_owned());
393         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
394         if fresh {
395             match method {
396                 DiagnosticBuilderMethod::Note => {
397                     diag_builder.note(message);
398                 },
399                 DiagnosticBuilderMethod::SpanNote => {
400                     let span = span_maybe.expect("span_note needs a span");
401                     diag_builder.span_note(span, message);
402                 },
403                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
404                     let span = span_maybe.expect("span_suggestion needs a span");
405                     diag_builder.span_suggestion(span, message, suggestion);
406                 }
407             }
408         }
409     }
410
411     pub fn diag_span_note_once<'a, 'b>(&'a self,
412                                        diag_builder: &'b mut DiagnosticBuilder<'a>,
413                                        msg_id: DiagnosticMessageId, span: Span, message: &str) {
414         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote,
415                        msg_id, message, Some(span));
416     }
417
418     pub fn diag_note_once<'a, 'b>(&'a self,
419                                   diag_builder: &'b mut DiagnosticBuilder<'a>,
420                                   msg_id: DiagnosticMessageId, message: &str) {
421         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
422     }
423
424     pub fn diag_span_suggestion_once<'a, 'b>(&'a self,
425                                              diag_builder: &'b mut DiagnosticBuilder<'a>,
426                                              msg_id: DiagnosticMessageId,
427                                              span: Span,
428                                              message: &str,
429                                              suggestion: String) {
430         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanSuggestion(suggestion),
431                        msg_id, message, Some(span));
432     }
433
434     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
435         self.parse_sess.codemap()
436     }
437     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
438     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
439     pub fn profile_queries(&self) -> bool {
440         self.opts.debugging_opts.profile_queries ||
441             self.opts.debugging_opts.profile_queries_and_keys
442     }
443     pub fn profile_queries_and_keys(&self) -> bool {
444         self.opts.debugging_opts.profile_queries_and_keys
445     }
446     pub fn count_llvm_insns(&self) -> bool {
447         self.opts.debugging_opts.count_llvm_insns
448     }
449     pub fn time_llvm_passes(&self) -> bool {
450         self.opts.debugging_opts.time_llvm_passes
451     }
452     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
453     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
454     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
455     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
456     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
457     pub fn print_llvm_passes(&self) -> bool {
458         self.opts.debugging_opts.print_llvm_passes
459     }
460
461     /// Get the features enabled for the current compilation session.
462     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
463     /// dependency tracking. Use tcx.features() instead.
464     #[inline]
465     pub fn features_untracked(&self) -> cell::Ref<feature_gate::Features> {
466         let features = self.features.borrow();
467
468         if features.is_none() {
469             bug!("Access to Session::features before it is initialized");
470         }
471
472         cell::Ref::map(features, |r| r.as_ref().unwrap())
473     }
474
475     pub fn init_features(&self, features: feature_gate::Features) {
476         *(self.features.borrow_mut()) = Some(features);
477     }
478
479     /// If true, we should gather causal information during NLL
480     /// checking. This will eventually be the normal thing, but right
481     /// now it is too unoptimized.
482     pub fn nll_dump_cause(&self) -> bool {
483         self.opts.debugging_opts.nll_dump_cause
484     }
485
486     /// Calculates the flavor of LTO to use for this compilation.
487     pub fn lto(&self) -> config::Lto {
488         // If our target has codegen requirements ignore the command line
489         if self.target.target.options.requires_lto {
490             return config::Lto::Fat
491         }
492
493         // If the user specified something, return that. If they only said `-C
494         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
495         // then ensure we can't use a ThinLTO.
496         match self.opts.cg.lto {
497             config::Lto::No => {}
498             config::Lto::Yes if self.opts.cli_forced_thinlto_off => {
499                 return config::Lto::Fat
500             }
501             other => return other,
502         }
503
504         // Ok at this point the target doesn't require anything and the user
505         // hasn't asked for anything. Our next decision is whether or not
506         // we enable "auto" ThinLTO where we use multiple codegen units and
507         // then do ThinLTO over those codegen units. The logic below will
508         // either return `No` or `ThinLocal`.
509
510         // If processing command line options determined that we're incompatible
511         // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
512         if self.opts.cli_forced_thinlto_off {
513             return config::Lto::No
514         }
515
516         // If `-Z thinlto` specified process that, but note that this is mostly
517         // a deprecated option now that `-C lto=thin` exists.
518         if let Some(enabled) = self.opts.debugging_opts.thinlto {
519             if enabled {
520                 return config::Lto::ThinLocal
521             } else {
522                 return config::Lto::No
523             }
524         }
525
526         // If there's only one codegen unit and LTO isn't enabled then there's
527         // no need for ThinLTO so just return false.
528         if self.codegen_units() == 1 {
529             return config::Lto::No
530         }
531
532         // Right now ThinLTO isn't compatible with incremental compilation.
533         if self.opts.incremental.is_some() {
534             return config::Lto::No
535         }
536
537         // Now we're in "defaults" territory. By default we enable ThinLTO for
538         // optimized compiles (anything greater than O0).
539         match self.opts.optimize {
540             config::OptLevel::No => config::Lto::No,
541             _ => config::Lto::ThinLocal,
542         }
543     }
544
545     /// Returns the panic strategy for this compile session. If the user explicitly selected one
546     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
547     pub fn panic_strategy(&self) -> PanicStrategy {
548         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
549     }
550     pub fn linker_flavor(&self) -> LinkerFlavor {
551         self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
552     }
553
554     pub fn fewer_names(&self) -> bool {
555         let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly) ||
556                          self.opts.output_types.contains_key(&OutputType::Bitcode);
557         self.opts.debugging_opts.fewer_names || !more_names
558     }
559
560     pub fn no_landing_pads(&self) -> bool {
561         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
562     }
563     pub fn unstable_options(&self) -> bool {
564         self.opts.debugging_opts.unstable_options
565     }
566     pub fn nonzeroing_move_hints(&self) -> bool {
567         self.opts.debugging_opts.enable_nonzeroing_move_hints
568     }
569     pub fn overflow_checks(&self) -> bool {
570         self.opts.cg.overflow_checks
571             .or(self.opts.debugging_opts.force_overflow_checks)
572             .unwrap_or(self.opts.debug_assertions)
573     }
574
575     pub fn crt_static(&self) -> bool {
576         // If the target does not opt in to crt-static support, use its default.
577         if self.target.target.options.crt_static_respected {
578             self.crt_static_feature()
579         } else {
580             self.target.target.options.crt_static_default
581         }
582     }
583
584     pub fn crt_static_feature(&self) -> bool {
585         let requested_features = self.opts.cg.target_feature.split(',');
586         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
587         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
588
589         // If the target we're compiling for requests a static crt by default,
590         // then see if the `-crt-static` feature was passed to disable that.
591         // Otherwise if we don't have a static crt by default then see if the
592         // `+crt-static` feature was passed.
593         if self.target.target.options.crt_static_default {
594             !found_negative
595         } else {
596             found_positive
597         }
598     }
599
600     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
601         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
602         !self.target.target.options.eliminate_frame_pointer
603     }
604
605     /// Returns the symbol name for the registrar function,
606     /// given the crate Svh and the function DefIndex.
607     pub fn generate_plugin_registrar_symbol(&self,
608                                             disambiguator: CrateDisambiguator)
609                                             -> String {
610         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
611     }
612
613     pub fn generate_derive_registrar_symbol(&self,
614                                             disambiguator: CrateDisambiguator)
615                                             -> String {
616         format!("__rustc_derive_registrar_{}__", disambiguator.to_fingerprint().to_hex())
617     }
618
619     pub fn sysroot<'a>(&'a self) -> &'a Path {
620         match self.opts.maybe_sysroot {
621             Some (ref sysroot) => sysroot,
622             None => self.default_sysroot.as_ref()
623                         .expect("missing sysroot and default_sysroot in Session")
624         }
625     }
626     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
627         filesearch::FileSearch::new(self.sysroot(),
628                                     &self.opts.target_triple,
629                                     &self.opts.search_paths,
630                                     kind)
631     }
632     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
633         filesearch::FileSearch::new(
634             self.sysroot(),
635             config::host_triple(),
636             &self.opts.search_paths,
637             kind)
638     }
639
640     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
641         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
642
643         match *incr_comp_session {
644             IncrCompSession::Active { ref mut load_dep_graph, .. } => {
645                 *load_dep_graph = load;
646             }
647             _ => {}
648         }
649     }
650
651     pub fn incr_session_load_dep_graph(&self) -> bool {
652         let incr_comp_session = self.incr_comp_session.borrow();
653         match *incr_comp_session {
654             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
655             _ => false,
656         }
657     }
658
659     pub fn init_incr_comp_session(&self,
660                                   session_dir: PathBuf,
661                                   lock_file: flock::Lock,
662                                   load_dep_graph: bool) {
663         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
664
665         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
666             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
667         }
668
669         *incr_comp_session = IncrCompSession::Active {
670             session_directory: session_dir,
671             lock_file,
672             load_dep_graph,
673         };
674     }
675
676     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
677         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
678
679         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
680             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
681         }
682
683         // Note: This will also drop the lock file, thus unlocking the directory
684         *incr_comp_session = IncrCompSession::Finalized {
685             session_directory: new_directory_path,
686         };
687     }
688
689     pub fn mark_incr_comp_session_as_invalid(&self) {
690         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
691
692         let session_directory = match *incr_comp_session {
693             IncrCompSession::Active { ref session_directory, .. } => {
694                 session_directory.clone()
695             }
696             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
697             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
698                       *incr_comp_session),
699         };
700
701         // Note: This will also drop the lock file, thus unlocking the directory
702         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
703             session_directory,
704         };
705     }
706
707     pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
708         let incr_comp_session = self.incr_comp_session.borrow();
709         cell::Ref::map(incr_comp_session, |incr_comp_session| {
710             match *incr_comp_session {
711                 IncrCompSession::NotInitialized => {
712                     bug!("Trying to get session directory from IncrCompSession `{:?}`",
713                         *incr_comp_session)
714                 }
715                 IncrCompSession::Active { ref session_directory, .. } |
716                 IncrCompSession::Finalized { ref session_directory } |
717                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
718                     session_directory
719                 }
720             }
721         })
722     }
723
724     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
725         if self.opts.incremental.is_some() {
726             Some(self.incr_comp_session_dir())
727         } else {
728             None
729         }
730     }
731
732     pub fn print_perf_stats(&self) {
733         println!("Total time spent computing SVHs:               {}",
734                  duration_to_secs_str(self.perf_stats.svh_time.get()));
735         println!("Total time spent computing incr. comp. hashes: {}",
736                  duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
737         println!("Total number of incr. comp. hashes computed:   {}",
738                  self.perf_stats.incr_comp_hashes_count.get());
739         println!("Total number of bytes hashed for incr. comp.:  {}",
740                  self.perf_stats.incr_comp_bytes_hashed.get());
741         if self.perf_stats.incr_comp_hashes_count.get() != 0 {
742             println!("Average bytes hashed per incr. comp. HIR node: {}",
743                     self.perf_stats.incr_comp_bytes_hashed.get() /
744                     self.perf_stats.incr_comp_hashes_count.get());
745         } else {
746             println!("Average bytes hashed per incr. comp. HIR node: N/A");
747         }
748         println!("Total time spent computing symbol hashes:      {}",
749                  duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
750         println!("Total time spent decoding DefPath tables:      {}",
751                  duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
752     }
753
754     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
755     /// This expends fuel if applicable, and records fuel if applicable.
756     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
757         let mut ret = true;
758         match self.optimization_fuel_crate {
759             Some(ref c) if c == crate_name => {
760                 let fuel = self.optimization_fuel_limit.get();
761                 ret = fuel != 0;
762                 if fuel == 0 && !self.out_of_fuel.get() {
763                     println!("optimization-fuel-exhausted: {}", msg());
764                     self.out_of_fuel.set(true);
765                 } else if fuel > 0 {
766                     self.optimization_fuel_limit.set(fuel-1);
767                 }
768             }
769             _ => {}
770         }
771         match self.print_fuel_crate {
772             Some(ref c) if c == crate_name=> {
773                 self.print_fuel.set(self.print_fuel.get()+1);
774             },
775             _ => {}
776         }
777         ret
778     }
779
780     /// Returns the number of query threads that should be used for this
781     /// compilation
782     pub fn query_threads(&self) -> usize {
783         self.opts.debugging_opts.query_threads.unwrap_or(1)
784     }
785
786     /// Returns the number of codegen units that should be used for this
787     /// compilation
788     pub fn codegen_units(&self) -> usize {
789         if let Some(n) = self.opts.cli_forced_codegen_units {
790             return n
791         }
792         if let Some(n) = self.target.target.options.default_codegen_units {
793             return n as usize
794         }
795
796         // Why is 16 codegen units the default all the time?
797         //
798         // The main reason for enabling multiple codegen units by default is to
799         // leverage the ability for the trans backend to do translation and
800         // codegen in parallel. This allows us, especially for large crates, to
801         // make good use of all available resources on the machine once we've
802         // hit that stage of compilation. Large crates especially then often
803         // take a long time in trans/codegen and this helps us amortize that
804         // cost.
805         //
806         // Note that a high number here doesn't mean that we'll be spawning a
807         // large number of threads in parallel. The backend of rustc contains
808         // global rate limiting through the `jobserver` crate so we'll never
809         // overload the system with too much work, but rather we'll only be
810         // optimizing when we're otherwise cooperating with other instances of
811         // rustc.
812         //
813         // Rather a high number here means that we should be able to keep a lot
814         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
815         // to build we'll be guaranteed that all cpus will finish pretty closely
816         // to one another and we should make relatively optimal use of system
817         // resources
818         //
819         // Note that the main cost of codegen units is that it prevents LLVM
820         // from inlining across codegen units. Users in general don't have a lot
821         // of control over how codegen units are split up so it's our job in the
822         // compiler to ensure that undue performance isn't lost when using
823         // codegen units (aka we can't require everyone to slap `#[inline]` on
824         // everything).
825         //
826         // If we're compiling at `-O0` then the number doesn't really matter too
827         // much because performance doesn't matter and inlining is ok to lose.
828         // In debug mode we just want to try to guarantee that no cpu is stuck
829         // doing work that could otherwise be farmed to others.
830         //
831         // In release mode, however (O1 and above) performance does indeed
832         // matter! To recover the loss in performance due to inlining we'll be
833         // enabling ThinLTO by default (the function for which is just below).
834         // This will ensure that we recover any inlining wins we otherwise lost
835         // through codegen unit partitioning.
836         //
837         // ---
838         //
839         // Ok that's a lot of words but the basic tl;dr; is that we want a high
840         // number here -- but not too high. Additionally we're "safe" to have it
841         // always at the same number at all optimization levels.
842         //
843         // As a result 16 was chosen here! Mostly because it was a power of 2
844         // and most benchmarks agreed it was roughly a local optimum. Not very
845         // scientific.
846         16
847     }
848
849     pub fn teach(&self, code: &DiagnosticId) -> bool {
850         self.opts.debugging_opts.teach && !self.parse_sess.span_diagnostic.code_emitted(code)
851     }
852
853     /// Are we allowed to use features from the Rust 2018 epoch?
854     pub fn rust_2018(&self) -> bool {
855         self.opts.debugging_opts.epoch >= Epoch::Epoch2018
856     }
857
858     pub fn epoch(&self) -> Epoch {
859         self.opts.debugging_opts.epoch
860     }
861 }
862
863 pub fn build_session(sopts: config::Options,
864                      local_crate_source_file: Option<PathBuf>,
865                      registry: errors::registry::Registry)
866                      -> Session {
867     let file_path_mapping = sopts.file_path_mapping();
868
869     build_session_with_codemap(sopts,
870                                local_crate_source_file,
871                                registry,
872                                Lrc::new(codemap::CodeMap::new(file_path_mapping)),
873                                None)
874 }
875
876 pub fn build_session_with_codemap(sopts: config::Options,
877                                   local_crate_source_file: Option<PathBuf>,
878                                   registry: errors::registry::Registry,
879                                   codemap: Lrc<codemap::CodeMap>,
880                                   emitter_dest: Option<Box<dyn Write + Send>>)
881                                   -> Session {
882     // FIXME: This is not general enough to make the warning lint completely override
883     // normal diagnostic warnings, since the warning lint can also be denied and changed
884     // later via the source code.
885     let warnings_allow = sopts.lint_opts
886         .iter()
887         .filter(|&&(ref key, _)| *key == "warnings")
888         .map(|&(_, ref level)| *level == lint::Allow)
889         .last()
890         .unwrap_or(false);
891     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
892
893     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
894
895     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
896
897     let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
898
899     let emitter: Box<dyn Emitter> = match (sopts.error_format, emitter_dest) {
900         (config::ErrorOutputType::HumanReadable(color_config), None) => {
901             Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()),
902                      false, sopts.debugging_opts.teach)
903                      .ui_testing(sopts.debugging_opts.ui_testing))
904         }
905         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
906             Box::new(EmitterWriter::new(dst, Some(codemap.clone()),
907                      false, false)
908                      .ui_testing(sopts.debugging_opts.ui_testing))
909         }
910         (config::ErrorOutputType::Json(pretty), None) => {
911             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone(),
912                      pretty, sopts.debugging_opts.approximate_suggestions)
913                      .ui_testing(sopts.debugging_opts.ui_testing))
914         }
915         (config::ErrorOutputType::Json(pretty), Some(dst)) => {
916             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone(),
917                      pretty, sopts.debugging_opts.approximate_suggestions)
918                      .ui_testing(sopts.debugging_opts.ui_testing))
919         }
920         (config::ErrorOutputType::Short(color_config), None) => {
921             Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false))
922         }
923         (config::ErrorOutputType::Short(_), Some(dst)) => {
924             Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
925         }
926     };
927
928     let diagnostic_handler =
929         errors::Handler::with_emitter_and_flags(
930             emitter,
931             errors::HandlerFlags {
932                 can_emit_warnings,
933                 treat_err_as_bug,
934                 external_macro_backtrace,
935                 .. Default::default()
936             });
937
938     build_session_(sopts,
939                    local_crate_source_file,
940                    diagnostic_handler,
941                    codemap)
942 }
943
944 pub fn build_session_(sopts: config::Options,
945                       local_crate_source_file: Option<PathBuf>,
946                       span_diagnostic: errors::Handler,
947                       codemap: Lrc<codemap::CodeMap>)
948                       -> Session {
949     let host = match Target::search(config::host_triple()) {
950         Ok(t) => t,
951         Err(e) => {
952             span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise();
953         }
954     };
955     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
956
957     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
958     let default_sysroot = match sopts.maybe_sysroot {
959         Some(_) => None,
960         None => Some(filesearch::get_or_default_sysroot())
961     };
962
963     let file_path_mapping = sopts.file_path_mapping();
964
965     let local_crate_source_file = local_crate_source_file.map(|path| {
966         file_path_mapping.map_prefix(path).0
967     });
968
969     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
970     let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
971         .map(|i| i.1).unwrap_or(0));
972     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
973     let print_fuel = Cell::new(0);
974
975     let working_dir = match env::current_dir() {
976         Ok(dir) => dir,
977         Err(e) => {
978             p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
979         }
980     };
981     let working_dir = file_path_mapping.map_prefix(working_dir);
982
983     let sess = Session {
984         target: target_cfg,
985         host,
986         opts: sopts,
987         parse_sess: p_s,
988         // For a library crate, this is always none
989         entry_fn: RefCell::new(None),
990         entry_type: Cell::new(None),
991         plugin_registrar_fn: Cell::new(None),
992         derive_registrar_fn: Cell::new(None),
993         default_sysroot,
994         local_crate_source_file,
995         working_dir,
996         lint_store: RefCell::new(lint::LintStore::new()),
997         buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
998         one_time_diagnostics: RefCell::new(FxHashSet()),
999         plugin_llvm_passes: RefCell::new(Vec::new()),
1000         plugin_attributes: RefCell::new(Vec::new()),
1001         crate_types: RefCell::new(Vec::new()),
1002         dependency_formats: RefCell::new(FxHashMap()),
1003         crate_disambiguator: RefCell::new(None),
1004         features: RefCell::new(None),
1005         recursion_limit: Cell::new(64),
1006         type_length_limit: Cell::new(1048576),
1007         next_node_id: Cell::new(NodeId::new(1)),
1008         injected_allocator: Cell::new(None),
1009         allocator_kind: Cell::new(None),
1010         injected_panic_runtime: Cell::new(None),
1011         imported_macro_spans: RefCell::new(HashMap::new()),
1012         incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
1013         ignored_attr_names: ich::compute_ignored_attr_names(),
1014         perf_stats: PerfStats {
1015             svh_time: Cell::new(Duration::from_secs(0)),
1016             incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
1017             incr_comp_hashes_count: Cell::new(0),
1018             incr_comp_bytes_hashed: Cell::new(0),
1019             symbol_hash_time: Cell::new(Duration::from_secs(0)),
1020             decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
1021         },
1022         code_stats: RefCell::new(CodeStats::new()),
1023         optimization_fuel_crate,
1024         optimization_fuel_limit,
1025         print_fuel_crate,
1026         print_fuel,
1027         out_of_fuel: Cell::new(false),
1028         // Note that this is unsafe because it may misinterpret file descriptors
1029         // on Unix as jobserver file descriptors. We hopefully execute this near
1030         // the beginning of the process though to ensure we don't get false
1031         // positives, or in other words we try to execute this before we open
1032         // any file descriptors ourselves.
1033         //
1034         // Also note that we stick this in a global because there could be
1035         // multiple `Session` instances in this process, and the jobserver is
1036         // per-process.
1037         jobserver_from_env: unsafe {
1038             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
1039             static INIT: Once = ONCE_INIT;
1040             INIT.call_once(|| {
1041                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
1042             });
1043             (*GLOBAL_JOBSERVER).clone()
1044         },
1045         has_global_allocator: Cell::new(false),
1046     };
1047
1048     sess
1049 }
1050
1051 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1052 /// compiler. Together with the crate-name forms a unique global identifier for
1053 /// the crate.
1054 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1055 pub struct CrateDisambiguator(Fingerprint);
1056
1057 impl CrateDisambiguator {
1058     pub fn to_fingerprint(self) -> Fingerprint {
1059         self.0
1060     }
1061 }
1062
1063 impl From<Fingerprint> for CrateDisambiguator {
1064     fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1065         CrateDisambiguator(fingerprint)
1066     }
1067 }
1068
1069 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1070
1071 /// Holds data on the current incremental compilation session, if there is one.
1072 #[derive(Debug)]
1073 pub enum IncrCompSession {
1074     /// This is the state the session will be in until the incr. comp. dir is
1075     /// needed.
1076     NotInitialized,
1077     /// This is the state during which the session directory is private and can
1078     /// be modified.
1079     Active {
1080         session_directory: PathBuf,
1081         lock_file: flock::Lock,
1082         load_dep_graph: bool,
1083     },
1084     /// This is the state after the session directory has been finalized. In this
1085     /// state, the contents of the directory must not be modified any more.
1086     Finalized {
1087         session_directory: PathBuf,
1088     },
1089     /// This is an error state that is reached when some compilation error has
1090     /// occurred. It indicates that the contents of the session directory must
1091     /// not be used, since they might be invalid.
1092     InvalidBecauseOfErrors {
1093         session_directory: PathBuf,
1094     }
1095 }
1096
1097 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1098     let emitter: Box<dyn Emitter> = match output {
1099         config::ErrorOutputType::HumanReadable(color_config) => {
1100             Box::new(EmitterWriter::stderr(color_config, None, false, false))
1101         }
1102         config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1103         config::ErrorOutputType::Short(color_config) => {
1104             Box::new(EmitterWriter::stderr(color_config, None, true, false))
1105         }
1106     };
1107     let handler = errors::Handler::with_emitter(true, false, emitter);
1108     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1109     errors::FatalError.raise();
1110 }
1111
1112 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1113     let emitter: Box<dyn Emitter> = match output {
1114         config::ErrorOutputType::HumanReadable(color_config) => {
1115             Box::new(EmitterWriter::stderr(color_config, None, false, false))
1116         }
1117         config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1118         config::ErrorOutputType::Short(color_config) => {
1119             Box::new(EmitterWriter::stderr(color_config, None, true, false))
1120         }
1121     };
1122     let handler = errors::Handler::with_emitter(true, false, emitter);
1123     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1124 }
1125
1126 #[derive(Copy, Clone, Debug)]
1127 pub enum CompileIncomplete {
1128     Stopped,
1129     Errored(ErrorReported)
1130 }
1131 impl From<ErrorReported> for CompileIncomplete {
1132     fn from(err: ErrorReported) -> CompileIncomplete {
1133         CompileIncomplete::Errored(err)
1134     }
1135 }
1136 pub type CompileResult = Result<(), CompileIncomplete>;
1137
1138 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1139     if err_count == 0 {
1140         Ok(())
1141     } else {
1142         Err(CompileIncomplete::Errored(ErrorReported))
1143     }
1144 }
1145
1146 #[cold]
1147 #[inline(never)]
1148 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1149     // this wrapper mostly exists so I don't have to write a fully
1150     // qualified path of None::<Span> inside the bug!() macro definition
1151     opt_span_bug_fmt(file, line, None::<Span>, args);
1152 }
1153
1154 #[cold]
1155 #[inline(never)]
1156 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1157                                         line: u32,
1158                                         span: S,
1159                                         args: fmt::Arguments) -> ! {
1160     opt_span_bug_fmt(file, line, Some(span), args);
1161 }
1162
1163 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1164                                         line: u32,
1165                                         span: Option<S>,
1166                                         args: fmt::Arguments) -> ! {
1167     tls::with_opt(move |tcx| {
1168         let msg = format!("{}:{}: {}", file, line, args);
1169         match (tcx, span) {
1170             (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1171             (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1172             (None, _) => panic!(msg)
1173         }
1174     });
1175     unreachable!();
1176 }