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