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)]
11 #![feature(extern_types)]
12 #![feature(once_cell)]
13 #![feature(iter_intersperse)]
14 #![recursion_limit = "256"]
15 #![allow(rustc::potential_query_instability)]
18 extern crate rustc_macros;
22 use back::write::{create_informational_target_machine, create_target_machine};
24 pub use llvm_util::target_features;
25 use rustc_ast::expand::allocator::AllocatorKind;
26 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
27 use rustc_codegen_ssa::back::write::{
28 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
30 use rustc_codegen_ssa::traits::*;
31 use rustc_codegen_ssa::ModuleCodegen;
32 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
33 use rustc_data_structures::fx::FxHashMap;
34 use rustc_errors::{ErrorGuaranteed, FatalError, Handler};
35 use rustc_metadata::EncodedMetadata;
36 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
37 use rustc_middle::ty::query::Providers;
38 use rustc_middle::ty::TyCtxt;
39 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
40 use rustc_session::Session;
41 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 has_alloc_error_handler: bool,
114 let mut module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
116 allocator::codegen(tcx, &mut module_llvm, module_name, kind, has_alloc_error_handler);
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)
135 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
136 llvm_util::target_cpu(sess)
138 fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
139 llvm_util::tune_cpu(sess)
142 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
148 std::thread::spawn(move || {
149 let _profiler = TimeTraceProfiler::new(time_trace);
154 fn spawn_named_thread<F, T>(
158 ) -> std::io::Result<std::thread::JoinHandle<T>>
164 std::thread::Builder::new().name(name).spawn(move || {
165 let _profiler = TimeTraceProfiler::new(time_trace);
171 impl WriteBackendMethods for LlvmCodegenBackend {
172 type Module = ModuleLlvm;
173 type ModuleBuffer = back::lto::ModuleBuffer;
174 type Context = llvm::Context;
175 type TargetMachine = &'static mut llvm::TargetMachine;
176 type ThinData = back::lto::ThinData;
177 type ThinBuffer = back::lto::ThinBuffer;
178 fn print_pass_timings(&self) {
180 llvm::LLVMRustPrintPassTimings();
184 cgcx: &CodegenContext<Self>,
185 diag_handler: &Handler,
186 modules: Vec<ModuleCodegen<Self::Module>>,
187 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
188 back::write::link(cgcx, diag_handler, modules)
191 cgcx: &CodegenContext<Self>,
192 modules: Vec<FatLTOInput<Self>>,
193 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
194 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
195 back::lto::run_fat(cgcx, modules, cached_modules)
198 cgcx: &CodegenContext<Self>,
199 modules: Vec<(String, Self::ThinBuffer)>,
200 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
201 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
202 back::lto::run_thin(cgcx, modules, cached_modules)
205 cgcx: &CodegenContext<Self>,
206 diag_handler: &Handler,
207 module: &ModuleCodegen<Self::Module>,
208 config: &ModuleConfig,
209 ) -> Result<(), FatalError> {
210 back::write::optimize(cgcx, diag_handler, module, config)
213 cgcx: &CodegenContext<Self>,
214 module: &mut ModuleCodegen<Self::Module>,
215 ) -> Result<(), FatalError> {
216 let diag_handler = cgcx.create_diag_handler();
217 back::lto::run_pass_manager(cgcx, &diag_handler, module, false)
219 unsafe fn optimize_thin(
220 cgcx: &CodegenContext<Self>,
221 thin: ThinModule<Self>,
222 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
223 back::lto::optimize_thin_module(thin, cgcx)
226 cgcx: &CodegenContext<Self>,
227 diag_handler: &Handler,
228 module: ModuleCodegen<Self::Module>,
229 config: &ModuleConfig,
230 ) -> Result<CompiledModule, FatalError> {
231 back::write::codegen(cgcx, diag_handler, module, config)
233 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
234 back::lto::prepare_thin(module)
236 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
237 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
241 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
242 unsafe impl Sync for LlvmCodegenBackend {}
244 impl LlvmCodegenBackend {
245 pub fn new() -> Box<dyn CodegenBackend> {
246 Box::new(LlvmCodegenBackend(()))
250 impl CodegenBackend for LlvmCodegenBackend {
251 fn init(&self, sess: &Session) {
252 llvm_util::init(sess); // Make sure llvm is inited
255 fn provide(&self, providers: &mut Providers) {
256 providers.global_backend_features =
257 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
260 fn print(&self, req: PrintRequest, sess: &Session) {
262 PrintRequest::RelocationModels => {
263 println!("Available relocation models:");
274 println!(" {}", name);
278 PrintRequest::CodeModels => {
279 println!("Available code models:");
280 for name in &["tiny", "small", "kernel", "medium", "large"] {
281 println!(" {}", name);
285 PrintRequest::TlsModels => {
286 println!("Available TLS models:");
287 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
288 println!(" {}", name);
292 PrintRequest::StackProtectorStrategies => {
294 r#"Available stack protector strategies:
296 Generate stack canaries in all functions.
299 Generate stack canaries in a function if it either:
300 - has a local variable of `[T; N]` type, regardless of `T` and `N`
301 - takes the address of a local variable.
303 (Note that a local variable being borrowed is not equivalent to its
304 address being taken: e.g. some borrows may be removed by optimization,
305 while by-value argument passing may be implemented with reference to a
306 local stack variable in the ABI.)
309 Generate stack canaries in functions with local variables of `[T; N]`
310 type, where `T` is byte-sized and `N` >= 8.
313 Do not generate stack canaries.
317 req => llvm_util::print(req, sess),
321 fn print_passes(&self) {
322 llvm_util::print_passes();
325 fn print_version(&self) {
326 llvm_util::print_version();
329 fn target_features(&self, sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
330 target_features(sess, allow_unstable)
333 fn codegen_crate<'tcx>(
336 metadata: EncodedMetadata,
337 need_metadata_module: bool,
339 Box::new(rustc_codegen_ssa::base::codegen_crate(
340 LlvmCodegenBackend(()),
342 crate::llvm_util::target_cpu(tcx.sess).to_string(),
344 need_metadata_module,
350 ongoing_codegen: Box<dyn Any>,
352 outputs: &OutputFilenames,
353 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
354 let (codegen_results, work_products) = ongoing_codegen
355 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
356 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
359 sess.time("llvm_dump_timing_file", || {
360 if sess.opts.unstable_opts.llvm_time_trace {
361 let file_name = outputs.with_extension("llvm_timings.json");
362 llvm_util::time_trace_profiler_finish(&file_name);
366 Ok((codegen_results, work_products))
372 codegen_results: CodegenResults,
373 outputs: &OutputFilenames,
374 ) -> Result<(), ErrorGuaranteed> {
375 use crate::back::archive::LlvmArchiveBuilderBuilder;
376 use rustc_codegen_ssa::back::link::link_binary;
378 // Run the linker on any artifacts that resulted from the LLVM run.
379 // This should produce either a finished executable or library.
380 link_binary(sess, &LlvmArchiveBuilderBuilder, &codegen_results, outputs)
384 pub struct ModuleLlvm {
385 llcx: &'static mut llvm::Context,
386 llmod_raw: *const llvm::Module,
387 tm: &'static mut llvm::TargetMachine,
390 unsafe impl Send for ModuleLlvm {}
391 unsafe impl Sync for ModuleLlvm {}
394 fn new(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_target_machine(tcx, mod_name) }
402 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
404 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
405 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
406 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
411 cgcx: &CodegenContext<LlvmCodegenBackend>,
415 ) -> Result<Self, FatalError> {
417 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
418 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
419 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
420 let tm = match (cgcx.tm_factory)(tm_factory_config) {
423 handler.struct_err(&e).emit();
424 return Err(FatalError);
428 Ok(ModuleLlvm { llmod_raw, llcx, tm })
432 fn llmod(&self) -> &llvm::Module {
433 unsafe { &*self.llmod_raw }
437 impl Drop for ModuleLlvm {
440 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
441 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));