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::hir::{self, map as hir_map};
12 use rustc::hir::lowering::lower_crate;
13 use rustc::ich::Fingerprint;
14 use rustc_data_structures::stable_hasher::StableHasher;
16 use rustc::session::{Session, CompileResult, compile_result_from_err_count};
17 use rustc::session::config::{self, Input, OutputFilenames, OutputType,
19 use rustc::session::search_paths::PathKind;
21 use rustc::middle::{self, dependency_format, stability, reachable};
22 use rustc::middle::privacy::AccessLevels;
23 use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas};
24 use rustc::util::common::time;
25 use rustc::util::nodemap::NodeSet;
26 use rustc::util::fs::rename_or_copy_remove;
27 use rustc_borrowck as borrowck;
28 use rustc_incremental::{self, IncrementalHashesMap};
29 use rustc_resolve::{MakeGlobMap, Resolver};
30 use rustc_metadata::creader::CrateLoader;
31 use rustc_metadata::cstore::{self, CStore};
32 use rustc_trans::back::{link, write};
33 use rustc_trans as trans;
34 use rustc_typeck as typeck;
36 use rustc_plugin::registry::Registry;
37 use rustc_plugin as plugin;
38 use rustc_passes::{ast_validation, no_asm, loops, consts,
39 static_recursion, hir_stats, mir_stats};
40 use rustc_const_eval::{self, check_match};
41 use super::Compilation;
46 use std::ffi::{OsString, OsStr};
48 use std::io::{self, Write};
50 use std::path::{Path, PathBuf};
52 use syntax::{ast, diagnostics, visit};
54 use syntax::ext::base::ExtCtxt;
55 use syntax::parse::{self, PResult};
56 use syntax::symbol::Symbol;
57 use syntax::util::node_count::NodeCounter;
60 use arena::DroplessArena;
64 pub fn compile_input(sess: &Session,
67 outdir: &Option<PathBuf>,
68 output: &Option<PathBuf>,
69 addl_plugins: Option<Vec<String>>,
70 control: &CompileController) -> CompileResult {
71 macro_rules! controller_entry_point {
72 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
73 let state = &mut $make_state;
74 let phase_result: &CompileResult = &$phase_result;
75 if phase_result.is_ok() || control.$point.run_callback_on_error {
76 (control.$point.callback)(state);
79 if control.$point.stop == Compilation::Stop {
80 return compile_result_from_err_count($tsess.err_count());
85 // We need nested scopes here, because the intermediate results can keep
86 // large chunks of memory alive and we want to free them as soon as
87 // possible to keep the peak memory usage low
88 let (outputs, trans) = {
89 let krate = match phase_1_parse_input(sess, input) {
91 Err(mut parse_error) => {
97 let (krate, registry) = {
98 let mut compile_state = CompileState::state_after_parse(input,
104 controller_entry_point!(after_parse,
109 (compile_state.krate.unwrap(), compile_state.registry)
112 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
113 let crate_name = link::find_crate_name(Some(sess), &krate.attrs, input);
114 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
115 phase_2_configure_and_expand(
116 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
118 let mut state = CompileState::state_after_expand(
119 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
121 controller_entry_point!(after_expand, sess, state, Ok(()));
127 write_out_deps(sess, &outputs, &crate_name);
128 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
129 sess.opts.output_types.keys().count() == 1 {
133 let arena = DroplessArena::new();
134 let arenas = GlobalArenas::new();
136 // Construct the HIR map
137 let hir_map = time(sess.time_passes(),
139 || hir_map::map_crate(&mut hir_forest, defs));
142 let _ignore = hir_map.dep_graph.in_ignore();
143 controller_entry_point!(after_hir_lowering,
145 CompileState::state_after_hir_lowering(input,
161 time(sess.time_passes(), "attribute checking", || {
162 hir::check_attr::check_crate(sess, &expanded_crate);
165 let opt_crate = if keep_ast(sess) {
166 Some(&expanded_crate)
168 drop(expanded_crate);
172 phase_3_run_analysis_passes(sess,
179 |tcx, analysis, incremental_hashes_map, result| {
181 // Eventually, we will want to track plugins.
182 let _ignore = tcx.dep_graph.in_ignore();
184 let mut state = CompileState::state_after_analysis(input,
193 (control.after_analysis.callback)(&mut state);
195 if control.after_analysis.stop == Compilation::Stop {
196 return result.and_then(|_| Err(0usize));
202 if log_enabled!(::log::LogLevel::Info) {
203 println!("Pre-trans");
204 tcx.print_debug_stats();
206 let trans = phase_4_translate_to_llvm(tcx, analysis, &incremental_hashes_map);
208 if log_enabled!(::log::LogLevel::Info) {
209 println!("Post-trans");
210 tcx.print_debug_stats();
213 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
214 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
215 sess.err(&format!("could not emit MIR: {}", e));
216 sess.abort_if_errors();
224 if sess.opts.debugging_opts.print_type_sizes {
225 sess.code_stats.borrow().print_type_sizes();
228 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
230 controller_entry_point!(after_llvm,
232 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
236 write::cleanup_llvm(&trans);
238 phase_6_link_output(sess, &trans, &outputs);
240 // Now that we won't touch anything in the incremental compilation directory
241 // any more, we can finalize it (which involves renaming it)
242 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
244 if sess.opts.debugging_opts.perf_stats {
245 sess.print_perf_stats();
248 controller_entry_point!(compilation_done,
250 CompileState::state_when_compilation_done(input, sess, outdir, output),
256 fn keep_hygiene_data(sess: &Session) -> bool {
257 sess.opts.debugging_opts.keep_hygiene_data
260 fn keep_ast(sess: &Session) -> bool {
261 sess.opts.debugging_opts.keep_ast || ::save_analysis(sess)
264 /// The name used for source code that doesn't originate in a file
265 /// (e.g. source from stdin or a string)
266 pub fn anon_src() -> String {
270 pub fn source_name(input: &Input) -> String {
272 // FIXME (#9639): This needs to handle non-utf8 paths
273 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
274 Input::Str { ref name, .. } => name.clone(),
278 /// CompileController is used to customise compilation, it allows compilation to
279 /// be stopped and/or to call arbitrary code at various points in compilation.
280 /// It also allows for various flags to be set to influence what information gets
281 /// collected during compilation.
283 /// This is a somewhat higher level controller than a Session - the Session
284 /// controls what happens in each phase, whereas the CompileController controls
285 /// whether a phase is run at all and whether other code (from outside the
286 /// the compiler) is run between phases.
288 /// Note that if compilation is set to stop and a callback is provided for a
289 /// given entry point, the callback is called before compilation is stopped.
291 /// Expect more entry points to be added in the future.
292 pub struct CompileController<'a> {
293 pub after_parse: PhaseController<'a>,
294 pub after_expand: PhaseController<'a>,
295 pub after_hir_lowering: PhaseController<'a>,
296 pub after_analysis: PhaseController<'a>,
297 pub after_llvm: PhaseController<'a>,
298 pub compilation_done: PhaseController<'a>,
300 pub make_glob_map: MakeGlobMap,
303 impl<'a> CompileController<'a> {
304 pub fn basic() -> CompileController<'a> {
306 after_parse: PhaseController::basic(),
307 after_expand: PhaseController::basic(),
308 after_hir_lowering: PhaseController::basic(),
309 after_analysis: PhaseController::basic(),
310 after_llvm: PhaseController::basic(),
311 compilation_done: PhaseController::basic(),
312 make_glob_map: MakeGlobMap::No,
317 pub struct PhaseController<'a> {
318 pub stop: Compilation,
319 // If true then the compiler will try to run the callback even if the phase
320 // ends with an error. Note that this is not always possible.
321 pub run_callback_on_error: bool,
322 pub callback: Box<Fn(&mut CompileState) + 'a>,
325 impl<'a> PhaseController<'a> {
326 pub fn basic() -> PhaseController<'a> {
328 stop: Compilation::Continue,
329 run_callback_on_error: false,
330 callback: box |_| {},
335 /// State that is passed to a callback. What state is available depends on when
336 /// during compilation the callback is made. See the various constructor methods
337 /// (`state_*`) in the impl to see which data is provided for any given entry point.
338 pub struct CompileState<'a, 'tcx: 'a> {
339 pub input: &'a Input,
340 pub session: &'tcx Session,
341 pub krate: Option<ast::Crate>,
342 pub registry: Option<Registry<'a>>,
343 pub cstore: Option<&'a CStore>,
344 pub crate_name: Option<&'a str>,
345 pub output_filenames: Option<&'a OutputFilenames>,
346 pub out_dir: Option<&'a Path>,
347 pub out_file: Option<&'a Path>,
348 pub arena: Option<&'tcx DroplessArena>,
349 pub arenas: Option<&'tcx GlobalArenas<'tcx>>,
350 pub expanded_crate: Option<&'a ast::Crate>,
351 pub hir_crate: Option<&'a hir::Crate>,
352 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
353 pub resolutions: Option<&'a Resolutions>,
354 pub analysis: Option<&'a ty::CrateAnalysis>,
355 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
356 pub trans: Option<&'a trans::CrateTranslation>,
359 impl<'a, 'tcx> CompileState<'a, 'tcx> {
360 fn empty(input: &'a Input,
361 session: &'tcx Session,
362 out_dir: &'a Option<PathBuf>)
367 out_dir: out_dir.as_ref().map(|s| &**s),
375 output_filenames: None,
376 expanded_crate: None,
386 fn state_after_parse(input: &'a Input,
387 session: &'tcx Session,
388 out_dir: &'a Option<PathBuf>,
389 out_file: &'a Option<PathBuf>,
394 // Initialize the registry before moving `krate`
395 registry: Some(Registry::new(&session, krate.span)),
397 cstore: Some(cstore),
398 out_file: out_file.as_ref().map(|s| &**s),
399 ..CompileState::empty(input, session, out_dir)
403 fn state_after_expand(input: &'a Input,
404 session: &'tcx Session,
405 out_dir: &'a Option<PathBuf>,
406 out_file: &'a Option<PathBuf>,
408 expanded_crate: &'a ast::Crate,
412 crate_name: Some(crate_name),
413 cstore: Some(cstore),
414 expanded_crate: Some(expanded_crate),
415 out_file: out_file.as_ref().map(|s| &**s),
416 ..CompileState::empty(input, session, out_dir)
420 fn state_after_hir_lowering(input: &'a Input,
421 session: &'tcx Session,
422 out_dir: &'a Option<PathBuf>,
423 out_file: &'a Option<PathBuf>,
424 arena: &'tcx DroplessArena,
425 arenas: &'tcx GlobalArenas<'tcx>,
427 hir_map: &'a hir_map::Map<'tcx>,
428 analysis: &'a ty::CrateAnalysis,
429 resolutions: &'a Resolutions,
430 krate: &'a ast::Crate,
431 hir_crate: &'a hir::Crate,
435 crate_name: Some(crate_name),
437 arenas: Some(arenas),
438 cstore: Some(cstore),
439 hir_map: Some(hir_map),
440 analysis: Some(analysis),
441 resolutions: Some(resolutions),
442 expanded_crate: Some(krate),
443 hir_crate: Some(hir_crate),
444 out_file: out_file.as_ref().map(|s| &**s),
445 ..CompileState::empty(input, session, out_dir)
449 fn state_after_analysis(input: &'a Input,
450 session: &'tcx Session,
451 out_dir: &'a Option<PathBuf>,
452 out_file: &'a Option<PathBuf>,
453 krate: Option<&'a ast::Crate>,
454 hir_crate: &'a hir::Crate,
455 analysis: &'a ty::CrateAnalysis,
456 tcx: TyCtxt<'a, 'tcx, 'tcx>,
460 analysis: Some(analysis),
462 expanded_crate: krate,
463 hir_crate: Some(hir_crate),
464 crate_name: Some(crate_name),
465 out_file: out_file.as_ref().map(|s| &**s),
466 ..CompileState::empty(input, session, out_dir)
471 fn state_after_llvm(input: &'a Input,
472 session: &'tcx Session,
473 out_dir: &'a Option<PathBuf>,
474 out_file: &'a Option<PathBuf>,
475 trans: &'a trans::CrateTranslation)
479 out_file: out_file.as_ref().map(|s| &**s),
480 ..CompileState::empty(input, session, out_dir)
484 fn state_when_compilation_done(input: &'a Input,
485 session: &'tcx Session,
486 out_dir: &'a Option<PathBuf>,
487 out_file: &'a Option<PathBuf>)
490 out_file: out_file.as_ref().map(|s| &**s),
491 ..CompileState::empty(input, session, out_dir)
496 pub fn phase_1_parse_input<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
497 let continue_after_error = sess.opts.debugging_opts.continue_parse_after_error;
498 sess.diagnostic().set_continue_after_error(continue_after_error);
500 let krate = time(sess.time_passes(), "parsing", || {
502 Input::File(ref file) => {
503 parse::parse_crate_from_file(file, &sess.parse_sess)
505 Input::Str { ref input, ref name } => {
506 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
511 sess.diagnostic().set_continue_after_error(true);
513 if sess.opts.debugging_opts.ast_json_noexpand {
514 println!("{}", json::as_json(&krate));
517 if sess.opts.debugging_opts.input_stats {
518 println!("Lines of code: {}", sess.codemap().count_lines());
519 println!("Pre-expansion node count: {}", count_nodes(&krate));
522 if let Some(ref s) = sess.opts.debugging_opts.show_span {
523 syntax::show_span::run(sess.diagnostic(), s, &krate);
526 if sess.opts.debugging_opts.hir_stats {
527 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
533 fn count_nodes(krate: &ast::Crate) -> usize {
534 let mut counter = NodeCounter::new();
535 visit::walk_crate(&mut counter, krate);
539 // For continuing compilation after a parsed crate has been
542 pub struct ExpansionResult {
543 pub expanded_crate: ast::Crate,
544 pub defs: hir_map::Definitions,
545 pub analysis: ty::CrateAnalysis,
546 pub resolutions: Resolutions,
547 pub hir_forest: hir_map::Forest,
550 /// Run the "early phases" of the compiler: initial `cfg` processing,
551 /// loading compiler plugins (including those from `addl_plugins`),
552 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
553 /// harness if one is to be provided, injection of a dependency on the
554 /// standard library and prelude, and name resolution.
556 /// Returns `None` if we're aborting after handling -W help.
557 pub fn phase_2_configure_and_expand<F>(sess: &Session,
560 registry: Option<Registry>,
562 addl_plugins: Option<Vec<String>>,
563 make_glob_map: MakeGlobMap,
565 -> Result<ExpansionResult, usize>
566 where F: FnOnce(&ast::Crate) -> CompileResult,
568 let time_passes = sess.time_passes();
570 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
571 // these need to be set "early" so that expansion sees `quote` if enabled.
572 *sess.features.borrow_mut() = features;
574 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
575 *sess.crate_disambiguator.borrow_mut() = Symbol::intern(&compute_crate_disambiguator(sess));
577 time(time_passes, "recursion limit", || {
578 middle::recursion_limit::update_limits(sess, &krate);
581 krate = time(time_passes, "crate injection", || {
582 let alt_std_name = sess.opts.alt_std_name.clone();
583 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
586 let mut addl_plugins = Some(addl_plugins);
587 let registrars = time(time_passes, "plugin loading", || {
588 plugin::load::load_plugins(sess,
592 addl_plugins.take().unwrap())
595 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
597 time(time_passes, "plugin registration", || {
598 if sess.features.borrow().rustc_diagnostic_macros {
599 registry.register_macro("__diagnostic_used",
600 diagnostics::plugin::expand_diagnostic_used);
601 registry.register_macro("__register_diagnostic",
602 diagnostics::plugin::expand_register_diagnostic);
603 registry.register_macro("__build_diagnostic_array",
604 diagnostics::plugin::expand_build_diagnostic_array);
607 for registrar in registrars {
608 registry.args_hidden = Some(registrar.args);
609 (registrar.fun)(&mut registry);
613 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
614 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
615 llvm_passes, attributes, .. } = registry;
617 sess.track_errors(|| {
618 let mut ls = sess.lint_store.borrow_mut();
619 for pass in early_lint_passes {
620 ls.register_early_pass(Some(sess), true, pass);
622 for pass in late_lint_passes {
623 ls.register_late_pass(Some(sess), true, pass);
626 for (name, to) in lint_groups {
627 ls.register_group(Some(sess), true, name, to);
630 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
631 *sess.plugin_attributes.borrow_mut() = attributes.clone();
634 // Lint plugins are registered; now we can process command line flags.
635 if sess.opts.describe_lints {
636 super::describe_lints(&sess.lint_store.borrow(), true);
639 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
641 // Currently, we ignore the name resolution data structures for the purposes of dependency
642 // tracking. Instead we will run name resolution and include its output in the hash of each
643 // item, much like we do for macro expansion. In other words, the hash reflects not just
644 // its contents but the results of name resolution on those contents. Hopefully we'll push
645 // this back at some point.
646 let _ignore = sess.dep_graph.in_ignore();
647 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
648 crate_loader.preprocess(&krate);
649 let resolver_arenas = Resolver::arenas();
650 let mut resolver = Resolver::new(sess,
656 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
657 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
659 krate = time(time_passes, "expansion", || {
660 // Windows dlls do not have rpaths, so they don't know how to find their
661 // dependencies. It's up to us to tell the system where to find all the
662 // dependent dlls. Note that this uses cfg!(windows) as opposed to
663 // targ_cfg because syntax extensions are always loaded for the host
664 // compiler, not for the target.
666 // This is somewhat of an inherently racy operation, however, as
667 // multiple threads calling this function could possibly continue
668 // extending PATH far beyond what it should. To solve this for now we
669 // just don't add any new elements to PATH which are already there
670 // within PATH. This is basically a targeted fix at #17360 for rustdoc
671 // which runs rustc in parallel but has been seen (#33844) to cause
672 // problems with PATH becoming too long.
673 let mut old_path = OsString::new();
675 old_path = env::var_os("PATH").unwrap_or(old_path);
676 let mut new_path = sess.host_filesearch(PathKind::All)
677 .get_dylib_search_paths();
678 for path in env::split_paths(&old_path) {
679 if !new_path.contains(&path) {
684 &env::join_paths(new_path.iter()
685 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
688 let features = sess.features.borrow();
689 let cfg = syntax::ext::expand::ExpansionConfig {
690 features: Some(&features),
691 recursion_limit: sess.recursion_limit.get(),
692 trace_mac: sess.opts.debugging_opts.trace_macros,
693 should_test: sess.opts.test,
694 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
697 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
698 let err_count = ecx.parse_sess.span_diagnostic.err_count();
700 let krate = ecx.monotonic_expander().expand_crate(krate);
702 let mut missing_fragment_specifiers: Vec<_> =
703 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
704 missing_fragment_specifiers.sort();
705 for span in missing_fragment_specifiers {
706 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
707 let msg = "missing fragment specifier".to_string();
708 sess.add_lint(lint, ast::CRATE_NODE_ID, span, msg);
710 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
711 ecx.parse_sess.span_diagnostic.abort_if_errors();
714 env::set_var("PATH", &old_path);
719 krate = time(time_passes, "maybe building test harness", || {
720 syntax::test::modify_for_testing(&sess.parse_sess,
727 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
728 // bunch of checks in the `modify` function below. For now just skip this
729 // step entirely if we're rustdoc as it's not too useful anyway.
730 if !sess.opts.actually_rustdoc {
731 krate = time(time_passes, "maybe creating a macro crate", || {
732 let crate_types = sess.crate_types.borrow();
733 let num_crate_types = crate_types.len();
734 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
735 let is_test_crate = sess.opts.test;
736 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
746 after_expand(&krate)?;
748 if sess.opts.debugging_opts.input_stats {
749 println!("Post-expansion node count: {}", count_nodes(&krate));
752 if sess.opts.debugging_opts.hir_stats {
753 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
756 if sess.opts.debugging_opts.ast_json {
757 println!("{}", json::as_json(&krate));
761 "checking for inline asm in case the target doesn't support it",
762 || no_asm::check_crate(sess, &krate));
766 || lint::check_ast_crate(sess, &krate));
770 || ast_validation::check_crate(sess, &krate));
772 time(time_passes, "name resolution", || -> CompileResult {
773 resolver.resolve_crate(&krate);
777 if resolver.found_unresolved_macro {
778 sess.parse_sess.span_diagnostic.abort_if_errors();
781 // Needs to go *after* expansion to be able to check the results of macro expansion.
782 time(time_passes, "complete gated feature checking", || {
783 sess.track_errors(|| {
784 syntax::feature_gate::check_crate(&krate,
786 &sess.features.borrow(),
788 sess.opts.unstable_features);
793 let hir_forest = time(time_passes, "lowering ast -> hir", || {
794 let hir_crate = lower_crate(sess, &krate, &mut resolver);
796 if sess.opts.debugging_opts.hir_stats {
797 hir_stats::print_hir_stats(&hir_crate);
800 hir_map::Forest::new(hir_crate, &sess.dep_graph)
803 // Discard hygiene data, which isn't required after lowering to HIR.
804 if !keep_hygiene_data(sess) {
805 syntax::ext::hygiene::clear_markings();
809 expanded_crate: krate,
810 defs: resolver.definitions,
811 analysis: ty::CrateAnalysis {
812 access_levels: Rc::new(AccessLevels::default()),
813 reachable: Rc::new(NodeSet()),
814 name: crate_name.to_string(),
815 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
817 resolutions: Resolutions {
818 freevars: resolver.freevars,
819 export_map: resolver.export_map,
820 trait_map: resolver.trait_map,
821 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
823 hir_forest: hir_forest,
827 /// Run the resolution, typechecking, region checking and other
828 /// miscellaneous analysis passes on the crate. Return various
829 /// structures carrying the results of the analysis.
830 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
831 hir_map: hir_map::Map<'tcx>,
832 mut analysis: ty::CrateAnalysis,
833 resolutions: Resolutions,
834 arena: &'tcx DroplessArena,
835 arenas: &'tcx GlobalArenas<'tcx>,
839 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
841 IncrementalHashesMap,
844 macro_rules! try_with_f {
845 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
849 f($t, $a, $h, Err(x));
856 let time_passes = sess.time_passes();
858 let lang_items = time(time_passes, "language item collection", || {
859 sess.track_errors(|| {
860 middle::lang_items::collect_language_items(&sess, &hir_map)
864 let named_region_map = time(time_passes,
865 "lifetime resolution",
866 || middle::resolve_lifetime::krate(sess, &hir_map))?;
869 "looking for entry point",
870 || middle::entry::find_entry_point(sess, &hir_map));
872 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
873 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
875 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
879 || loops::check_crate(sess, &hir_map));
882 "static item recursion checking",
883 || static_recursion::check_crate(sess, &hir_map))?;
885 let index = stability::Index::new(&hir_map);
887 let mut local_providers = ty::maps::Providers::default();
888 borrowck::provide(&mut local_providers);
889 mir::provide(&mut local_providers);
890 reachable::provide(&mut local_providers);
891 rustc_privacy::provide(&mut local_providers);
892 trans::provide(&mut local_providers);
893 typeck::provide(&mut local_providers);
894 ty::provide(&mut local_providers);
895 reachable::provide(&mut local_providers);
896 rustc_const_eval::provide(&mut local_providers);
897 middle::region::provide(&mut local_providers);
899 let mut extern_providers = ty::maps::Providers::default();
900 cstore::provide(&mut extern_providers);
901 trans::provide(&mut extern_providers);
902 ty::provide_extern(&mut extern_providers);
903 // FIXME(eddyb) get rid of this once we replace const_eval with miri.
904 rustc_const_eval::provide(&mut extern_providers);
906 TyCtxt::create_and_enter(sess,
918 let incremental_hashes_map =
920 "compute_incremental_hashes_map",
921 || rustc_incremental::compute_incremental_hashes_map(tcx));
925 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
927 time(time_passes, "stability index", || {
928 tcx.stability.borrow_mut().build(tcx)
932 "stability checking",
933 || stability::check_unstable_api_usage(tcx));
935 // passes are timed inside typeck
936 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
940 || consts::check_crate(tcx));
942 analysis.access_levels =
943 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
946 "intrinsic checking",
947 || middle::intrinsicck::check_crate(tcx));
951 || middle::effect::check_crate(tcx));
955 || check_match::check_crate(tcx));
957 // this must run before MIR dump, because
958 // "not all control paths return a value" is reported here.
960 // maybe move the check to a MIR pass?
963 || middle::liveness::check_crate(tcx));
967 || mir::mir_map::build_mir_for_crate(tcx));
969 if sess.opts.debugging_opts.mir_stats {
970 mir_stats::print_mir_stats(tcx, "PRE CLEANUP MIR STATS");
973 time(time_passes, "MIR cleanup and validation", || {
974 let mut passes = sess.mir_passes.borrow_mut();
975 // Push all the built-in validation passes.
976 // NB: if you’re adding an *optimisation* it ought to go to another set of passes
978 passes.push_hook(box mir::transform::dump_mir::DumpMir);
979 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("initial"));
980 passes.push_pass(box mir::transform::type_check::TypeckMir);
981 passes.push_pass(box mir::transform::qualify_consts::QualifyAndPromoteConstants);
983 box mir::transform::simplify_branches::SimplifyBranches::new("initial"));
984 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
985 // And run everything.
986 passes.run_passes(tcx);
991 || borrowck::check_crate(tcx));
993 // Avoid overwhelming user with errors if type checking failed.
994 // I'm not sure how helpful this is, to be honest, but it avoids
996 // lot of annoying errors in the compile-fail tests (basically,
997 // lint warnings and so on -- kindck used to do this abort, but
998 // kindck is gone now). -nmatsakis
999 if sess.err_count() > 0 {
1000 return Ok(f(tcx, analysis, incremental_hashes_map, Err(sess.err_count())));
1003 analysis.reachable =
1005 "reachability checking",
1006 || reachable::find_reachable(tcx));
1008 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1010 time(time_passes, "unused lib feature checking", || {
1011 stability::check_unused_or_stable_features(tcx)
1014 time(time_passes, "lint checking", || lint::check_crate(tcx));
1016 // The above three passes generate errors w/o aborting
1017 if sess.err_count() > 0 {
1018 return Ok(f(tcx, analysis, incremental_hashes_map, Err(sess.err_count())));
1021 Ok(f(tcx, analysis, incremental_hashes_map, Ok(())))
1025 /// Run the translation phase to LLVM, after which the AST and analysis can
1027 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1028 analysis: ty::CrateAnalysis,
1029 incremental_hashes_map: &IncrementalHashesMap)
1030 -> trans::CrateTranslation {
1031 let time_passes = tcx.sess.time_passes();
1034 "resolving dependency formats",
1035 || dependency_format::calculate(&tcx.sess));
1037 if tcx.sess.opts.debugging_opts.mir_stats {
1038 mir_stats::print_mir_stats(tcx, "PRE OPTIMISATION MIR STATS");
1041 // Run the passes that transform the MIR into a more suitable form for translation to LLVM
1043 time(time_passes, "MIR optimisations", || {
1044 let mut passes = ::rustc::mir::transform::Passes::new();
1045 passes.push_hook(box mir::transform::dump_mir::DumpMir);
1046 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1047 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("no-landing-pads"));
1049 // From here on out, regions are gone.
1050 passes.push_pass(box mir::transform::erase_regions::EraseRegions);
1052 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1053 passes.push_pass(box borrowck::ElaborateDrops);
1054 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1055 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("elaborate-drops"));
1057 // No lifetime analysis based on borrowing can be done from here on out.
1058 passes.push_pass(box mir::transform::inline::Inline);
1059 passes.push_pass(box mir::transform::instcombine::InstCombine::new());
1060 passes.push_pass(box mir::transform::deaggregator::Deaggregator);
1061 passes.push_pass(box mir::transform::copy_prop::CopyPropagation);
1063 passes.push_pass(box mir::transform::simplify::SimplifyLocals);
1064 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1065 passes.push_pass(box mir::transform::dump_mir::Marker("PreTrans"));
1067 passes.run_passes(tcx);
1070 if tcx.sess.opts.debugging_opts.mir_stats {
1071 mir_stats::print_mir_stats(tcx, "POST OPTIMISATION MIR STATS");
1077 move || trans::trans_crate(tcx, analysis, &incremental_hashes_map));
1081 || rustc_incremental::assert_dep_graph(tcx));
1084 "serialize dep graph",
1085 || rustc_incremental::save_dep_graph(tcx,
1086 &incremental_hashes_map,
1087 &translation.metadata.hashes,
1088 translation.link.crate_hash));
1092 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1093 /// as a side effect.
1094 pub fn phase_5_run_llvm_passes(sess: &Session,
1095 trans: &trans::CrateTranslation,
1096 outputs: &OutputFilenames) -> CompileResult {
1097 if sess.opts.cg.no_integrated_as ||
1098 (sess.target.target.options.no_integrated_as &&
1099 (outputs.outputs.contains_key(&OutputType::Object) ||
1100 outputs.outputs.contains_key(&OutputType::Exe)))
1102 let output_types = OutputTypes::new(&[(OutputType::Assembly, None)]);
1103 time(sess.time_passes(),
1105 || write::run_passes(sess, trans, &output_types, outputs));
1107 write::run_assembler(sess, outputs);
1109 // HACK the linker expects the object file to be named foo.0.o but
1110 // `run_assembler` produces an object named just foo.o. Rename it if we
1111 // are going to build an executable
1112 if sess.opts.output_types.contains_key(&OutputType::Exe) {
1113 let f = outputs.path(OutputType::Object);
1114 rename_or_copy_remove(&f,
1115 f.with_file_name(format!("{}.0.o",
1116 f.file_stem().unwrap().to_string_lossy()))).unwrap();
1119 // Remove assembly source, unless --save-temps was specified
1120 if !sess.opts.cg.save_temps {
1121 fs::remove_file(&outputs.temp_path(OutputType::Assembly, None)).unwrap();
1124 time(sess.time_passes(),
1126 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1129 time(sess.time_passes(),
1130 "serialize work products",
1131 move || rustc_incremental::save_work_products(sess));
1133 if sess.err_count() > 0 {
1134 Err(sess.err_count())
1140 /// Run the linker on any artifacts that resulted from the LLVM run.
1141 /// This should produce either a finished executable or library.
1142 pub fn phase_6_link_output(sess: &Session,
1143 trans: &trans::CrateTranslation,
1144 outputs: &OutputFilenames) {
1145 time(sess.time_passes(),
1147 || link::link_binary(sess, trans, outputs, &trans.crate_name.as_str()));
1150 fn escape_dep_filename(filename: &str) -> String {
1151 // Apparently clang and gcc *only* escape spaces:
1152 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1153 filename.replace(" ", "\\ ")
1156 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1157 let mut out_filenames = Vec::new();
1158 for output_type in sess.opts.output_types.keys() {
1159 let file = outputs.path(*output_type);
1160 match *output_type {
1161 OutputType::Exe => {
1162 for output in sess.crate_types.borrow().iter() {
1163 let p = link::filename_for_input(sess, *output, crate_name, outputs);
1164 out_filenames.push(p);
1168 out_filenames.push(file);
1173 // Write out dependency rules to the dep-info file if requested
1174 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1177 let deps_filename = outputs.path(OutputType::DepInfo);
1180 (|| -> io::Result<()> {
1181 // Build a list of files used to compile the output and
1182 // write Makefile-compatible dependency rules
1183 let files: Vec<String> = sess.codemap()
1187 .filter(|fmap| fmap.is_real_file())
1188 .filter(|fmap| !fmap.is_imported())
1189 .map(|fmap| escape_dep_filename(&fmap.name))
1191 let mut file = fs::File::create(&deps_filename)?;
1192 for path in &out_filenames {
1193 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1196 // Emit a fake target for each input file to the compilation. This
1197 // prevents `make` from spitting out an error if a file is later
1198 // deleted. For more info see #28735
1200 writeln!(file, "{}:", path)?;
1208 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1209 deps_filename.display(),
1215 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1216 // Unconditionally collect crate types from attributes to make them used
1217 let attr_types: Vec<config::CrateType> =
1220 if a.check_name("crate_type") {
1221 match a.value_str() {
1222 Some(ref n) if *n == "rlib" => {
1223 Some(config::CrateTypeRlib)
1225 Some(ref n) if *n == "dylib" => {
1226 Some(config::CrateTypeDylib)
1228 Some(ref n) if *n == "cdylib" => {
1229 Some(config::CrateTypeCdylib)
1231 Some(ref n) if *n == "lib" => {
1232 Some(config::default_lib_output())
1234 Some(ref n) if *n == "staticlib" => {
1235 Some(config::CrateTypeStaticlib)
1237 Some(ref n) if *n == "proc-macro" => {
1238 Some(config::CrateTypeProcMacro)
1240 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1242 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1245 "invalid `crate_type` value".to_string());
1249 session.struct_span_err(a.span, "`crate_type` requires a value")
1250 .note("for example: `#![crate_type=\"lib\"]`")
1261 // If we're generating a test executable, then ignore all other output
1262 // styles at all other locations
1263 if session.opts.test {
1264 return vec![config::CrateTypeExecutable];
1267 // Only check command line flags if present. If no types are specified by
1268 // command line, then reuse the empty `base` Vec to hold the types that
1269 // will be found in crate attributes.
1270 let mut base = session.opts.crate_types.clone();
1271 if base.is_empty() {
1272 base.extend(attr_types);
1273 if base.is_empty() {
1274 base.push(link::default_output_for_target(session));
1281 .filter(|crate_type| {
1282 let res = !link::invalid_output_for_target(session, *crate_type);
1285 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1287 session.opts.target_triple));
1295 pub fn compute_crate_disambiguator(session: &Session) -> String {
1296 use std::hash::Hasher;
1298 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1299 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1300 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1301 // should still be safe enough to avoid collisions in practice.
1302 // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1303 // a hex-string instead of raw bytes. We should really use the
1304 // smaller representation.
1305 let mut hasher = StableHasher::<Fingerprint>::new();
1307 let mut metadata = session.opts.cg.metadata.clone();
1308 // We don't want the crate_disambiguator to dependent on the order
1309 // -C metadata arguments, so sort them:
1311 // Every distinct -C metadata value is only incorporated once:
1314 hasher.write(b"metadata");
1315 for s in &metadata {
1316 // Also incorporate the length of a metadata string, so that we generate
1317 // different values for `-Cmetadata=ab -Cmetadata=c` and
1318 // `-Cmetadata=a -Cmetadata=bc`
1319 hasher.write_usize(s.len());
1320 hasher.write(s.as_bytes());
1323 // If this is an executable, add a special suffix, so that we don't get
1324 // symbol conflicts when linking against a library of the same name.
1325 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1327 format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
1330 pub fn build_output_filenames(input: &Input,
1331 odir: &Option<PathBuf>,
1332 ofile: &Option<PathBuf>,
1333 attrs: &[ast::Attribute],
1335 -> OutputFilenames {
1338 // "-" as input file will cause the parser to read from stdin so we
1339 // have to make up a name
1340 // We want to toss everything after the final '.'
1341 let dirpath = match *odir {
1342 Some(ref d) => d.clone(),
1343 None => PathBuf::new(),
1346 // If a crate name is present, we use it as the link name
1347 let stem = sess.opts
1350 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1351 .unwrap_or(input.filestem());
1354 out_directory: dirpath,
1356 single_output_file: None,
1357 extra: sess.opts.cg.extra_filename.clone(),
1358 outputs: sess.opts.output_types.clone(),
1362 Some(ref out_file) => {
1363 let unnamed_output_types = sess.opts
1366 .filter(|a| a.is_none())
1368 let ofile = if unnamed_output_types > 1 {
1369 sess.warn("due to multiple output types requested, the explicitly specified \
1370 output file name will be adapted for each output type");
1373 Some(out_file.clone())
1376 sess.warn("ignoring --out-dir flag due to -o flag.");
1379 let cur_dir = Path::new("");
1382 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1383 out_filestem: out_file.file_stem()
1384 .unwrap_or(OsStr::new(""))
1388 single_output_file: ofile,
1389 extra: sess.opts.cg.extra_filename.clone(),
1390 outputs: sess.opts.output_types.clone(),