rustc_codegen_llvm/back/
owned_target_machine.rs

1use std::ffi::{CStr, c_char};
2use std::marker::PhantomData;
3use std::ptr::NonNull;
4
5use rustc_data_structures::small_c_str::SmallCStr;
6
7use crate::errors::LlvmError;
8use crate::llvm;
9
10/// Responsible for safely creating and disposing llvm::TargetMachine via ffi functions.
11/// Not cloneable as there is no clone function for llvm::TargetMachine.
12#[repr(transparent)]
13pub struct OwnedTargetMachine {
14    tm_unique: NonNull<llvm::TargetMachine>,
15    phantom: PhantomData<llvm::TargetMachine>,
16}
17
18impl OwnedTargetMachine {
19    pub(crate) fn new(
20        triple: &CStr,
21        cpu: &CStr,
22        features: &CStr,
23        abi: &CStr,
24        model: llvm::CodeModel,
25        reloc: llvm::RelocModel,
26        level: llvm::CodeGenOptLevel,
27        float_abi: llvm::FloatAbi,
28        function_sections: bool,
29        data_sections: bool,
30        unique_section_names: bool,
31        trap_unreachable: bool,
32        singlethread: bool,
33        verbose_asm: bool,
34        emit_stack_size_section: bool,
35        relax_elf_relocations: bool,
36        use_init_array: bool,
37        split_dwarf_file: &CStr,
38        output_obj_file: &CStr,
39        debug_info_compression: &CStr,
40        use_emulated_tls: bool,
41        args_cstr_buff: &[u8],
42        use_wasm_eh: bool,
43    ) -> Result<Self, LlvmError<'static>> {
44        assert!(args_cstr_buff.len() > 0);
45        assert!(
46            *args_cstr_buff.last().unwrap() == 0,
47            "The last character must be a null terminator."
48        );
49
50        // SAFETY: llvm::LLVMRustCreateTargetMachine copies pointed to data
51        let tm_ptr = unsafe {
52            llvm::LLVMRustCreateTargetMachine(
53                triple.as_ptr(),
54                cpu.as_ptr(),
55                features.as_ptr(),
56                abi.as_ptr(),
57                model,
58                reloc,
59                level,
60                float_abi,
61                function_sections,
62                data_sections,
63                unique_section_names,
64                trap_unreachable,
65                singlethread,
66                verbose_asm,
67                emit_stack_size_section,
68                relax_elf_relocations,
69                use_init_array,
70                split_dwarf_file.as_ptr(),
71                output_obj_file.as_ptr(),
72                debug_info_compression.as_ptr(),
73                use_emulated_tls,
74                args_cstr_buff.as_ptr() as *const c_char,
75                args_cstr_buff.len(),
76                use_wasm_eh,
77            )
78        };
79
80        NonNull::new(tm_ptr)
81            .map(|tm_unique| Self { tm_unique, phantom: PhantomData })
82            .ok_or_else(|| LlvmError::CreateTargetMachine { triple: SmallCStr::from(triple) })
83    }
84
85    /// Returns inner `llvm::TargetMachine` type.
86    ///
87    /// This could be a `Deref` implementation, but `llvm::TargetMachine` is an extern type and
88    /// `Deref::Target: ?Sized`.
89    pub fn raw(&self) -> &llvm::TargetMachine {
90        // SAFETY: constructing ensures we have a valid pointer created by
91        // llvm::LLVMRustCreateTargetMachine.
92        unsafe { self.tm_unique.as_ref() }
93    }
94}
95
96impl Drop for OwnedTargetMachine {
97    fn drop(&mut self) {
98        // SAFETY: constructing ensures we have a valid pointer created by
99        // llvm::LLVMRustCreateTargetMachine OwnedTargetMachine is not copyable so there is no
100        // double free or use after free.
101        unsafe {
102            llvm::LLVMRustDisposeTargetMachine(self.tm_unique.as_mut());
103        }
104    }
105}