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};
17 use rustc::session::CompileIncomplete;
18 use rustc::session::config::{self, Input, OutputFilenames, OutputType,
20 use rustc::session::search_paths::PathKind;
22 use rustc::middle::{self, dependency_format, stability, reachable};
23 use rustc::middle::privacy::AccessLevels;
24 use rustc::mir::transform::{MIR_CONST, MIR_VALIDATED, MIR_OPTIMIZED, Passes};
25 use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas};
27 use rustc::util::common::{ErrorReported, time};
28 use rustc::util::nodemap::NodeSet;
29 use rustc::util::fs::rename_or_copy_remove;
30 use rustc_borrowck as borrowck;
31 use rustc_incremental::{self, IncrementalHashesMap};
32 use rustc_resolve::{MakeGlobMap, Resolver};
33 use rustc_metadata::creader::CrateLoader;
34 use rustc_metadata::cstore::{self, CStore};
35 use rustc_trans::back::{link, write};
36 use rustc_trans as trans;
37 use rustc_typeck as typeck;
39 use rustc_plugin::registry::Registry;
40 use rustc_plugin as plugin;
41 use rustc_passes::{ast_validation, no_asm, loops, consts, static_recursion, hir_stats};
42 use rustc_const_eval::{self, check_match};
43 use super::Compilation;
48 use std::ffi::{OsString, OsStr};
50 use std::io::{self, Write};
52 use std::path::{Path, PathBuf};
54 use syntax::{ast, diagnostics, visit};
56 use syntax::ext::base::ExtCtxt;
57 use syntax::parse::{self, PResult};
58 use syntax::symbol::Symbol;
59 use syntax::util::node_count::NodeCounter;
62 use arena::DroplessArena;
66 pub fn compile_input(sess: &Session,
69 outdir: &Option<PathBuf>,
70 output: &Option<PathBuf>,
71 addl_plugins: Option<Vec<String>>,
72 control: &CompileController) -> CompileResult {
73 macro_rules! controller_entry_point {
74 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
75 let state = &mut $make_state;
76 let phase_result: &CompileResult = &$phase_result;
77 if phase_result.is_ok() || control.$point.run_callback_on_error {
78 (control.$point.callback)(state);
81 if control.$point.stop == Compilation::Stop {
82 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
83 // if there are no errors?
84 return $tsess.compile_status();
89 // We need nested scopes here, because the intermediate results can keep
90 // large chunks of memory alive and we want to free them as soon as
91 // possible to keep the peak memory usage low
92 let (outputs, trans) = {
93 let krate = match phase_1_parse_input(sess, input) {
95 Err(mut parse_error) => {
97 return Err(CompileIncomplete::Errored(ErrorReported));
101 let (krate, registry) = {
102 let mut compile_state = CompileState::state_after_parse(input,
108 controller_entry_point!(after_parse,
113 (compile_state.krate.unwrap(), compile_state.registry)
116 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
117 let crate_name = link::find_crate_name(Some(sess), &krate.attrs, input);
118 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
119 phase_2_configure_and_expand(
120 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
122 let mut state = CompileState::state_after_expand(
123 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
125 controller_entry_point!(after_expand, sess, state, Ok(()));
131 write_out_deps(sess, &outputs, &crate_name);
132 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
133 sess.opts.output_types.keys().count() == 1 {
137 let arena = DroplessArena::new();
138 let arenas = GlobalArenas::new();
140 // Construct the HIR map
141 let hir_map = time(sess.time_passes(),
143 || hir_map::map_crate(&mut hir_forest, defs));
146 let _ignore = hir_map.dep_graph.in_ignore();
147 controller_entry_point!(after_hir_lowering,
149 CompileState::state_after_hir_lowering(input,
165 time(sess.time_passes(), "attribute checking", || {
166 hir::check_attr::check_crate(sess, &expanded_crate);
169 let opt_crate = if keep_ast(sess) {
170 Some(&expanded_crate)
172 drop(expanded_crate);
176 phase_3_run_analysis_passes(sess,
183 |tcx, analysis, incremental_hashes_map, result| {
185 // Eventually, we will want to track plugins.
186 let _ignore = tcx.dep_graph.in_ignore();
188 let mut state = CompileState::state_after_analysis(input,
197 (control.after_analysis.callback)(&mut state);
199 if control.after_analysis.stop == Compilation::Stop {
200 return result.and_then(|_| Err(CompileIncomplete::Stopped));
206 if log_enabled!(::log::LogLevel::Info) {
207 println!("Pre-trans");
208 tcx.print_debug_stats();
210 let trans = phase_4_translate_to_llvm(tcx, analysis, &incremental_hashes_map,
213 if log_enabled!(::log::LogLevel::Info) {
214 println!("Post-trans");
215 tcx.print_debug_stats();
218 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
219 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
220 sess.err(&format!("could not emit MIR: {}", e));
221 sess.abort_if_errors();
229 if sess.opts.debugging_opts.print_type_sizes {
230 sess.code_stats.borrow().print_type_sizes();
233 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
235 controller_entry_point!(after_llvm,
237 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
241 write::cleanup_llvm(&trans);
243 phase_6_link_output(sess, &trans, &outputs);
245 // Now that we won't touch anything in the incremental compilation directory
246 // any more, we can finalize it (which involves renaming it)
247 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
249 if sess.opts.debugging_opts.perf_stats {
250 sess.print_perf_stats();
253 controller_entry_point!(compilation_done,
255 CompileState::state_when_compilation_done(input, sess, outdir, output),
261 fn keep_hygiene_data(sess: &Session) -> bool {
262 sess.opts.debugging_opts.keep_hygiene_data
265 fn keep_ast(sess: &Session) -> bool {
266 sess.opts.debugging_opts.keep_ast || ::save_analysis(sess)
269 /// The name used for source code that doesn't originate in a file
270 /// (e.g. source from stdin or a string)
271 pub fn anon_src() -> String {
275 pub fn source_name(input: &Input) -> String {
277 // FIXME (#9639): This needs to handle non-utf8 paths
278 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
279 Input::Str { ref name, .. } => name.clone(),
283 /// CompileController is used to customise compilation, it allows compilation to
284 /// be stopped and/or to call arbitrary code at various points in compilation.
285 /// It also allows for various flags to be set to influence what information gets
286 /// collected during compilation.
288 /// This is a somewhat higher level controller than a Session - the Session
289 /// controls what happens in each phase, whereas the CompileController controls
290 /// whether a phase is run at all and whether other code (from outside the
291 /// the compiler) is run between phases.
293 /// Note that if compilation is set to stop and a callback is provided for a
294 /// given entry point, the callback is called before compilation is stopped.
296 /// Expect more entry points to be added in the future.
297 pub struct CompileController<'a> {
298 pub after_parse: PhaseController<'a>,
299 pub after_expand: PhaseController<'a>,
300 pub after_hir_lowering: PhaseController<'a>,
301 pub after_analysis: PhaseController<'a>,
302 pub after_llvm: PhaseController<'a>,
303 pub compilation_done: PhaseController<'a>,
305 pub make_glob_map: MakeGlobMap,
308 impl<'a> CompileController<'a> {
309 pub fn basic() -> CompileController<'a> {
311 after_parse: PhaseController::basic(),
312 after_expand: PhaseController::basic(),
313 after_hir_lowering: PhaseController::basic(),
314 after_analysis: PhaseController::basic(),
315 after_llvm: PhaseController::basic(),
316 compilation_done: PhaseController::basic(),
317 make_glob_map: MakeGlobMap::No,
322 pub struct PhaseController<'a> {
323 pub stop: Compilation,
324 // If true then the compiler will try to run the callback even if the phase
325 // ends with an error. Note that this is not always possible.
326 pub run_callback_on_error: bool,
327 pub callback: Box<Fn(&mut CompileState) + 'a>,
330 impl<'a> PhaseController<'a> {
331 pub fn basic() -> PhaseController<'a> {
333 stop: Compilation::Continue,
334 run_callback_on_error: false,
335 callback: box |_| {},
340 /// State that is passed to a callback. What state is available depends on when
341 /// during compilation the callback is made. See the various constructor methods
342 /// (`state_*`) in the impl to see which data is provided for any given entry point.
343 pub struct CompileState<'a, 'tcx: 'a> {
344 pub input: &'a Input,
345 pub session: &'tcx Session,
346 pub krate: Option<ast::Crate>,
347 pub registry: Option<Registry<'a>>,
348 pub cstore: Option<&'a CStore>,
349 pub crate_name: Option<&'a str>,
350 pub output_filenames: Option<&'a OutputFilenames>,
351 pub out_dir: Option<&'a Path>,
352 pub out_file: Option<&'a Path>,
353 pub arena: Option<&'tcx DroplessArena>,
354 pub arenas: Option<&'tcx GlobalArenas<'tcx>>,
355 pub expanded_crate: Option<&'a ast::Crate>,
356 pub hir_crate: Option<&'a hir::Crate>,
357 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
358 pub resolutions: Option<&'a Resolutions>,
359 pub analysis: Option<&'a ty::CrateAnalysis>,
360 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
361 pub trans: Option<&'a trans::CrateTranslation>,
364 impl<'a, 'tcx> CompileState<'a, 'tcx> {
365 fn empty(input: &'a Input,
366 session: &'tcx Session,
367 out_dir: &'a Option<PathBuf>)
372 out_dir: out_dir.as_ref().map(|s| &**s),
380 output_filenames: None,
381 expanded_crate: None,
391 fn state_after_parse(input: &'a Input,
392 session: &'tcx Session,
393 out_dir: &'a Option<PathBuf>,
394 out_file: &'a Option<PathBuf>,
399 // Initialize the registry before moving `krate`
400 registry: Some(Registry::new(&session, krate.span)),
402 cstore: Some(cstore),
403 out_file: out_file.as_ref().map(|s| &**s),
404 ..CompileState::empty(input, session, out_dir)
408 fn state_after_expand(input: &'a Input,
409 session: &'tcx Session,
410 out_dir: &'a Option<PathBuf>,
411 out_file: &'a Option<PathBuf>,
413 expanded_crate: &'a ast::Crate,
417 crate_name: Some(crate_name),
418 cstore: Some(cstore),
419 expanded_crate: Some(expanded_crate),
420 out_file: out_file.as_ref().map(|s| &**s),
421 ..CompileState::empty(input, session, out_dir)
425 fn state_after_hir_lowering(input: &'a Input,
426 session: &'tcx Session,
427 out_dir: &'a Option<PathBuf>,
428 out_file: &'a Option<PathBuf>,
429 arena: &'tcx DroplessArena,
430 arenas: &'tcx GlobalArenas<'tcx>,
432 hir_map: &'a hir_map::Map<'tcx>,
433 analysis: &'a ty::CrateAnalysis,
434 resolutions: &'a Resolutions,
435 krate: &'a ast::Crate,
436 hir_crate: &'a hir::Crate,
440 crate_name: Some(crate_name),
442 arenas: Some(arenas),
443 cstore: Some(cstore),
444 hir_map: Some(hir_map),
445 analysis: Some(analysis),
446 resolutions: Some(resolutions),
447 expanded_crate: Some(krate),
448 hir_crate: Some(hir_crate),
449 out_file: out_file.as_ref().map(|s| &**s),
450 ..CompileState::empty(input, session, out_dir)
454 fn state_after_analysis(input: &'a Input,
455 session: &'tcx Session,
456 out_dir: &'a Option<PathBuf>,
457 out_file: &'a Option<PathBuf>,
458 krate: Option<&'a ast::Crate>,
459 hir_crate: &'a hir::Crate,
460 analysis: &'a ty::CrateAnalysis,
461 tcx: TyCtxt<'a, 'tcx, 'tcx>,
465 analysis: Some(analysis),
467 expanded_crate: krate,
468 hir_crate: Some(hir_crate),
469 crate_name: Some(crate_name),
470 out_file: out_file.as_ref().map(|s| &**s),
471 ..CompileState::empty(input, session, out_dir)
476 fn state_after_llvm(input: &'a Input,
477 session: &'tcx Session,
478 out_dir: &'a Option<PathBuf>,
479 out_file: &'a Option<PathBuf>,
480 trans: &'a trans::CrateTranslation)
484 out_file: out_file.as_ref().map(|s| &**s),
485 ..CompileState::empty(input, session, out_dir)
489 fn state_when_compilation_done(input: &'a Input,
490 session: &'tcx Session,
491 out_dir: &'a Option<PathBuf>,
492 out_file: &'a Option<PathBuf>)
495 out_file: out_file.as_ref().map(|s| &**s),
496 ..CompileState::empty(input, session, out_dir)
501 pub fn phase_1_parse_input<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
502 let continue_after_error = sess.opts.debugging_opts.continue_parse_after_error;
503 sess.diagnostic().set_continue_after_error(continue_after_error);
505 let krate = time(sess.time_passes(), "parsing", || {
507 Input::File(ref file) => {
508 parse::parse_crate_from_file(file, &sess.parse_sess)
510 Input::Str { ref input, ref name } => {
511 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
516 sess.diagnostic().set_continue_after_error(true);
518 if sess.opts.debugging_opts.ast_json_noexpand {
519 println!("{}", json::as_json(&krate));
522 if sess.opts.debugging_opts.input_stats {
523 println!("Lines of code: {}", sess.codemap().count_lines());
524 println!("Pre-expansion node count: {}", count_nodes(&krate));
527 if let Some(ref s) = sess.opts.debugging_opts.show_span {
528 syntax::show_span::run(sess.diagnostic(), s, &krate);
531 if sess.opts.debugging_opts.hir_stats {
532 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
538 fn count_nodes(krate: &ast::Crate) -> usize {
539 let mut counter = NodeCounter::new();
540 visit::walk_crate(&mut counter, krate);
544 // For continuing compilation after a parsed crate has been
547 pub struct ExpansionResult {
548 pub expanded_crate: ast::Crate,
549 pub defs: hir_map::Definitions,
550 pub analysis: ty::CrateAnalysis,
551 pub resolutions: Resolutions,
552 pub hir_forest: hir_map::Forest,
555 /// Run the "early phases" of the compiler: initial `cfg` processing,
556 /// loading compiler plugins (including those from `addl_plugins`),
557 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
558 /// harness if one is to be provided, injection of a dependency on the
559 /// standard library and prelude, and name resolution.
561 /// Returns `None` if we're aborting after handling -W help.
562 pub fn phase_2_configure_and_expand<F>(sess: &Session,
565 registry: Option<Registry>,
567 addl_plugins: Option<Vec<String>>,
568 make_glob_map: MakeGlobMap,
570 -> Result<ExpansionResult, CompileIncomplete>
571 where F: FnOnce(&ast::Crate) -> CompileResult,
573 let time_passes = sess.time_passes();
575 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
576 // these need to be set "early" so that expansion sees `quote` if enabled.
577 *sess.features.borrow_mut() = features;
579 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
580 *sess.crate_disambiguator.borrow_mut() = Symbol::intern(&compute_crate_disambiguator(sess));
582 time(time_passes, "recursion limit", || {
583 middle::recursion_limit::update_limits(sess, &krate);
586 krate = time(time_passes, "crate injection", || {
587 let alt_std_name = sess.opts.alt_std_name.clone();
588 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
591 let mut addl_plugins = Some(addl_plugins);
592 let registrars = time(time_passes, "plugin loading", || {
593 plugin::load::load_plugins(sess,
597 addl_plugins.take().unwrap())
600 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
602 time(time_passes, "plugin registration", || {
603 if sess.features.borrow().rustc_diagnostic_macros {
604 registry.register_macro("__diagnostic_used",
605 diagnostics::plugin::expand_diagnostic_used);
606 registry.register_macro("__register_diagnostic",
607 diagnostics::plugin::expand_register_diagnostic);
608 registry.register_macro("__build_diagnostic_array",
609 diagnostics::plugin::expand_build_diagnostic_array);
612 for registrar in registrars {
613 registry.args_hidden = Some(registrar.args);
614 (registrar.fun)(&mut registry);
618 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
619 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
620 llvm_passes, attributes, .. } = registry;
622 sess.track_errors(|| {
623 let mut ls = sess.lint_store.borrow_mut();
624 for pass in early_lint_passes {
625 ls.register_early_pass(Some(sess), true, pass);
627 for pass in late_lint_passes {
628 ls.register_late_pass(Some(sess), true, pass);
631 for (name, to) in lint_groups {
632 ls.register_group(Some(sess), true, name, to);
635 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
636 *sess.plugin_attributes.borrow_mut() = attributes.clone();
639 // Lint plugins are registered; now we can process command line flags.
640 if sess.opts.describe_lints {
641 super::describe_lints(&sess.lint_store.borrow(), true);
642 return Err(CompileIncomplete::Stopped);
644 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
646 // Currently, we ignore the name resolution data structures for the purposes of dependency
647 // tracking. Instead we will run name resolution and include its output in the hash of each
648 // item, much like we do for macro expansion. In other words, the hash reflects not just
649 // its contents but the results of name resolution on those contents. Hopefully we'll push
650 // this back at some point.
651 let _ignore = sess.dep_graph.in_ignore();
652 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
653 crate_loader.preprocess(&krate);
654 let resolver_arenas = Resolver::arenas();
655 let mut resolver = Resolver::new(sess,
661 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
662 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
664 krate = time(time_passes, "expansion", || {
665 // Windows dlls do not have rpaths, so they don't know how to find their
666 // dependencies. It's up to us to tell the system where to find all the
667 // dependent dlls. Note that this uses cfg!(windows) as opposed to
668 // targ_cfg because syntax extensions are always loaded for the host
669 // compiler, not for the target.
671 // This is somewhat of an inherently racy operation, however, as
672 // multiple threads calling this function could possibly continue
673 // extending PATH far beyond what it should. To solve this for now we
674 // just don't add any new elements to PATH which are already there
675 // within PATH. This is basically a targeted fix at #17360 for rustdoc
676 // which runs rustc in parallel but has been seen (#33844) to cause
677 // problems with PATH becoming too long.
678 let mut old_path = OsString::new();
680 old_path = env::var_os("PATH").unwrap_or(old_path);
681 let mut new_path = sess.host_filesearch(PathKind::All)
682 .get_dylib_search_paths();
683 for path in env::split_paths(&old_path) {
684 if !new_path.contains(&path) {
689 &env::join_paths(new_path.iter()
690 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
693 let features = sess.features.borrow();
694 let cfg = syntax::ext::expand::ExpansionConfig {
695 features: Some(&features),
696 recursion_limit: sess.recursion_limit.get(),
697 trace_mac: sess.opts.debugging_opts.trace_macros,
698 should_test: sess.opts.test,
699 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
702 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
703 let err_count = ecx.parse_sess.span_diagnostic.err_count();
705 let krate = ecx.monotonic_expander().expand_crate(krate);
707 ecx.check_unused_macros();
709 let mut missing_fragment_specifiers: Vec<_> =
710 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
711 missing_fragment_specifiers.sort();
712 for span in missing_fragment_specifiers {
713 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
714 let msg = "missing fragment specifier".to_string();
715 sess.add_lint(lint, ast::CRATE_NODE_ID, span, msg);
717 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
718 ecx.parse_sess.span_diagnostic.abort_if_errors();
721 env::set_var("PATH", &old_path);
726 krate = time(time_passes, "maybe building test harness", || {
727 syntax::test::modify_for_testing(&sess.parse_sess,
734 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
735 // bunch of checks in the `modify` function below. For now just skip this
736 // step entirely if we're rustdoc as it's not too useful anyway.
737 if !sess.opts.actually_rustdoc {
738 krate = time(time_passes, "maybe creating a macro crate", || {
739 let crate_types = sess.crate_types.borrow();
740 let num_crate_types = crate_types.len();
741 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
742 let is_test_crate = sess.opts.test;
743 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
753 after_expand(&krate)?;
755 if sess.opts.debugging_opts.input_stats {
756 println!("Post-expansion node count: {}", count_nodes(&krate));
759 if sess.opts.debugging_opts.hir_stats {
760 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
763 if sess.opts.debugging_opts.ast_json {
764 println!("{}", json::as_json(&krate));
768 "checking for inline asm in case the target doesn't support it",
769 || no_asm::check_crate(sess, &krate));
773 || lint::check_ast_crate(sess, &krate));
777 || ast_validation::check_crate(sess, &krate));
779 time(time_passes, "name resolution", || -> CompileResult {
780 resolver.resolve_crate(&krate);
784 if resolver.found_unresolved_macro {
785 sess.parse_sess.span_diagnostic.abort_if_errors();
788 // Needs to go *after* expansion to be able to check the results of macro expansion.
789 time(time_passes, "complete gated feature checking", || {
790 sess.track_errors(|| {
791 syntax::feature_gate::check_crate(&krate,
793 &sess.features.borrow(),
795 sess.opts.unstable_features);
800 let hir_forest = time(time_passes, "lowering ast -> hir", || {
801 let hir_crate = lower_crate(sess, &krate, &mut resolver);
803 if sess.opts.debugging_opts.hir_stats {
804 hir_stats::print_hir_stats(&hir_crate);
807 hir_map::Forest::new(hir_crate, &sess.dep_graph)
810 // Discard hygiene data, which isn't required after lowering to HIR.
811 if !keep_hygiene_data(sess) {
812 syntax::ext::hygiene::clear_markings();
816 expanded_crate: krate,
817 defs: resolver.definitions,
818 analysis: ty::CrateAnalysis {
819 access_levels: Rc::new(AccessLevels::default()),
820 reachable: Rc::new(NodeSet()),
821 name: crate_name.to_string(),
822 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
824 resolutions: Resolutions {
825 freevars: resolver.freevars,
826 export_map: resolver.export_map,
827 trait_map: resolver.trait_map,
828 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
830 hir_forest: hir_forest,
834 /// Run the resolution, typechecking, region checking and other
835 /// miscellaneous analysis passes on the crate. Return various
836 /// structures carrying the results of the analysis.
837 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
838 hir_map: hir_map::Map<'tcx>,
839 mut analysis: ty::CrateAnalysis,
840 resolutions: Resolutions,
841 arena: &'tcx DroplessArena,
842 arenas: &'tcx GlobalArenas<'tcx>,
845 -> Result<R, CompileIncomplete>
846 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
848 IncrementalHashesMap,
851 macro_rules! try_with_f {
852 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
856 f($t, $a, $h, Err(x));
863 let time_passes = sess.time_passes();
865 let lang_items = time(time_passes, "language item collection", || {
866 sess.track_errors(|| {
867 middle::lang_items::collect_language_items(&sess, &hir_map)
871 let named_region_map = time(time_passes,
872 "lifetime resolution",
873 || middle::resolve_lifetime::krate(sess, &hir_map))?;
876 "looking for entry point",
877 || middle::entry::find_entry_point(sess, &hir_map));
879 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
880 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
882 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
886 || loops::check_crate(sess, &hir_map));
889 "static item recursion checking",
890 || static_recursion::check_crate(sess, &hir_map))?;
892 let index = stability::Index::new(&sess);
894 let mut local_providers = ty::maps::Providers::default();
895 borrowck::provide(&mut local_providers);
896 mir::provide(&mut local_providers);
897 reachable::provide(&mut local_providers);
898 rustc_privacy::provide(&mut local_providers);
899 trans::provide(&mut local_providers);
900 typeck::provide(&mut local_providers);
901 ty::provide(&mut local_providers);
902 traits::provide(&mut local_providers);
903 reachable::provide(&mut local_providers);
904 rustc_const_eval::provide(&mut local_providers);
905 middle::region::provide(&mut local_providers);
906 cstore::provide_local(&mut local_providers);
908 let mut extern_providers = ty::maps::Providers::default();
909 cstore::provide(&mut extern_providers);
910 trans::provide(&mut extern_providers);
911 ty::provide_extern(&mut extern_providers);
912 traits::provide_extern(&mut extern_providers);
913 // FIXME(eddyb) get rid of this once we replace const_eval with miri.
914 rustc_const_eval::provide(&mut extern_providers);
916 // Setup the MIR passes that we want to run.
917 let mut passes = Passes::new();
918 passes.push_hook(mir::transform::dump_mir::DumpMir);
920 // Remove all `EndRegion` statements that are not involved in borrows.
921 passes.push_pass(MIR_CONST, mir::transform::clean_end_regions::CleanEndRegions);
923 // What we need to do constant evaluation.
924 passes.push_pass(MIR_CONST, mir::transform::simplify::SimplifyCfg::new("initial"));
925 passes.push_pass(MIR_CONST, mir::transform::type_check::TypeckMir);
926 passes.push_pass(MIR_CONST, mir::transform::rustc_peek::SanityCheck);
928 // What we need to run borrowck etc.
929 passes.push_pass(MIR_VALIDATED, mir::transform::qualify_consts::QualifyAndPromoteConstants);
930 passes.push_pass(MIR_VALIDATED,
931 mir::transform::simplify_branches::SimplifyBranches::new("initial"));
932 passes.push_pass(MIR_VALIDATED, mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
934 // Optimizations begin.
935 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
936 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyCfg::new("no-landing-pads"));
938 // From here on out, regions are gone.
939 passes.push_pass(MIR_OPTIMIZED, mir::transform::erase_regions::EraseRegions);
940 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::AddCallGuards);
941 passes.push_pass(MIR_OPTIMIZED, mir::transform::elaborate_drops::ElaborateDrops);
942 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
943 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyCfg::new("elaborate-drops"));
945 // No lifetime analysis based on borrowing can be done from here on out.
946 passes.push_pass(MIR_OPTIMIZED, mir::transform::inline::Inline);
947 passes.push_pass(MIR_OPTIMIZED, mir::transform::instcombine::InstCombine);
948 passes.push_pass(MIR_OPTIMIZED, mir::transform::deaggregator::Deaggregator);
949 passes.push_pass(MIR_OPTIMIZED, mir::transform::copy_prop::CopyPropagation);
950 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyLocals);
951 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::AddCallGuards);
952 passes.push_pass(MIR_OPTIMIZED, mir::transform::dump_mir::Marker("PreTrans"));
954 TyCtxt::create_and_enter(sess,
967 let incremental_hashes_map =
969 "compute_incremental_hashes_map",
970 || rustc_incremental::compute_incremental_hashes_map(tcx));
974 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
976 time(time_passes, "stability index", || {
977 tcx.stability.borrow_mut().build(tcx)
981 "stability checking",
982 || stability::check_unstable_api_usage(tcx));
984 // passes are timed inside typeck
985 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
989 || consts::check_crate(tcx));
991 analysis.access_levels =
992 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
995 "intrinsic checking",
996 || middle::intrinsicck::check_crate(tcx));
1000 || middle::effect::check_crate(tcx));
1004 || check_match::check_crate(tcx));
1006 // this must run before MIR dump, because
1007 // "not all control paths return a value" is reported here.
1009 // maybe move the check to a MIR pass?
1011 "liveness checking",
1012 || middle::liveness::check_crate(tcx));
1016 || borrowck::check_crate(tcx));
1018 // Avoid overwhelming user with errors if type checking failed.
1019 // I'm not sure how helpful this is, to be honest, but it avoids
1021 // lot of annoying errors in the compile-fail tests (basically,
1022 // lint warnings and so on -- kindck used to do this abort, but
1023 // kindck is gone now). -nmatsakis
1024 if sess.err_count() > 0 {
1025 return Ok(f(tcx, analysis, incremental_hashes_map, sess.compile_status()));
1028 analysis.reachable =
1030 "reachability checking",
1031 || reachable::find_reachable(tcx));
1033 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1035 time(time_passes, "unused lib feature checking", || {
1036 stability::check_unused_or_stable_features(tcx)
1039 time(time_passes, "lint checking", || lint::check_crate(tcx));
1041 return Ok(f(tcx, analysis, incremental_hashes_map, tcx.sess.compile_status()));
1045 /// Run the translation phase to LLVM, after which the AST and analysis can
1047 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1048 analysis: ty::CrateAnalysis,
1049 incremental_hashes_map: &IncrementalHashesMap,
1050 output_filenames: &OutputFilenames)
1051 -> trans::CrateTranslation {
1052 let time_passes = tcx.sess.time_passes();
1055 "resolving dependency formats",
1056 || dependency_format::calculate(tcx));
1061 move || trans::trans_crate(tcx, analysis, &incremental_hashes_map, output_filenames));
1065 || rustc_incremental::assert_dep_graph(tcx));
1068 "serialize dep graph",
1069 || rustc_incremental::save_dep_graph(tcx,
1070 &incremental_hashes_map,
1071 &translation.metadata.hashes,
1072 translation.link.crate_hash));
1076 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1077 /// as a side effect.
1078 pub fn phase_5_run_llvm_passes(sess: &Session,
1079 trans: &trans::CrateTranslation,
1080 outputs: &OutputFilenames) -> CompileResult {
1081 if sess.opts.cg.no_integrated_as ||
1082 (sess.target.target.options.no_integrated_as &&
1083 (outputs.outputs.contains_key(&OutputType::Object) ||
1084 outputs.outputs.contains_key(&OutputType::Exe)))
1086 let output_types = OutputTypes::new(&[(OutputType::Assembly, None)]);
1087 time(sess.time_passes(),
1089 || write::run_passes(sess, trans, &output_types, outputs));
1091 write::run_assembler(sess, outputs);
1093 // HACK the linker expects the object file to be named foo.0.o but
1094 // `run_assembler` produces an object named just foo.o. Rename it if we
1095 // are going to build an executable
1096 if sess.opts.output_types.contains_key(&OutputType::Exe) {
1097 let f = outputs.path(OutputType::Object);
1098 rename_or_copy_remove(&f,
1099 f.with_file_name(format!("{}.0.o",
1100 f.file_stem().unwrap().to_string_lossy()))).unwrap();
1103 // Remove assembly source, unless --save-temps was specified
1104 if !sess.opts.cg.save_temps {
1105 fs::remove_file(&outputs.temp_path(OutputType::Assembly, None)).unwrap();
1108 time(sess.time_passes(),
1110 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1113 time(sess.time_passes(),
1114 "serialize work products",
1115 move || rustc_incremental::save_work_products(sess));
1117 sess.compile_status()
1120 /// Run the linker on any artifacts that resulted from the LLVM run.
1121 /// This should produce either a finished executable or library.
1122 pub fn phase_6_link_output(sess: &Session,
1123 trans: &trans::CrateTranslation,
1124 outputs: &OutputFilenames) {
1125 time(sess.time_passes(),
1127 || link::link_binary(sess, trans, outputs, &trans.crate_name.as_str()));
1130 fn escape_dep_filename(filename: &str) -> String {
1131 // Apparently clang and gcc *only* escape spaces:
1132 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1133 filename.replace(" ", "\\ ")
1136 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1137 let mut out_filenames = Vec::new();
1138 for output_type in sess.opts.output_types.keys() {
1139 let file = outputs.path(*output_type);
1140 match *output_type {
1141 OutputType::Exe => {
1142 for output in sess.crate_types.borrow().iter() {
1143 let p = link::filename_for_input(sess, *output, crate_name, outputs);
1144 out_filenames.push(p);
1148 out_filenames.push(file);
1153 // Write out dependency rules to the dep-info file if requested
1154 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1157 let deps_filename = outputs.path(OutputType::DepInfo);
1160 (|| -> io::Result<()> {
1161 // Build a list of files used to compile the output and
1162 // write Makefile-compatible dependency rules
1163 let files: Vec<String> = sess.codemap()
1166 .filter(|fmap| fmap.is_real_file())
1167 .filter(|fmap| !fmap.is_imported())
1168 .map(|fmap| escape_dep_filename(&fmap.name))
1170 let mut file = fs::File::create(&deps_filename)?;
1171 for path in &out_filenames {
1172 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1175 // Emit a fake target for each input file to the compilation. This
1176 // prevents `make` from spitting out an error if a file is later
1177 // deleted. For more info see #28735
1179 writeln!(file, "{}:", path)?;
1187 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1188 deps_filename.display(),
1194 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1195 // Unconditionally collect crate types from attributes to make them used
1196 let attr_types: Vec<config::CrateType> =
1199 if a.check_name("crate_type") {
1200 match a.value_str() {
1201 Some(ref n) if *n == "rlib" => {
1202 Some(config::CrateTypeRlib)
1204 Some(ref n) if *n == "dylib" => {
1205 Some(config::CrateTypeDylib)
1207 Some(ref n) if *n == "cdylib" => {
1208 Some(config::CrateTypeCdylib)
1210 Some(ref n) if *n == "lib" => {
1211 Some(config::default_lib_output())
1213 Some(ref n) if *n == "staticlib" => {
1214 Some(config::CrateTypeStaticlib)
1216 Some(ref n) if *n == "proc-macro" => {
1217 Some(config::CrateTypeProcMacro)
1219 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1221 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1224 "invalid `crate_type` value".to_string());
1228 session.struct_span_err(a.span, "`crate_type` requires a value")
1229 .note("for example: `#![crate_type=\"lib\"]`")
1240 // If we're generating a test executable, then ignore all other output
1241 // styles at all other locations
1242 if session.opts.test {
1243 return vec![config::CrateTypeExecutable];
1246 // Only check command line flags if present. If no types are specified by
1247 // command line, then reuse the empty `base` Vec to hold the types that
1248 // will be found in crate attributes.
1249 let mut base = session.opts.crate_types.clone();
1250 if base.is_empty() {
1251 base.extend(attr_types);
1252 if base.is_empty() {
1253 base.push(link::default_output_for_target(session));
1260 .filter(|crate_type| {
1261 let res = !link::invalid_output_for_target(session, *crate_type);
1264 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1266 session.opts.target_triple));
1274 pub fn compute_crate_disambiguator(session: &Session) -> String {
1275 use std::hash::Hasher;
1277 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1278 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1279 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1280 // should still be safe enough to avoid collisions in practice.
1281 // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1282 // a hex-string instead of raw bytes. We should really use the
1283 // smaller representation.
1284 let mut hasher = StableHasher::<Fingerprint>::new();
1286 let mut metadata = session.opts.cg.metadata.clone();
1287 // We don't want the crate_disambiguator to dependent on the order
1288 // -C metadata arguments, so sort them:
1290 // Every distinct -C metadata value is only incorporated once:
1293 hasher.write(b"metadata");
1294 for s in &metadata {
1295 // Also incorporate the length of a metadata string, so that we generate
1296 // different values for `-Cmetadata=ab -Cmetadata=c` and
1297 // `-Cmetadata=a -Cmetadata=bc`
1298 hasher.write_usize(s.len());
1299 hasher.write(s.as_bytes());
1302 // If this is an executable, add a special suffix, so that we don't get
1303 // symbol conflicts when linking against a library of the same name.
1304 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1306 format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
1309 pub fn build_output_filenames(input: &Input,
1310 odir: &Option<PathBuf>,
1311 ofile: &Option<PathBuf>,
1312 attrs: &[ast::Attribute],
1314 -> OutputFilenames {
1317 // "-" as input file will cause the parser to read from stdin so we
1318 // have to make up a name
1319 // We want to toss everything after the final '.'
1320 let dirpath = match *odir {
1321 Some(ref d) => d.clone(),
1322 None => PathBuf::new(),
1325 // If a crate name is present, we use it as the link name
1326 let stem = sess.opts
1329 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1330 .unwrap_or(input.filestem());
1333 out_directory: dirpath,
1335 single_output_file: None,
1336 extra: sess.opts.cg.extra_filename.clone(),
1337 outputs: sess.opts.output_types.clone(),
1341 Some(ref out_file) => {
1342 let unnamed_output_types = sess.opts
1345 .filter(|a| a.is_none())
1347 let ofile = if unnamed_output_types > 1 {
1348 sess.warn("due to multiple output types requested, the explicitly specified \
1349 output file name will be adapted for each output type");
1352 Some(out_file.clone())
1355 sess.warn("ignoring --out-dir flag due to -o flag.");
1358 let cur_dir = Path::new("");
1361 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1362 out_filestem: out_file.file_stem()
1363 .unwrap_or(OsStr::new(""))
1367 single_output_file: ofile,
1368 extra: sess.opts.cg.extra_filename.clone(),
1369 outputs: sess.opts.output_types.clone(),