1 // Copyright 2012-2015 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 use rustc::dep_graph::DepGraph;
13 use rustc::front::map as hir_map;
15 use rustc::mir::mir_map::MirMap;
16 use rustc::session::{Session, CompileResult, compile_result_from_err_count};
17 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
18 use rustc::session::search_paths::PathKind;
20 use rustc::middle::{self, dependency_format, stability, ty, reachable};
21 use rustc::middle::privacy::AccessLevels;
22 use rustc::middle::ty::TyCtxt;
23 use rustc::util::common::time;
24 use rustc::util::nodemap::NodeSet;
25 use rustc_back::sha2::{Sha256, Digest};
26 use rustc_borrowck as borrowck;
27 use rustc_resolve as resolve;
28 use rustc_metadata::macro_import;
29 use rustc_metadata::creader::LocalCrateReader;
30 use rustc_metadata::cstore::CStore;
31 use rustc_trans::back::link;
32 use rustc_trans::back::write;
33 use rustc_trans::trans;
34 use rustc_typeck as typeck;
36 use rustc_plugin::registry::Registry;
37 use rustc_plugin as plugin;
39 use rustc_front::lowering::{lower_crate, LoweringContext};
40 use rustc_passes::{no_asm, loops, consts, const_fn, rvalues, static_recursion};
41 use super::Compilation;
45 use std::collections::HashMap;
47 use std::ffi::{OsString, OsStr};
49 use std::io::{self, Write};
50 use std::path::{Path, PathBuf};
51 use syntax::ast::{self, NodeIdAssigner};
52 use syntax::attr::{self, AttrMetaMethods};
53 use syntax::diagnostics;
54 use syntax::fold::Folder;
55 use syntax::parse::{self, PResult, token};
56 use syntax::util::node_count::NodeCounter;
61 pub fn compile_input(sess: &Session,
63 cfg: ast::CrateConfig,
65 outdir: &Option<PathBuf>,
66 output: &Option<PathBuf>,
67 addl_plugins: Option<Vec<String>>,
68 control: &CompileController) -> CompileResult {
69 macro_rules! controller_entry_point {
70 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
71 let state = $make_state;
72 let phase_result: &CompileResult = &$phase_result;
73 if phase_result.is_ok() || control.$point.run_callback_on_error {
74 (control.$point.callback)(state);
77 if control.$point.stop == Compilation::Stop {
78 return compile_result_from_err_count($tsess.err_count());
83 // We need nested scopes here, because the intermediate results can keep
84 // large chunks of memory alive and we want to free them as soon as
85 // possible to keep the peak memory usage low
86 let (outputs, trans) = {
87 let (outputs, expanded_crate, id) = {
88 let krate = match phase_1_parse_input(sess, cfg, input) {
90 Err(mut parse_error) => {
96 controller_entry_point!(after_parse,
98 CompileState::state_after_parse(input, sess, outdir, &krate),
101 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
102 let id = link::find_crate_name(Some(sess), &krate.attrs, input);
103 let expanded_crate = phase_2_configure_and_expand(sess,
109 (outputs, expanded_crate, id)
112 controller_entry_point!(after_expand,
114 CompileState::state_after_expand(input,
121 let expanded_crate = assign_node_ids(sess, expanded_crate);
123 let lcx = LoweringContext::new(sess, Some(&expanded_crate));
124 let dep_graph = DepGraph::new(sess.opts.build_dep_graph);
125 let mut hir_forest = time(sess.time_passes(),
126 "lowering ast -> hir",
127 || hir_map::Forest::new(lower_crate(&lcx, &expanded_crate),
130 // Discard MTWT tables that aren't required past lowering to HIR.
131 if !sess.opts.debugging_opts.keep_mtwt_tables &&
132 !sess.opts.debugging_opts.save_analysis {
133 syntax::ext::mtwt::clear_tables();
136 let arenas = ty::CtxtArenas::new();
137 let hir_map = make_map(sess, &mut hir_forest);
139 write_out_deps(sess, &outputs, &id);
142 let _ignore = hir_map.dep_graph.in_ignore();
143 controller_entry_point!(after_write_deps,
145 CompileState::state_after_write_deps(input,
156 time(sess.time_passes(), "attribute checking", || {
157 front::check_attr::check_crate(sess, &expanded_crate);
160 time(sess.time_passes(),
162 || lint::check_ast_crate(sess, &expanded_crate));
164 let opt_crate = if sess.opts.debugging_opts.keep_ast ||
165 sess.opts.debugging_opts.save_analysis {
166 Some(&expanded_crate)
168 drop(expanded_crate);
172 phase_3_run_analysis_passes(sess,
177 control.make_glob_map,
178 |tcx, mir_map, analysis, result| {
180 // Eventually, we will want to track plugins.
181 let _ignore = tcx.dep_graph.in_ignore();
183 let state = CompileState::state_after_analysis(input,
193 (control.after_analysis.callback)(state);
195 if control.after_analysis.stop == Compilation::Stop {
202 if log_enabled!(::log::INFO) {
203 println!("Pre-trans");
204 tcx.print_debug_stats();
206 let trans = phase_4_translate_to_llvm(tcx,
210 if log_enabled!(::log::INFO) {
211 println!("Post-trans");
212 tcx.print_debug_stats();
215 // Discard interned strings as they are no longer required.
216 token::get_ident_interner().clear();
222 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
224 controller_entry_point!(after_llvm,
226 CompileState::state_after_llvm(input, sess, outdir, &trans),
230 phase_6_link_output(sess, &trans, &outputs);
235 /// The name used for source code that doesn't originate in a file
236 /// (e.g. source from stdin or a string)
237 pub fn anon_src() -> String {
241 pub fn source_name(input: &Input) -> String {
243 // FIXME (#9639): This needs to handle non-utf8 paths
244 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
245 Input::Str { ref name, .. } => name.clone(),
249 /// CompileController is used to customise compilation, it allows compilation to
250 /// be stopped and/or to call arbitrary code at various points in compilation.
251 /// It also allows for various flags to be set to influence what information gets
252 /// collected during compilation.
254 /// This is a somewhat higher level controller than a Session - the Session
255 /// controls what happens in each phase, whereas the CompileController controls
256 /// whether a phase is run at all and whether other code (from outside the
257 /// the compiler) is run between phases.
259 /// Note that if compilation is set to stop and a callback is provided for a
260 /// given entry point, the callback is called before compilation is stopped.
262 /// Expect more entry points to be added in the future.
263 pub struct CompileController<'a> {
264 pub after_parse: PhaseController<'a>,
265 pub after_expand: PhaseController<'a>,
266 pub after_write_deps: PhaseController<'a>,
267 pub after_analysis: PhaseController<'a>,
268 pub after_llvm: PhaseController<'a>,
270 pub make_glob_map: resolve::MakeGlobMap,
273 impl<'a> CompileController<'a> {
274 pub fn basic() -> CompileController<'a> {
276 after_parse: PhaseController::basic(),
277 after_expand: PhaseController::basic(),
278 after_write_deps: PhaseController::basic(),
279 after_analysis: PhaseController::basic(),
280 after_llvm: PhaseController::basic(),
281 make_glob_map: resolve::MakeGlobMap::No,
286 pub struct PhaseController<'a> {
287 pub stop: Compilation,
288 // If true then the compiler will try to run the callback even if the phase
289 // ends with an error. Note that this is not always possible.
290 pub run_callback_on_error: bool,
291 pub callback: Box<Fn(CompileState) -> () + 'a>,
294 impl<'a> PhaseController<'a> {
295 pub fn basic() -> PhaseController<'a> {
297 stop: Compilation::Continue,
298 run_callback_on_error: false,
299 callback: box |_| {},
304 /// State that is passed to a callback. What state is available depends on when
305 /// during compilation the callback is made. See the various constructor methods
306 /// (`state_*`) in the impl to see which data is provided for any given entry point.
307 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
308 pub input: &'a Input,
309 pub session: &'a Session,
310 pub cfg: Option<&'a ast::CrateConfig>,
311 pub krate: Option<&'a ast::Crate>,
312 pub crate_name: Option<&'a str>,
313 pub output_filenames: Option<&'a OutputFilenames>,
314 pub out_dir: Option<&'a Path>,
315 pub expanded_crate: Option<&'a ast::Crate>,
316 pub hir_crate: Option<&'a hir::Crate>,
317 pub ast_map: Option<&'a hir_map::Map<'ast>>,
318 pub mir_map: Option<&'a MirMap<'tcx>>,
319 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
320 pub tcx: Option<&'a TyCtxt<'tcx>>,
321 pub lcx: Option<&'a LoweringContext<'a>>,
322 pub trans: Option<&'a trans::CrateTranslation>,
325 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
326 fn empty(input: &'a Input,
327 session: &'a Session,
328 out_dir: &'a Option<PathBuf>)
329 -> CompileState<'a, 'ast, 'tcx> {
333 out_dir: out_dir.as_ref().map(|s| &**s),
337 output_filenames: None,
338 expanded_crate: None,
349 fn state_after_parse(input: &'a Input,
350 session: &'a Session,
351 out_dir: &'a Option<PathBuf>,
352 krate: &'a ast::Crate)
353 -> CompileState<'a, 'ast, 'tcx> {
354 CompileState { krate: Some(krate), ..CompileState::empty(input, session, out_dir) }
357 fn state_after_expand(input: &'a Input,
358 session: &'a Session,
359 out_dir: &'a Option<PathBuf>,
360 expanded_crate: &'a ast::Crate,
362 -> CompileState<'a, 'ast, 'tcx> {
364 crate_name: Some(crate_name),
365 expanded_crate: Some(expanded_crate),
366 ..CompileState::empty(input, session, out_dir)
370 fn state_after_write_deps(input: &'a Input,
371 session: &'a Session,
372 out_dir: &'a Option<PathBuf>,
373 hir_map: &'a hir_map::Map<'ast>,
374 krate: &'a ast::Crate,
375 hir_crate: &'a hir::Crate,
377 lcx: &'a LoweringContext<'a>)
378 -> CompileState<'a, 'ast, 'tcx> {
380 crate_name: Some(crate_name),
381 ast_map: Some(hir_map),
383 hir_crate: Some(hir_crate),
385 ..CompileState::empty(input, session, out_dir)
389 fn state_after_analysis(input: &'a Input,
390 session: &'a Session,
391 out_dir: &'a Option<PathBuf>,
392 krate: Option<&'a ast::Crate>,
393 hir_crate: &'a hir::Crate,
394 analysis: &'a ty::CrateAnalysis,
395 mir_map: Option<&'a MirMap<'tcx>>,
396 tcx: &'a TyCtxt<'tcx>,
397 lcx: &'a LoweringContext<'a>,
399 -> CompileState<'a, 'ast, 'tcx> {
401 analysis: Some(analysis),
405 hir_crate: Some(hir_crate),
407 crate_name: Some(crate_name),
408 ..CompileState::empty(input, session, out_dir)
413 fn state_after_llvm(input: &'a Input,
414 session: &'a Session,
415 out_dir: &'a Option<PathBuf>,
416 trans: &'a trans::CrateTranslation)
417 -> CompileState<'a, 'ast, 'tcx> {
418 CompileState { trans: Some(trans), ..CompileState::empty(input, session, out_dir) }
422 pub fn phase_1_parse_input<'a>(sess: &'a Session,
423 cfg: ast::CrateConfig,
425 -> PResult<'a, ast::Crate> {
426 // These may be left in an incoherent state after a previous compile.
427 // `clear_tables` and `get_ident_interner().clear()` can be used to free
428 // memory, but they do not restore the initial state.
429 syntax::ext::mtwt::reset_tables();
430 token::reset_ident_interner();
432 let krate = time(sess.time_passes(), "parsing", || {
434 Input::File(ref file) => {
435 parse::parse_crate_from_file(file, cfg.clone(), &sess.parse_sess)
437 Input::Str { ref input, ref name } => {
438 parse::parse_crate_from_source_str(name.clone(),
446 if sess.opts.debugging_opts.ast_json_noexpand {
447 println!("{}", json::as_json(&krate));
450 if sess.opts.debugging_opts.input_stats {
451 println!("Lines of code: {}", sess.codemap().count_lines());
452 println!("Pre-expansion node count: {}", count_nodes(&krate));
455 if let Some(ref s) = sess.opts.debugging_opts.show_span {
456 syntax::show_span::run(sess.diagnostic(), s, &krate);
462 fn count_nodes(krate: &ast::Crate) -> usize {
463 let mut counter = NodeCounter::new();
464 visit::walk_crate(&mut counter, krate);
468 // For continuing compilation after a parsed crate has been
471 /// Run the "early phases" of the compiler: initial `cfg` processing,
472 /// loading compiler plugins (including those from `addl_plugins`),
473 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
474 /// harness if one is to be provided and injection of a dependency on the
475 /// standard library and prelude.
477 /// Returns `None` if we're aborting after handling -W help.
478 pub fn phase_2_configure_and_expand(sess: &Session,
480 mut krate: ast::Crate,
482 addl_plugins: Option<Vec<String>>)
483 -> Result<ast::Crate, usize> {
484 let time_passes = sess.time_passes();
486 // strip before anything else because crate metadata may use #[cfg_attr]
487 // and so macros can depend on configuration variables, such as
489 // #[macro_use] #[cfg(foo)]
490 // mod bar { macro_rules! baz!(() => {{}}) }
492 // baz! should not use this definition unless foo is enabled.
494 let mut feature_gated_cfgs = vec![];
495 krate = time(time_passes, "configuration 1", || {
496 sess.track_errors(|| {
497 syntax::config::strip_unconfigured_items(sess.diagnostic(),
499 &mut feature_gated_cfgs)
503 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
504 *sess.crate_disambiguator.borrow_mut() = compute_crate_disambiguator(sess);
506 time(time_passes, "recursion limit", || {
507 middle::recursion_limit::update_recursion_limit(sess, &krate);
510 time(time_passes, "gated macro checking", || {
511 sess.track_errors(|| {
513 syntax::feature_gate::check_crate_macros(sess.codemap(),
514 &sess.parse_sess.span_diagnostic,
517 // these need to be set "early" so that expansion sees `quote` if enabled.
518 *sess.features.borrow_mut() = features;
523 krate = time(time_passes, "crate injection", || {
524 syntax::std_inject::maybe_inject_crates_ref(krate, sess.opts.alt_std_name.clone())
527 let macros = time(time_passes,
529 || macro_import::read_macro_defs(sess, &cstore, &krate));
531 let mut addl_plugins = Some(addl_plugins);
532 let registrars = time(time_passes, "plugin loading", || {
533 plugin::load::load_plugins(sess, &cstore, &krate, addl_plugins.take().unwrap())
536 let mut registry = Registry::new(sess, &krate);
538 time(time_passes, "plugin registration", || {
539 if sess.features.borrow().rustc_diagnostic_macros {
540 registry.register_macro("__diagnostic_used",
541 diagnostics::plugin::expand_diagnostic_used);
542 registry.register_macro("__register_diagnostic",
543 diagnostics::plugin::expand_register_diagnostic);
544 registry.register_macro("__build_diagnostic_array",
545 diagnostics::plugin::expand_build_diagnostic_array);
548 for registrar in registrars {
549 registry.args_hidden = Some(registrar.args);
550 (registrar.fun)(&mut registry);
554 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
555 llvm_passes, attributes, mir_passes, .. } = registry;
557 sess.track_errors(|| {
558 let mut ls = sess.lint_store.borrow_mut();
559 for pass in early_lint_passes {
560 ls.register_early_pass(Some(sess), true, pass);
562 for pass in late_lint_passes {
563 ls.register_late_pass(Some(sess), true, pass);
566 for (name, to) in lint_groups {
567 ls.register_group(Some(sess), true, name, to);
570 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
571 sess.mir_passes.borrow_mut().extend(mir_passes);
572 *sess.plugin_attributes.borrow_mut() = attributes.clone();
575 // Lint plugins are registered; now we can process command line flags.
576 if sess.opts.describe_lints {
577 super::describe_lints(&sess.lint_store.borrow(), true);
580 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
582 krate = time(time_passes, "expansion", || {
583 // Windows dlls do not have rpaths, so they don't know how to find their
584 // dependencies. It's up to us to tell the system where to find all the
585 // dependent dlls. Note that this uses cfg!(windows) as opposed to
586 // targ_cfg because syntax extensions are always loaded for the host
587 // compiler, not for the target.
588 let mut _old_path = OsString::new();
590 _old_path = env::var_os("PATH").unwrap_or(_old_path);
591 let mut new_path = sess.host_filesearch(PathKind::All)
592 .get_dylib_search_paths();
593 new_path.extend(env::split_paths(&_old_path));
594 env::set_var("PATH", &env::join_paths(new_path).unwrap());
596 let features = sess.features.borrow();
597 let cfg = syntax::ext::expand::ExpansionConfig {
598 crate_name: crate_name.to_string(),
599 features: Some(&features),
600 recursion_limit: sess.recursion_limit.get(),
601 trace_mac: sess.opts.debugging_opts.trace_macros,
603 let mut ecx = syntax::ext::base::ExtCtxt::new(&sess.parse_sess,
604 krate.config.clone(),
606 &mut feature_gated_cfgs);
607 syntax_ext::register_builtins(&mut ecx.syntax_env);
608 let (ret, macro_names) = syntax::ext::expand::expand_crate(ecx,
613 env::set_var("PATH", &_old_path);
615 *sess.available_macros.borrow_mut() = macro_names;
619 // Needs to go *after* expansion to be able to check the results
620 // of macro expansion. This runs before #[cfg] to try to catch as
621 // much as possible (e.g. help the programmer avoid platform
622 // specific differences)
623 time(time_passes, "complete gated feature checking 1", || {
624 sess.track_errors(|| {
625 let features = syntax::feature_gate::check_crate(sess.codemap(),
626 &sess.parse_sess.span_diagnostic,
629 sess.opts.unstable_features);
630 *sess.features.borrow_mut() = features;
634 // JBC: make CFG processing part of expansion to avoid this problem:
636 // strip again, in case expansion added anything with a #[cfg].
637 krate = sess.track_errors(|| {
638 let krate = time(time_passes, "configuration 2", || {
639 syntax::config::strip_unconfigured_items(sess.diagnostic(),
641 &mut feature_gated_cfgs)
644 time(time_passes, "gated configuration checking", || {
645 let features = sess.features.borrow();
646 feature_gated_cfgs.sort();
647 feature_gated_cfgs.dedup();
648 for cfg in &feature_gated_cfgs {
649 cfg.check_and_emit(sess.diagnostic(), &features, sess.codemap());
656 krate = time(time_passes, "maybe building test harness", || {
657 syntax::test::modify_for_testing(&sess.parse_sess, &sess.opts.cfg, krate, sess.diagnostic())
660 krate = time(time_passes,
662 || syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
665 "checking that all macro invocations are gone",
666 || syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
669 "checking for inline asm in case the target doesn't support it",
670 || no_asm::check_crate(sess, &krate));
672 // One final feature gating of the true AST that gets compiled
673 // later, to make sure we've got everything (e.g. configuration
674 // can insert new attributes via `cfg_attr`)
675 time(time_passes, "complete gated feature checking 2", || {
676 sess.track_errors(|| {
677 let features = syntax::feature_gate::check_crate(sess.codemap(),
678 &sess.parse_sess.span_diagnostic,
681 sess.opts.unstable_features);
682 *sess.features.borrow_mut() = features;
687 "const fn bodies and arguments",
688 || const_fn::check_crate(sess, &krate))?;
690 if sess.opts.debugging_opts.input_stats {
691 println!("Post-expansion node count: {}", count_nodes(&krate));
697 pub fn assign_node_ids(sess: &Session, krate: ast::Crate) -> ast::Crate {
698 struct NodeIdAssigner<'a> {
702 impl<'a> Folder for NodeIdAssigner<'a> {
703 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
704 assert_eq!(old_id, ast::DUMMY_NODE_ID);
705 self.sess.next_node_id()
709 let krate = time(sess.time_passes(),
710 "assigning node ids",
711 || NodeIdAssigner { sess: sess }.fold_crate(krate));
713 if sess.opts.debugging_opts.ast_json {
714 println!("{}", json::as_json(&krate));
720 pub fn make_map<'ast>(sess: &Session,
721 forest: &'ast mut hir_map::Forest)
722 -> hir_map::Map<'ast> {
723 // Construct the HIR map
724 time(sess.time_passes(),
726 move || hir_map::map_crate(forest))
729 /// Run the resolution, typechecking, region checking and other
730 /// miscellaneous analysis passes on the crate. Return various
731 /// structures carrying the results of the analysis.
732 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
734 hir_map: hir_map::Map<'tcx>,
735 arenas: &'tcx ty::CtxtArenas<'tcx>,
737 make_glob_map: resolve::MakeGlobMap,
740 where F: FnOnce(&TyCtxt<'tcx>, Option<MirMap<'tcx>>, ty::CrateAnalysis, CompileResult) -> R
742 macro_rules! try_with_f {
743 ($e: expr, ($t: expr, $m: expr, $a: expr)) => {
747 f($t, $m, $a, Err(x));
754 let time_passes = sess.time_passes();
757 "external crate/lib resolution",
758 || LocalCrateReader::new(sess, cstore, &hir_map).read_crates());
760 let lang_items = time(time_passes, "language item collection", || {
761 sess.track_errors(|| {
762 middle::lang_items::collect_language_items(&sess, &hir_map)
766 let resolve::CrateMap {
772 } = time(time_passes,
774 || resolve::resolve_crate(sess, &hir_map, make_glob_map));
776 let mut analysis = ty::CrateAnalysis {
777 export_map: export_map,
778 access_levels: AccessLevels::default(),
779 reachable: NodeSet(),
784 let named_region_map = time(time_passes,
785 "lifetime resolution",
786 || middle::resolve_lifetime::krate(sess,
788 &def_map.borrow()))?;
791 "looking for entry point",
792 || middle::entry::find_entry_point(sess, &hir_map));
794 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
795 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
798 let region_map = time(time_passes,
800 || middle::region::resolve_crate(sess, &hir_map));
804 || loops::check_crate(sess, &hir_map));
807 "static item recursion checking",
808 || static_recursion::check_crate(sess, &def_map.borrow(), &hir_map))?;
810 let index = stability::Index::new(&hir_map);
812 TyCtxt::create_and_enter(sess,
823 // passes are timed inside typeck
824 try_with_f!(typeck::check_crate(tcx, trait_map), (tcx, None, analysis));
828 || consts::check_crate(tcx));
830 analysis.access_levels =
831 time(time_passes, "privacy checking", || {
832 rustc_privacy::check_crate(tcx, &analysis.export_map)
835 // Do not move this check past lint
836 time(time_passes, "stability index", || {
837 tcx.stability.borrow_mut().build(tcx, &analysis.access_levels)
841 "intrinsic checking",
842 || middle::intrinsicck::check_crate(tcx));
846 || middle::effect::check_crate(tcx));
850 || middle::check_match::check_crate(tcx));
852 // this must run before MIR dump, because
853 // "not all control paths return a value" is reported here.
855 // maybe move the check to a MIR pass?
858 || middle::liveness::check_crate(tcx));
862 || rvalues::check_crate(tcx));
867 || mir::mir_map::build_mir_for_crate(tcx));
869 time(time_passes, "MIR passes", || {
870 let mut passes = sess.mir_passes.borrow_mut();
871 // Push all the built-in passes.
872 passes.push_pass(box mir::transform::remove_dead_blocks::RemoveDeadBlocks);
873 passes.push_pass(box mir::transform::type_check::TypeckMir);
874 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg);
876 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
877 passes.push_pass(box mir::transform::remove_dead_blocks::RemoveDeadBlocks);
878 passes.push_pass(box mir::transform::erase_regions::EraseRegions);
879 // And run everything.
880 passes.run_passes(tcx, &mut mir_map);
885 || borrowck::check_crate(tcx, &mir_map));
887 // Avoid overwhelming user with errors if type checking failed.
888 // I'm not sure how helpful this is, to be honest, but it avoids
890 // lot of annoying errors in the compile-fail tests (basically,
891 // lint warnings and so on -- kindck used to do this abort, but
892 // kindck is gone now). -nmatsakis
893 if sess.err_count() > 0 {
894 return Ok(f(tcx, Some(mir_map), analysis, Err(sess.err_count())));
899 "reachability checking",
900 || reachable::find_reachable(tcx, &analysis.access_levels));
902 time(time_passes, "death checking", || {
903 middle::dead::check_crate(tcx, &analysis.access_levels);
906 let ref lib_features_used =
908 "stability checking",
909 || stability::check_unstable_api_usage(tcx));
911 time(time_passes, "unused lib feature checking", || {
912 stability::check_unused_or_stable_features(&tcx.sess,
918 || lint::check_crate(tcx, &analysis.access_levels));
920 // The above three passes generate errors w/o aborting
921 if sess.err_count() > 0 {
922 return Ok(f(tcx, Some(mir_map), analysis, Err(sess.err_count())));
925 Ok(f(tcx, Some(mir_map), analysis, Ok(())))
929 /// Run the translation phase to LLVM, after which the AST and analysis can
930 pub fn phase_4_translate_to_llvm<'tcx>(tcx: &TyCtxt<'tcx>,
931 mir_map: MirMap<'tcx>,
932 analysis: ty::CrateAnalysis)
933 -> trans::CrateTranslation {
934 let time_passes = tcx.sess.time_passes();
937 "resolving dependency formats",
938 || dependency_format::calculate(&tcx.sess));
940 // Option dance to work around the lack of stack once closures.
943 move || trans::trans_crate(tcx, &mir_map, analysis))
946 /// Run LLVM itself, producing a bitcode file, assembly file or object file
947 /// as a side effect.
948 pub fn phase_5_run_llvm_passes(sess: &Session,
949 trans: &trans::CrateTranslation,
950 outputs: &OutputFilenames) -> CompileResult {
951 if sess.opts.cg.no_integrated_as {
952 let mut map = HashMap::new();
953 map.insert(OutputType::Assembly, None);
954 time(sess.time_passes(),
956 || write::run_passes(sess, trans, &map, outputs));
958 write::run_assembler(sess, outputs);
960 // Remove assembly source, unless --save-temps was specified
961 if !sess.opts.cg.save_temps {
962 fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
965 time(sess.time_passes(),
967 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
970 if sess.err_count() > 0 {
971 Err(sess.err_count())
977 /// Run the linker on any artifacts that resulted from the LLVM run.
978 /// This should produce either a finished executable or library.
979 pub fn phase_6_link_output(sess: &Session,
980 trans: &trans::CrateTranslation,
981 outputs: &OutputFilenames) {
982 time(sess.time_passes(),
984 || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
987 fn escape_dep_filename(filename: &str) -> String {
988 // Apparently clang and gcc *only* escape spaces:
989 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
990 filename.replace(" ", "\\ ")
993 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
994 let mut out_filenames = Vec::new();
995 for output_type in sess.opts.output_types.keys() {
996 let file = outputs.path(*output_type);
999 for output in sess.crate_types.borrow().iter() {
1000 let p = link::filename_for_input(sess, *output, id, outputs);
1001 out_filenames.push(p);
1005 out_filenames.push(file);
1010 // Write out dependency rules to the dep-info file if requested
1011 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1014 let deps_filename = outputs.path(OutputType::DepInfo);
1017 (|| -> io::Result<()> {
1018 // Build a list of files used to compile the output and
1019 // write Makefile-compatible dependency rules
1020 let files: Vec<String> = sess.codemap()
1024 .filter(|fmap| fmap.is_real_file())
1025 .filter(|fmap| !fmap.is_imported())
1026 .map(|fmap| escape_dep_filename(&fmap.name))
1028 let mut file = fs::File::create(&deps_filename)?;
1029 for path in &out_filenames {
1030 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1033 // Emit a fake target for each input file to the compilation. This
1034 // prevents `make` from spitting out an error if a file is later
1035 // deleted. For more info see #28735
1037 writeln!(file, "{}:", path)?;
1045 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1046 deps_filename.display(),
1052 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1053 // Unconditionally collect crate types from attributes to make them used
1054 let attr_types: Vec<config::CrateType> =
1057 if a.check_name("crate_type") {
1058 match a.value_str() {
1059 Some(ref n) if *n == "rlib" => {
1060 Some(config::CrateTypeRlib)
1062 Some(ref n) if *n == "dylib" => {
1063 Some(config::CrateTypeDylib)
1065 Some(ref n) if *n == "lib" => {
1066 Some(config::default_lib_output())
1068 Some(ref n) if *n == "staticlib" => {
1069 Some(config::CrateTypeStaticlib)
1071 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1073 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1076 "invalid `crate_type` value".to_string());
1080 session.struct_span_err(a.span, "`crate_type` requires a value")
1081 .note("for example: `#![crate_type=\"lib\"]`")
1092 // If we're generating a test executable, then ignore all other output
1093 // styles at all other locations
1094 if session.opts.test {
1095 return vec![config::CrateTypeExecutable];
1098 // Only check command line flags if present. If no types are specified by
1099 // command line, then reuse the empty `base` Vec to hold the types that
1100 // will be found in crate attributes.
1101 let mut base = session.opts.crate_types.clone();
1102 if base.is_empty() {
1103 base.extend(attr_types);
1104 if base.is_empty() {
1105 base.push(link::default_output_for_target(session));
1112 .filter(|crate_type| {
1113 let res = !link::invalid_output_for_target(session, *crate_type);
1116 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1118 session.opts.target_triple));
1126 pub fn compute_crate_disambiguator(session: &Session) -> String {
1127 let mut hasher = Sha256::new();
1129 let mut metadata = session.opts.cg.metadata.clone();
1130 // We don't want the crate_disambiguator to dependent on the order
1131 // -C metadata arguments, so sort them:
1133 // Every distinct -C metadata value is only incorporated once:
1136 hasher.input_str("metadata");
1137 for s in &metadata {
1138 // Also incorporate the length of a metadata string, so that we generate
1139 // different values for `-Cmetadata=ab -Cmetadata=c` and
1140 // `-Cmetadata=a -Cmetadata=bc`
1141 hasher.input_str(&format!("{}", s.len())[..]);
1142 hasher.input_str(&s[..]);
1145 let mut hash = hasher.result_str();
1147 // If this is an executable, add a special suffix, so that we don't get
1148 // symbol conflicts when linking against a library of the same name.
1149 if session.crate_types.borrow().contains(&config::CrateTypeExecutable) {
1150 hash.push_str("-exe");
1156 pub fn build_output_filenames(input: &Input,
1157 odir: &Option<PathBuf>,
1158 ofile: &Option<PathBuf>,
1159 attrs: &[ast::Attribute],
1161 -> OutputFilenames {
1164 // "-" as input file will cause the parser to read from stdin so we
1165 // have to make up a name
1166 // We want to toss everything after the final '.'
1167 let dirpath = match *odir {
1168 Some(ref d) => d.clone(),
1169 None => PathBuf::new(),
1172 // If a crate name is present, we use it as the link name
1173 let stem = sess.opts
1176 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1177 .unwrap_or(input.filestem());
1180 out_directory: dirpath,
1182 single_output_file: None,
1183 extra: sess.opts.cg.extra_filename.clone(),
1184 outputs: sess.opts.output_types.clone(),
1188 Some(ref out_file) => {
1189 let unnamed_output_types = sess.opts
1192 .filter(|a| a.is_none())
1194 let ofile = if unnamed_output_types > 1 {
1195 sess.warn("ignoring specified output filename because multiple outputs were \
1199 Some(out_file.clone())
1202 sess.warn("ignoring --out-dir flag due to -o flag.");
1205 let cur_dir = Path::new("");
1208 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1209 out_filestem: out_file.file_stem()
1210 .unwrap_or(OsStr::new(""))
1214 single_output_file: ofile,
1215 extra: sess.opts.cg.extra_filename.clone(),
1216 outputs: sess.opts.output_types.clone(),