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 #![cfg_attr(not(feature="llvm"), allow(dead_code))]
13 use rustc::hir::{self, map as hir_map};
14 use rustc::hir::lowering::lower_crate;
15 use rustc::ich::Fingerprint;
16 use rustc_data_structures::stable_hasher::StableHasher;
18 use rustc::session::{Session, CompileResult};
19 use rustc::session::CompileIncomplete;
20 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
21 use rustc::session::search_paths::PathKind;
23 use rustc::middle::{self, stability, reachable};
24 use rustc::middle::privacy::AccessLevels;
25 use rustc::mir::transform::{MIR_CONST, MIR_VALIDATED, MIR_OPTIMIZED, Passes};
26 use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas};
28 use rustc::util::common::{ErrorReported, time};
29 use rustc::util::nodemap::NodeSet;
30 use rustc_allocator as allocator;
31 use rustc_borrowck as borrowck;
32 use rustc_incremental::{self, IncrementalHashesMap};
33 use rustc_resolve::{MakeGlobMap, Resolver};
34 use rustc_metadata::creader::CrateLoader;
35 use rustc_metadata::cstore::{self, CStore};
36 use rustc_trans::back::write;
37 use rustc_trans as trans;
38 use rustc_typeck as typeck;
40 use rustc_plugin::registry::Registry;
41 use rustc_plugin as plugin;
42 use rustc_passes::{ast_validation, no_asm, loops, consts, static_recursion, hir_stats};
43 use rustc_const_eval::{self, check_match};
44 use super::Compilation;
49 use std::ffi::{OsString, OsStr};
51 use std::io::{self, Write};
53 use std::path::{Path, PathBuf};
55 use syntax::{ast, diagnostics, visit};
57 use syntax::ext::base::ExtCtxt;
58 use syntax::parse::{self, PResult};
59 use syntax::symbol::Symbol;
60 use syntax::util::node_count::NodeCounter;
63 use arena::DroplessArena;
69 pub fn compile_input(sess: &Session,
72 outdir: &Option<PathBuf>,
73 output: &Option<PathBuf>,
74 addl_plugins: Option<Vec<String>>,
75 control: &CompileController) -> CompileResult {
76 use rustc_trans::back::write::OngoingCrateTranslation;
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 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
87 // if there are no errors?
88 return $tsess.compile_status();
93 if cfg!(not(feature="llvm")) {
94 use rustc::session::config::CrateType;
95 if !sess.opts.debugging_opts.no_trans && sess.opts.output_types.should_trans() {
96 sess.err("LLVM is not supported by this rustc. Please use -Z no-trans to compile")
99 if sess.opts.crate_types.iter().all(|&t|{
100 t != CrateType::CrateTypeRlib && t != CrateType::CrateTypeExecutable
101 }) && !sess.opts.crate_types.is_empty() {
103 "LLVM is not supported by this rustc, so non rlib libraries are not supported"
107 sess.abort_if_errors();
110 if sess.profile_queries() {
114 // We need nested scopes here, because the intermediate results can keep
115 // large chunks of memory alive and we want to free them as soon as
116 // possible to keep the peak memory usage low
117 let (outputs, trans): (OutputFilenames, OngoingCrateTranslation) = {
118 let krate = match phase_1_parse_input(control, sess, input) {
120 Err(mut parse_error) => {
122 return Err(CompileIncomplete::Errored(ErrorReported));
126 let (krate, registry) = {
127 let mut compile_state = CompileState::state_after_parse(input,
133 controller_entry_point!(after_parse,
138 (compile_state.krate.unwrap(), compile_state.registry)
141 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
143 ::rustc_trans_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
144 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
145 phase_2_configure_and_expand(
146 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
148 let mut state = CompileState::state_after_expand(
149 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
151 controller_entry_point!(after_expand, sess, state, Ok(()));
157 write_out_deps(sess, &outputs, &crate_name);
158 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
159 sess.opts.output_types.keys().count() == 1 {
163 let arena = DroplessArena::new();
164 let arenas = GlobalArenas::new();
166 // Construct the HIR map
167 let hir_map = time(sess.time_passes(),
169 || hir_map::map_crate(&mut hir_forest, defs));
172 let _ignore = hir_map.dep_graph.in_ignore();
173 controller_entry_point!(after_hir_lowering,
175 CompileState::state_after_hir_lowering(input,
191 time(sess.time_passes(), "attribute checking", || {
192 hir::check_attr::check_crate(sess, &expanded_crate);
195 let opt_crate = if control.keep_ast {
196 Some(&expanded_crate)
198 drop(expanded_crate);
202 phase_3_run_analysis_passes(sess,
209 |tcx, analysis, incremental_hashes_map, result| {
211 // Eventually, we will want to track plugins.
212 let _ignore = tcx.dep_graph.in_ignore();
214 let mut state = CompileState::state_after_analysis(input,
223 (control.after_analysis.callback)(&mut state);
225 if control.after_analysis.stop == Compilation::Stop {
226 return result.and_then(|_| Err(CompileIncomplete::Stopped));
232 if log_enabled!(::log::LogLevel::Info) {
233 println!("Pre-trans");
234 tcx.print_debug_stats();
237 let trans = phase_4_translate_to_llvm(tcx, analysis, incremental_hashes_map,
240 if log_enabled!(::log::LogLevel::Info) {
241 println!("Post-trans");
242 tcx.print_debug_stats();
245 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
246 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
247 sess.err(&format!("could not emit MIR: {}", e));
248 sess.abort_if_errors();
256 if cfg!(not(feature="llvm")) {
257 let (_, _) = (outputs, trans);
258 sess.fatal("LLVM is not supported by this rustc");
261 #[cfg(feature="llvm")]
263 if sess.opts.debugging_opts.print_type_sizes {
264 sess.code_stats.borrow().print_type_sizes();
267 let (phase5_result, trans) = phase_5_run_llvm_passes(sess, trans);
269 controller_entry_point!(after_llvm,
271 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
275 phase_6_link_output(sess, &trans, &outputs);
277 // Now that we won't touch anything in the incremental compilation directory
278 // any more, we can finalize it (which involves renaming it)
279 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
281 if sess.opts.debugging_opts.perf_stats {
282 sess.print_perf_stats();
285 controller_entry_point!(
288 CompileState::state_when_compilation_done(input, sess, outdir, output),
296 fn keep_hygiene_data(sess: &Session) -> bool {
297 sess.opts.debugging_opts.keep_hygiene_data
301 /// The name used for source code that doesn't originate in a file
302 /// (e.g. source from stdin or a string)
303 pub fn anon_src() -> String {
307 pub fn source_name(input: &Input) -> String {
309 // FIXME (#9639): This needs to handle non-utf8 paths
310 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
311 Input::Str { ref name, .. } => name.clone(),
315 /// CompileController is used to customize compilation, it allows compilation to
316 /// be stopped and/or to call arbitrary code at various points in compilation.
317 /// It also allows for various flags to be set to influence what information gets
318 /// collected during compilation.
320 /// This is a somewhat higher level controller than a Session - the Session
321 /// controls what happens in each phase, whereas the CompileController controls
322 /// whether a phase is run at all and whether other code (from outside the
323 /// compiler) is run between phases.
325 /// Note that if compilation is set to stop and a callback is provided for a
326 /// given entry point, the callback is called before compilation is stopped.
328 /// Expect more entry points to be added in the future.
329 pub struct CompileController<'a> {
330 pub after_parse: PhaseController<'a>,
331 pub after_expand: PhaseController<'a>,
332 pub after_hir_lowering: PhaseController<'a>,
333 pub after_analysis: PhaseController<'a>,
334 pub after_llvm: PhaseController<'a>,
335 pub compilation_done: PhaseController<'a>,
337 // FIXME we probably want to group the below options together and offer a
338 // better API, rather than this ad-hoc approach.
339 pub make_glob_map: MakeGlobMap,
340 // Whether the compiler should keep the ast beyond parsing.
342 // -Zcontinue-parse-after-error
343 pub continue_parse_after_error: bool,
346 impl<'a> CompileController<'a> {
347 pub fn basic() -> CompileController<'a> {
349 after_parse: PhaseController::basic(),
350 after_expand: PhaseController::basic(),
351 after_hir_lowering: PhaseController::basic(),
352 after_analysis: PhaseController::basic(),
353 after_llvm: PhaseController::basic(),
354 compilation_done: PhaseController::basic(),
355 make_glob_map: MakeGlobMap::No,
357 continue_parse_after_error: false,
362 pub struct PhaseController<'a> {
363 pub stop: Compilation,
364 // If true then the compiler will try to run the callback even if the phase
365 // ends with an error. Note that this is not always possible.
366 pub run_callback_on_error: bool,
367 pub callback: Box<Fn(&mut CompileState) + 'a>,
370 impl<'a> PhaseController<'a> {
371 pub fn basic() -> PhaseController<'a> {
373 stop: Compilation::Continue,
374 run_callback_on_error: false,
375 callback: box |_| {},
380 /// State that is passed to a callback. What state is available depends on when
381 /// during compilation the callback is made. See the various constructor methods
382 /// (`state_*`) in the impl to see which data is provided for any given entry point.
383 pub struct CompileState<'a, 'tcx: 'a> {
384 pub input: &'a Input,
385 pub session: &'tcx Session,
386 pub krate: Option<ast::Crate>,
387 pub registry: Option<Registry<'a>>,
388 pub cstore: Option<&'a CStore>,
389 pub crate_name: Option<&'a str>,
390 pub output_filenames: Option<&'a OutputFilenames>,
391 pub out_dir: Option<&'a Path>,
392 pub out_file: Option<&'a Path>,
393 pub arena: Option<&'tcx DroplessArena>,
394 pub arenas: Option<&'tcx GlobalArenas<'tcx>>,
395 pub expanded_crate: Option<&'a ast::Crate>,
396 pub hir_crate: Option<&'a hir::Crate>,
397 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
398 pub resolutions: Option<&'a Resolutions>,
399 pub analysis: Option<&'a ty::CrateAnalysis>,
400 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
401 pub trans: Option<&'a trans::CrateTranslation>,
404 impl<'a, 'tcx> CompileState<'a, 'tcx> {
405 fn empty(input: &'a Input,
406 session: &'tcx Session,
407 out_dir: &'a Option<PathBuf>)
412 out_dir: out_dir.as_ref().map(|s| &**s),
420 output_filenames: None,
421 expanded_crate: None,
431 fn state_after_parse(input: &'a Input,
432 session: &'tcx Session,
433 out_dir: &'a Option<PathBuf>,
434 out_file: &'a Option<PathBuf>,
439 // Initialize the registry before moving `krate`
440 registry: Some(Registry::new(&session, krate.span)),
442 cstore: Some(cstore),
443 out_file: out_file.as_ref().map(|s| &**s),
444 ..CompileState::empty(input, session, out_dir)
448 fn state_after_expand(input: &'a Input,
449 session: &'tcx Session,
450 out_dir: &'a Option<PathBuf>,
451 out_file: &'a Option<PathBuf>,
453 expanded_crate: &'a ast::Crate,
457 crate_name: Some(crate_name),
458 cstore: Some(cstore),
459 expanded_crate: Some(expanded_crate),
460 out_file: out_file.as_ref().map(|s| &**s),
461 ..CompileState::empty(input, session, out_dir)
465 fn state_after_hir_lowering(input: &'a Input,
466 session: &'tcx Session,
467 out_dir: &'a Option<PathBuf>,
468 out_file: &'a Option<PathBuf>,
469 arena: &'tcx DroplessArena,
470 arenas: &'tcx GlobalArenas<'tcx>,
472 hir_map: &'a hir_map::Map<'tcx>,
473 analysis: &'a ty::CrateAnalysis,
474 resolutions: &'a Resolutions,
475 krate: &'a ast::Crate,
476 hir_crate: &'a hir::Crate,
480 crate_name: Some(crate_name),
482 arenas: Some(arenas),
483 cstore: Some(cstore),
484 hir_map: Some(hir_map),
485 analysis: Some(analysis),
486 resolutions: Some(resolutions),
487 expanded_crate: Some(krate),
488 hir_crate: Some(hir_crate),
489 out_file: out_file.as_ref().map(|s| &**s),
490 ..CompileState::empty(input, session, out_dir)
494 fn state_after_analysis(input: &'a Input,
495 session: &'tcx Session,
496 out_dir: &'a Option<PathBuf>,
497 out_file: &'a Option<PathBuf>,
498 krate: Option<&'a ast::Crate>,
499 hir_crate: &'a hir::Crate,
500 analysis: &'a ty::CrateAnalysis,
501 tcx: TyCtxt<'a, 'tcx, 'tcx>,
505 analysis: Some(analysis),
507 expanded_crate: krate,
508 hir_crate: Some(hir_crate),
509 crate_name: Some(crate_name),
510 out_file: out_file.as_ref().map(|s| &**s),
511 ..CompileState::empty(input, session, out_dir)
515 fn state_after_llvm(input: &'a Input,
516 session: &'tcx Session,
517 out_dir: &'a Option<PathBuf>,
518 out_file: &'a Option<PathBuf>,
519 trans: &'a trans::CrateTranslation)
523 out_file: out_file.as_ref().map(|s| &**s),
524 ..CompileState::empty(input, session, out_dir)
528 fn state_when_compilation_done(input: &'a Input,
529 session: &'tcx Session,
530 out_dir: &'a Option<PathBuf>,
531 out_file: &'a Option<PathBuf>)
534 out_file: out_file.as_ref().map(|s| &**s),
535 ..CompileState::empty(input, session, out_dir)
540 pub fn phase_1_parse_input<'a>(control: &CompileController,
543 -> PResult<'a, ast::Crate> {
544 sess.diagnostic().set_continue_after_error(control.continue_parse_after_error);
546 if sess.profile_queries() {
550 let krate = time(sess.time_passes(), "parsing", || {
552 Input::File(ref file) => {
553 parse::parse_crate_from_file(file, &sess.parse_sess)
555 Input::Str { ref input, ref name } => {
556 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
561 sess.diagnostic().set_continue_after_error(true);
563 if sess.opts.debugging_opts.ast_json_noexpand {
564 println!("{}", json::as_json(&krate));
567 if sess.opts.debugging_opts.input_stats {
568 println!("Lines of code: {}", sess.codemap().count_lines());
569 println!("Pre-expansion node count: {}", count_nodes(&krate));
572 if let Some(ref s) = sess.opts.debugging_opts.show_span {
573 syntax::show_span::run(sess.diagnostic(), s, &krate);
576 if sess.opts.debugging_opts.hir_stats {
577 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
583 fn count_nodes(krate: &ast::Crate) -> usize {
584 let mut counter = NodeCounter::new();
585 visit::walk_crate(&mut counter, krate);
589 // For continuing compilation after a parsed crate has been
592 pub struct ExpansionResult {
593 pub expanded_crate: ast::Crate,
594 pub defs: hir_map::Definitions,
595 pub analysis: ty::CrateAnalysis,
596 pub resolutions: Resolutions,
597 pub hir_forest: hir_map::Forest,
600 /// Run the "early phases" of the compiler: initial `cfg` processing,
601 /// loading compiler plugins (including those from `addl_plugins`),
602 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
603 /// harness if one is to be provided, injection of a dependency on the
604 /// standard library and prelude, and name resolution.
606 /// Returns `None` if we're aborting after handling -W help.
607 pub fn phase_2_configure_and_expand<F>(sess: &Session,
610 registry: Option<Registry>,
612 addl_plugins: Option<Vec<String>>,
613 make_glob_map: MakeGlobMap,
615 -> Result<ExpansionResult, CompileIncomplete>
616 where F: FnOnce(&ast::Crate) -> CompileResult,
618 let time_passes = sess.time_passes();
620 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
621 // these need to be set "early" so that expansion sees `quote` if enabled.
622 *sess.features.borrow_mut() = features;
624 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
625 *sess.crate_disambiguator.borrow_mut() = Symbol::intern(&compute_crate_disambiguator(sess));
627 time(time_passes, "recursion limit", || {
628 middle::recursion_limit::update_limits(sess, &krate);
631 krate = time(time_passes, "crate injection", || {
632 let alt_std_name = sess.opts.alt_std_name.clone();
633 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
636 let mut addl_plugins = Some(addl_plugins);
637 let registrars = time(time_passes, "plugin loading", || {
638 plugin::load::load_plugins(sess,
642 addl_plugins.take().unwrap())
645 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
647 time(time_passes, "plugin registration", || {
648 if sess.features.borrow().rustc_diagnostic_macros {
649 registry.register_macro("__diagnostic_used",
650 diagnostics::plugin::expand_diagnostic_used);
651 registry.register_macro("__register_diagnostic",
652 diagnostics::plugin::expand_register_diagnostic);
653 registry.register_macro("__build_diagnostic_array",
654 diagnostics::plugin::expand_build_diagnostic_array);
657 for registrar in registrars {
658 registry.args_hidden = Some(registrar.args);
659 (registrar.fun)(&mut registry);
663 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
664 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
665 llvm_passes, attributes, .. } = registry;
667 sess.track_errors(|| {
668 let mut ls = sess.lint_store.borrow_mut();
669 for pass in early_lint_passes {
670 ls.register_early_pass(Some(sess), true, pass);
672 for pass in late_lint_passes {
673 ls.register_late_pass(Some(sess), true, pass);
676 for (name, to) in lint_groups {
677 ls.register_group(Some(sess), true, name, to);
680 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
681 *sess.plugin_attributes.borrow_mut() = attributes.clone();
684 // Lint plugins are registered; now we can process command line flags.
685 if sess.opts.describe_lints {
686 super::describe_lints(&sess.lint_store.borrow(), true);
687 return Err(CompileIncomplete::Stopped);
690 // Currently, we ignore the name resolution data structures for the purposes of dependency
691 // tracking. Instead we will run name resolution and include its output in the hash of each
692 // item, much like we do for macro expansion. In other words, the hash reflects not just
693 // its contents but the results of name resolution on those contents. Hopefully we'll push
694 // this back at some point.
695 let _ignore = sess.dep_graph.in_ignore();
696 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
697 crate_loader.preprocess(&krate);
698 let resolver_arenas = Resolver::arenas();
699 let mut resolver = Resolver::new(sess,
705 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
706 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
708 krate = time(time_passes, "expansion", || {
709 // Windows dlls do not have rpaths, so they don't know how to find their
710 // dependencies. It's up to us to tell the system where to find all the
711 // dependent dlls. Note that this uses cfg!(windows) as opposed to
712 // targ_cfg because syntax extensions are always loaded for the host
713 // compiler, not for the target.
715 // This is somewhat of an inherently racy operation, however, as
716 // multiple threads calling this function could possibly continue
717 // extending PATH far beyond what it should. To solve this for now we
718 // just don't add any new elements to PATH which are already there
719 // within PATH. This is basically a targeted fix at #17360 for rustdoc
720 // which runs rustc in parallel but has been seen (#33844) to cause
721 // problems with PATH becoming too long.
722 let mut old_path = OsString::new();
724 old_path = env::var_os("PATH").unwrap_or(old_path);
725 let mut new_path = sess.host_filesearch(PathKind::All)
726 .get_dylib_search_paths();
727 for path in env::split_paths(&old_path) {
728 if !new_path.contains(&path) {
733 &env::join_paths(new_path.iter()
734 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
737 let features = sess.features.borrow();
738 let cfg = syntax::ext::expand::ExpansionConfig {
739 features: Some(&features),
740 recursion_limit: sess.recursion_limit.get(),
741 trace_mac: sess.opts.debugging_opts.trace_macros,
742 should_test: sess.opts.test,
743 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
746 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
747 let err_count = ecx.parse_sess.span_diagnostic.err_count();
749 let krate = ecx.monotonic_expander().expand_crate(krate);
751 ecx.check_unused_macros();
753 let mut missing_fragment_specifiers: Vec<_> =
754 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
755 missing_fragment_specifiers.sort();
756 for span in missing_fragment_specifiers {
757 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
758 let msg = "missing fragment specifier";
759 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
761 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
762 ecx.parse_sess.span_diagnostic.abort_if_errors();
765 env::set_var("PATH", &old_path);
770 krate = time(time_passes, "maybe building test harness", || {
771 syntax::test::modify_for_testing(&sess.parse_sess,
778 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
779 // bunch of checks in the `modify` function below. For now just skip this
780 // step entirely if we're rustdoc as it's not too useful anyway.
781 if !sess.opts.actually_rustdoc {
782 krate = time(time_passes, "maybe creating a macro crate", || {
783 let crate_types = sess.crate_types.borrow();
784 let num_crate_types = crate_types.len();
785 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
786 let is_test_crate = sess.opts.test;
787 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
797 krate = time(time_passes, "creating allocators", || {
798 allocator::expand::modify(&sess.parse_sess,
804 after_expand(&krate)?;
806 if sess.opts.debugging_opts.input_stats {
807 println!("Post-expansion node count: {}", count_nodes(&krate));
810 if sess.opts.debugging_opts.hir_stats {
811 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
814 if sess.opts.debugging_opts.ast_json {
815 println!("{}", json::as_json(&krate));
819 "checking for inline asm in case the target doesn't support it",
820 || no_asm::check_crate(sess, &krate));
824 || ast_validation::check_crate(sess, &krate));
826 time(time_passes, "name resolution", || -> CompileResult {
827 resolver.resolve_crate(&krate);
831 if resolver.found_unresolved_macro {
832 sess.parse_sess.span_diagnostic.abort_if_errors();
835 // Needs to go *after* expansion to be able to check the results of macro expansion.
836 time(time_passes, "complete gated feature checking", || {
837 sess.track_errors(|| {
838 syntax::feature_gate::check_crate(&krate,
840 &sess.features.borrow(),
842 sess.opts.unstable_features);
847 let hir_forest = time(time_passes, "lowering ast -> hir", || {
848 let hir_crate = lower_crate(sess, &krate, &mut resolver);
850 if sess.opts.debugging_opts.hir_stats {
851 hir_stats::print_hir_stats(&hir_crate);
854 hir_map::Forest::new(hir_crate, &sess.dep_graph)
859 || lint::check_ast_crate(sess, &krate));
861 // Discard hygiene data, which isn't required after lowering to HIR.
862 if !keep_hygiene_data(sess) {
863 syntax::ext::hygiene::clear_markings();
867 expanded_crate: krate,
868 defs: resolver.definitions,
869 analysis: ty::CrateAnalysis {
870 access_levels: Rc::new(AccessLevels::default()),
871 reachable: Rc::new(NodeSet()),
872 name: crate_name.to_string(),
873 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
875 resolutions: Resolutions {
876 freevars: resolver.freevars,
877 export_map: resolver.export_map,
878 trait_map: resolver.trait_map,
879 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
880 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
886 /// Run the resolution, typechecking, region checking and other
887 /// miscellaneous analysis passes on the crate. Return various
888 /// structures carrying the results of the analysis.
889 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
890 hir_map: hir_map::Map<'tcx>,
891 mut analysis: ty::CrateAnalysis,
892 resolutions: Resolutions,
893 arena: &'tcx DroplessArena,
894 arenas: &'tcx GlobalArenas<'tcx>,
897 -> Result<R, CompileIncomplete>
898 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
900 IncrementalHashesMap,
903 macro_rules! try_with_f {
904 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
908 f($t, $a, $h, Err(x));
915 let time_passes = sess.time_passes();
917 let lang_items = time(time_passes, "language item collection", || {
918 sess.track_errors(|| {
919 middle::lang_items::collect_language_items(&sess, &hir_map)
923 let named_region_map = time(time_passes,
924 "lifetime resolution",
925 || middle::resolve_lifetime::krate(sess, &hir_map))?;
928 "looking for entry point",
929 || middle::entry::find_entry_point(sess, &hir_map));
931 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
932 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
934 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
938 || loops::check_crate(sess, &hir_map));
941 "static item recursion checking",
942 || static_recursion::check_crate(sess, &hir_map))?;
944 let index = stability::Index::new(&sess);
946 let mut local_providers = ty::maps::Providers::default();
947 borrowck::provide(&mut local_providers);
948 mir::provide(&mut local_providers);
949 reachable::provide(&mut local_providers);
950 rustc_privacy::provide(&mut local_providers);
951 trans::provide(&mut local_providers);
952 typeck::provide(&mut local_providers);
953 ty::provide(&mut local_providers);
954 traits::provide(&mut local_providers);
955 reachable::provide(&mut local_providers);
956 rustc_const_eval::provide(&mut local_providers);
957 middle::region::provide(&mut local_providers);
958 cstore::provide_local(&mut local_providers);
959 lint::provide(&mut local_providers);
961 let mut extern_providers = ty::maps::Providers::default();
962 cstore::provide(&mut extern_providers);
963 trans::provide(&mut extern_providers);
964 ty::provide_extern(&mut extern_providers);
965 traits::provide_extern(&mut extern_providers);
966 // FIXME(eddyb) get rid of this once we replace const_eval with miri.
967 rustc_const_eval::provide(&mut extern_providers);
969 // Setup the MIR passes that we want to run.
970 let mut passes = Passes::new();
971 passes.push_hook(mir::transform::dump_mir::DumpMir);
973 // Remove all `EndRegion` statements that are not involved in borrows.
974 passes.push_pass(MIR_CONST, mir::transform::clean_end_regions::CleanEndRegions);
976 // What we need to do constant evaluation.
977 passes.push_pass(MIR_CONST, mir::transform::simplify::SimplifyCfg::new("initial"));
978 passes.push_pass(MIR_CONST, mir::transform::type_check::TypeckMir);
979 passes.push_pass(MIR_CONST, mir::transform::rustc_peek::SanityCheck);
981 // We compute "constant qualifications" between MIR_CONST and MIR_VALIDATED.
983 // What we need to run borrowck etc.
985 passes.push_pass(MIR_VALIDATED, mir::transform::qualify_consts::QualifyAndPromoteConstants);
987 // FIXME: ariel points SimplifyBranches should run after
988 // mir-borrowck; otherwise code within `if false { ... }` would
990 passes.push_pass(MIR_VALIDATED,
991 mir::transform::simplify_branches::SimplifyBranches::new("initial"));
992 passes.push_pass(MIR_VALIDATED, mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
993 passes.push_pass(MIR_VALIDATED, mir::transform::nll::NLL);
995 // borrowck runs between MIR_VALIDATED and MIR_OPTIMIZED.
997 // These next passes must be executed together
998 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
999 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::CriticalCallEdges);
1000 passes.push_pass(MIR_OPTIMIZED, mir::transform::elaborate_drops::ElaborateDrops);
1001 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
1002 // AddValidation needs to run after ElaborateDrops and before EraseRegions, and it needs
1003 // an AllCallEdges pass right before it.
1004 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::AllCallEdges);
1005 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_validation::AddValidation);
1006 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyCfg::new("elaborate-drops"));
1007 // No lifetime analysis based on borrowing can be done from here on out.
1009 // From here on out, regions are gone.
1010 passes.push_pass(MIR_OPTIMIZED, mir::transform::erase_regions::EraseRegions);
1012 // Optimizations begin.
1013 passes.push_pass(MIR_OPTIMIZED, mir::transform::inline::Inline);
1014 passes.push_pass(MIR_OPTIMIZED, mir::transform::instcombine::InstCombine);
1015 passes.push_pass(MIR_OPTIMIZED, mir::transform::deaggregator::Deaggregator);
1016 passes.push_pass(MIR_OPTIMIZED, mir::transform::copy_prop::CopyPropagation);
1017 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyLocals);
1019 passes.push_pass(MIR_OPTIMIZED, mir::transform::generator::StateTransform);
1020 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::CriticalCallEdges);
1021 passes.push_pass(MIR_OPTIMIZED, mir::transform::dump_mir::Marker("PreTrans"));
1023 TyCtxt::create_and_enter(sess,
1036 let incremental_hashes_map =
1038 "compute_incremental_hashes_map",
1039 || rustc_incremental::compute_incremental_hashes_map(tcx));
1043 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
1045 time(time_passes, "stability index", || {
1046 tcx.stability.borrow_mut().build(tcx)
1050 "stability checking",
1051 || stability::check_unstable_api_usage(tcx));
1053 // passes are timed inside typeck
1054 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
1058 || consts::check_crate(tcx));
1060 analysis.access_levels =
1061 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1064 "intrinsic checking",
1065 || middle::intrinsicck::check_crate(tcx));
1069 || middle::effect::check_crate(tcx));
1073 || check_match::check_crate(tcx));
1075 // this must run before MIR dump, because
1076 // "not all control paths return a value" is reported here.
1078 // maybe move the check to a MIR pass?
1080 "liveness checking",
1081 || middle::liveness::check_crate(tcx));
1085 || borrowck::check_crate(tcx));
1088 "MIR borrow checking",
1089 || for def_id in tcx.body_owners() { tcx.mir_borrowck(def_id) });
1091 // Avoid overwhelming user with errors if type checking failed.
1092 // I'm not sure how helpful this is, to be honest, but it avoids
1094 // lot of annoying errors in the compile-fail tests (basically,
1095 // lint warnings and so on -- kindck used to do this abort, but
1096 // kindck is gone now). -nmatsakis
1097 if sess.err_count() > 0 {
1098 return Ok(f(tcx, analysis, incremental_hashes_map, sess.compile_status()));
1101 analysis.reachable =
1103 "reachability checking",
1104 || reachable::find_reachable(tcx));
1106 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1108 time(time_passes, "unused lib feature checking", || {
1109 stability::check_unused_or_stable_features(tcx)
1112 time(time_passes, "lint checking", || lint::check_crate(tcx));
1114 return Ok(f(tcx, analysis, incremental_hashes_map, tcx.sess.compile_status()));
1118 /// Run the translation phase to LLVM, after which the AST and analysis can
1120 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1121 analysis: ty::CrateAnalysis,
1122 incremental_hashes_map: IncrementalHashesMap,
1123 output_filenames: &OutputFilenames)
1124 -> write::OngoingCrateTranslation {
1125 let time_passes = tcx.sess.time_passes();
1128 "resolving dependency formats",
1129 || ::rustc::middle::dependency_format::calculate(tcx));
1134 move || trans::trans_crate(tcx, analysis, incremental_hashes_map, output_filenames));
1136 if tcx.sess.profile_queries() {
1137 profile::dump("profile_queries".to_string())
1143 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1144 /// as a side effect.
1145 #[cfg(feature="llvm")]
1146 pub fn phase_5_run_llvm_passes(sess: &Session,
1147 trans: write::OngoingCrateTranslation)
1148 -> (CompileResult, trans::CrateTranslation) {
1149 let trans = trans.join(sess);
1151 if sess.opts.debugging_opts.incremental_info {
1152 write::dump_incremental_data(&trans);
1155 time(sess.time_passes(),
1156 "serialize work products",
1157 move || rustc_incremental::save_work_products(sess));
1159 (sess.compile_status(), trans)
1162 /// Run the linker on any artifacts that resulted from the LLVM run.
1163 /// This should produce either a finished executable or library.
1164 #[cfg(feature="llvm")]
1165 pub fn phase_6_link_output(sess: &Session,
1166 trans: &trans::CrateTranslation,
1167 outputs: &OutputFilenames) {
1168 time(sess.time_passes(), "linking", || {
1169 ::rustc_trans::back::link::link_binary(sess, trans, outputs, &trans.crate_name.as_str())
1173 fn escape_dep_filename(filename: &str) -> String {
1174 // Apparently clang and gcc *only* escape spaces:
1175 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1176 filename.replace(" ", "\\ ")
1179 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1180 let mut out_filenames = Vec::new();
1181 for output_type in sess.opts.output_types.keys() {
1182 let file = outputs.path(*output_type);
1183 match *output_type {
1184 OutputType::Exe => {
1185 for output in sess.crate_types.borrow().iter() {
1186 let p = ::rustc_trans_utils::link::filename_for_input(
1192 out_filenames.push(p);
1196 out_filenames.push(file);
1201 // Write out dependency rules to the dep-info file if requested
1202 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1205 let deps_filename = outputs.path(OutputType::DepInfo);
1208 (|| -> io::Result<()> {
1209 // Build a list of files used to compile the output and
1210 // write Makefile-compatible dependency rules
1211 let files: Vec<String> = sess.codemap()
1214 .filter(|fmap| fmap.is_real_file())
1215 .filter(|fmap| !fmap.is_imported())
1216 .map(|fmap| escape_dep_filename(&fmap.name))
1218 let mut file = fs::File::create(&deps_filename)?;
1219 for path in &out_filenames {
1220 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1223 // Emit a fake target for each input file to the compilation. This
1224 // prevents `make` from spitting out an error if a file is later
1225 // deleted. For more info see #28735
1227 writeln!(file, "{}:", path)?;
1235 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1236 deps_filename.display(),
1242 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1243 // Unconditionally collect crate types from attributes to make them used
1244 let attr_types: Vec<config::CrateType> =
1247 if a.check_name("crate_type") {
1248 match a.value_str() {
1249 Some(ref n) if *n == "rlib" => {
1250 Some(config::CrateTypeRlib)
1252 Some(ref n) if *n == "dylib" => {
1253 Some(config::CrateTypeDylib)
1255 Some(ref n) if *n == "cdylib" => {
1256 Some(config::CrateTypeCdylib)
1258 Some(ref n) if *n == "lib" => {
1259 Some(config::default_lib_output())
1261 Some(ref n) if *n == "staticlib" => {
1262 Some(config::CrateTypeStaticlib)
1264 Some(ref n) if *n == "proc-macro" => {
1265 Some(config::CrateTypeProcMacro)
1267 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1269 session.buffer_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1272 "invalid `crate_type` value");
1276 session.struct_span_err(a.span, "`crate_type` requires a value")
1277 .note("for example: `#![crate_type=\"lib\"]`")
1288 // If we're generating a test executable, then ignore all other output
1289 // styles at all other locations
1290 if session.opts.test {
1291 return vec![config::CrateTypeExecutable];
1294 // Only check command line flags if present. If no types are specified by
1295 // command line, then reuse the empty `base` Vec to hold the types that
1296 // will be found in crate attributes.
1297 let mut base = session.opts.crate_types.clone();
1298 if base.is_empty() {
1299 base.extend(attr_types);
1300 if base.is_empty() {
1301 base.push(::rustc_trans_utils::link::default_output_for_target(session));
1308 .filter(|crate_type| {
1309 let res = !::rustc_trans_utils::link::invalid_output_for_target(session, *crate_type);
1312 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1314 session.opts.target_triple));
1322 pub fn compute_crate_disambiguator(session: &Session) -> String {
1323 use std::hash::Hasher;
1325 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1326 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1327 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1328 // should still be safe enough to avoid collisions in practice.
1329 // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1330 // a hex-string instead of raw bytes. We should really use the
1331 // smaller representation.
1332 let mut hasher = StableHasher::<Fingerprint>::new();
1334 let mut metadata = session.opts.cg.metadata.clone();
1335 // We don't want the crate_disambiguator to dependent on the order
1336 // -C metadata arguments, so sort them:
1338 // Every distinct -C metadata value is only incorporated once:
1341 hasher.write(b"metadata");
1342 for s in &metadata {
1343 // Also incorporate the length of a metadata string, so that we generate
1344 // different values for `-Cmetadata=ab -Cmetadata=c` and
1345 // `-Cmetadata=a -Cmetadata=bc`
1346 hasher.write_usize(s.len());
1347 hasher.write(s.as_bytes());
1350 // If this is an executable, add a special suffix, so that we don't get
1351 // symbol conflicts when linking against a library of the same name.
1352 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1354 format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
1357 pub fn build_output_filenames(input: &Input,
1358 odir: &Option<PathBuf>,
1359 ofile: &Option<PathBuf>,
1360 attrs: &[ast::Attribute],
1362 -> OutputFilenames {
1365 // "-" as input file will cause the parser to read from stdin so we
1366 // have to make up a name
1367 // We want to toss everything after the final '.'
1368 let dirpath = match *odir {
1369 Some(ref d) => d.clone(),
1370 None => PathBuf::new(),
1373 // If a crate name is present, we use it as the link name
1374 let stem = sess.opts
1377 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1378 .unwrap_or(input.filestem());
1381 out_directory: dirpath,
1383 single_output_file: None,
1384 extra: sess.opts.cg.extra_filename.clone(),
1385 outputs: sess.opts.output_types.clone(),
1389 Some(ref out_file) => {
1390 let unnamed_output_types = sess.opts
1393 .filter(|a| a.is_none())
1395 let ofile = if unnamed_output_types > 1 {
1396 sess.warn("due to multiple output types requested, the explicitly specified \
1397 output file name will be adapted for each output type");
1400 Some(out_file.clone())
1403 sess.warn("ignoring --out-dir flag due to -o flag.");
1406 let cur_dir = Path::new("");
1409 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1410 out_filestem: out_file.file_stem()
1411 .unwrap_or(OsStr::new(""))
1415 single_output_file: ofile,
1416 extra: sess.opts.cg.extra_filename.clone(),
1417 outputs: sess.opts.output_types.clone(),