[go: up one dir, main page]

rustc_codegen_llvm/
lib.rs

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