]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Auto merge of #67084 - Pagten:feature/print-msg-from-elf-entrypoint, r=Amanieu
[rust.git] / src / librustc_codegen_llvm / lib.rs
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8
9 #![feature(bool_to_option)]
10 #![feature(box_patterns)]
11 #![feature(box_syntax)]
12 #![feature(const_cstr_unchecked)]
13 #![feature(crate_visibility_modifier)]
14 #![feature(extern_types)]
15 #![feature(in_band_lifetimes)]
16 #![feature(libc)]
17 #![feature(nll)]
18 #![feature(optin_builtin_traits)]
19 #![feature(concat_idents)]
20 #![feature(link_args)]
21 #![feature(static_nobundle)]
22 #![feature(trusted_len)]
23
24 use back::write::{create_target_machine, create_informational_target_machine};
25 use syntax_pos::symbol::Symbol;
26
27 use rustc_codegen_ssa::traits::*;
28 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, FatLTOInput};
29 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
30 use rustc_codegen_ssa::CompiledModule;
31 use rustc_errors::{FatalError, Handler};
32 use rustc::dep_graph::WorkProduct;
33 use syntax::expand::allocator::AllocatorKind;
34 pub use llvm_util::target_features;
35 use std::any::Any;
36 use std::sync::Arc;
37 use std::ffi::CStr;
38
39 use rustc::dep_graph::DepGraph;
40 use rustc::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
41 use rustc::session::Session;
42 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest, OptLevel};
43 use rustc::ty::{self, TyCtxt};
44 use rustc::util::common::ErrorReported;
45 use rustc_codegen_ssa::ModuleCodegen;
46 use rustc_codegen_utils::codegen_backend::CodegenBackend;
47
48 mod back {
49     pub mod archive;
50     pub mod bytecode;
51     pub mod lto;
52     pub mod write;
53 }
54
55 mod abi;
56 mod allocator;
57 mod asm;
58 mod attributes;
59 mod base;
60 mod builder;
61 mod callee;
62 mod common;
63 mod consts;
64 mod context;
65 mod debuginfo;
66 mod declare;
67 mod intrinsic;
68
69 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
70 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
71
72 mod llvm_util;
73 mod metadata;
74 mod mono_item;
75 mod type_;
76 mod type_of;
77 mod value;
78 mod va_arg;
79
80 #[derive(Clone)]
81 pub struct LlvmCodegenBackend(());
82
83 impl ExtraBackendMethods for LlvmCodegenBackend {
84     fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
85         ModuleLlvm::new_metadata(tcx, mod_name)
86     }
87
88     fn write_compressed_metadata<'tcx>(
89         &self,
90         tcx: TyCtxt<'tcx>,
91         metadata: &EncodedMetadata,
92         llvm_module: &mut ModuleLlvm,
93     ) {
94         base::write_compressed_metadata(tcx, metadata, llvm_module)
95     }
96     fn codegen_allocator<'tcx>(
97         &self,
98         tcx: TyCtxt<'tcx>,
99         mods: &mut ModuleLlvm,
100         kind: AllocatorKind,
101     ) {
102         unsafe { allocator::codegen(tcx, mods, kind) }
103     }
104     fn compile_codegen_unit(
105         &self, tcx: TyCtxt<'_>,
106         cgu_name: Symbol,
107         tx: &std::sync::mpsc::Sender<Box<dyn Any + Send>>,
108     ) {
109         base::compile_codegen_unit(tcx, cgu_name, tx);
110     }
111     fn target_machine_factory(
112         &self,
113         sess: &Session,
114         optlvl: OptLevel,
115         find_features: bool
116     ) -> Arc<dyn Fn() ->
117         Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
118         back::write::target_machine_factory(sess, optlvl, find_features)
119     }
120     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
121         llvm_util::target_cpu(sess)
122     }
123 }
124
125 impl WriteBackendMethods for LlvmCodegenBackend {
126     type Module = ModuleLlvm;
127     type ModuleBuffer = back::lto::ModuleBuffer;
128     type Context = llvm::Context;
129     type TargetMachine = &'static mut llvm::TargetMachine;
130     type ThinData = back::lto::ThinData;
131     type ThinBuffer = back::lto::ThinBuffer;
132     fn print_pass_timings(&self) {
133             unsafe { llvm::LLVMRustPrintPassTimings(); }
134     }
135     fn run_fat_lto(
136         cgcx: &CodegenContext<Self>,
137         modules: Vec<FatLTOInput<Self>>,
138         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
139     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
140         back::lto::run_fat(cgcx, modules, cached_modules)
141     }
142     fn run_thin_lto(
143         cgcx: &CodegenContext<Self>,
144         modules: Vec<(String, Self::ThinBuffer)>,
145         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
146     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
147         back::lto::run_thin(cgcx, modules, cached_modules)
148     }
149     unsafe fn optimize(
150         cgcx: &CodegenContext<Self>,
151         diag_handler: &Handler,
152         module: &ModuleCodegen<Self::Module>,
153         config: &ModuleConfig,
154     ) -> Result<(), FatalError> {
155         back::write::optimize(cgcx, diag_handler, module, config)
156     }
157     unsafe fn optimize_thin(
158         cgcx: &CodegenContext<Self>,
159         thin: &mut ThinModule<Self>,
160     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
161         back::lto::optimize_thin_module(thin, cgcx)
162     }
163     unsafe fn codegen(
164         cgcx: &CodegenContext<Self>,
165         diag_handler: &Handler,
166         module: ModuleCodegen<Self::Module>,
167         config: &ModuleConfig,
168     ) -> Result<CompiledModule, FatalError> {
169         back::write::codegen(cgcx, diag_handler, module, config)
170     }
171     fn prepare_thin(
172         module: ModuleCodegen<Self::Module>
173     ) -> (String, Self::ThinBuffer) {
174         back::lto::prepare_thin(module)
175     }
176     fn serialize_module(
177         module: ModuleCodegen<Self::Module>
178     ) -> (String, Self::ModuleBuffer) {
179         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
180     }
181     fn run_lto_pass_manager(
182         cgcx: &CodegenContext<Self>,
183         module: &ModuleCodegen<Self::Module>,
184         config: &ModuleConfig,
185         thin: bool
186     ) {
187         back::lto::run_pass_manager(cgcx, module, config, thin)
188     }
189 }
190
191 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
192 unsafe impl Sync for LlvmCodegenBackend {}
193
194 impl LlvmCodegenBackend {
195     pub fn new() -> Box<dyn CodegenBackend> {
196         box LlvmCodegenBackend(())
197     }
198 }
199
200 impl CodegenBackend for LlvmCodegenBackend {
201     fn init(&self, sess: &Session) {
202         llvm_util::init(sess); // Make sure llvm is inited
203     }
204
205     fn print(&self, req: PrintRequest, sess: &Session) {
206         match req {
207             PrintRequest::RelocationModels => {
208                 println!("Available relocation models:");
209                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
210                     println!("    {}", name);
211                 }
212                 println!();
213             }
214             PrintRequest::CodeModels => {
215                 println!("Available code models:");
216                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
217                     println!("    {}", name);
218                 }
219                 println!();
220             }
221             PrintRequest::TlsModels => {
222                 println!("Available TLS models:");
223                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
224                     println!("    {}", name);
225                 }
226                 println!();
227             }
228             req => llvm_util::print(req, sess),
229         }
230     }
231
232     fn print_passes(&self) {
233         llvm_util::print_passes();
234     }
235
236     fn print_version(&self) {
237         llvm_util::print_version();
238     }
239
240     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
241         target_features(sess)
242     }
243
244     fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
245         box metadata::LlvmMetadataLoader
246     }
247
248     fn provide(&self, providers: &mut ty::query::Providers<'_>) {
249         attributes::provide(providers);
250     }
251
252     fn provide_extern(&self, providers: &mut ty::query::Providers<'_>) {
253         attributes::provide_extern(providers);
254     }
255
256     fn codegen_crate<'tcx>(
257         &self,
258         tcx: TyCtxt<'tcx>,
259         metadata: EncodedMetadata,
260         need_metadata_module: bool,
261     ) -> Box<dyn Any> {
262         box rustc_codegen_ssa::base::codegen_crate(
263             LlvmCodegenBackend(()), tcx, metadata, need_metadata_module)
264     }
265
266     fn join_codegen_and_link(
267         &self,
268         ongoing_codegen: Box<dyn Any>,
269         sess: &Session,
270         dep_graph: &DepGraph,
271         outputs: &OutputFilenames,
272     ) -> Result<(), ErrorReported> {
273         use rustc::util::common::time;
274         let (codegen_results, work_products) =
275             ongoing_codegen.downcast::
276                 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
277                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
278                 .join(sess);
279         if sess.opts.debugging_opts.incremental_info {
280             rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
281         }
282
283         time(sess,
284              "serialize work products",
285              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
286
287         sess.compile_status()?;
288
289         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
290                                                    i == OutputType::Metadata) {
291             return Ok(());
292         }
293
294         // Run the linker on any artifacts that resulted from the LLVM run.
295         // This should produce either a finished executable or library.
296         time(sess, "linking", || {
297             let _prof_timer = sess.prof.generic_activity("link_crate");
298
299             use rustc_codegen_ssa::back::link::link_binary;
300             use crate::back::archive::LlvmArchiveBuilder;
301
302             let target_cpu = crate::llvm_util::target_cpu(sess);
303             link_binary::<LlvmArchiveBuilder<'_>>(
304                 sess,
305                 &codegen_results,
306                 outputs,
307                 &codegen_results.crate_name.as_str(),
308                 target_cpu,
309             );
310         });
311
312         // Now that we won't touch anything in the incremental compilation directory
313         // any more, we can finalize it (which involves renaming it)
314         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
315
316         Ok(())
317     }
318 }
319
320 pub struct ModuleLlvm {
321     llcx: &'static mut llvm::Context,
322     llmod_raw: *const llvm::Module,
323     tm: &'static mut llvm::TargetMachine,
324 }
325
326 unsafe impl Send for ModuleLlvm { }
327 unsafe impl Sync for ModuleLlvm { }
328
329 impl ModuleLlvm {
330     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
331         unsafe {
332             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
333             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
334             ModuleLlvm {
335                 llmod_raw,
336                 llcx,
337                 tm: create_target_machine(tcx, false),
338             }
339         }
340     }
341
342     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
343         unsafe {
344             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
345             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
346             ModuleLlvm {
347                 llmod_raw,
348                 llcx,
349                 tm: create_informational_target_machine(&tcx.sess, false),
350             }
351         }
352     }
353
354     fn parse(
355         cgcx: &CodegenContext<LlvmCodegenBackend>,
356         name: &CStr,
357         buffer: &[u8],
358         handler: &Handler,
359     ) -> Result<Self, FatalError> {
360         unsafe {
361             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
362             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
363             let tm = match (cgcx.tm_factory.0)() {
364                 Ok(m) => m,
365                 Err(e) => {
366                     handler.struct_err(&e).emit();
367                     return Err(FatalError)
368                 }
369             };
370
371             Ok(ModuleLlvm {
372                 llmod_raw,
373                 llcx,
374                 tm,
375             })
376         }
377     }
378
379     fn llmod(&self) -> &llvm::Module {
380         unsafe {
381             &*self.llmod_raw
382         }
383     }
384 }
385
386 impl Drop for ModuleLlvm {
387     fn drop(&mut self) {
388         unsafe {
389             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
390             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
391         }
392     }
393 }