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.
12 use rustc::hir::{map as hir_map, FreevarMap, TraitMap};
13 use rustc::hir::def::DefMap;
14 use rustc::hir::lowering::lower_crate;
15 use rustc_data_structures::blake2b::Blake2bHasher;
16 use rustc_data_structures::fmt_wrap::FmtWrap;
17 use rustc::ty::util::ArchIndependentHasher;
19 use rustc::session::{Session, CompileResult, compile_result_from_err_count};
20 use rustc::session::config::{self, Input, OutputFilenames, OutputType,
22 use rustc::session::search_paths::PathKind;
24 use rustc::middle::{self, dependency_format, stability, reachable};
25 use rustc::middle::privacy::AccessLevels;
26 use rustc::ty::{self, TyCtxt};
27 use rustc::util::common::time;
28 use rustc::util::nodemap::NodeSet;
29 use rustc_borrowck as borrowck;
30 use rustc_incremental::{self, IncrementalHashesMap};
31 use rustc_resolve::{MakeGlobMap, Resolver};
32 use rustc_metadata::creader::CrateLoader;
33 use rustc_metadata::cstore::CStore;
34 use rustc_trans::back::{link, write};
35 use rustc_trans as trans;
36 use rustc_typeck as typeck;
38 use rustc_plugin::registry::Registry;
39 use rustc_plugin as plugin;
40 use rustc_passes::{ast_validation, no_asm, loops, consts, rvalues, static_recursion};
41 use rustc_const_eval::check_match;
42 use super::Compilation;
48 use std::ffi::{OsString, OsStr};
50 use std::io::{self, Write};
51 use std::path::{Path, PathBuf};
52 use syntax::{ast, diagnostics, visit};
54 use syntax::ext::base::ExtCtxt;
55 use syntax::parse::{self, PResult, token};
56 use syntax::util::node_count::NodeCounter;
63 pub struct Resolutions {
65 pub freevars: FreevarMap,
66 pub trait_map: TraitMap,
67 pub maybe_unused_trait_imports: NodeSet,
70 pub fn compile_input(sess: &Session,
73 outdir: &Option<PathBuf>,
74 output: &Option<PathBuf>,
75 addl_plugins: Option<Vec<String>>,
76 control: &CompileController) -> CompileResult {
77 macro_rules! controller_entry_point {
78 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
79 let state = &mut $make_state;
80 let phase_result: &CompileResult = &$phase_result;
81 if phase_result.is_ok() || control.$point.run_callback_on_error {
82 (control.$point.callback)(state);
85 if control.$point.stop == Compilation::Stop {
86 return compile_result_from_err_count($tsess.err_count());
91 // We need nested scopes here, because the intermediate results can keep
92 // large chunks of memory alive and we want to free them as soon as
93 // possible to keep the peak memory usage low
94 let (outputs, trans) = {
95 let krate = match phase_1_parse_input(sess, input) {
97 Err(mut parse_error) => {
103 let (krate, registry) = {
104 let mut compile_state = CompileState::state_after_parse(input,
110 controller_entry_point!(after_parse,
115 (compile_state.krate.unwrap(), compile_state.registry)
118 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
119 let crate_name = link::find_crate_name(Some(sess), &krate.attrs, input);
120 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
121 phase_2_configure_and_expand(
122 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
124 let mut state = CompileState::state_after_expand(
125 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
127 controller_entry_point!(after_expand, sess, state, Ok(()));
133 write_out_deps(sess, &outputs, &crate_name);
135 let arenas = ty::CtxtArenas::new();
137 // Construct the HIR map
138 let hir_map = time(sess.time_passes(),
140 || hir_map::map_crate(&mut hir_forest, defs));
143 let _ignore = hir_map.dep_graph.in_ignore();
144 controller_entry_point!(after_hir_lowering,
146 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,
178 |tcx, analysis, incremental_hashes_map, result| {
180 // Eventually, we will want to track plugins.
181 let _ignore = tcx.dep_graph.in_ignore();
183 let mut state = CompileState::state_after_analysis(input,
192 (control.after_analysis.callback)(&mut state);
194 if control.after_analysis.stop == Compilation::Stop {
195 return result.and_then(|_| Err(0usize));
201 if log_enabled!(::log::INFO) {
202 println!("Pre-trans");
203 tcx.print_debug_stats();
205 let trans = phase_4_translate_to_llvm(tcx, analysis, &incremental_hashes_map);
207 if log_enabled!(::log::INFO) {
208 println!("Post-trans");
209 tcx.print_debug_stats();
212 // Discard interned strings as they are no longer required.
213 token::clear_ident_interner();
219 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
221 controller_entry_point!(after_llvm,
223 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
227 write::cleanup_llvm(&trans);
229 phase_6_link_output(sess, &trans, &outputs);
231 // Now that we won't touch anything in the incremental compilation directory
232 // any more, we can finalize it (which involves renaming it)
233 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
235 if sess.opts.debugging_opts.perf_stats {
236 sess.print_perf_stats();
239 controller_entry_point!(compilation_done,
241 CompileState::state_when_compilation_done(input, sess, outdir, output),
247 fn keep_hygiene_data(sess: &Session) -> bool {
248 sess.opts.debugging_opts.keep_hygiene_data
251 fn keep_ast(sess: &Session) -> bool {
252 sess.opts.debugging_opts.keep_ast ||
253 sess.opts.debugging_opts.save_analysis ||
254 sess.opts.debugging_opts.save_analysis_csv ||
255 sess.opts.debugging_opts.save_analysis_api
258 /// The name used for source code that doesn't originate in a file
259 /// (e.g. source from stdin or a string)
260 pub fn anon_src() -> String {
264 pub fn source_name(input: &Input) -> String {
266 // FIXME (#9639): This needs to handle non-utf8 paths
267 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
268 Input::Str { ref name, .. } => name.clone(),
272 /// CompileController is used to customise compilation, it allows compilation to
273 /// be stopped and/or to call arbitrary code at various points in compilation.
274 /// It also allows for various flags to be set to influence what information gets
275 /// collected during compilation.
277 /// This is a somewhat higher level controller than a Session - the Session
278 /// controls what happens in each phase, whereas the CompileController controls
279 /// whether a phase is run at all and whether other code (from outside the
280 /// the compiler) is run between phases.
282 /// Note that if compilation is set to stop and a callback is provided for a
283 /// given entry point, the callback is called before compilation is stopped.
285 /// Expect more entry points to be added in the future.
286 pub struct CompileController<'a> {
287 pub after_parse: PhaseController<'a>,
288 pub after_expand: PhaseController<'a>,
289 pub after_hir_lowering: PhaseController<'a>,
290 pub after_analysis: PhaseController<'a>,
291 pub after_llvm: PhaseController<'a>,
292 pub compilation_done: PhaseController<'a>,
294 pub make_glob_map: MakeGlobMap,
297 impl<'a> CompileController<'a> {
298 pub fn basic() -> CompileController<'a> {
300 after_parse: PhaseController::basic(),
301 after_expand: PhaseController::basic(),
302 after_hir_lowering: PhaseController::basic(),
303 after_analysis: PhaseController::basic(),
304 after_llvm: PhaseController::basic(),
305 compilation_done: PhaseController::basic(),
306 make_glob_map: MakeGlobMap::No,
311 pub struct PhaseController<'a> {
312 pub stop: Compilation,
313 // If true then the compiler will try to run the callback even if the phase
314 // ends with an error. Note that this is not always possible.
315 pub run_callback_on_error: bool,
316 pub callback: Box<Fn(&mut CompileState) + 'a>,
319 impl<'a> PhaseController<'a> {
320 pub fn basic() -> PhaseController<'a> {
322 stop: Compilation::Continue,
323 run_callback_on_error: false,
324 callback: box |_| {},
329 /// State that is passed to a callback. What state is available depends on when
330 /// during compilation the callback is made. See the various constructor methods
331 /// (`state_*`) in the impl to see which data is provided for any given entry point.
332 pub struct CompileState<'a, 'b, 'ast: 'a, 'tcx: 'b> where 'ast: 'tcx {
333 pub input: &'a Input,
334 pub session: &'ast Session,
335 pub krate: Option<ast::Crate>,
336 pub registry: Option<Registry<'a>>,
337 pub cstore: Option<&'a CStore>,
338 pub crate_name: Option<&'a str>,
339 pub output_filenames: Option<&'a OutputFilenames>,
340 pub out_dir: Option<&'a Path>,
341 pub out_file: Option<&'a Path>,
342 pub arenas: Option<&'ast ty::CtxtArenas<'ast>>,
343 pub expanded_crate: Option<&'a ast::Crate>,
344 pub hir_crate: Option<&'a hir::Crate>,
345 pub ast_map: Option<&'a hir_map::Map<'ast>>,
346 pub resolutions: Option<&'a Resolutions>,
347 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
348 pub tcx: Option<TyCtxt<'b, 'tcx, 'tcx>>,
349 pub trans: Option<&'a trans::CrateTranslation>,
352 impl<'a, 'b, 'ast, 'tcx> CompileState<'a, 'b, 'ast, 'tcx> {
353 fn empty(input: &'a Input,
354 session: &'ast Session,
355 out_dir: &'a Option<PathBuf>)
356 -> CompileState<'a, 'b, 'ast, 'tcx> {
360 out_dir: out_dir.as_ref().map(|s| &**s),
367 output_filenames: None,
368 expanded_crate: None,
378 fn state_after_parse(input: &'a Input,
379 session: &'ast Session,
380 out_dir: &'a Option<PathBuf>,
381 out_file: &'a Option<PathBuf>,
384 -> CompileState<'a, 'b, 'ast, 'tcx> {
386 // Initialize the registry before moving `krate`
387 registry: Some(Registry::new(&session, krate.span)),
389 cstore: Some(cstore),
390 out_file: out_file.as_ref().map(|s| &**s),
391 ..CompileState::empty(input, session, out_dir)
395 fn state_after_expand(input: &'a Input,
396 session: &'ast Session,
397 out_dir: &'a Option<PathBuf>,
398 out_file: &'a Option<PathBuf>,
400 expanded_crate: &'a ast::Crate,
402 -> CompileState<'a, 'b, 'ast, 'tcx> {
404 crate_name: Some(crate_name),
405 cstore: Some(cstore),
406 expanded_crate: Some(expanded_crate),
407 out_file: out_file.as_ref().map(|s| &**s),
408 ..CompileState::empty(input, session, out_dir)
412 fn state_after_hir_lowering(input: &'a Input,
413 session: &'ast Session,
414 out_dir: &'a Option<PathBuf>,
415 out_file: &'a Option<PathBuf>,
416 arenas: &'ast ty::CtxtArenas<'ast>,
418 hir_map: &'a hir_map::Map<'ast>,
419 analysis: &'a ty::CrateAnalysis,
420 resolutions: &'a Resolutions,
421 krate: &'a ast::Crate,
422 hir_crate: &'a hir::Crate,
424 -> CompileState<'a, 'b, 'ast, 'tcx> {
426 crate_name: Some(crate_name),
427 arenas: Some(arenas),
428 cstore: Some(cstore),
429 ast_map: Some(hir_map),
430 analysis: Some(analysis),
431 resolutions: Some(resolutions),
432 expanded_crate: Some(krate),
433 hir_crate: Some(hir_crate),
434 out_file: out_file.as_ref().map(|s| &**s),
435 ..CompileState::empty(input, session, out_dir)
439 fn state_after_analysis(input: &'a Input,
440 session: &'ast Session,
441 out_dir: &'a Option<PathBuf>,
442 out_file: &'a Option<PathBuf>,
443 krate: Option<&'a ast::Crate>,
444 hir_crate: &'a hir::Crate,
445 analysis: &'a ty::CrateAnalysis<'a>,
446 tcx: TyCtxt<'b, 'tcx, 'tcx>,
448 -> CompileState<'a, 'b, 'ast, 'tcx> {
450 analysis: Some(analysis),
452 expanded_crate: krate,
453 hir_crate: Some(hir_crate),
454 crate_name: Some(crate_name),
455 out_file: out_file.as_ref().map(|s| &**s),
456 ..CompileState::empty(input, session, out_dir)
461 fn state_after_llvm(input: &'a Input,
462 session: &'ast Session,
463 out_dir: &'a Option<PathBuf>,
464 out_file: &'a Option<PathBuf>,
465 trans: &'a trans::CrateTranslation)
466 -> CompileState<'a, 'b, 'ast, 'tcx> {
469 out_file: out_file.as_ref().map(|s| &**s),
470 ..CompileState::empty(input, session, out_dir)
474 fn state_when_compilation_done(input: &'a Input,
475 session: &'ast Session,
476 out_dir: &'a Option<PathBuf>,
477 out_file: &'a Option<PathBuf>)
478 -> CompileState<'a, 'b, 'ast, 'tcx> {
480 out_file: out_file.as_ref().map(|s| &**s),
481 ..CompileState::empty(input, session, out_dir)
486 pub fn phase_1_parse_input<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
487 let continue_after_error = sess.opts.debugging_opts.continue_parse_after_error;
488 sess.diagnostic().set_continue_after_error(continue_after_error);
490 let krate = time(sess.time_passes(), "parsing", || {
492 Input::File(ref file) => {
493 parse::parse_crate_from_file(file, &sess.parse_sess)
495 Input::Str { ref input, ref name } => {
496 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
501 sess.diagnostic().set_continue_after_error(true);
503 if sess.opts.debugging_opts.ast_json_noexpand {
504 println!("{}", json::as_json(&krate));
507 if sess.opts.debugging_opts.input_stats {
508 println!("Lines of code: {}", sess.codemap().count_lines());
509 println!("Pre-expansion node count: {}", count_nodes(&krate));
512 if let Some(ref s) = sess.opts.debugging_opts.show_span {
513 syntax::show_span::run(sess.diagnostic(), s, &krate);
519 fn count_nodes(krate: &ast::Crate) -> usize {
520 let mut counter = NodeCounter::new();
521 visit::walk_crate(&mut counter, krate);
525 // For continuing compilation after a parsed crate has been
528 pub struct ExpansionResult<'a> {
529 pub expanded_crate: ast::Crate,
530 pub defs: hir_map::Definitions,
531 pub analysis: ty::CrateAnalysis<'a>,
532 pub resolutions: Resolutions,
533 pub hir_forest: hir_map::Forest,
536 /// Run the "early phases" of the compiler: initial `cfg` processing,
537 /// loading compiler plugins (including those from `addl_plugins`),
538 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
539 /// harness if one is to be provided, injection of a dependency on the
540 /// standard library and prelude, and name resolution.
542 /// Returns `None` if we're aborting after handling -W help.
543 pub fn phase_2_configure_and_expand<'a, F>(sess: &Session,
546 registry: Option<Registry>,
548 addl_plugins: Option<Vec<String>>,
549 make_glob_map: MakeGlobMap,
551 -> Result<ExpansionResult<'a>, usize>
552 where F: FnOnce(&ast::Crate) -> CompileResult,
554 let time_passes = sess.time_passes();
556 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
557 // these need to be set "early" so that expansion sees `quote` if enabled.
558 *sess.features.borrow_mut() = features;
560 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
561 *sess.crate_disambiguator.borrow_mut() =
562 token::intern(&compute_crate_disambiguator(sess)).as_str();
564 time(time_passes, "recursion limit", || {
565 middle::recursion_limit::update_recursion_limit(sess, &krate);
568 krate = time(time_passes, "crate injection", || {
569 let alt_std_name = sess.opts.alt_std_name.clone();
570 syntax::std_inject::maybe_inject_crates_ref(&sess.parse_sess, krate, alt_std_name)
573 let mut addl_plugins = Some(addl_plugins);
574 let registrars = time(time_passes, "plugin loading", || {
575 plugin::load::load_plugins(sess,
579 addl_plugins.take().unwrap())
582 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
584 time(time_passes, "plugin registration", || {
585 if sess.features.borrow().rustc_diagnostic_macros {
586 registry.register_macro("__diagnostic_used",
587 diagnostics::plugin::expand_diagnostic_used);
588 registry.register_macro("__register_diagnostic",
589 diagnostics::plugin::expand_register_diagnostic);
590 registry.register_macro("__build_diagnostic_array",
591 diagnostics::plugin::expand_build_diagnostic_array);
594 for registrar in registrars {
595 registry.args_hidden = Some(registrar.args);
596 (registrar.fun)(&mut registry);
600 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
601 llvm_passes, attributes, mir_passes, .. } = registry;
603 sess.track_errors(|| {
604 let mut ls = sess.lint_store.borrow_mut();
605 for pass in early_lint_passes {
606 ls.register_early_pass(Some(sess), true, pass);
608 for pass in late_lint_passes {
609 ls.register_late_pass(Some(sess), true, pass);
612 for (name, to) in lint_groups {
613 ls.register_group(Some(sess), true, name, to);
616 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
617 sess.mir_passes.borrow_mut().extend(mir_passes);
618 *sess.plugin_attributes.borrow_mut() = attributes.clone();
621 // Lint plugins are registered; now we can process command line flags.
622 if sess.opts.describe_lints {
623 super::describe_lints(&sess.lint_store.borrow(), true);
626 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
628 // Currently, we ignore the name resolution data structures for the purposes of dependency
629 // tracking. Instead we will run name resolution and include its output in the hash of each
630 // item, much like we do for macro expansion. In other words, the hash reflects not just
631 // its contents but the results of name resolution on those contents. Hopefully we'll push
632 // this back at some point.
633 let _ignore = sess.dep_graph.in_ignore();
634 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
635 crate_loader.preprocess(&krate);
636 let resolver_arenas = Resolver::arenas();
638 Resolver::new(sess, &krate, make_glob_map, &mut crate_loader, &resolver_arenas);
639 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
641 krate = time(time_passes, "expansion", || {
642 // Windows dlls do not have rpaths, so they don't know how to find their
643 // dependencies. It's up to us to tell the system where to find all the
644 // dependent dlls. Note that this uses cfg!(windows) as opposed to
645 // targ_cfg because syntax extensions are always loaded for the host
646 // compiler, not for the target.
648 // This is somewhat of an inherently racy operation, however, as
649 // multiple threads calling this function could possibly continue
650 // extending PATH far beyond what it should. To solve this for now we
651 // just don't add any new elements to PATH which are already there
652 // within PATH. This is basically a targeted fix at #17360 for rustdoc
653 // which runs rustc in parallel but has been seen (#33844) to cause
654 // problems with PATH becoming too long.
655 let mut old_path = OsString::new();
657 old_path = env::var_os("PATH").unwrap_or(old_path);
658 let mut new_path = sess.host_filesearch(PathKind::All)
659 .get_dylib_search_paths();
660 for path in env::split_paths(&old_path) {
661 if !new_path.contains(&path) {
665 env::set_var("PATH", &env::join_paths(new_path).unwrap());
667 let features = sess.features.borrow();
668 let cfg = syntax::ext::expand::ExpansionConfig {
669 features: Some(&features),
670 recursion_limit: sess.recursion_limit.get(),
671 trace_mac: sess.opts.debugging_opts.trace_macros,
672 should_test: sess.opts.test,
673 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
675 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
676 let err_count = ecx.parse_sess.span_diagnostic.err_count();
678 let krate = ecx.monotonic_expander().expand_crate(krate);
680 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
681 ecx.parse_sess.span_diagnostic.abort_if_errors();
684 env::set_var("PATH", &old_path);
689 krate.exported_macros = mem::replace(&mut resolver.exported_macros, Vec::new());
691 krate = time(time_passes, "maybe building test harness", || {
692 syntax::test::modify_for_testing(&sess.parse_sess,
699 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
700 // bunch of checks in the `modify` function below. For now just skip this
701 // step entirely if we're rustdoc as it's not too useful anyway.
702 if !sess.opts.actually_rustdoc {
703 krate = time(time_passes, "maybe creating a macro crate", || {
704 let crate_types = sess.crate_types.borrow();
705 let num_crate_types = crate_types.len();
706 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
707 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
713 &sess.features.borrow())
717 if sess.opts.debugging_opts.input_stats {
718 println!("Post-expansion node count: {}", count_nodes(&krate));
721 if sess.opts.debugging_opts.ast_json {
722 println!("{}", json::as_json(&krate));
726 "checking for inline asm in case the target doesn't support it",
727 || no_asm::check_crate(sess, &krate));
729 // Needs to go *after* expansion to be able to check the results of macro expansion.
730 time(time_passes, "complete gated feature checking", || {
731 sess.track_errors(|| {
732 syntax::feature_gate::check_crate(&krate,
734 &sess.features.borrow(),
736 sess.opts.unstable_features);
740 time(sess.time_passes(),
742 || lint::check_ast_crate(sess, &krate));
744 time(sess.time_passes(),
746 || ast_validation::check_crate(sess, &krate));
748 time(sess.time_passes(), "name resolution", || -> CompileResult {
749 resolver.resolve_imports();
751 // Since import resolution will eventually happen in expansion,
752 // don't perform `after_expand` until after import resolution.
753 after_expand(&krate)?;
755 resolver.resolve_crate(&krate);
760 let hir_forest = time(sess.time_passes(), "lowering ast -> hir", || {
761 hir_map::Forest::new(lower_crate(sess, &krate, &mut resolver), &sess.dep_graph)
764 // Discard hygiene data, which isn't required past lowering to HIR.
765 if !keep_hygiene_data(sess) {
766 syntax::ext::hygiene::reset_hygiene_data();
770 expanded_crate: krate,
771 defs: resolver.definitions,
772 analysis: ty::CrateAnalysis {
773 export_map: resolver.export_map,
774 access_levels: AccessLevels::default(),
775 reachable: NodeSet(),
777 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
779 resolutions: Resolutions {
780 def_map: resolver.def_map,
781 freevars: resolver.freevars,
782 trait_map: resolver.trait_map,
783 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
785 hir_forest: hir_forest
789 /// Run the resolution, typechecking, region checking and other
790 /// miscellaneous analysis passes on the crate. Return various
791 /// structures carrying the results of the analysis.
792 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
793 hir_map: hir_map::Map<'tcx>,
794 mut analysis: ty::CrateAnalysis,
795 resolutions: Resolutions,
796 arenas: &'tcx ty::CtxtArenas<'tcx>,
800 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
802 IncrementalHashesMap,
805 macro_rules! try_with_f {
806 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
810 f($t, $a, $h, Err(x));
817 let time_passes = sess.time_passes();
819 let lang_items = time(time_passes, "language item collection", || {
820 sess.track_errors(|| {
821 middle::lang_items::collect_language_items(&sess, &hir_map)
825 let named_region_map = time(time_passes,
826 "lifetime resolution",
827 || middle::resolve_lifetime::krate(sess,
829 &resolutions.def_map))?;
832 "looking for entry point",
833 || middle::entry::find_entry_point(sess, &hir_map));
835 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
836 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
838 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
840 let region_map = time(time_passes,
842 || middle::region::resolve_crate(sess, &hir_map));
846 || loops::check_crate(sess, &hir_map));
849 "static item recursion checking",
850 || static_recursion::check_crate(sess, &resolutions.def_map, &hir_map))?;
852 let index = stability::Index::new(&hir_map);
854 TyCtxt::create_and_enter(sess,
857 resolutions.trait_map,
860 resolutions.freevars,
861 resolutions.maybe_unused_trait_imports,
867 let incremental_hashes_map =
869 "compute_incremental_hashes_map",
870 || rustc_incremental::compute_incremental_hashes_map(tcx));
873 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
875 // passes are timed inside typeck
876 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
880 || consts::check_crate(tcx));
882 analysis.access_levels =
883 time(time_passes, "privacy checking", || {
884 rustc_privacy::check_crate(tcx, &analysis.export_map)
887 // Do not move this check past lint
888 time(time_passes, "stability index", || {
889 tcx.stability.borrow_mut().build(tcx, &analysis.access_levels)
893 "intrinsic checking",
894 || middle::intrinsicck::check_crate(tcx));
898 || middle::effect::check_crate(tcx));
902 || check_match::check_crate(tcx));
904 // this must run before MIR dump, because
905 // "not all control paths return a value" is reported here.
907 // maybe move the check to a MIR pass?
910 || middle::liveness::check_crate(tcx));
914 || rvalues::check_crate(tcx));
918 || mir::mir_map::build_mir_for_crate(tcx));
920 time(time_passes, "MIR passes", || {
921 let mut passes = sess.mir_passes.borrow_mut();
922 // Push all the built-in passes.
923 passes.push_hook(box mir::transform::dump_mir::DumpMir);
924 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("initial"));
926 box mir::transform::qualify_consts::QualifyAndPromoteConstants::default());
927 passes.push_pass(box mir::transform::type_check::TypeckMir);
929 box mir::transform::simplify_branches::SimplifyBranches::new("initial"));
930 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("qualify-consts"));
931 // And run everything.
932 passes.run_passes(tcx);
937 || borrowck::check_crate(tcx));
939 // Avoid overwhelming user with errors if type checking failed.
940 // I'm not sure how helpful this is, to be honest, but it avoids
942 // lot of annoying errors in the compile-fail tests (basically,
943 // lint warnings and so on -- kindck used to do this abort, but
944 // kindck is gone now). -nmatsakis
945 if sess.err_count() > 0 {
946 return Ok(f(tcx, analysis, incremental_hashes_map, Err(sess.err_count())));
951 "reachability checking",
952 || reachable::find_reachable(tcx, &analysis.access_levels));
954 time(time_passes, "death checking", || {
955 middle::dead::check_crate(tcx, &analysis.access_levels);
958 let ref lib_features_used =
960 "stability checking",
961 || stability::check_unstable_api_usage(tcx));
963 time(time_passes, "unused lib feature checking", || {
964 stability::check_unused_or_stable_features(&tcx.sess,
970 || lint::check_crate(tcx, &analysis.access_levels));
972 // The above three passes generate errors w/o aborting
973 if sess.err_count() > 0 {
974 return Ok(f(tcx, analysis, incremental_hashes_map, Err(sess.err_count())));
977 Ok(f(tcx, analysis, incremental_hashes_map, Ok(())))
981 /// Run the translation phase to LLVM, after which the AST and analysis can
982 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
983 analysis: ty::CrateAnalysis,
984 incremental_hashes_map: &IncrementalHashesMap)
985 -> trans::CrateTranslation {
986 let time_passes = tcx.sess.time_passes();
989 "resolving dependency formats",
990 || dependency_format::calculate(&tcx.sess));
992 // Run the passes that transform the MIR into a more suitable for translation
994 time(time_passes, "Prepare MIR codegen passes", || {
995 let mut passes = ::rustc::mir::transform::Passes::new();
996 passes.push_hook(box mir::transform::dump_mir::DumpMir);
997 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
998 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("no-landing-pads"));
1000 // From here on out, regions are gone.
1001 passes.push_pass(box mir::transform::erase_regions::EraseRegions);
1003 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1004 passes.push_pass(box borrowck::ElaborateDrops);
1005 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1006 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("elaborate-drops"));
1008 // No lifetime analysis based on borrowing can be done from here on out.
1009 passes.push_pass(box mir::transform::instcombine::InstCombine::new());
1010 passes.push_pass(box mir::transform::deaggregator::Deaggregator);
1011 passes.push_pass(box mir::transform::copy_prop::CopyPropagation);
1013 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1014 passes.push_pass(box mir::transform::dump_mir::Marker("PreTrans"));
1016 passes.run_passes(tcx);
1022 move || trans::trans_crate(tcx, analysis, &incremental_hashes_map));
1026 || rustc_incremental::assert_dep_graph(tcx));
1029 "serialize dep graph",
1030 || rustc_incremental::save_dep_graph(tcx,
1031 &incremental_hashes_map,
1032 translation.link.crate_hash));
1036 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1037 /// as a side effect.
1038 pub fn phase_5_run_llvm_passes(sess: &Session,
1039 trans: &trans::CrateTranslation,
1040 outputs: &OutputFilenames) -> CompileResult {
1041 if sess.opts.cg.no_integrated_as {
1042 let output_types = OutputTypes::new(&[(OutputType::Assembly, None)]);
1043 time(sess.time_passes(),
1045 || write::run_passes(sess, trans, &output_types, outputs));
1047 write::run_assembler(sess, outputs);
1049 // Remove assembly source, unless --save-temps was specified
1050 if !sess.opts.cg.save_temps {
1051 fs::remove_file(&outputs.temp_path(OutputType::Assembly, None)).unwrap();
1054 time(sess.time_passes(),
1056 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1059 time(sess.time_passes(),
1060 "serialize work products",
1061 move || rustc_incremental::save_work_products(sess));
1063 if sess.err_count() > 0 {
1064 Err(sess.err_count())
1070 /// Run the linker on any artifacts that resulted from the LLVM run.
1071 /// This should produce either a finished executable or library.
1072 pub fn phase_6_link_output(sess: &Session,
1073 trans: &trans::CrateTranslation,
1074 outputs: &OutputFilenames) {
1075 time(sess.time_passes(),
1077 || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
1080 fn escape_dep_filename(filename: &str) -> String {
1081 // Apparently clang and gcc *only* escape spaces:
1082 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1083 filename.replace(" ", "\\ ")
1086 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1087 let mut out_filenames = Vec::new();
1088 for output_type in sess.opts.output_types.keys() {
1089 let file = outputs.path(*output_type);
1090 match *output_type {
1091 OutputType::Exe => {
1092 for output in sess.crate_types.borrow().iter() {
1093 let p = link::filename_for_input(sess, *output, crate_name, outputs);
1094 out_filenames.push(p);
1098 out_filenames.push(file);
1103 // Write out dependency rules to the dep-info file if requested
1104 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1107 let deps_filename = outputs.path(OutputType::DepInfo);
1110 (|| -> io::Result<()> {
1111 // Build a list of files used to compile the output and
1112 // write Makefile-compatible dependency rules
1113 let files: Vec<String> = sess.codemap()
1117 .filter(|fmap| fmap.is_real_file())
1118 .filter(|fmap| !fmap.is_imported())
1119 .map(|fmap| escape_dep_filename(&fmap.name))
1121 let mut file = fs::File::create(&deps_filename)?;
1122 for path in &out_filenames {
1123 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1126 // Emit a fake target for each input file to the compilation. This
1127 // prevents `make` from spitting out an error if a file is later
1128 // deleted. For more info see #28735
1130 writeln!(file, "{}:", path)?;
1138 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1139 deps_filename.display(),
1145 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1146 // Unconditionally collect crate types from attributes to make them used
1147 let attr_types: Vec<config::CrateType> =
1150 if a.check_name("crate_type") {
1151 match a.value_str() {
1152 Some(ref n) if *n == "rlib" => {
1153 Some(config::CrateTypeRlib)
1155 Some(ref n) if *n == "dylib" => {
1156 Some(config::CrateTypeDylib)
1158 Some(ref n) if *n == "cdylib" => {
1159 Some(config::CrateTypeCdylib)
1161 Some(ref n) if *n == "lib" => {
1162 Some(config::default_lib_output())
1164 Some(ref n) if *n == "staticlib" => {
1165 Some(config::CrateTypeStaticlib)
1167 Some(ref n) if *n == "proc-macro" => {
1168 Some(config::CrateTypeProcMacro)
1170 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1172 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1175 "invalid `crate_type` value".to_string());
1179 session.struct_span_err(a.span, "`crate_type` requires a value")
1180 .note("for example: `#![crate_type=\"lib\"]`")
1191 // If we're generating a test executable, then ignore all other output
1192 // styles at all other locations
1193 if session.opts.test {
1194 return vec![config::CrateTypeExecutable];
1197 // Only check command line flags if present. If no types are specified by
1198 // command line, then reuse the empty `base` Vec to hold the types that
1199 // will be found in crate attributes.
1200 let mut base = session.opts.crate_types.clone();
1201 if base.is_empty() {
1202 base.extend(attr_types);
1203 if base.is_empty() {
1204 base.push(link::default_output_for_target(session));
1211 .filter(|crate_type| {
1212 let res = !link::invalid_output_for_target(session, *crate_type);
1215 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1217 session.opts.target_triple));
1225 pub fn compute_crate_disambiguator(session: &Session) -> String {
1226 use std::hash::Hasher;
1228 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1229 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1230 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1231 // should still be safe enough to avoid collisions in practice.
1232 // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1233 // a hex-string instead of raw bytes. We should really use the
1234 // smaller representation.
1235 let mut hasher = ArchIndependentHasher::new(Blake2bHasher::new(128 / 8, &[]));
1237 let mut metadata = session.opts.cg.metadata.clone();
1238 // We don't want the crate_disambiguator to dependent on the order
1239 // -C metadata arguments, so sort them:
1241 // Every distinct -C metadata value is only incorporated once:
1244 hasher.write(b"metadata");
1245 for s in &metadata {
1246 // Also incorporate the length of a metadata string, so that we generate
1247 // different values for `-Cmetadata=ab -Cmetadata=c` and
1248 // `-Cmetadata=a -Cmetadata=bc`
1249 hasher.write_usize(s.len());
1250 hasher.write(s.as_bytes());
1253 let mut hash_state = hasher.into_inner();
1254 let hash_bytes = hash_state.finalize();
1256 // If this is an executable, add a special suffix, so that we don't get
1257 // symbol conflicts when linking against a library of the same name.
1258 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1260 format!("{:x}{}", FmtWrap(hash_bytes), if is_exe { "-exe" } else {""})
1263 pub fn build_output_filenames(input: &Input,
1264 odir: &Option<PathBuf>,
1265 ofile: &Option<PathBuf>,
1266 attrs: &[ast::Attribute],
1268 -> OutputFilenames {
1271 // "-" as input file will cause the parser to read from stdin so we
1272 // have to make up a name
1273 // We want to toss everything after the final '.'
1274 let dirpath = match *odir {
1275 Some(ref d) => d.clone(),
1276 None => PathBuf::new(),
1279 // If a crate name is present, we use it as the link name
1280 let stem = sess.opts
1283 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1284 .unwrap_or(input.filestem());
1287 out_directory: dirpath,
1289 single_output_file: None,
1290 extra: sess.opts.cg.extra_filename.clone(),
1291 outputs: sess.opts.output_types.clone(),
1295 Some(ref out_file) => {
1296 let unnamed_output_types = sess.opts
1299 .filter(|a| a.is_none())
1301 let ofile = if unnamed_output_types > 1 {
1302 sess.warn("ignoring specified output filename because multiple outputs were \
1306 Some(out_file.clone())
1309 sess.warn("ignoring --out-dir flag due to -o flag.");
1312 let cur_dir = Path::new("");
1315 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1316 out_filestem: out_file.file_stem()
1317 .unwrap_or(OsStr::new(""))
1321 single_output_file: ofile,
1322 extra: sess.opts.cg.extra_filename.clone(),
1323 outputs: sess.opts.output_types.clone(),
1329 // For use by the `rusti` project (https://github.com/murarth/rusti).
1330 pub fn reset_thread_local_state() {
1331 // These may be left in an incoherent state after a previous compile.
1332 syntax::ext::hygiene::reset_hygiene_data();
1333 // `clear_ident_interner` can be used to free memory, but it does not restore the initial state.
1334 token::reset_ident_interner();