]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
Auto merge of #38981 - sdleffler:patch-1, 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 dep_graph::DepGraph;
15 use hir::def_id::{CrateNum, DefIndex};
16 use hir::svh::Svh;
17 use lint;
18 use middle::cstore::CrateStore;
19 use middle::dependency_format;
20 use session::search_paths::PathKind;
21 use session::config::DebugInfoLevel;
22 use ty::tls;
23 use util::nodemap::{FxHashMap, FxHashSet};
24 use util::common::duration_to_secs_str;
25 use mir::transform as mir_pass;
26
27 use syntax::ast::NodeId;
28 use errors::{self, DiagnosticBuilder};
29 use errors::emitter::{Emitter, EmitterWriter};
30 use syntax::json::JsonEmitter;
31 use syntax::feature_gate;
32 use syntax::parse;
33 use syntax::parse::ParseSess;
34 use syntax::symbol::Symbol;
35 use syntax::{ast, codemap};
36 use syntax::feature_gate::AttributeType;
37 use syntax_pos::{Span, MultiSpan};
38
39 use rustc_back::PanicStrategy;
40 use rustc_back::target::Target;
41 use rustc_data_structures::flock;
42 use llvm;
43
44 use std::path::{Path, PathBuf};
45 use std::cell::{self, Cell, RefCell};
46 use std::collections::HashMap;
47 use std::env;
48 use std::ffi::CString;
49 use std::io::Write;
50 use std::rc::Rc;
51 use std::fmt;
52 use std::time::Duration;
53 use libc::c_int;
54
55 mod code_stats;
56 pub mod config;
57 pub mod filesearch;
58 pub mod search_paths;
59
60 // Represents the data associated with a compilation
61 // session for a single crate.
62 pub struct Session {
63     pub dep_graph: DepGraph,
64     pub target: config::Config,
65     pub host: Target,
66     pub opts: config::Options,
67     pub cstore: Rc<for<'a> CrateStore<'a>>,
68     pub parse_sess: ParseSess,
69     // For a library crate, this is always none
70     pub entry_fn: RefCell<Option<(NodeId, Span)>>,
71     pub entry_type: Cell<Option<config::EntryFnType>>,
72     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
73     pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
74     pub default_sysroot: Option<PathBuf>,
75     // The name of the root source file of the crate, in the local file system.
76     // The path is always expected to be absolute. `None` means that there is no
77     // source file.
78     pub local_crate_source_file: Option<PathBuf>,
79     pub working_dir: PathBuf,
80     pub lint_store: RefCell<lint::LintStore>,
81     pub lints: RefCell<lint::LintTable>,
82     /// Set of (LintId, span, message) tuples tracking lint (sub)diagnostics
83     /// that have been set once, but should not be set again, in order to avoid
84     /// redundantly verbose output (Issue #24690).
85     pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Span, String)>>,
86     pub plugin_llvm_passes: RefCell<Vec<String>>,
87     pub mir_passes: RefCell<mir_pass::Passes>,
88     pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
89     pub crate_types: RefCell<Vec<config::CrateType>>,
90     pub dependency_formats: RefCell<dependency_format::Dependencies>,
91     // The crate_disambiguator is constructed out of all the `-C metadata`
92     // arguments passed to the compiler. Its value together with the crate-name
93     // forms a unique global identifier for the crate. It is used to allow
94     // multiple crates with the same name to coexist. See the
95     // trans::back::symbol_names module for more information.
96     pub crate_disambiguator: RefCell<Symbol>,
97     pub features: RefCell<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 injected_panic_runtime: Cell<Option<CrateNum>>,
111
112     /// Map from imported macro spans (which consist of
113     /// the localized span for the macro body) to the
114     /// macro name and defintion span in the source crate.
115     pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
116
117     incr_comp_session: RefCell<IncrCompSession>,
118
119     /// Some measurements that are being gathered during compilation.
120     pub perf_stats: PerfStats,
121
122     /// Data about code being compiled, gathered during compilation.
123     pub code_stats: RefCell<CodeStats>,
124
125     next_node_id: Cell<ast::NodeId>,
126 }
127
128 pub struct PerfStats {
129     // The accumulated time needed for computing the SVH of the crate
130     pub svh_time: Cell<Duration>,
131     // The accumulated time spent on computing incr. comp. hashes
132     pub incr_comp_hashes_time: Cell<Duration>,
133     // The number of incr. comp. hash computations performed
134     pub incr_comp_hashes_count: Cell<u64>,
135     // The number of bytes hashed when computing ICH values
136     pub incr_comp_bytes_hashed: Cell<u64>,
137     // The accumulated time spent on computing symbol hashes
138     pub symbol_hash_time: Cell<Duration>,
139     // The accumulated time spent decoding def path tables from metadata
140     pub decode_def_path_tables_time: Cell<Duration>,
141 }
142
143 impl Session {
144     pub fn local_crate_disambiguator(&self) -> Symbol {
145         *self.crate_disambiguator.borrow()
146     }
147     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
148                                                     sp: S,
149                                                     msg: &str)
150                                                     -> DiagnosticBuilder<'a>  {
151         self.diagnostic().struct_span_warn(sp, msg)
152     }
153     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
154                                                               sp: S,
155                                                               msg: &str,
156                                                               code: &str)
157                                                               -> DiagnosticBuilder<'a>  {
158         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
159     }
160     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
161         self.diagnostic().struct_warn(msg)
162     }
163     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
164                                                    sp: S,
165                                                    msg: &str)
166                                                    -> DiagnosticBuilder<'a>  {
167         self.diagnostic().struct_span_err(sp, msg)
168     }
169     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
170                                                              sp: S,
171                                                              msg: &str,
172                                                              code: &str)
173                                                              -> DiagnosticBuilder<'a>  {
174         self.diagnostic().struct_span_err_with_code(sp, msg, code)
175     }
176     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
177         self.diagnostic().struct_err(msg)
178     }
179     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
180                                                      sp: S,
181                                                      msg: &str)
182                                                      -> DiagnosticBuilder<'a>  {
183         self.diagnostic().struct_span_fatal(sp, msg)
184     }
185     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
186                                                                sp: S,
187                                                                msg: &str,
188                                                                code: &str)
189                                                                -> DiagnosticBuilder<'a>  {
190         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
191     }
192     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
193         self.diagnostic().struct_fatal(msg)
194     }
195
196     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
197         panic!(self.diagnostic().span_fatal(sp, msg))
198     }
199     pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
200         panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
201     }
202     pub fn fatal(&self, msg: &str) -> ! {
203         panic!(self.diagnostic().fatal(msg))
204     }
205     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
206         if is_warning {
207             self.span_warn(sp, msg);
208         } else {
209             self.span_err(sp, msg);
210         }
211     }
212     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
213         self.diagnostic().span_err(sp, msg)
214     }
215     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
216         self.diagnostic().span_err_with_code(sp, &msg, code)
217     }
218     pub fn err(&self, msg: &str) {
219         self.diagnostic().err(msg)
220     }
221     pub fn err_count(&self) -> usize {
222         self.diagnostic().err_count()
223     }
224     pub fn has_errors(&self) -> bool {
225         self.diagnostic().has_errors()
226     }
227     pub fn abort_if_errors(&self) {
228         self.diagnostic().abort_if_errors();
229     }
230     pub fn track_errors<F, T>(&self, f: F) -> Result<T, usize>
231         where F: FnOnce() -> T
232     {
233         let old_count = self.err_count();
234         let result = f();
235         let errors = self.err_count() - old_count;
236         if errors == 0 {
237             Ok(result)
238         } else {
239             Err(errors)
240         }
241     }
242     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
243         self.diagnostic().span_warn(sp, msg)
244     }
245     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
246         self.diagnostic().span_warn_with_code(sp, msg, code)
247     }
248     pub fn warn(&self, msg: &str) {
249         self.diagnostic().warn(msg)
250     }
251     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
252         match opt_sp {
253             Some(sp) => self.span_warn(sp, msg),
254             None => self.warn(msg),
255         }
256     }
257     /// Delay a span_bug() call until abort_if_errors()
258     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
259         self.diagnostic().delay_span_bug(sp, msg)
260     }
261     pub fn note_without_error(&self, msg: &str) {
262         self.diagnostic().note_without_error(msg)
263     }
264     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
265         self.diagnostic().span_note_without_error(sp, msg)
266     }
267     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
268         self.diagnostic().span_unimpl(sp, msg)
269     }
270     pub fn unimpl(&self, msg: &str) -> ! {
271         self.diagnostic().unimpl(msg)
272     }
273
274     pub fn add_lint<S: Into<MultiSpan>>(&self,
275                                         lint: &'static lint::Lint,
276                                         id: ast::NodeId,
277                                         sp: S,
278                                         msg: String)
279     {
280         self.lints.borrow_mut().add_lint(lint, id, sp, msg);
281     }
282
283     pub fn add_lint_diagnostic<M>(&self,
284                                   lint: &'static lint::Lint,
285                                   id: ast::NodeId,
286                                   msg: M)
287         where M: lint::IntoEarlyLint,
288     {
289         self.lints.borrow_mut().add_lint_diagnostic(lint, id, msg);
290     }
291
292     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
293         let id = self.next_node_id.get();
294
295         match id.as_usize().checked_add(count) {
296             Some(next) => {
297                 self.next_node_id.set(ast::NodeId::new(next));
298             }
299             None => bug!("Input too large, ran out of node ids!")
300         }
301
302         id
303     }
304     pub fn next_node_id(&self) -> NodeId {
305         self.reserve_node_ids(1)
306     }
307     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
308         &self.parse_sess.span_diagnostic
309     }
310
311     /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but
312     /// deduplicates on lint ID, span, and message for this `Session` if we're
313     /// not outputting in JSON mode.
314     //
315     // FIXME: if the need arises for one-time diagnostics other than
316     // `span_note`, we almost certainly want to generalize this
317     // "check/insert-into the one-time diagnostics map, then set message if
318     // it's not already there" code to accomodate all of them
319     pub fn diag_span_note_once<'a, 'b>(&'a self,
320                                        diag_builder: &'b mut DiagnosticBuilder<'a>,
321                                        lint: &'static lint::Lint, span: Span, message: &str) {
322         match self.opts.error_format {
323             // when outputting JSON for tool consumption, the tool might want
324             // the duplicates
325             config::ErrorOutputType::Json => {
326                 diag_builder.span_note(span, &message);
327             },
328             _ => {
329                 let lint_id = lint::LintId::of(lint);
330                 let id_span_message = (lint_id, span, message.to_owned());
331                 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
332                 if fresh {
333                     diag_builder.span_note(span, &message);
334                 }
335             }
336         }
337     }
338
339     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
340         self.parse_sess.codemap()
341     }
342     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
343     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
344     pub fn count_llvm_insns(&self) -> bool {
345         self.opts.debugging_opts.count_llvm_insns
346     }
347     pub fn time_llvm_passes(&self) -> bool {
348         self.opts.debugging_opts.time_llvm_passes
349     }
350     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
351     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
352     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
353     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
354     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
355     pub fn print_llvm_passes(&self) -> bool {
356         self.opts.debugging_opts.print_llvm_passes
357     }
358     pub fn lto(&self) -> bool {
359         self.opts.cg.lto
360     }
361     /// Returns the panic strategy for this compile session. If the user explicitly selected one
362     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
363     pub fn panic_strategy(&self) -> PanicStrategy {
364         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
365     }
366     pub fn no_landing_pads(&self) -> bool {
367         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
368     }
369     pub fn unstable_options(&self) -> bool {
370         self.opts.debugging_opts.unstable_options
371     }
372     pub fn nonzeroing_move_hints(&self) -> bool {
373         self.opts.debugging_opts.enable_nonzeroing_move_hints
374     }
375
376     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
377         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
378         !self.target.target.options.eliminate_frame_pointer
379     }
380
381     /// Returns the symbol name for the registrar function,
382     /// given the crate Svh and the function DefIndex.
383     pub fn generate_plugin_registrar_symbol(&self, svh: &Svh, index: DefIndex)
384                                             -> String {
385         format!("__rustc_plugin_registrar__{}_{}", svh, index.as_usize())
386     }
387
388     pub fn generate_derive_registrar_symbol(&self,
389                                             svh: &Svh,
390                                             index: DefIndex) -> String {
391         format!("__rustc_derive_registrar__{}_{}", svh, index.as_usize())
392     }
393
394     pub fn sysroot<'a>(&'a self) -> &'a Path {
395         match self.opts.maybe_sysroot {
396             Some (ref sysroot) => sysroot,
397             None => self.default_sysroot.as_ref()
398                         .expect("missing sysroot and default_sysroot in Session")
399         }
400     }
401     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
402         filesearch::FileSearch::new(self.sysroot(),
403                                     &self.opts.target_triple,
404                                     &self.opts.search_paths,
405                                     kind)
406     }
407     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
408         filesearch::FileSearch::new(
409             self.sysroot(),
410             config::host_triple(),
411             &self.opts.search_paths,
412             kind)
413     }
414
415     pub fn init_incr_comp_session(&self,
416                                   session_dir: PathBuf,
417                                   lock_file: flock::Lock) {
418         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
419
420         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
421             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
422         }
423
424         *incr_comp_session = IncrCompSession::Active {
425             session_directory: session_dir,
426             lock_file: lock_file,
427         };
428     }
429
430     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
431         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
432
433         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
434             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
435         }
436
437         // Note: This will also drop the lock file, thus unlocking the directory
438         *incr_comp_session = IncrCompSession::Finalized {
439             session_directory: new_directory_path,
440         };
441     }
442
443     pub fn mark_incr_comp_session_as_invalid(&self) {
444         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
445
446         let session_directory = match *incr_comp_session {
447             IncrCompSession::Active { ref session_directory, .. } => {
448                 session_directory.clone()
449             }
450             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
451                       *incr_comp_session),
452         };
453
454         // Note: This will also drop the lock file, thus unlocking the directory
455         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
456             session_directory: session_directory
457         };
458     }
459
460     pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
461         let incr_comp_session = self.incr_comp_session.borrow();
462         cell::Ref::map(incr_comp_session, |incr_comp_session| {
463             match *incr_comp_session {
464                 IncrCompSession::NotInitialized => {
465                     bug!("Trying to get session directory from IncrCompSession `{:?}`",
466                         *incr_comp_session)
467                 }
468                 IncrCompSession::Active { ref session_directory, .. } |
469                 IncrCompSession::Finalized { ref session_directory } |
470                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
471                     session_directory
472                 }
473             }
474         })
475     }
476
477     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
478         if self.opts.incremental.is_some() {
479             Some(self.incr_comp_session_dir())
480         } else {
481             None
482         }
483     }
484
485     pub fn print_perf_stats(&self) {
486         println!("Total time spent computing SVHs:               {}",
487                  duration_to_secs_str(self.perf_stats.svh_time.get()));
488         println!("Total time spent computing incr. comp. hashes: {}",
489                  duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
490         println!("Total number of incr. comp. hashes computed:   {}",
491                  self.perf_stats.incr_comp_hashes_count.get());
492         println!("Total number of bytes hashed for incr. comp.:  {}",
493                  self.perf_stats.incr_comp_bytes_hashed.get());
494         println!("Average bytes hashed per incr. comp. HIR node: {}",
495                  self.perf_stats.incr_comp_bytes_hashed.get() /
496                  self.perf_stats.incr_comp_hashes_count.get());
497         println!("Total time spent computing symbol hashes:      {}",
498                  duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
499         println!("Total time spent decoding DefPath tables:      {}",
500                  duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
501     }
502 }
503
504 pub fn build_session(sopts: config::Options,
505                      dep_graph: &DepGraph,
506                      local_crate_source_file: Option<PathBuf>,
507                      registry: errors::registry::Registry,
508                      cstore: Rc<for<'a> CrateStore<'a>>)
509                      -> Session {
510     build_session_with_codemap(sopts,
511                                dep_graph,
512                                local_crate_source_file,
513                                registry,
514                                cstore,
515                                Rc::new(codemap::CodeMap::new()),
516                                None)
517 }
518
519 pub fn build_session_with_codemap(sopts: config::Options,
520                                   dep_graph: &DepGraph,
521                                   local_crate_source_file: Option<PathBuf>,
522                                   registry: errors::registry::Registry,
523                                   cstore: Rc<for<'a> CrateStore<'a>>,
524                                   codemap: Rc<codemap::CodeMap>,
525                                   emitter_dest: Option<Box<Write + Send>>)
526                                   -> Session {
527     // FIXME: This is not general enough to make the warning lint completely override
528     // normal diagnostic warnings, since the warning lint can also be denied and changed
529     // later via the source code.
530     let can_print_warnings = sopts.lint_opts
531         .iter()
532         .filter(|&&(ref key, _)| *key == "warnings")
533         .map(|&(_, ref level)| *level != lint::Allow)
534         .last()
535         .unwrap_or(true);
536     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
537
538     let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
539         (config::ErrorOutputType::HumanReadable(color_config), None) => {
540             Box::new(EmitterWriter::stderr(color_config,
541                                            Some(codemap.clone())))
542         }
543         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
544             Box::new(EmitterWriter::new(dst,
545                                         Some(codemap.clone())))
546         }
547         (config::ErrorOutputType::Json, None) => {
548             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
549         }
550         (config::ErrorOutputType::Json, Some(dst)) => {
551             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
552         }
553     };
554
555     let diagnostic_handler =
556         errors::Handler::with_emitter(can_print_warnings,
557                                       treat_err_as_bug,
558                                       emitter);
559
560     build_session_(sopts,
561                    dep_graph,
562                    local_crate_source_file,
563                    diagnostic_handler,
564                    codemap,
565                    cstore)
566 }
567
568 pub fn build_session_(sopts: config::Options,
569                       dep_graph: &DepGraph,
570                       local_crate_source_file: Option<PathBuf>,
571                       span_diagnostic: errors::Handler,
572                       codemap: Rc<codemap::CodeMap>,
573                       cstore: Rc<for<'a> CrateStore<'a>>)
574                       -> Session {
575     let host = match Target::search(config::host_triple()) {
576         Ok(t) => t,
577         Err(e) => {
578             panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
579     }
580     };
581     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
582     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
583     let default_sysroot = match sopts.maybe_sysroot {
584         Some(_) => None,
585         None => Some(filesearch::get_or_default_sysroot())
586     };
587
588     // Make the path absolute, if necessary
589     let local_crate_source_file = local_crate_source_file.map(|path|
590         if path.is_absolute() {
591             path.clone()
592         } else {
593             env::current_dir().unwrap().join(&path)
594         }
595     );
596
597     let sess = Session {
598         dep_graph: dep_graph.clone(),
599         target: target_cfg,
600         host: host,
601         opts: sopts,
602         cstore: cstore,
603         parse_sess: p_s,
604         // For a library crate, this is always none
605         entry_fn: RefCell::new(None),
606         entry_type: Cell::new(None),
607         plugin_registrar_fn: Cell::new(None),
608         derive_registrar_fn: Cell::new(None),
609         default_sysroot: default_sysroot,
610         local_crate_source_file: local_crate_source_file,
611         working_dir: env::current_dir().unwrap(),
612         lint_store: RefCell::new(lint::LintStore::new()),
613         lints: RefCell::new(lint::LintTable::new()),
614         one_time_diagnostics: RefCell::new(FxHashSet()),
615         plugin_llvm_passes: RefCell::new(Vec::new()),
616         mir_passes: RefCell::new(mir_pass::Passes::new()),
617         plugin_attributes: RefCell::new(Vec::new()),
618         crate_types: RefCell::new(Vec::new()),
619         dependency_formats: RefCell::new(FxHashMap()),
620         crate_disambiguator: RefCell::new(Symbol::intern("")),
621         features: RefCell::new(feature_gate::Features::new()),
622         recursion_limit: Cell::new(64),
623         type_length_limit: Cell::new(1048576),
624         next_node_id: Cell::new(NodeId::new(1)),
625         injected_allocator: Cell::new(None),
626         injected_panic_runtime: Cell::new(None),
627         imported_macro_spans: RefCell::new(HashMap::new()),
628         incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
629         perf_stats: PerfStats {
630             svh_time: Cell::new(Duration::from_secs(0)),
631             incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
632             incr_comp_hashes_count: Cell::new(0),
633             incr_comp_bytes_hashed: Cell::new(0),
634             symbol_hash_time: Cell::new(Duration::from_secs(0)),
635             decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
636         },
637         code_stats: RefCell::new(CodeStats::new()),
638     };
639
640     init_llvm(&sess);
641
642     sess
643 }
644
645 /// Holds data on the current incremental compilation session, if there is one.
646 #[derive(Debug)]
647 pub enum IncrCompSession {
648     // This is the state the session will be in until the incr. comp. dir is
649     // needed.
650     NotInitialized,
651     // This is the state during which the session directory is private and can
652     // be modified.
653     Active {
654         session_directory: PathBuf,
655         lock_file: flock::Lock,
656     },
657     // This is the state after the session directory has been finalized. In this
658     // state, the contents of the directory must not be modified any more.
659     Finalized {
660         session_directory: PathBuf,
661     },
662     // This is an error state that is reached when some compilation error has
663     // occurred. It indicates that the contents of the session directory must
664     // not be used, since they might be invalid.
665     InvalidBecauseOfErrors {
666         session_directory: PathBuf,
667     }
668 }
669
670 fn init_llvm(sess: &Session) {
671     unsafe {
672         // Before we touch LLVM, make sure that multithreading is enabled.
673         use std::sync::Once;
674         static INIT: Once = Once::new();
675         static mut POISONED: bool = false;
676         INIT.call_once(|| {
677             if llvm::LLVMStartMultithreaded() != 1 {
678                 // use an extra bool to make sure that all future usage of LLVM
679                 // cannot proceed despite the Once not running more than once.
680                 POISONED = true;
681             }
682
683             configure_llvm(sess);
684         });
685
686         if POISONED {
687             bug!("couldn't enable multi-threaded LLVM");
688         }
689     }
690 }
691
692 unsafe fn configure_llvm(sess: &Session) {
693     let mut llvm_c_strs = Vec::new();
694     let mut llvm_args = Vec::new();
695
696     {
697         let mut add = |arg: &str| {
698             let s = CString::new(arg).unwrap();
699             llvm_args.push(s.as_ptr());
700             llvm_c_strs.push(s);
701         };
702         add("rustc"); // fake program name
703         if sess.time_llvm_passes() { add("-time-passes"); }
704         if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
705
706         for arg in &sess.opts.cg.llvm_args {
707             add(&(*arg));
708         }
709     }
710
711     llvm::LLVMInitializePasses();
712
713     llvm::initialize_available_targets();
714
715     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
716                                  llvm_args.as_ptr());
717 }
718
719 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
720     let emitter: Box<Emitter> = match output {
721         config::ErrorOutputType::HumanReadable(color_config) => {
722             Box::new(EmitterWriter::stderr(color_config,
723                                            None))
724         }
725         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
726     };
727     let handler = errors::Handler::with_emitter(true, false, emitter);
728     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
729     panic!(errors::FatalError);
730 }
731
732 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
733     let emitter: Box<Emitter> = match output {
734         config::ErrorOutputType::HumanReadable(color_config) => {
735             Box::new(EmitterWriter::stderr(color_config,
736                                            None))
737         }
738         config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
739     };
740     let handler = errors::Handler::with_emitter(true, false, emitter);
741     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
742 }
743
744 // Err(0) means compilation was stopped, but no errors were found.
745 // This would be better as a dedicated enum, but using try! is so convenient.
746 pub type CompileResult = Result<(), usize>;
747
748 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
749     if err_count == 0 {
750         Ok(())
751     } else {
752         Err(err_count)
753     }
754 }
755
756 #[cold]
757 #[inline(never)]
758 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
759     // this wrapper mostly exists so I don't have to write a fully
760     // qualified path of None::<Span> inside the bug!() macro defintion
761     opt_span_bug_fmt(file, line, None::<Span>, args);
762 }
763
764 #[cold]
765 #[inline(never)]
766 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
767                                         line: u32,
768                                         span: S,
769                                         args: fmt::Arguments) -> ! {
770     opt_span_bug_fmt(file, line, Some(span), args);
771 }
772
773 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
774                                         line: u32,
775                                         span: Option<S>,
776                                         args: fmt::Arguments) -> ! {
777     tls::with_opt(move |tcx| {
778         let msg = format!("{}:{}: {}", file, line, args);
779         match (tcx, span) {
780             (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
781             (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
782             (None, _) => panic!(msg)
783         }
784     });
785     unreachable!();
786 }