1 // Copyright 2012-2013 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 back::target_strs;
14 use driver::driver::host_triple;
16 use metadata::filesearch;
19 use util::nodemap::NodeMap;
21 use syntax::attr::AttrMetaMethods;
22 use syntax::ast::NodeId;
23 use syntax::ast::{IntTy, UintTy};
24 use syntax::codemap::Span;
25 use syntax::diagnostic;
26 use syntax::parse::ParseSess;
27 use syntax::{abi, ast, codemap};
30 use std::cell::{Cell, RefCell};
31 use collections::HashSet;
35 arch: abi::Architecture,
36 target_strs: target_strs::t,
41 macro_rules! debugging_opts(
42 ([ $opt:ident ] $cnt:expr ) => (
43 pub static $opt: u64 = 1 << $cnt;
45 ([ $opt:ident, $($rest:ident),* ] $cnt:expr ) => (
46 pub static $opt: u64 = 1 << $cnt;
47 debugging_opts!([ $($rest),* ] $cnt + 1)
77 pub fn debugging_opts_map() -> Vec<(&'static str, &'static str, u64)> {
78 vec!(("verbose", "in general, enable more debug printouts", VERBOSE),
79 ("time-passes", "measure time of each rustc pass", TIME_PASSES),
80 ("count-llvm-insns", "count where LLVM \
81 instrs originate", COUNT_LLVM_INSNS),
82 ("time-llvm-passes", "measure time of each LLVM pass",
84 ("trans-stats", "gather trans statistics", TRANS_STATS),
85 ("asm-comments", "generate comments into the assembly (may change behavior)",
87 ("no-verify", "skip LLVM verification", NO_VERIFY),
88 ("borrowck-stats", "gather borrowck statistics", BORROWCK_STATS),
89 ("no-landing-pads", "omit landing pads for unwinding",
91 ("debug-llvm", "enable debug output from LLVM", DEBUG_LLVM),
92 ("show-span", "show spans for compiler debugging", SHOW_SPAN),
93 ("count-type-sizes", "count the sizes of aggregate types",
95 ("meta-stats", "gather metadata statistics", META_STATS),
96 ("no-opt", "do not optimize, even if -O is passed", NO_OPT),
97 ("print-link-args", "Print the arguments passed to the linker",
99 ("gc", "Garbage collect shared data (experimental)", GC),
100 ("print-llvm-passes",
101 "Prints the llvm optimization passes being run",
103 ("lto", "Perform LLVM link-time optimizations", LTO),
104 ("ast-json", "Print the AST as JSON and halt", AST_JSON),
105 ("ast-json-noexpand", "Print the pre-expansion AST as JSON and halt", AST_JSON_NOEXPAND))
108 #[deriving(Clone, Eq)]
116 #[deriving(Clone, Eq)]
117 pub enum DebugInfoLevel {
125 // The crate config requested for the session, which may be combined
126 // with additional crate configurations during the compile process
127 crate_types: Vec<CrateType> ,
131 debuginfo: DebugInfoLevel,
132 lint_opts: Vec<(lint::Lint, lint::level)> ,
133 output_types: Vec<back::link::OutputType> ,
134 // This was mutable for rustpkg, which updates search paths based on the
135 // parsed code. It remains mutable in case its replacements wants to use
137 addl_lib_search_paths: RefCell<HashSet<Path>>,
138 maybe_sysroot: Option<Path>,
140 // User-specified cfg meta items. The compiler itself will add additional
141 // items to the crate config, and during parsing the entire crate config
142 // will be added to the crate AST node. This should not be used for
143 // anything except building the full crate config prior to parsing.
144 cfg: ast::CrateConfig,
150 /// Whether to write dependency files. It's (enabled, optional filename).
151 write_dependency_info: (bool, Option<Path>),
152 /// Crate id-related things to maybe print. It's (crate_id, crate_name, crate_file_name).
153 print_metas: (bool, bool, bool),
157 // The type of entry function, so
158 // users can have their own entry
159 // functions that don't start a
162 pub enum EntryFnType {
168 #[deriving(Eq, Ord, Clone, TotalOrd, TotalEq)]
179 cstore: metadata::cstore::CStore,
180 parse_sess: ParseSess,
181 // For a library crate, this is always none
182 entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
183 entry_type: Cell<Option<EntryFnType>>,
184 macro_registrar_fn: RefCell<Option<ast::DefId>>,
185 default_sysroot: Option<Path>,
186 building_library: Cell<bool>,
187 // The name of the root source file of the crate, in the local file system. The path is always
188 // expected to be absolute. `None` means that there is no source file.
189 local_crate_source_file: Option<Path>,
191 lints: RefCell<NodeMap<Vec<(lint::Lint, codemap::Span, ~str)>>>,
192 node_id: Cell<ast::NodeId>,
193 crate_types: RefCell<Vec<CrateType>>,
194 features: front::feature_gate::Features,
196 /// The maximum recursion limit for potentially infinitely recursive
197 /// operations such as auto-dereference and monomorphization.
198 recursion_limit: Cell<uint>,
202 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
203 self.diagnostic().span_fatal(sp, msg)
205 pub fn fatal(&self, msg: &str) -> ! {
206 self.diagnostic().handler().fatal(msg)
208 pub fn span_err(&self, sp: Span, msg: &str) {
209 self.diagnostic().span_err(sp, msg)
211 pub fn err(&self, msg: &str) {
212 self.diagnostic().handler().err(msg)
214 pub fn err_count(&self) -> uint {
215 self.diagnostic().handler().err_count()
217 pub fn has_errors(&self) -> bool {
218 self.diagnostic().handler().has_errors()
220 pub fn abort_if_errors(&self) {
221 self.diagnostic().handler().abort_if_errors()
223 pub fn span_warn(&self, sp: Span, msg: &str) {
224 self.diagnostic().span_warn(sp, msg)
226 pub fn warn(&self, msg: &str) {
227 self.diagnostic().handler().warn(msg)
229 pub fn span_note(&self, sp: Span, msg: &str) {
230 self.diagnostic().span_note(sp, msg)
232 pub fn span_end_note(&self, sp: Span, msg: &str) {
233 self.diagnostic().span_end_note(sp, msg)
235 pub fn note(&self, msg: &str) {
236 self.diagnostic().handler().note(msg)
238 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
239 self.diagnostic().span_bug(sp, msg)
241 pub fn bug(&self, msg: &str) -> ! {
242 self.diagnostic().handler().bug(msg)
244 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
245 self.diagnostic().span_unimpl(sp, msg)
247 pub fn unimpl(&self, msg: &str) -> ! {
248 self.diagnostic().handler().unimpl(msg)
250 pub fn add_lint(&self,
255 let mut lints = self.lints.borrow_mut();
256 match lints.get().find_mut(&id) {
257 Some(arr) => { arr.push((lint, sp, msg)); return; }
260 lints.get().insert(id, vec!((lint, sp, msg)));
262 pub fn next_node_id(&self) -> ast::NodeId {
263 self.reserve_node_ids(1)
265 pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
266 let v = self.node_id.get();
268 match v.checked_add(&count) {
269 Some(next) => { self.node_id.set(next); }
270 None => self.bug("Input too large, ran out of node ids!")
275 pub fn diagnostic<'a>(&'a self) -> &'a diagnostic::SpanHandler {
276 &self.parse_sess.span_diagnostic
278 pub fn debugging_opt(&self, opt: u64) -> bool {
279 (self.opts.debugging_opts & opt) != 0
281 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
282 &self.parse_sess.span_diagnostic.cm
284 // This exists to help with refactoring to eliminate impossible
286 pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
287 self.span_bug(sp, format!("impossible case reached: {}", msg));
289 pub fn verbose(&self) -> bool { self.debugging_opt(VERBOSE) }
290 pub fn time_passes(&self) -> bool { self.debugging_opt(TIME_PASSES) }
291 pub fn count_llvm_insns(&self) -> bool {
292 self.debugging_opt(COUNT_LLVM_INSNS)
294 pub fn count_type_sizes(&self) -> bool {
295 self.debugging_opt(COUNT_TYPE_SIZES)
297 pub fn time_llvm_passes(&self) -> bool {
298 self.debugging_opt(TIME_LLVM_PASSES)
300 pub fn trans_stats(&self) -> bool { self.debugging_opt(TRANS_STATS) }
301 pub fn meta_stats(&self) -> bool { self.debugging_opt(META_STATS) }
302 pub fn asm_comments(&self) -> bool { self.debugging_opt(ASM_COMMENTS) }
303 pub fn no_verify(&self) -> bool { self.debugging_opt(NO_VERIFY) }
304 pub fn borrowck_stats(&self) -> bool { self.debugging_opt(BORROWCK_STATS) }
305 pub fn print_llvm_passes(&self) -> bool {
306 self.debugging_opt(PRINT_LLVM_PASSES)
308 pub fn lto(&self) -> bool {
309 self.debugging_opt(LTO)
311 pub fn no_landing_pads(&self) -> bool {
312 self.debugging_opt(NO_LANDING_PADS)
314 pub fn show_span(&self) -> bool {
315 self.debugging_opt(SHOW_SPAN)
317 pub fn filesearch<'a>(&'a self) -> filesearch::FileSearch<'a> {
318 let sysroot = match self.opts.maybe_sysroot {
319 Some(ref sysroot) => sysroot,
320 None => self.default_sysroot.as_ref()
321 .expect("missing sysroot and default_sysroot in Session")
323 filesearch::FileSearch::new(
325 self.opts.target_triple,
326 &self.opts.addl_lib_search_paths)
330 /// Some reasonable defaults
331 pub fn basic_options() -> Options {
333 crate_types: Vec::new(),
336 debuginfo: NoDebugInfo,
337 lint_opts: Vec::new(),
338 output_types: Vec::new(),
339 addl_lib_search_paths: RefCell::new(HashSet::new()),
341 target_triple: host_triple(),
348 write_dependency_info: (false, None),
349 print_metas: (false, false, false),
350 cg: basic_codegen_options(),
354 /// Declare a macro that will define all CodegenOptions fields and parsers all
355 /// at once. The goal of this macro is to define an interface that can be
356 /// programmatically used by the option parser in order to initialize the struct
357 /// without hardcoding field names all over the place.
359 /// The goal is to invoke this macro once with the correct fields, and then this
360 /// macro generates all necessary code. The main gotcha of this macro is the
361 /// cgsetters module which is a bunch of generated code to parse an option into
362 /// its respective field in the struct. There are a few hand-written parsers for
363 /// parsing specific types of values in this module.
364 macro_rules! cgoptions(
365 ($($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
368 pub struct CodegenOptions { $($opt: $t),* }
370 pub fn basic_codegen_options() -> CodegenOptions {
371 CodegenOptions { $($opt: $init),* }
374 pub type CodegenSetter = fn(&mut CodegenOptions, v: Option<&str>) -> bool;
375 pub static CG_OPTIONS: &'static [(&'static str, CodegenSetter,
377 &[ $( (stringify!($opt), cgsetters::$opt, $desc) ),* ];
380 use super::CodegenOptions;
383 pub fn $opt(cg: &mut CodegenOptions, v: Option<&str>) -> bool {
384 $parse(&mut cg.$opt, v)
388 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
391 None => { *slot = true; true }
395 fn parse_opt_string(slot: &mut Option<~str>, v: Option<&str>) -> bool {
397 Some(s) => { *slot = Some(s.to_owned()); true },
402 fn parse_string(slot: &mut ~str, v: Option<&str>) -> bool {
404 Some(s) => { *slot = s.to_owned(); true },
409 fn parse_list(slot: &mut Vec<~str>, v: Option<&str>)
414 slot.push(s.to_owned());
426 ar: Option<~str> = (None, parse_opt_string,
427 "tool to assemble archives with"),
428 linker: Option<~str> = (None, parse_opt_string,
429 "system linker to link outputs with"),
430 link_args: Vec<~str> = (Vec::new(), parse_list,
431 "extra arguments to pass to the linker (space separated)"),
432 target_cpu: ~str = (~"generic", parse_string,
433 "select target processor (llc -mcpu=help for details)"),
434 target_feature: ~str = (~"", parse_string,
435 "target specific attributes (llc -mattr=help for details)"),
436 passes: Vec<~str> = (Vec::new(), parse_list,
437 "a list of extra LLVM passes to run (space separated)"),
438 llvm_args: Vec<~str> = (Vec::new(), parse_list,
439 "a list of arguments to pass to llvm (space separated)"),
440 save_temps: bool = (false, parse_bool,
441 "save all temporary output files during compilation"),
442 android_cross_path: Option<~str> = (None, parse_opt_string,
443 "the path to the Android NDK"),
444 no_rpath: bool = (false, parse_bool,
445 "disables setting the rpath in libs/exes"),
446 no_prepopulate_passes: bool = (false, parse_bool,
447 "don't pre-populate the pass manager with a list of passes"),
448 no_vectorize_loops: bool = (false, parse_bool,
449 "don't run the loop vectorization optimization passes"),
450 no_vectorize_slp: bool = (false, parse_bool,
451 "don't run LLVM's SLP vectorization pass"),
452 soft_float: bool = (false, parse_bool,
453 "generate software floating point library calls"),
454 gen_crate_map: bool = (false, parse_bool,
455 "force generation of a toplevel crate map"),
456 prefer_dynamic: bool = (false, parse_bool,
457 "prefer dynamic linking to static linking"),
458 no_integrated_as: bool = (false, parse_bool,
459 "use an external assembler rather than LLVM's integrated one"),
462 // Seems out of place, but it uses session, so I'm putting it here
463 pub fn expect<T:Clone>(sess: &Session, opt: Option<T>, msg: || -> ~str) -> T {
464 diagnostic::expect(sess.diagnostic(), opt, msg)
467 pub fn building_library(options: &Options, krate: &ast::Crate) -> bool {
468 if options.test { return false }
469 for output in options.crate_types.iter() {
471 CrateTypeExecutable => {}
472 CrateTypeStaticlib | CrateTypeDylib | CrateTypeRlib => return true
475 match syntax::attr::first_attr_value_str_by_name(krate.attrs.as_slice(),
479 s.equiv(&("rlib")) ||
480 s.equiv(&("dylib")) ||
481 s.equiv(&("staticlib"))
487 pub fn default_lib_output() -> CrateType {
491 pub fn collect_crate_types(session: &Session,
492 attrs: &[ast::Attribute]) -> Vec<CrateType> {
493 // If we're generating a test executable, then ignore all other output
494 // styles at all other locations
495 if session.opts.test {
496 return vec!(CrateTypeExecutable)
498 let mut base = session.opts.crate_types.clone();
499 let mut iter = attrs.iter().filter_map(|a| {
500 if a.name().equiv(&("crate_type")) {
501 match a.value_str() {
502 Some(ref n) if n.equiv(&("rlib")) => Some(CrateTypeRlib),
503 Some(ref n) if n.equiv(&("dylib")) => Some(CrateTypeDylib),
504 Some(ref n) if n.equiv(&("lib")) => {
505 Some(default_lib_output())
507 Some(ref n) if n.equiv(&("staticlib")) => {
508 Some(CrateTypeStaticlib)
510 Some(ref n) if n.equiv(&("bin")) => Some(CrateTypeExecutable),
512 session.add_lint(lint::UnknownCrateType,
515 ~"invalid `crate_type` value");
519 session.add_lint(lint::UnknownCrateType, ast::CRATE_NODE_ID,
520 a.span, ~"`crate_type` requires a value");
528 base.extend(&mut iter);
530 base.push(CrateTypeExecutable);
532 base.as_mut_slice().sort();
537 pub fn sess_os_to_meta_os(os: abi::Os) -> metadata::loader::Os {
538 use metadata::loader;
541 abi::OsWin32 => loader::OsWin32,
542 abi::OsLinux => loader::OsLinux,
543 abi::OsAndroid => loader::OsAndroid,
544 abi::OsMacos => loader::OsMacos,
545 abi::OsFreebsd => loader::OsFreebsd