1#![feature(assert_matches)]
9#![feature(extern_types)]
10#![feature(file_buffered)]
11#![feature(if_let_guard)]
12#![feature(impl_trait_in_assoc_type)]
13#![feature(iter_intersperse)]
14#![feature(macro_derive)]
15#![feature(once_cell_try)]
16#![feature(trim_prefix_suffix)]
17#![feature(try_blocks)]
18use std::any::Any;
21use std::ffi::CStr;
22use std::mem::ManuallyDrop;
23use std::path::PathBuf;
24
25use back::owned_target_machine::OwnedTargetMachine;
26use back::write::{create_informational_target_machine, create_target_machine};
27use context::SimpleCx;
28use errors::ParseTargetMachineConfig;
29use llvm_util::target_config;
30use rustc_ast::expand::allocator::AllocatorMethod;
31use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
32use rustc_codegen_ssa::back::write::{
33 CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
34};
35use rustc_codegen_ssa::traits::*;
36use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen, TargetConfig};
37use rustc_data_structures::fx::FxIndexMap;
38use rustc_errors::DiagCtxtHandle;
39use rustc_metadata::EncodedMetadata;
40use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
41use rustc_middle::ty::TyCtxt;
42use rustc_middle::util::Providers;
43use rustc_session::Session;
44use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
45use rustc_span::Symbol;
46use rustc_target::spec::{RelocModel, TlsModel};
47
48use crate::llvm::ToLlvmBool;
49
50mod abi;
51mod allocator;
52mod asm;
53mod attributes;
54mod back;
55mod base;
56mod builder;
57mod callee;
58mod common;
59mod consts;
60mod context;
61mod coverageinfo;
62mod debuginfo;
63mod declare;
64mod errors;
65mod intrinsic;
66mod llvm;
67mod llvm_util;
68mod macros;
69mod mono_item;
70mod type_;
71mod type_of;
72mod typetree;
73mod va_arg;
74mod value;
75
76rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
77
78pub(crate) use macros::TryFromU32;
79
80#[derive(Clone)]
81pub struct LlvmCodegenBackend(());
82
83struct TimeTraceProfiler {
84 enabled: bool,
85}
86
87impl TimeTraceProfiler {
88 fn new(enabled: bool) -> Self {
89 if enabled {
90 unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
91 }
92 TimeTraceProfiler { enabled }
93 }
94}
95
96impl Drop for TimeTraceProfiler {
97 fn drop(&mut self) {
98 if self.enabled {
99 unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
100 }
101 }
102}
103
104impl ExtraBackendMethods for LlvmCodegenBackend {
105 fn codegen_allocator<'tcx>(
106 &self,
107 tcx: TyCtxt<'tcx>,
108 module_name: &str,
109 methods: &[AllocatorMethod],
110 ) -> ModuleLlvm {
111 let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
112 let cx =
113 SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
114 unsafe {
115 allocator::codegen(tcx, cx, module_name, methods);
116 }
117 module_llvm
118 }
119 fn compile_codegen_unit(
120 &self,
121 tcx: TyCtxt<'_>,
122 cgu_name: Symbol,
123 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
124 base::compile_codegen_unit(tcx, cgu_name)
125 }
126 fn target_machine_factory(
127 &self,
128 sess: &Session,
129 optlvl: OptLevel,
130 target_features: &[String],
131 ) -> TargetMachineFactoryFn<Self> {
132 back::write::target_machine_factory(sess, optlvl, target_features)
133 }
134
135 fn spawn_named_thread<F, T>(
136 time_trace: bool,
137 name: String,
138 f: F,
139 ) -> std::io::Result<std::thread::JoinHandle<T>>
140 where
141 F: FnOnce() -> T,
142 F: Send + 'static,
143 T: Send + 'static,
144 {
145 std::thread::Builder::new().name(name).spawn(move || {
146 let _profiler = TimeTraceProfiler::new(time_trace);
147 f()
148 })
149 }
150}
151
152impl WriteBackendMethods for LlvmCodegenBackend {
153 type Module = ModuleLlvm;
154 type ModuleBuffer = back::lto::ModuleBuffer;
155 type TargetMachine = OwnedTargetMachine;
156 type TargetMachineError = crate::errors::LlvmError<'static>;
157 type ThinData = back::lto::ThinData;
158 type ThinBuffer = back::lto::ThinBuffer;
159 fn print_pass_timings(&self) {
160 let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
161 print!("{timings}");
162 }
163 fn print_statistics(&self) {
164 let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
165 print!("{stats}");
166 }
167 fn run_and_optimize_fat_lto(
168 cgcx: &CodegenContext<Self>,
169 exported_symbols_for_lto: &[String],
170 each_linked_rlib_for_lto: &[PathBuf],
171 modules: Vec<FatLtoInput<Self>>,
172 ) -> ModuleCodegen<Self::Module> {
173 let mut module =
174 back::lto::run_fat(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, modules);
175
176 let dcx = cgcx.create_dcx();
177 let dcx = dcx.handle();
178 back::lto::run_pass_manager(cgcx, dcx, &mut module, false);
179
180 module
181 }
182 fn run_thin_lto(
183 cgcx: &CodegenContext<Self>,
184 exported_symbols_for_lto: &[String],
185 each_linked_rlib_for_lto: &[PathBuf],
186 modules: Vec<(String, Self::ThinBuffer)>,
187 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
188 ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
189 back::lto::run_thin(
190 cgcx,
191 exported_symbols_for_lto,
192 each_linked_rlib_for_lto,
193 modules,
194 cached_modules,
195 )
196 }
197 fn optimize(
198 cgcx: &CodegenContext<Self>,
199 dcx: DiagCtxtHandle<'_>,
200 module: &mut ModuleCodegen<Self::Module>,
201 config: &ModuleConfig,
202 ) {
203 back::write::optimize(cgcx, dcx, module, config)
204 }
205 fn optimize_thin(
206 cgcx: &CodegenContext<Self>,
207 thin: ThinModule<Self>,
208 ) -> ModuleCodegen<Self::Module> {
209 back::lto::optimize_thin_module(thin, cgcx)
210 }
211 fn codegen(
212 cgcx: &CodegenContext<Self>,
213 module: ModuleCodegen<Self::Module>,
214 config: &ModuleConfig,
215 ) -> CompiledModule {
216 back::write::codegen(cgcx, module, config)
217 }
218 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
219 back::lto::prepare_thin(module)
220 }
221 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
222 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
223 }
224}
225
226impl LlvmCodegenBackend {
227 pub fn new() -> Box<dyn CodegenBackend> {
228 Box::new(LlvmCodegenBackend(()))
229 }
230}
231
232impl CodegenBackend for LlvmCodegenBackend {
233 fn locale_resource(&self) -> &'static str {
234 crate::DEFAULT_LOCALE_RESOURCE
235 }
236
237 fn name(&self) -> &'static str {
238 "llvm"
239 }
240
241 fn init(&self, sess: &Session) {
242 llvm_util::init(sess); {
248 use rustc_session::config::AutoDiff;
249
250 use crate::back::lto::enable_autodiff_settings;
251 if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
252 match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
253 Ok(_) => {}
254 Err(llvm::EnzymeLibraryError::NotFound { err }) => {
255 sess.dcx().emit_fatal(crate::errors::AutoDiffComponentMissing { err });
256 }
257 Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
258 sess.dcx().emit_fatal(crate::errors::AutoDiffComponentUnavailable { err });
259 }
260 }
261 enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
262 }
263 }
264 }
265
266 fn provide(&self, providers: &mut Providers) {
267 providers.global_backend_features =
268 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, false)
269 }
270
271 fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
272 use std::fmt::Write;
273 match req.kind {
274 PrintKind::RelocationModels => {
275 writeln!(out, "Available relocation models:").unwrap();
276 for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
277 writeln!(out, " {name}").unwrap();
278 }
279 writeln!(out).unwrap();
280 }
281 PrintKind::CodeModels => {
282 writeln!(out, "Available code models:").unwrap();
283 for name in &["tiny", "small", "kernel", "medium", "large"] {
284 writeln!(out, " {name}").unwrap();
285 }
286 writeln!(out).unwrap();
287 }
288 PrintKind::TlsModels => {
289 writeln!(out, "Available TLS models:").unwrap();
290 for name in TlsModel::ALL.iter().map(TlsModel::desc) {
291 writeln!(out, " {name}").unwrap();
292 }
293 writeln!(out).unwrap();
294 }
295 PrintKind::StackProtectorStrategies => {
296 writeln!(
297 out,
298 r#"Available stack protector strategies:
299 all
300 Generate stack canaries in all functions.
301
302 strong
303 Generate stack canaries in a function if it either:
304 - has a local variable of `[T; N]` type, regardless of `T` and `N`
305 - takes the address of a local variable.
306
307 (Note that a local variable being borrowed is not equivalent to its
308 address being taken: e.g. some borrows may be removed by optimization,
309 while by-value argument passing may be implemented with reference to a
310 local stack variable in the ABI.)
311
312 basic
313 Generate stack canaries in functions with local variables of `[T; N]`
314 type, where `T` is byte-sized and `N` >= 8.
315
316 none
317 Do not generate stack canaries.
318"#
319 )
320 .unwrap();
321 }
322 _other => llvm_util::print(req, out, sess),
323 }
324 }
325
326 fn print_passes(&self) {
327 llvm_util::print_passes();
328 }
329
330 fn print_version(&self) {
331 llvm_util::print_version();
332 }
333
334 fn has_zstd(&self) -> bool {
335 llvm::LLVMRustLLVMHasZstdCompression()
336 }
337
338 fn target_config(&self, sess: &Session) -> TargetConfig {
339 target_config(sess)
340 }
341
342 fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
343 Box::new(rustc_codegen_ssa::base::codegen_crate(
344 LlvmCodegenBackend(()),
345 tcx,
346 crate::llvm_util::target_cpu(tcx.sess).to_string(),
347 ))
348 }
349
350 fn join_codegen(
351 &self,
352 ongoing_codegen: Box<dyn Any>,
353 sess: &Session,
354 outputs: &OutputFilenames,
355 ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
356 let (codegen_results, work_products) = ongoing_codegen
357 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
358 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
359 .join(sess);
360
361 if sess.opts.unstable_opts.llvm_time_trace {
362 sess.time("llvm_dump_timing_file", || {
363 let file_name = outputs.with_extension("llvm_timings.json");
364 llvm_util::time_trace_profiler_finish(&file_name);
365 });
366 }
367
368 (codegen_results, work_products)
369 }
370
371 fn link(
372 &self,
373 sess: &Session,
374 codegen_results: CodegenResults,
375 metadata: EncodedMetadata,
376 outputs: &OutputFilenames,
377 ) {
378 use rustc_codegen_ssa::back::link::link_binary;
379
380 use crate::back::archive::LlvmArchiveBuilderBuilder;
381
382 link_binary(
385 sess,
386 &LlvmArchiveBuilderBuilder,
387 codegen_results,
388 metadata,
389 outputs,
390 self.name(),
391 );
392 }
393}
394
395pub struct ModuleLlvm {
396 llcx: &'static mut llvm::Context,
397 llmod_raw: *const llvm::Module,
398
399 tm: ManuallyDrop<OwnedTargetMachine>,
402}
403
404unsafe impl Send for ModuleLlvm {}
405unsafe impl Sync for ModuleLlvm {}
406
407impl ModuleLlvm {
408 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
409 unsafe {
410 let llcx = llvm::LLVMContextCreate();
411 llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
412 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
413 ModuleLlvm {
414 llmod_raw,
415 llcx,
416 tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
417 }
418 }
419 }
420
421 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
422 unsafe {
423 let llcx = llvm::LLVMContextCreate();
424 llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
425 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
426 ModuleLlvm {
427 llmod_raw,
428 llcx,
429 tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
430 }
431 }
432 }
433
434 fn tm_from_cgcx(
435 cgcx: &CodegenContext<LlvmCodegenBackend>,
436 name: &str,
437 dcx: DiagCtxtHandle<'_>,
438 ) -> OwnedTargetMachine {
439 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name);
440 match (cgcx.tm_factory)(tm_factory_config) {
441 Ok(m) => m,
442 Err(e) => {
443 dcx.emit_fatal(ParseTargetMachineConfig(e));
444 }
445 }
446 }
447
448 fn parse(
449 cgcx: &CodegenContext<LlvmCodegenBackend>,
450 name: &CStr,
451 buffer: &[u8],
452 dcx: DiagCtxtHandle<'_>,
453 ) -> Self {
454 unsafe {
455 let llcx = llvm::LLVMContextCreate();
456 llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
457 let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
458 let tm = ModuleLlvm::tm_from_cgcx(cgcx, name.to_str().unwrap(), dcx);
459
460 ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
461 }
462 }
463
464 fn llmod(&self) -> &llvm::Module {
465 unsafe { &*self.llmod_raw }
466 }
467}
468
469impl Drop for ModuleLlvm {
470 fn drop(&mut self) {
471 unsafe {
472 ManuallyDrop::drop(&mut self.tm);
473 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
474 }
475 }
476}