5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(bool_to_option)]
9 #![feature(const_cstr_unchecked)]
10 #![feature(crate_visibility_modifier)]
11 #![feature(extern_types)]
12 #![feature(in_band_lifetimes)]
15 #![recursion_limit = "256"]
17 use back::write::{create_informational_target_machine, create_target_machine};
19 pub use llvm_util::target_features;
20 use rustc_ast::expand::allocator::AllocatorKind;
21 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
22 use rustc_codegen_ssa::back::write::{
23 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
25 use rustc_codegen_ssa::traits::*;
26 use rustc_codegen_ssa::ModuleCodegen;
27 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc_errors::{ErrorReported, FatalError, Handler};
30 use rustc_metadata::EncodedMetadata;
31 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
32 use rustc_middle::ty::TyCtxt;
33 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
34 use rustc_session::Session;
35 use rustc_span::symbol::Symbol;
62 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
63 #[path = "llvm/mod.rs"]
66 pub use super::llvm_::*;
77 pub struct LlvmCodegenBackend(());
79 struct TimeTraceProfiler {
83 impl TimeTraceProfiler {
84 fn new(enabled: bool) -> Self {
86 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
88 TimeTraceProfiler { enabled }
92 impl Drop for TimeTraceProfiler {
95 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
100 impl ExtraBackendMethods for LlvmCodegenBackend {
101 fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
102 ModuleLlvm::new_metadata(tcx, mod_name)
105 fn write_compressed_metadata<'tcx>(
108 metadata: &EncodedMetadata,
109 llvm_module: &mut ModuleLlvm,
111 base::write_compressed_metadata(tcx, metadata, llvm_module)
113 fn codegen_allocator<'tcx>(
116 module_llvm: &mut ModuleLlvm,
119 has_alloc_error_handler: bool,
121 unsafe { allocator::codegen(tcx, module_llvm, module_name, kind, has_alloc_error_handler) }
123 fn compile_codegen_unit(
127 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
128 base::compile_codegen_unit(tcx, cgu_name)
130 fn target_machine_factory(
134 ) -> TargetMachineFactoryFn<Self> {
135 back::write::target_machine_factory(sess, optlvl)
137 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
138 llvm_util::target_cpu(sess)
140 fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
141 llvm_util::tune_cpu(sess)
144 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
150 std::thread::spawn(move || {
151 let _profiler = TimeTraceProfiler::new(time_trace);
156 fn spawn_named_thread<F, T>(
160 ) -> std::io::Result<std::thread::JoinHandle<T>>
166 std::thread::Builder::new().name(name).spawn(move || {
167 let _profiler = TimeTraceProfiler::new(time_trace);
173 impl WriteBackendMethods for LlvmCodegenBackend {
174 type Module = ModuleLlvm;
175 type ModuleBuffer = back::lto::ModuleBuffer;
176 type Context = llvm::Context;
177 type TargetMachine = &'static mut llvm::TargetMachine;
178 type ThinData = back::lto::ThinData;
179 type ThinBuffer = back::lto::ThinBuffer;
180 fn print_pass_timings(&self) {
182 llvm::LLVMRustPrintPassTimings();
186 cgcx: &CodegenContext<Self>,
187 diag_handler: &Handler,
188 modules: Vec<ModuleCodegen<Self::Module>>,
189 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
190 back::write::link(cgcx, diag_handler, modules)
193 cgcx: &CodegenContext<Self>,
194 modules: Vec<FatLTOInput<Self>>,
195 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
196 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
197 back::lto::run_fat(cgcx, modules, cached_modules)
200 cgcx: &CodegenContext<Self>,
201 modules: Vec<(String, Self::ThinBuffer)>,
202 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
203 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
204 back::lto::run_thin(cgcx, modules, cached_modules)
207 cgcx: &CodegenContext<Self>,
208 diag_handler: &Handler,
209 module: &ModuleCodegen<Self::Module>,
210 config: &ModuleConfig,
211 ) -> Result<(), FatalError> {
212 back::write::optimize(cgcx, diag_handler, module, config)
214 unsafe fn optimize_thin(
215 cgcx: &CodegenContext<Self>,
216 thin: &mut ThinModule<Self>,
217 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
218 back::lto::optimize_thin_module(thin, cgcx)
221 cgcx: &CodegenContext<Self>,
222 diag_handler: &Handler,
223 module: ModuleCodegen<Self::Module>,
224 config: &ModuleConfig,
225 ) -> Result<CompiledModule, FatalError> {
226 back::write::codegen(cgcx, diag_handler, module, config)
228 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
229 back::lto::prepare_thin(module)
231 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
232 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
234 fn run_lto_pass_manager(
235 cgcx: &CodegenContext<Self>,
236 module: &ModuleCodegen<Self::Module>,
237 config: &ModuleConfig,
239 ) -> Result<(), FatalError> {
240 let diag_handler = cgcx.create_diag_handler();
241 back::lto::run_pass_manager(cgcx, &diag_handler, module, config, thin)
245 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
246 unsafe impl Sync for LlvmCodegenBackend {}
248 impl LlvmCodegenBackend {
249 pub fn new() -> Box<dyn CodegenBackend> {
250 Box::new(LlvmCodegenBackend(()))
254 impl CodegenBackend for LlvmCodegenBackend {
255 fn init(&self, sess: &Session) {
256 llvm_util::init(sess); // Make sure llvm is inited
259 fn print(&self, req: PrintRequest, sess: &Session) {
261 PrintRequest::RelocationModels => {
262 println!("Available relocation models:");
273 println!(" {}", name);
277 PrintRequest::CodeModels => {
278 println!("Available code models:");
279 for name in &["tiny", "small", "kernel", "medium", "large"] {
280 println!(" {}", name);
284 PrintRequest::TlsModels => {
285 println!("Available TLS models:");
286 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
287 println!(" {}", name);
291 req => llvm_util::print(req, sess),
295 fn print_passes(&self) {
296 llvm_util::print_passes();
299 fn print_version(&self) {
300 llvm_util::print_version();
303 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
304 target_features(sess)
307 fn codegen_crate<'tcx>(
310 metadata: EncodedMetadata,
311 need_metadata_module: bool,
313 Box::new(rustc_codegen_ssa::base::codegen_crate(
314 LlvmCodegenBackend(()),
316 crate::llvm_util::target_cpu(tcx.sess).to_string(),
318 need_metadata_module,
324 ongoing_codegen: Box<dyn Any>,
326 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
327 let (codegen_results, work_products) = ongoing_codegen
328 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
329 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
332 sess.time("llvm_dump_timing_file", || {
333 if sess.opts.debugging_opts.llvm_time_trace {
334 llvm_util::time_trace_profiler_finish("llvm_timings.json");
338 Ok((codegen_results, work_products))
344 codegen_results: CodegenResults,
345 outputs: &OutputFilenames,
346 ) -> Result<(), ErrorReported> {
347 use crate::back::archive::LlvmArchiveBuilder;
348 use rustc_codegen_ssa::back::link::link_binary;
350 // Run the linker on any artifacts that resulted from the LLVM run.
351 // This should produce either a finished executable or library.
352 link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
356 pub struct ModuleLlvm {
357 llcx: &'static mut llvm::Context,
358 llmod_raw: *const llvm::Module,
359 tm: &'static mut llvm::TargetMachine,
362 unsafe impl Send for ModuleLlvm {}
363 unsafe impl Sync for ModuleLlvm {}
366 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
368 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
369 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
370 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
374 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
376 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
377 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
378 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
383 cgcx: &CodegenContext<LlvmCodegenBackend>,
387 ) -> Result<Self, FatalError> {
389 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
390 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
391 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
392 let tm = match (cgcx.tm_factory)(tm_factory_config) {
395 handler.struct_err(&e).emit();
396 return Err(FatalError);
400 Ok(ModuleLlvm { llmod_raw, llcx, tm })
404 fn llmod(&self) -> &llvm::Module {
405 unsafe { &*self.llmod_raw }
409 impl Drop for ModuleLlvm {
412 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
413 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));