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;
68 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
69 #[path = "llvm/mod.rs"]
72 pub use super::llvm_::*;
83 pub struct LlvmCodegenBackend(());
85 struct TimeTraceProfiler {
89 impl TimeTraceProfiler {
90 fn new(enabled: bool) -> Self {
92 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
94 TimeTraceProfiler { enabled }
98 impl Drop for TimeTraceProfiler {
101 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
106 impl ExtraBackendMethods for LlvmCodegenBackend {
107 fn codegen_allocator<'tcx>(
112 alloc_error_handler_kind: AllocatorKind,
114 let mut module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
116 allocator::codegen(tcx, &mut module_llvm, module_name, kind, alloc_error_handler_kind);
120 fn compile_codegen_unit(
124 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
125 base::compile_codegen_unit(tcx, cgu_name)
127 fn target_machine_factory(
131 target_features: &[String],
132 ) -> TargetMachineFactoryFn<Self> {
133 back::write::target_machine_factory(sess, optlvl, target_features)
136 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
142 std::thread::spawn(move || {
143 let _profiler = TimeTraceProfiler::new(time_trace);
148 fn spawn_named_thread<F, T>(
152 ) -> std::io::Result<std::thread::JoinHandle<T>>
158 std::thread::Builder::new().name(name).spawn(move || {
159 let _profiler = TimeTraceProfiler::new(time_trace);
165 impl WriteBackendMethods for LlvmCodegenBackend {
166 type Module = ModuleLlvm;
167 type ModuleBuffer = back::lto::ModuleBuffer;
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)
206 cgcx: &CodegenContext<Self>,
207 module: &mut ModuleCodegen<Self::Module>,
208 ) -> Result<(), FatalError> {
209 let diag_handler = cgcx.create_diag_handler();
210 back::lto::run_pass_manager(cgcx, &diag_handler, module, false)
212 unsafe fn optimize_thin(
213 cgcx: &CodegenContext<Self>,
214 thin: ThinModule<Self>,
215 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
216 back::lto::optimize_thin_module(thin, cgcx)
219 cgcx: &CodegenContext<Self>,
220 diag_handler: &Handler,
221 module: ModuleCodegen<Self::Module>,
222 config: &ModuleConfig,
223 ) -> Result<CompiledModule, FatalError> {
224 back::write::codegen(cgcx, diag_handler, module, config)
226 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
227 back::lto::prepare_thin(module)
229 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
230 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
234 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
235 unsafe impl Sync for LlvmCodegenBackend {}
237 impl LlvmCodegenBackend {
238 pub fn new() -> Box<dyn CodegenBackend> {
239 Box::new(LlvmCodegenBackend(()))
243 impl CodegenBackend for LlvmCodegenBackend {
244 fn init(&self, sess: &Session) {
245 llvm_util::init(sess); // Make sure llvm is inited
248 fn provide(&self, providers: &mut Providers) {
249 providers.global_backend_features =
250 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
253 fn print(&self, req: PrintRequest, sess: &Session) {
255 PrintRequest::RelocationModels => {
256 println!("Available relocation models:");
267 println!(" {}", name);
271 PrintRequest::CodeModels => {
272 println!("Available code models:");
273 for name in &["tiny", "small", "kernel", "medium", "large"] {
274 println!(" {}", name);
278 PrintRequest::TlsModels => {
279 println!("Available TLS models:");
280 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
281 println!(" {}", name);
285 PrintRequest::StackProtectorStrategies => {
287 r#"Available stack protector strategies:
289 Generate stack canaries in all functions.
292 Generate stack canaries in a function if it either:
293 - has a local variable of `[T; N]` type, regardless of `T` and `N`
294 - takes the address of a local variable.
296 (Note that a local variable being borrowed is not equivalent to its
297 address being taken: e.g. some borrows may be removed by optimization,
298 while by-value argument passing may be implemented with reference to a
299 local stack variable in the ABI.)
302 Generate stack canaries in functions with local variables of `[T; N]`
303 type, where `T` is byte-sized and `N` >= 8.
306 Do not generate stack canaries.
310 req => llvm_util::print(req, sess),
314 fn print_passes(&self) {
315 llvm_util::print_passes();
318 fn print_version(&self) {
319 llvm_util::print_version();
322 fn target_features(&self, sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
323 target_features(sess, allow_unstable)
326 fn codegen_crate<'tcx>(
329 metadata: EncodedMetadata,
330 need_metadata_module: bool,
332 Box::new(rustc_codegen_ssa::base::codegen_crate(
333 LlvmCodegenBackend(()),
335 crate::llvm_util::target_cpu(tcx.sess).to_string(),
337 need_metadata_module,
343 ongoing_codegen: Box<dyn Any>,
345 outputs: &OutputFilenames,
346 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
347 let (codegen_results, work_products) = ongoing_codegen
348 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
349 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
352 sess.time("llvm_dump_timing_file", || {
353 if sess.opts.unstable_opts.llvm_time_trace {
354 let file_name = outputs.with_extension("llvm_timings.json");
355 llvm_util::time_trace_profiler_finish(&file_name);
359 Ok((codegen_results, work_products))
365 codegen_results: CodegenResults,
366 outputs: &OutputFilenames,
367 ) -> Result<(), ErrorGuaranteed> {
368 use crate::back::archive::LlvmArchiveBuilderBuilder;
369 use rustc_codegen_ssa::back::link::link_binary;
371 // Run the linker on any artifacts that resulted from the LLVM run.
372 // This should produce either a finished executable or library.
373 link_binary(sess, &LlvmArchiveBuilderBuilder, &codegen_results, outputs)
377 pub struct ModuleLlvm {
378 llcx: &'static mut llvm::Context,
379 llmod_raw: *const llvm::Module,
380 tm: &'static mut llvm::TargetMachine,
383 unsafe impl Send for ModuleLlvm {}
384 unsafe impl Sync for ModuleLlvm {}
387 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
389 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
390 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
391 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
395 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
397 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
398 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
399 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
404 cgcx: &CodegenContext<LlvmCodegenBackend>,
408 ) -> Result<Self, FatalError> {
410 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
411 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
412 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
413 let tm = match (cgcx.tm_factory)(tm_factory_config) {
416 handler.struct_err(&e).emit();
417 return Err(FatalError);
421 Ok(ModuleLlvm { llmod_raw, llcx, tm })
425 fn llmod(&self) -> &llvm::Module {
426 unsafe { &*self.llmod_raw }
430 impl Drop for ModuleLlvm {
433 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
434 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));