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(crate_visibility_modifier)]
11 #![feature(extern_types)]
13 #![recursion_limit = "256"]
14 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
16 use back::write::{create_informational_target_machine, create_target_machine};
18 pub use llvm_util::target_features;
19 use rustc_ast::expand::allocator::AllocatorKind;
20 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
21 use rustc_codegen_ssa::back::write::{
22 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
24 use rustc_codegen_ssa::traits::*;
25 use rustc_codegen_ssa::ModuleCodegen;
26 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
27 use rustc_data_structures::fx::FxHashMap;
28 use rustc_errors::{ErrorReported, FatalError, Handler};
29 use rustc_metadata::EncodedMetadata;
30 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
31 use rustc_middle::ty::TyCtxt;
32 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
33 use rustc_session::Session;
34 use rustc_span::symbol::Symbol;
61 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
62 #[path = "llvm/mod.rs"]
65 pub use super::llvm_::*;
76 pub struct LlvmCodegenBackend(());
78 struct TimeTraceProfiler {
82 impl TimeTraceProfiler {
83 fn new(enabled: bool) -> Self {
85 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
87 TimeTraceProfiler { enabled }
91 impl Drop for TimeTraceProfiler {
94 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
99 impl ExtraBackendMethods for LlvmCodegenBackend {
100 fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
101 ModuleLlvm::new_metadata(tcx, mod_name)
104 fn codegen_allocator<'tcx>(
107 module_llvm: &mut ModuleLlvm,
110 has_alloc_error_handler: bool,
112 unsafe { allocator::codegen(tcx, module_llvm, module_name, kind, has_alloc_error_handler) }
114 fn compile_codegen_unit(
118 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
119 base::compile_codegen_unit(tcx, cgu_name)
121 fn target_machine_factory(
125 ) -> TargetMachineFactoryFn<Self> {
126 back::write::target_machine_factory(sess, optlvl)
128 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
129 llvm_util::target_cpu(sess)
131 fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
132 llvm_util::tune_cpu(sess)
135 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
141 std::thread::spawn(move || {
142 let _profiler = TimeTraceProfiler::new(time_trace);
147 fn spawn_named_thread<F, T>(
151 ) -> std::io::Result<std::thread::JoinHandle<T>>
157 std::thread::Builder::new().name(name).spawn(move || {
158 let _profiler = TimeTraceProfiler::new(time_trace);
164 impl WriteBackendMethods for LlvmCodegenBackend {
165 type Module = ModuleLlvm;
166 type ModuleBuffer = back::lto::ModuleBuffer;
167 type Context = llvm::Context;
168 type TargetMachine = &'static mut llvm::TargetMachine;
169 type ThinData = back::lto::ThinData;
170 type ThinBuffer = back::lto::ThinBuffer;
171 fn print_pass_timings(&self) {
173 llvm::LLVMRustPrintPassTimings();
177 cgcx: &CodegenContext<Self>,
178 diag_handler: &Handler,
179 modules: Vec<ModuleCodegen<Self::Module>>,
180 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
181 back::write::link(cgcx, diag_handler, modules)
184 cgcx: &CodegenContext<Self>,
185 modules: Vec<FatLTOInput<Self>>,
186 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
187 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
188 back::lto::run_fat(cgcx, modules, cached_modules)
191 cgcx: &CodegenContext<Self>,
192 modules: Vec<(String, Self::ThinBuffer)>,
193 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
194 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
195 back::lto::run_thin(cgcx, modules, cached_modules)
198 cgcx: &CodegenContext<Self>,
199 diag_handler: &Handler,
200 module: &ModuleCodegen<Self::Module>,
201 config: &ModuleConfig,
202 ) -> Result<(), FatalError> {
203 back::write::optimize(cgcx, diag_handler, module, config)
205 unsafe fn optimize_thin(
206 cgcx: &CodegenContext<Self>,
207 thin: &mut ThinModule<Self>,
208 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
209 back::lto::optimize_thin_module(thin, cgcx)
212 cgcx: &CodegenContext<Self>,
213 diag_handler: &Handler,
214 module: ModuleCodegen<Self::Module>,
215 config: &ModuleConfig,
216 ) -> Result<CompiledModule, FatalError> {
217 back::write::codegen(cgcx, diag_handler, module, config)
219 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
220 back::lto::prepare_thin(module)
222 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
223 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
225 fn run_lto_pass_manager(
226 cgcx: &CodegenContext<Self>,
227 module: &ModuleCodegen<Self::Module>,
228 config: &ModuleConfig,
230 ) -> Result<(), FatalError> {
231 let diag_handler = cgcx.create_diag_handler();
232 back::lto::run_pass_manager(cgcx, &diag_handler, module, config, thin)
236 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
237 unsafe impl Sync for LlvmCodegenBackend {}
239 impl LlvmCodegenBackend {
240 pub fn new() -> Box<dyn CodegenBackend> {
241 Box::new(LlvmCodegenBackend(()))
245 impl CodegenBackend for LlvmCodegenBackend {
246 fn init(&self, sess: &Session) {
247 llvm_util::init(sess); // Make sure llvm is inited
250 fn print(&self, req: PrintRequest, sess: &Session) {
252 PrintRequest::RelocationModels => {
253 println!("Available relocation models:");
264 println!(" {}", name);
268 PrintRequest::CodeModels => {
269 println!("Available code models:");
270 for name in &["tiny", "small", "kernel", "medium", "large"] {
271 println!(" {}", name);
275 PrintRequest::TlsModels => {
276 println!("Available TLS models:");
277 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
278 println!(" {}", name);
282 PrintRequest::StackProtectorStrategies => {
284 r#"Available stack protector strategies:
286 Generate stack canaries in all functions.
289 Generate stack canaries in a function if it either:
290 - has a local variable of `[T; N]` type, regardless of `T` and `N`
291 - takes the address of a local variable.
293 (Note that a local variable being borrowed is not equivalent to its
294 address being taken: e.g. some borrows may be removed by optimization,
295 while by-value argument passing may be implemented with reference to a
296 local stack variable in the ABI.)
299 Generate stack canaries in functions with:
300 - local variables of `[T; N]` type, where `T` is byte-sized and `N` > 8.
303 Do not generate stack canaries.
307 req => llvm_util::print(req, sess),
311 fn print_passes(&self) {
312 llvm_util::print_passes();
315 fn print_version(&self) {
316 llvm_util::print_version();
319 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
320 target_features(sess)
323 fn codegen_crate<'tcx>(
326 metadata: EncodedMetadata,
327 need_metadata_module: bool,
329 Box::new(rustc_codegen_ssa::base::codegen_crate(
330 LlvmCodegenBackend(()),
332 crate::llvm_util::target_cpu(tcx.sess).to_string(),
334 need_metadata_module,
340 ongoing_codegen: Box<dyn Any>,
342 outputs: &OutputFilenames,
343 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
344 let (codegen_results, work_products) = ongoing_codegen
345 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
346 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
349 sess.time("llvm_dump_timing_file", || {
350 if sess.opts.debugging_opts.llvm_time_trace {
351 let file_name = outputs.with_extension("llvm_timings.json");
352 llvm_util::time_trace_profiler_finish(&file_name);
356 Ok((codegen_results, work_products))
362 codegen_results: CodegenResults,
363 outputs: &OutputFilenames,
364 ) -> Result<(), ErrorReported> {
365 use crate::back::archive::LlvmArchiveBuilder;
366 use rustc_codegen_ssa::back::link::link_binary;
368 // Run the linker on any artifacts that resulted from the LLVM run.
369 // This should produce either a finished executable or library.
370 link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
374 pub struct ModuleLlvm {
375 llcx: &'static mut llvm::Context,
376 llmod_raw: *const llvm::Module,
377 tm: &'static mut llvm::TargetMachine,
380 unsafe impl Send for ModuleLlvm {}
381 unsafe impl Sync for ModuleLlvm {}
384 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
386 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
387 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
388 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
392 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
394 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
395 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
396 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
401 cgcx: &CodegenContext<LlvmCodegenBackend>,
405 ) -> Result<Self, FatalError> {
407 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
408 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
409 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
410 let tm = match (cgcx.tm_factory)(tm_factory_config) {
413 handler.struct_err(&e).emit();
414 return Err(FatalError);
418 Ok(ModuleLlvm { llmod_raw, llcx, tm })
422 fn llmod(&self) -> &llvm::Module {
423 unsafe { &*self.llmod_raw }
427 impl Drop for ModuleLlvm {
430 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
431 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));