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