1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
12 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
14 use dep_graph::DepGraph;
15 use hir::def_id::{CrateNum, DefIndex};
18 use middle::cstore::CrateStore;
19 use middle::dependency_format;
20 use session::search_paths::PathKind;
21 use session::config::DebugInfoLevel;
23 use util::nodemap::{FxHashMap, FxHashSet};
24 use util::common::duration_to_secs_str;
25 use mir::transform as mir_pass;
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;
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};
39 use rustc_back::{LinkerFlavor, PanicStrategy};
40 use rustc_back::target::Target;
41 use rustc_data_structures::flock;
44 use std::path::{Path, PathBuf};
45 use std::cell::{self, Cell, RefCell};
46 use std::collections::HashMap;
48 use std::ffi::CString;
52 use std::time::Duration;
60 // Represents the data associated with a compilation
61 // session for a single crate.
63 pub dep_graph: DepGraph,
64 pub target: config::Config,
66 pub opts: config::Options,
67 pub cstore: Rc<CrateStore>,
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
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>,
99 /// The maximum recursion limit for potentially infinitely recursive
100 /// operations such as auto-dereference and monomorphization.
101 pub recursion_limit: Cell<usize>,
103 /// The maximum length of types during monomorphization.
104 pub type_length_limit: Cell<usize>,
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
109 pub injected_allocator: Cell<Option<CrateNum>>,
110 pub injected_panic_runtime: Cell<Option<CrateNum>>,
112 /// Map from imported macro spans (which consist of
113 /// the localized span for the macro body) to the
114 /// macro name and defintion span in the source crate.
115 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
117 incr_comp_session: RefCell<IncrCompSession>,
119 /// Some measurements that are being gathered during compilation.
120 pub perf_stats: PerfStats,
122 /// Data about code being compiled, gathered during compilation.
123 pub code_stats: RefCell<CodeStats>,
125 next_node_id: Cell<ast::NodeId>,
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>,
144 pub fn local_crate_disambiguator(&self) -> Symbol {
145 *self.crate_disambiguator.borrow()
147 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
150 -> DiagnosticBuilder<'a> {
151 self.diagnostic().struct_span_warn(sp, msg)
153 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
157 -> DiagnosticBuilder<'a> {
158 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
160 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
161 self.diagnostic().struct_warn(msg)
163 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
166 -> DiagnosticBuilder<'a> {
167 self.diagnostic().struct_span_err(sp, msg)
169 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
173 -> DiagnosticBuilder<'a> {
174 self.diagnostic().struct_span_err_with_code(sp, msg, code)
176 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
177 self.diagnostic().struct_err(msg)
179 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
182 -> DiagnosticBuilder<'a> {
183 self.diagnostic().struct_span_fatal(sp, msg)
185 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
189 -> DiagnosticBuilder<'a> {
190 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
192 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
193 self.diagnostic().struct_fatal(msg)
196 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
197 panic!(self.diagnostic().span_fatal(sp, msg))
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))
202 pub fn fatal(&self, msg: &str) -> ! {
203 panic!(self.diagnostic().fatal(msg))
205 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
207 self.span_warn(sp, msg);
209 self.span_err(sp, msg);
212 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
213 self.diagnostic().span_err(sp, msg)
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)
218 pub fn err(&self, msg: &str) {
219 self.diagnostic().err(msg)
221 pub fn err_count(&self) -> usize {
222 self.diagnostic().err_count()
224 pub fn has_errors(&self) -> bool {
225 self.diagnostic().has_errors()
227 pub fn abort_if_errors(&self) {
228 self.diagnostic().abort_if_errors();
230 pub fn track_errors<F, T>(&self, f: F) -> Result<T, usize>
231 where F: FnOnce() -> T
233 let old_count = self.err_count();
235 let errors = self.err_count() - old_count;
242 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
243 self.diagnostic().span_warn(sp, msg)
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)
248 pub fn warn(&self, msg: &str) {
249 self.diagnostic().warn(msg)
251 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
253 Some(sp) => self.span_warn(sp, msg),
254 None => self.warn(msg),
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)
261 pub fn note_without_error(&self, msg: &str) {
262 self.diagnostic().note_without_error(msg)
264 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
265 self.diagnostic().span_note_without_error(sp, msg)
267 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
268 self.diagnostic().span_unimpl(sp, msg)
270 pub fn unimpl(&self, msg: &str) -> ! {
271 self.diagnostic().unimpl(msg)
274 pub fn add_lint<S: Into<MultiSpan>>(&self,
275 lint: &'static lint::Lint,
280 self.lints.borrow_mut().add_lint(lint, id, sp, msg);
283 pub fn add_lint_diagnostic<M>(&self,
284 lint: &'static lint::Lint,
287 where M: lint::IntoEarlyLint,
289 self.lints.borrow_mut().add_lint_diagnostic(lint, id, msg);
292 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
293 let id = self.next_node_id.get();
295 match id.as_usize().checked_add(count) {
297 self.next_node_id.set(ast::NodeId::new(next));
299 None => bug!("Input too large, ran out of node ids!")
304 pub fn next_node_id(&self) -> NodeId {
305 self.reserve_node_ids(1)
307 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
308 &self.parse_sess.span_diagnostic
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.
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
325 config::ErrorOutputType::Json => {
326 diag_builder.span_note(span, &message);
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);
333 diag_builder.span_note(span, &message);
339 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
340 self.parse_sess.codemap()
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
347 pub fn time_llvm_passes(&self) -> bool {
348 self.opts.debugging_opts.time_llvm_passes
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
358 pub fn lto(&self) -> bool {
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)
366 pub fn linker_flavor(&self) -> LinkerFlavor {
367 self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
369 pub fn no_landing_pads(&self) -> bool {
370 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
372 pub fn unstable_options(&self) -> bool {
373 self.opts.debugging_opts.unstable_options
375 pub fn nonzeroing_move_hints(&self) -> bool {
376 self.opts.debugging_opts.enable_nonzeroing_move_hints
378 pub fn overflow_checks(&self) -> bool {
379 self.opts.cg.overflow_checks
380 .or(self.opts.debugging_opts.force_overflow_checks)
381 .unwrap_or(self.opts.debug_assertions)
384 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
385 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
386 !self.target.target.options.eliminate_frame_pointer
389 /// Returns the symbol name for the registrar function,
390 /// given the crate Svh and the function DefIndex.
391 pub fn generate_plugin_registrar_symbol(&self, svh: &Svh, index: DefIndex)
393 format!("__rustc_plugin_registrar__{}_{}", svh, index.as_usize())
396 pub fn generate_derive_registrar_symbol(&self,
398 index: DefIndex) -> String {
399 format!("__rustc_derive_registrar__{}_{}", svh, index.as_usize())
402 pub fn sysroot<'a>(&'a self) -> &'a Path {
403 match self.opts.maybe_sysroot {
404 Some (ref sysroot) => sysroot,
405 None => self.default_sysroot.as_ref()
406 .expect("missing sysroot and default_sysroot in Session")
409 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
410 filesearch::FileSearch::new(self.sysroot(),
411 &self.opts.target_triple,
412 &self.opts.search_paths,
415 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
416 filesearch::FileSearch::new(
418 config::host_triple(),
419 &self.opts.search_paths,
423 pub fn init_incr_comp_session(&self,
424 session_dir: PathBuf,
425 lock_file: flock::Lock) {
426 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
428 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
429 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
432 *incr_comp_session = IncrCompSession::Active {
433 session_directory: session_dir,
434 lock_file: lock_file,
438 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
439 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
441 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
442 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
445 // Note: This will also drop the lock file, thus unlocking the directory
446 *incr_comp_session = IncrCompSession::Finalized {
447 session_directory: new_directory_path,
451 pub fn mark_incr_comp_session_as_invalid(&self) {
452 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
454 let session_directory = match *incr_comp_session {
455 IncrCompSession::Active { ref session_directory, .. } => {
456 session_directory.clone()
458 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
462 // Note: This will also drop the lock file, thus unlocking the directory
463 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
464 session_directory: session_directory
468 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
469 let incr_comp_session = self.incr_comp_session.borrow();
470 cell::Ref::map(incr_comp_session, |incr_comp_session| {
471 match *incr_comp_session {
472 IncrCompSession::NotInitialized => {
473 bug!("Trying to get session directory from IncrCompSession `{:?}`",
476 IncrCompSession::Active { ref session_directory, .. } |
477 IncrCompSession::Finalized { ref session_directory } |
478 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
485 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
486 if self.opts.incremental.is_some() {
487 Some(self.incr_comp_session_dir())
493 pub fn print_perf_stats(&self) {
494 println!("Total time spent computing SVHs: {}",
495 duration_to_secs_str(self.perf_stats.svh_time.get()));
496 println!("Total time spent computing incr. comp. hashes: {}",
497 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
498 println!("Total number of incr. comp. hashes computed: {}",
499 self.perf_stats.incr_comp_hashes_count.get());
500 println!("Total number of bytes hashed for incr. comp.: {}",
501 self.perf_stats.incr_comp_bytes_hashed.get());
502 println!("Average bytes hashed per incr. comp. HIR node: {}",
503 self.perf_stats.incr_comp_bytes_hashed.get() /
504 self.perf_stats.incr_comp_hashes_count.get());
505 println!("Total time spent computing symbol hashes: {}",
506 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
507 println!("Total time spent decoding DefPath tables: {}",
508 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
512 pub fn build_session(sopts: config::Options,
513 dep_graph: &DepGraph,
514 local_crate_source_file: Option<PathBuf>,
515 registry: errors::registry::Registry,
516 cstore: Rc<CrateStore>)
518 build_session_with_codemap(sopts,
520 local_crate_source_file,
523 Rc::new(codemap::CodeMap::new()),
527 pub fn build_session_with_codemap(sopts: config::Options,
528 dep_graph: &DepGraph,
529 local_crate_source_file: Option<PathBuf>,
530 registry: errors::registry::Registry,
531 cstore: Rc<CrateStore>,
532 codemap: Rc<codemap::CodeMap>,
533 emitter_dest: Option<Box<Write + Send>>)
535 // FIXME: This is not general enough to make the warning lint completely override
536 // normal diagnostic warnings, since the warning lint can also be denied and changed
537 // later via the source code.
538 let can_print_warnings = sopts.lint_opts
540 .filter(|&&(ref key, _)| *key == "warnings")
541 .map(|&(_, ref level)| *level != lint::Allow)
544 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
546 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
547 (config::ErrorOutputType::HumanReadable(color_config), None) => {
548 Box::new(EmitterWriter::stderr(color_config,
549 Some(codemap.clone())))
551 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
552 Box::new(EmitterWriter::new(dst,
553 Some(codemap.clone())))
555 (config::ErrorOutputType::Json, None) => {
556 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
558 (config::ErrorOutputType::Json, Some(dst)) => {
559 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
563 let diagnostic_handler =
564 errors::Handler::with_emitter(can_print_warnings,
568 build_session_(sopts,
570 local_crate_source_file,
576 pub fn build_session_(sopts: config::Options,
577 dep_graph: &DepGraph,
578 local_crate_source_file: Option<PathBuf>,
579 span_diagnostic: errors::Handler,
580 codemap: Rc<codemap::CodeMap>,
581 cstore: Rc<CrateStore>)
583 let host = match Target::search(config::host_triple()) {
586 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
589 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
590 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
591 let default_sysroot = match sopts.maybe_sysroot {
593 None => Some(filesearch::get_or_default_sysroot())
596 // Make the path absolute, if necessary
597 let local_crate_source_file = local_crate_source_file.map(|path|
598 if path.is_absolute() {
601 env::current_dir().unwrap().join(&path)
606 dep_graph: dep_graph.clone(),
612 // For a library crate, this is always none
613 entry_fn: RefCell::new(None),
614 entry_type: Cell::new(None),
615 plugin_registrar_fn: Cell::new(None),
616 derive_registrar_fn: Cell::new(None),
617 default_sysroot: default_sysroot,
618 local_crate_source_file: local_crate_source_file,
619 working_dir: env::current_dir().unwrap(),
620 lint_store: RefCell::new(lint::LintStore::new()),
621 lints: RefCell::new(lint::LintTable::new()),
622 one_time_diagnostics: RefCell::new(FxHashSet()),
623 plugin_llvm_passes: RefCell::new(Vec::new()),
624 mir_passes: RefCell::new(mir_pass::Passes::new()),
625 plugin_attributes: RefCell::new(Vec::new()),
626 crate_types: RefCell::new(Vec::new()),
627 dependency_formats: RefCell::new(FxHashMap()),
628 crate_disambiguator: RefCell::new(Symbol::intern("")),
629 features: RefCell::new(feature_gate::Features::new()),
630 recursion_limit: Cell::new(64),
631 type_length_limit: Cell::new(1048576),
632 next_node_id: Cell::new(NodeId::new(1)),
633 injected_allocator: Cell::new(None),
634 injected_panic_runtime: Cell::new(None),
635 imported_macro_spans: RefCell::new(HashMap::new()),
636 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
637 perf_stats: PerfStats {
638 svh_time: Cell::new(Duration::from_secs(0)),
639 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
640 incr_comp_hashes_count: Cell::new(0),
641 incr_comp_bytes_hashed: Cell::new(0),
642 symbol_hash_time: Cell::new(Duration::from_secs(0)),
643 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
645 code_stats: RefCell::new(CodeStats::new()),
653 /// Holds data on the current incremental compilation session, if there is one.
655 pub enum IncrCompSession {
656 // This is the state the session will be in until the incr. comp. dir is
659 // This is the state during which the session directory is private and can
662 session_directory: PathBuf,
663 lock_file: flock::Lock,
665 // This is the state after the session directory has been finalized. In this
666 // state, the contents of the directory must not be modified any more.
668 session_directory: PathBuf,
670 // This is an error state that is reached when some compilation error has
671 // occurred. It indicates that the contents of the session directory must
672 // not be used, since they might be invalid.
673 InvalidBecauseOfErrors {
674 session_directory: PathBuf,
678 fn init_llvm(sess: &Session) {
680 // Before we touch LLVM, make sure that multithreading is enabled.
682 static INIT: Once = Once::new();
683 static mut POISONED: bool = false;
685 if llvm::LLVMStartMultithreaded() != 1 {
686 // use an extra bool to make sure that all future usage of LLVM
687 // cannot proceed despite the Once not running more than once.
691 configure_llvm(sess);
695 bug!("couldn't enable multi-threaded LLVM");
700 unsafe fn configure_llvm(sess: &Session) {
701 let mut llvm_c_strs = Vec::new();
702 let mut llvm_args = Vec::new();
705 let mut add = |arg: &str| {
706 let s = CString::new(arg).unwrap();
707 llvm_args.push(s.as_ptr());
710 add("rustc"); // fake program name
711 if sess.time_llvm_passes() { add("-time-passes"); }
712 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
714 for arg in &sess.opts.cg.llvm_args {
719 llvm::LLVMInitializePasses();
721 llvm::initialize_available_targets();
723 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
727 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
728 let emitter: Box<Emitter> = match output {
729 config::ErrorOutputType::HumanReadable(color_config) => {
730 Box::new(EmitterWriter::stderr(color_config,
733 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
735 let handler = errors::Handler::with_emitter(true, false, emitter);
736 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
737 panic!(errors::FatalError);
740 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
741 let emitter: Box<Emitter> = match output {
742 config::ErrorOutputType::HumanReadable(color_config) => {
743 Box::new(EmitterWriter::stderr(color_config,
746 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
748 let handler = errors::Handler::with_emitter(true, false, emitter);
749 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
752 // Err(0) means compilation was stopped, but no errors were found.
753 // This would be better as a dedicated enum, but using try! is so convenient.
754 pub type CompileResult = Result<(), usize>;
756 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
766 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
767 // this wrapper mostly exists so I don't have to write a fully
768 // qualified path of None::<Span> inside the bug!() macro defintion
769 opt_span_bug_fmt(file, line, None::<Span>, args);
774 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
777 args: fmt::Arguments) -> ! {
778 opt_span_bug_fmt(file, line, Some(span), args);
781 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
784 args: fmt::Arguments) -> ! {
785 tls::with_opt(move |tcx| {
786 let msg = format!("{}:{}: {}", file, line, args);
788 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
789 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
790 (None, _) => panic!(msg)