]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Work around to fix issue https://github.com/rust-lang/rust/issues/53912
[rust.git] / src / librustc_codegen_llvm / 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(crate_visibility_modifier)]
24 #![feature(custom_attribute)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![allow(unused_attributes)]
28 #![feature(libc)]
29 #![feature(nll)]
30 #![feature(quote)]
31 #![feature(range_contains)]
32 #![feature(rustc_diagnostic_macros)]
33 #![feature(slice_sort_by_cached_key)]
34 #![feature(optin_builtin_traits)]
35 #![feature(concat_idents)]
36 #![feature(link_args)]
37 #![feature(static_nobundle)]
38
39 use back::write::create_target_machine;
40 use rustc::dep_graph::WorkProduct;
41 use syntax_pos::symbol::Symbol;
42
43 #[macro_use] extern crate bitflags;
44 extern crate flate2;
45 extern crate libc;
46 #[macro_use] extern crate rustc;
47 extern crate jobserver;
48 extern crate num_cpus;
49 extern crate rustc_mir;
50 extern crate rustc_allocator;
51 extern crate rustc_apfloat;
52 extern crate rustc_target;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_codegen_utils;
59 extern crate rustc_fs_util;
60
61 #[macro_use] extern crate log;
62 #[macro_use] extern crate syntax;
63 extern crate syntax_pos;
64 extern crate rustc_errors as errors;
65 extern crate serialize;
66 extern crate cc; // Used to locate MSVC
67 extern crate tempfile;
68 extern crate memmap;
69
70 use back::bytecode::RLIB_BYTECODE_EXTENSION;
71
72 pub use llvm_util::target_features;
73 use std::any::Any;
74 use std::sync::mpsc;
75 use rustc_data_structures::sync::Lrc;
76
77 use rustc::dep_graph::DepGraph;
78 use rustc::hir::def_id::CrateNum;
79 use rustc::middle::cstore::MetadataLoader;
80 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
81 use rustc::middle::lang_items::LangItem;
82 use rustc::session::{Session, CompileIncomplete};
83 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
84 use rustc::ty::{self, TyCtxt};
85 use rustc::util::time_graph;
86 use rustc::util::nodemap::{FxHashSet, FxHashMap};
87 use rustc::util::profiling::ProfileCategory;
88 use rustc_mir::monomorphize;
89 use rustc_codegen_utils::{CompiledModule, ModuleKind};
90 use rustc_codegen_utils::codegen_backend::CodegenBackend;
91 use rustc_data_structures::svh::Svh;
92
93 mod diagnostics;
94
95 mod back {
96     mod archive;
97     pub mod bytecode;
98     pub mod link;
99     pub mod lto;
100     pub mod write;
101     mod rpath;
102     pub mod wasm;
103 }
104
105 mod abi;
106 mod allocator;
107 mod asm;
108 mod attributes;
109 mod base;
110 mod builder;
111 mod callee;
112 mod common;
113 mod consts;
114 mod context;
115 mod debuginfo;
116 mod declare;
117 mod glue;
118 mod intrinsic;
119
120 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
121 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
122
123 mod llvm_util;
124 mod metadata;
125 mod meth;
126 mod mir;
127 mod mono_item;
128 mod type_;
129 mod type_of;
130 mod value;
131
132 pub struct LlvmCodegenBackend(());
133
134 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
135 impl !Sync for LlvmCodegenBackend {}
136
137 impl LlvmCodegenBackend {
138     pub fn new() -> Box<dyn CodegenBackend> {
139         box LlvmCodegenBackend(())
140     }
141 }
142
143 impl CodegenBackend for LlvmCodegenBackend {
144     fn init(&self, sess: &Session) {
145         llvm_util::init(sess); // Make sure llvm is inited
146     }
147
148     fn print(&self, req: PrintRequest, sess: &Session) {
149         match req {
150             PrintRequest::RelocationModels => {
151                 println!("Available relocation models:");
152                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
153                     println!("    {}", name);
154                 }
155                 println!("");
156             }
157             PrintRequest::CodeModels => {
158                 println!("Available code models:");
159                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
160                     println!("    {}", name);
161                 }
162                 println!("");
163             }
164             PrintRequest::TlsModels => {
165                 println!("Available TLS models:");
166                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
167                     println!("    {}", name);
168                 }
169                 println!("");
170             }
171             req => llvm_util::print(req, sess),
172         }
173     }
174
175     fn print_passes(&self) {
176         llvm_util::print_passes();
177     }
178
179     fn print_version(&self) {
180         llvm_util::print_version();
181     }
182
183     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
184         &DIAGNOSTICS
185     }
186
187     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
188         target_features(sess)
189     }
190
191     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
192         box metadata::LlvmMetadataLoader
193     }
194
195     fn provide(&self, providers: &mut ty::query::Providers) {
196         rustc_codegen_utils::symbol_export::provide(providers);
197         rustc_codegen_utils::symbol_names::provide(providers);
198         base::provide_both(providers);
199         attributes::provide(providers);
200     }
201
202     fn provide_extern(&self, providers: &mut ty::query::Providers) {
203         rustc_codegen_utils::symbol_export::provide_extern(providers);
204         base::provide_both(providers);
205         attributes::provide_extern(providers);
206     }
207
208     fn codegen_crate<'a, 'tcx>(
209         &self,
210         tcx: TyCtxt<'a, 'tcx, 'tcx>,
211         rx: mpsc::Receiver<Box<dyn Any + Send>>
212     ) -> Box<dyn Any> {
213         box base::codegen_crate(tcx, rx)
214     }
215
216     fn join_codegen_and_link(
217         &self,
218         ongoing_codegen: Box<dyn Any>,
219         sess: &Session,
220         dep_graph: &DepGraph,
221         outputs: &OutputFilenames,
222     ) -> Result<(), CompileIncomplete>{
223         use rustc::util::common::time;
224         let (ongoing_codegen, work_products) =
225             ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
226                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
227                 .join(sess);
228         if sess.opts.debugging_opts.incremental_info {
229             back::write::dump_incremental_data(&ongoing_codegen);
230         }
231
232         time(sess,
233              "serialize work products",
234              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
235
236         sess.compile_status()?;
237
238         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
239                                                    i == OutputType::Metadata) {
240             return Ok(());
241         }
242
243         // Run the linker on any artifacts that resulted from the LLVM run.
244         // This should produce either a finished executable or library.
245         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
246         time(sess, "linking", || {
247             back::link::link_binary(sess, &ongoing_codegen,
248                                     outputs, &ongoing_codegen.crate_name.as_str());
249         });
250         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
251
252         // Now that we won't touch anything in the incremental compilation directory
253         // any more, we can finalize it (which involves renaming it)
254         rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
255
256         Ok(())
257     }
258 }
259
260 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
261 #[no_mangle]
262 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
263     LlvmCodegenBackend::new()
264 }
265
266 struct ModuleCodegen {
267     /// The name of the module. When the crate may be saved between
268     /// compilations, incremental compilation requires that name be
269     /// unique amongst **all** crates.  Therefore, it should contain
270     /// something unique to this crate (e.g., a module path) as well
271     /// as the crate name and disambiguator.
272     /// We currently generate these names via CodegenUnit::build_cgu_name().
273     name: String,
274     module_llvm: ModuleLlvm,
275     kind: ModuleKind,
276 }
277
278 struct CachedModuleCodegen {
279     name: String,
280     source: WorkProduct,
281 }
282
283 impl ModuleCodegen {
284     fn into_compiled_module(self,
285                             emit_obj: bool,
286                             emit_bc: bool,
287                             emit_bc_compressed: bool,
288                             outputs: &OutputFilenames) -> CompiledModule {
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             name: self.name.clone(),
308             kind: self.kind,
309             object,
310             bytecode,
311             bytecode_compressed,
312         }
313     }
314 }
315
316 struct ModuleLlvm {
317     llcx: &'static mut llvm::Context,
318     llmod_raw: *const llvm::Module,
319     tm: &'static mut llvm::TargetMachine,
320 }
321
322 unsafe impl Send for ModuleLlvm { }
323 unsafe impl Sync for ModuleLlvm { }
324
325 impl ModuleLlvm {
326     fn new(sess: &Session, mod_name: &str) -> Self {
327         unsafe {
328             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
329             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
330
331             ModuleLlvm {
332                 llmod_raw,
333                 llcx,
334                 tm: create_target_machine(sess, false),
335             }
336         }
337     }
338
339     fn llmod(&self) -> &llvm::Module {
340         unsafe {
341             &*self.llmod_raw
342         }
343     }
344 }
345
346 impl Drop for ModuleLlvm {
347     fn drop(&mut self) {
348         unsafe {
349             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
350             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
351         }
352     }
353 }
354
355 struct CodegenResults {
356     crate_name: Symbol,
357     modules: Vec<CompiledModule>,
358     allocator_module: Option<CompiledModule>,
359     metadata_module: CompiledModule,
360     crate_hash: Svh,
361     metadata: rustc::middle::cstore::EncodedMetadata,
362     windows_subsystem: Option<String>,
363     linker_info: rustc_codegen_utils::linker::LinkerInfo,
364     crate_info: CrateInfo,
365 }
366
367 /// Misc info we load from metadata to persist beyond the tcx
368 struct CrateInfo {
369     panic_runtime: Option<CrateNum>,
370     compiler_builtins: Option<CrateNum>,
371     profiler_runtime: Option<CrateNum>,
372     sanitizer_runtime: Option<CrateNum>,
373     is_no_builtins: FxHashSet<CrateNum>,
374     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
375     crate_name: FxHashMap<CrateNum, String>,
376     used_libraries: Lrc<Vec<NativeLibrary>>,
377     link_args: Lrc<Vec<String>>,
378     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
379     used_crates_static: Vec<(CrateNum, LibSource)>,
380     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
381     wasm_imports: FxHashMap<String, String>,
382     lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
383     missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
384 }
385
386 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }