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(hash_raw_entry)]
9 #![feature(let_chains)]
10 #![feature(extern_types)]
11 #![feature(once_cell)]
12 #![feature(iter_intersperse)]
13 #![recursion_limit = "256"]
14 #![allow(rustc::potential_query_instability)]
17 extern crate rustc_macros;
21 use back::write::{create_informational_target_machine, create_target_machine};
23 pub use llvm_util::target_features;
24 use rustc_ast::expand::allocator::AllocatorKind;
25 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
26 use rustc_codegen_ssa::back::write::{
27 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
29 use rustc_codegen_ssa::traits::*;
30 use rustc_codegen_ssa::ModuleCodegen;
31 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
32 use rustc_data_structures::fx::FxHashMap;
33 use rustc_errors::{ErrorGuaranteed, FatalError, Handler};
34 use rustc_metadata::EncodedMetadata;
35 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
36 use rustc_middle::ty::query::Providers;
37 use rustc_middle::ty::TyCtxt;
38 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
39 use rustc_session::Session;
40 use rustc_span::symbol::Symbol;
67 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
68 #[path = "llvm/mod.rs"]
71 pub use super::llvm_::*;
82 pub struct LlvmCodegenBackend(());
84 struct TimeTraceProfiler {
88 impl TimeTraceProfiler {
89 fn new(enabled: bool) -> Self {
91 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
93 TimeTraceProfiler { enabled }
97 impl Drop for TimeTraceProfiler {
100 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
105 impl ExtraBackendMethods for LlvmCodegenBackend {
106 fn codegen_allocator<'tcx>(
111 alloc_error_handler_kind: AllocatorKind,
113 let mut module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
115 allocator::codegen(tcx, &mut module_llvm, module_name, kind, alloc_error_handler_kind);
119 fn compile_codegen_unit(
123 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
124 base::compile_codegen_unit(tcx, cgu_name)
126 fn target_machine_factory(
130 target_features: &[String],
131 ) -> TargetMachineFactoryFn<Self> {
132 back::write::target_machine_factory(sess, optlvl, target_features)
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 TargetMachine = &'static mut llvm::TargetMachine;
168 type ThinData = back::lto::ThinData;
169 type ThinBuffer = back::lto::ThinBuffer;
170 fn print_pass_timings(&self) {
172 llvm::LLVMRustPrintPassTimings();
176 cgcx: &CodegenContext<Self>,
177 diag_handler: &Handler,
178 modules: Vec<ModuleCodegen<Self::Module>>,
179 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
180 back::write::link(cgcx, diag_handler, modules)
183 cgcx: &CodegenContext<Self>,
184 modules: Vec<FatLTOInput<Self>>,
185 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
186 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
187 back::lto::run_fat(cgcx, modules, cached_modules)
190 cgcx: &CodegenContext<Self>,
191 modules: Vec<(String, Self::ThinBuffer)>,
192 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
193 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
194 back::lto::run_thin(cgcx, modules, cached_modules)
197 cgcx: &CodegenContext<Self>,
198 diag_handler: &Handler,
199 module: &ModuleCodegen<Self::Module>,
200 config: &ModuleConfig,
201 ) -> Result<(), FatalError> {
202 back::write::optimize(cgcx, diag_handler, module, config)
205 cgcx: &CodegenContext<Self>,
206 module: &mut ModuleCodegen<Self::Module>,
207 ) -> Result<(), FatalError> {
208 let diag_handler = cgcx.create_diag_handler();
209 back::lto::run_pass_manager(cgcx, &diag_handler, module, false)
211 unsafe fn optimize_thin(
212 cgcx: &CodegenContext<Self>,
213 thin: ThinModule<Self>,
214 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
215 back::lto::optimize_thin_module(thin, cgcx)
218 cgcx: &CodegenContext<Self>,
219 diag_handler: &Handler,
220 module: ModuleCodegen<Self::Module>,
221 config: &ModuleConfig,
222 ) -> Result<CompiledModule, FatalError> {
223 back::write::codegen(cgcx, diag_handler, module, config)
225 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
226 back::lto::prepare_thin(module)
228 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
229 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
233 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
234 unsafe impl Sync for LlvmCodegenBackend {}
236 impl LlvmCodegenBackend {
237 pub fn new() -> Box<dyn CodegenBackend> {
238 Box::new(LlvmCodegenBackend(()))
242 impl CodegenBackend for LlvmCodegenBackend {
243 fn init(&self, sess: &Session) {
244 llvm_util::init(sess); // Make sure llvm is inited
247 fn provide(&self, providers: &mut Providers) {
248 providers.global_backend_features =
249 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
252 fn print(&self, req: PrintRequest, sess: &Session) {
254 PrintRequest::RelocationModels => {
255 println!("Available relocation models:");
266 println!(" {}", name);
270 PrintRequest::CodeModels => {
271 println!("Available code models:");
272 for name in &["tiny", "small", "kernel", "medium", "large"] {
273 println!(" {}", name);
277 PrintRequest::TlsModels => {
278 println!("Available TLS models:");
279 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
280 println!(" {}", name);
284 PrintRequest::StackProtectorStrategies => {
286 r#"Available stack protector strategies:
288 Generate stack canaries in all functions.
291 Generate stack canaries in a function if it either:
292 - has a local variable of `[T; N]` type, regardless of `T` and `N`
293 - takes the address of a local variable.
295 (Note that a local variable being borrowed is not equivalent to its
296 address being taken: e.g. some borrows may be removed by optimization,
297 while by-value argument passing may be implemented with reference to a
298 local stack variable in the ABI.)
301 Generate stack canaries in functions with local variables of `[T; N]`
302 type, where `T` is byte-sized and `N` >= 8.
305 Do not generate stack canaries.
309 req => llvm_util::print(req, sess),
313 fn print_passes(&self) {
314 llvm_util::print_passes();
317 fn print_version(&self) {
318 llvm_util::print_version();
321 fn target_features(&self, sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
322 target_features(sess, allow_unstable)
325 fn codegen_crate<'tcx>(
328 metadata: EncodedMetadata,
329 need_metadata_module: bool,
331 Box::new(rustc_codegen_ssa::base::codegen_crate(
332 LlvmCodegenBackend(()),
334 crate::llvm_util::target_cpu(tcx.sess).to_string(),
336 need_metadata_module,
342 ongoing_codegen: Box<dyn Any>,
344 outputs: &OutputFilenames,
345 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
346 let (codegen_results, work_products) = ongoing_codegen
347 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
348 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
351 sess.time("llvm_dump_timing_file", || {
352 if sess.opts.unstable_opts.llvm_time_trace {
353 let file_name = outputs.with_extension("llvm_timings.json");
354 llvm_util::time_trace_profiler_finish(&file_name);
358 Ok((codegen_results, work_products))
364 codegen_results: CodegenResults,
365 outputs: &OutputFilenames,
366 ) -> Result<(), ErrorGuaranteed> {
367 use crate::back::archive::LlvmArchiveBuilderBuilder;
368 use rustc_codegen_ssa::back::link::link_binary;
370 // Run the linker on any artifacts that resulted from the LLVM run.
371 // This should produce either a finished executable or library.
372 link_binary(sess, &LlvmArchiveBuilderBuilder, &codegen_results, outputs)
376 pub struct ModuleLlvm {
377 llcx: &'static mut llvm::Context,
378 llmod_raw: *const llvm::Module,
379 tm: &'static mut llvm::TargetMachine,
382 unsafe impl Send for ModuleLlvm {}
383 unsafe impl Sync for ModuleLlvm {}
386 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
388 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
389 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
390 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
394 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
396 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
397 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
398 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
403 cgcx: &CodegenContext<LlvmCodegenBackend>,
407 ) -> Result<Self, FatalError> {
409 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
410 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
411 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
412 let tm = match (cgcx.tm_factory)(tm_factory_config) {
415 handler.struct_err(&e).emit();
416 return Err(FatalError);
420 Ok(ModuleLlvm { llmod_raw, llcx, tm })
424 fn llmod(&self) -> &llvm::Module {
425 unsafe { &*self.llmod_raw }
429 impl Drop for ModuleLlvm {
432 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
433 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));