]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/lib.rs
Fix conversion from Miri Value to ConstValue
[rust.git] / src / librustc_trans / lib.rs
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.
4 //
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.
10
11 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19       html_root_url = "https://doc.rust-lang.org/nightly/")]
20
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
23 #![feature(custom_attribute)]
24 #![feature(fs_read_write)]
25 #![allow(unused_attributes)]
26 #![feature(libc)]
27 #![feature(quote)]
28 #![feature(range_contains)]
29 #![feature(rustc_diagnostic_macros)]
30 #![feature(slice_sort_by_cached_key)]
31 #![feature(optin_builtin_traits)]
32 #![feature(inclusive_range_methods)]
33
34 use rustc::dep_graph::WorkProduct;
35 use syntax_pos::symbol::Symbol;
36
37 extern crate flate2;
38 extern crate libc;
39 #[macro_use] extern crate rustc;
40 extern crate jobserver;
41 extern crate num_cpus;
42 extern crate rustc_mir;
43 extern crate rustc_allocator;
44 extern crate rustc_apfloat;
45 extern crate rustc_target;
46 #[macro_use] extern crate rustc_data_structures;
47 extern crate rustc_demangle;
48 extern crate rustc_incremental;
49 extern crate rustc_llvm as llvm;
50 extern crate rustc_platform_intrinsics as intrinsics;
51 extern crate rustc_trans_utils;
52
53 #[macro_use] extern crate log;
54 #[macro_use] extern crate syntax;
55 extern crate syntax_pos;
56 extern crate rustc_errors as errors;
57 extern crate serialize;
58 extern crate cc; // Used to locate MSVC
59 extern crate tempdir;
60
61 use back::bytecode::RLIB_BYTECODE_EXTENSION;
62
63 pub use llvm_util::target_features;
64
65 use std::any::Any;
66 use std::path::PathBuf;
67 use std::sync::mpsc;
68 use std::collections::BTreeMap;
69 use rustc_data_structures::sync::Lrc;
70
71 use rustc::dep_graph::DepGraph;
72 use rustc::hir::def_id::CrateNum;
73 use rustc::middle::cstore::MetadataLoader;
74 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
75 use rustc::middle::lang_items::LangItem;
76 use rustc::session::{Session, CompileIncomplete};
77 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
78 use rustc::ty::{self, TyCtxt};
79 use rustc::util::nodemap::{FxHashSet, FxHashMap};
80 use rustc_mir::monomorphize;
81 use rustc_trans_utils::trans_crate::TransCrate;
82
83 mod diagnostics;
84
85 mod back {
86     pub use rustc_trans_utils::symbol_names;
87     mod archive;
88     pub mod bytecode;
89     mod command;
90     pub mod linker;
91     pub mod link;
92     mod lto;
93     pub mod symbol_export;
94     pub mod write;
95     mod rpath;
96     mod wasm;
97 }
98
99 mod abi;
100 mod allocator;
101 mod asm;
102 mod attributes;
103 mod base;
104 mod builder;
105 mod callee;
106 mod common;
107 mod consts;
108 mod context;
109 mod debuginfo;
110 mod declare;
111 mod glue;
112 mod intrinsic;
113 mod llvm_util;
114 mod metadata;
115 mod meth;
116 mod mir;
117 mod time_graph;
118 mod trans_item;
119 mod type_;
120 mod type_of;
121 mod value;
122
123 pub struct LlvmTransCrate(());
124
125 impl !Send for LlvmTransCrate {} // Llvm is on a per-thread basis
126 impl !Sync for LlvmTransCrate {}
127
128 impl LlvmTransCrate {
129     pub fn new() -> Box<TransCrate> {
130         box LlvmTransCrate(())
131     }
132 }
133
134 impl TransCrate for LlvmTransCrate {
135     fn init(&self, sess: &Session) {
136         llvm_util::init(sess); // Make sure llvm is inited
137     }
138
139     fn print(&self, req: PrintRequest, sess: &Session) {
140         match req {
141             PrintRequest::RelocationModels => {
142                 println!("Available relocation models:");
143                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
144                     println!("    {}", name);
145                 }
146                 println!("");
147             }
148             PrintRequest::CodeModels => {
149                 println!("Available code models:");
150                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
151                     println!("    {}", name);
152                 }
153                 println!("");
154             }
155             PrintRequest::TlsModels => {
156                 println!("Available TLS models:");
157                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
158                     println!("    {}", name);
159                 }
160                 println!("");
161             }
162             req => llvm_util::print(req, sess),
163         }
164     }
165
166     fn print_passes(&self) {
167         llvm_util::print_passes();
168     }
169
170     fn print_version(&self) {
171         llvm_util::print_version();
172     }
173
174     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
175         &DIAGNOSTICS
176     }
177
178     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
179         target_features(sess)
180     }
181
182     fn metadata_loader(&self) -> Box<MetadataLoader + Sync> {
183         box metadata::LlvmMetadataLoader
184     }
185
186     fn provide(&self, providers: &mut ty::maps::Providers) {
187         back::symbol_names::provide(providers);
188         back::symbol_export::provide(providers);
189         base::provide(providers);
190         attributes::provide(providers);
191     }
192
193     fn provide_extern(&self, providers: &mut ty::maps::Providers) {
194         back::symbol_export::provide_extern(providers);
195         base::provide_extern(providers);
196         attributes::provide_extern(providers);
197     }
198
199     fn trans_crate<'a, 'tcx>(
200         &self,
201         tcx: TyCtxt<'a, 'tcx, 'tcx>,
202         rx: mpsc::Receiver<Box<Any + Send>>
203     ) -> Box<Any> {
204         box base::trans_crate(tcx, rx)
205     }
206
207     fn join_trans_and_link(
208         &self,
209         trans: Box<Any>,
210         sess: &Session,
211         dep_graph: &DepGraph,
212         outputs: &OutputFilenames,
213     ) -> Result<(), CompileIncomplete>{
214         use rustc::util::common::time;
215         let (trans, work_products) = trans.downcast::<::back::write::OngoingCrateTranslation>()
216             .expect("Expected LlvmTransCrate's OngoingCrateTranslation, found Box<Any>")
217             .join(sess);
218         if sess.opts.debugging_opts.incremental_info {
219             back::write::dump_incremental_data(&trans);
220         }
221
222         time(sess,
223              "serialize work products",
224              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
225
226         sess.compile_status()?;
227
228         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
229                                                    i == OutputType::Metadata) {
230             return Ok(());
231         }
232
233         // Run the linker on any artifacts that resulted from the LLVM run.
234         // This should produce either a finished executable or library.
235         time(sess, "linking", || {
236             back::link::link_binary(sess, &trans, outputs, &trans.crate_name.as_str());
237         });
238
239         // Now that we won't touch anything in the incremental compilation directory
240         // any more, we can finalize it (which involves renaming it)
241         rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
242
243         Ok(())
244     }
245 }
246
247 /// This is the entrypoint for a hot plugged rustc_trans
248 #[no_mangle]
249 pub fn __rustc_codegen_backend() -> Box<TransCrate> {
250     LlvmTransCrate::new()
251 }
252
253 struct ModuleTranslation {
254     /// The name of the module. When the crate may be saved between
255     /// compilations, incremental compilation requires that name be
256     /// unique amongst **all** crates.  Therefore, it should contain
257     /// something unique to this crate (e.g., a module path) as well
258     /// as the crate name and disambiguator.
259     name: String,
260     llmod_id: String,
261     source: ModuleSource,
262     kind: ModuleKind,
263 }
264
265 #[derive(Copy, Clone, Debug, PartialEq)]
266 enum ModuleKind {
267     Regular,
268     Metadata,
269     Allocator,
270 }
271
272 impl ModuleTranslation {
273     fn llvm(&self) -> Option<&ModuleLlvm> {
274         match self.source {
275             ModuleSource::Translated(ref llvm) => Some(llvm),
276             ModuleSource::Preexisting(_) => None,
277         }
278     }
279
280     fn into_compiled_module(self,
281                                 emit_obj: bool,
282                                 emit_bc: bool,
283                                 emit_bc_compressed: bool,
284                                 outputs: &OutputFilenames) -> CompiledModule {
285         let pre_existing = match self.source {
286             ModuleSource::Preexisting(_) => true,
287             ModuleSource::Translated(_) => false,
288         };
289         let object = if emit_obj {
290             Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
291         } else {
292             None
293         };
294         let bytecode = if emit_bc {
295             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
296         } else {
297             None
298         };
299         let bytecode_compressed = if emit_bc_compressed {
300             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
301                     .with_extension(RLIB_BYTECODE_EXTENSION))
302         } else {
303             None
304         };
305
306         CompiledModule {
307             llmod_id: self.llmod_id,
308             name: self.name.clone(),
309             kind: self.kind,
310             pre_existing,
311             object,
312             bytecode,
313             bytecode_compressed,
314         }
315     }
316 }
317
318 #[derive(Debug)]
319 struct CompiledModule {
320     name: String,
321     llmod_id: String,
322     kind: ModuleKind,
323     pre_existing: bool,
324     object: Option<PathBuf>,
325     bytecode: Option<PathBuf>,
326     bytecode_compressed: Option<PathBuf>,
327 }
328
329 enum ModuleSource {
330     /// Copy the `.o` files or whatever from the incr. comp. directory.
331     Preexisting(WorkProduct),
332
333     /// Rebuild from this LLVM module.
334     Translated(ModuleLlvm),
335 }
336
337 #[derive(Debug)]
338 struct ModuleLlvm {
339     llcx: llvm::ContextRef,
340     llmod: llvm::ModuleRef,
341     tm: llvm::TargetMachineRef,
342 }
343
344 unsafe impl Send for ModuleLlvm { }
345 unsafe impl Sync for ModuleLlvm { }
346
347 impl Drop for ModuleLlvm {
348     fn drop(&mut self) {
349         unsafe {
350             llvm::LLVMDisposeModule(self.llmod);
351             llvm::LLVMContextDispose(self.llcx);
352             llvm::LLVMRustDisposeTargetMachine(self.tm);
353         }
354     }
355 }
356
357 struct CrateTranslation {
358     crate_name: Symbol,
359     modules: Vec<CompiledModule>,
360     allocator_module: Option<CompiledModule>,
361     metadata_module: CompiledModule,
362     link: rustc::middle::cstore::LinkMeta,
363     metadata: rustc::middle::cstore::EncodedMetadata,
364     windows_subsystem: Option<String>,
365     linker_info: back::linker::LinkerInfo,
366     crate_info: CrateInfo,
367 }
368
369 // Misc info we load from metadata to persist beyond the tcx
370 struct CrateInfo {
371     panic_runtime: Option<CrateNum>,
372     compiler_builtins: Option<CrateNum>,
373     profiler_runtime: Option<CrateNum>,
374     sanitizer_runtime: Option<CrateNum>,
375     is_no_builtins: FxHashSet<CrateNum>,
376     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
377     crate_name: FxHashMap<CrateNum, String>,
378     used_libraries: Lrc<Vec<NativeLibrary>>,
379     link_args: Lrc<Vec<String>>,
380     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
381     used_crates_static: Vec<(CrateNum, LibSource)>,
382     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
383     wasm_custom_sections: BTreeMap<String, Vec<u8>>,
384     wasm_imports: FxHashMap<String, String>,
385     lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
386     missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
387 }
388
389 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }