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#[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 ) -> Result<Self, LlvmError<'static>> {
43 assert!(args_cstr_buff.len() > 0);
44 assert!(
45 *args_cstr_buff.last().unwrap() == 0,
46 "The last character must be a null terminator."
47 );
48
49 let tm_ptr = unsafe {
51 llvm::LLVMRustCreateTargetMachine(
52 triple.as_ptr(),
53 cpu.as_ptr(),
54 features.as_ptr(),
55 abi.as_ptr(),
56 model,
57 reloc,
58 level,
59 float_abi,
60 function_sections,
61 data_sections,
62 unique_section_names,
63 trap_unreachable,
64 singlethread,
65 verbose_asm,
66 emit_stack_size_section,
67 relax_elf_relocations,
68 use_init_array,
69 split_dwarf_file.as_ptr(),
70 output_obj_file.as_ptr(),
71 debug_info_compression.as_ptr(),
72 use_emulated_tls,
73 args_cstr_buff.as_ptr() as *const c_char,
74 args_cstr_buff.len(),
75 )
76 };
77
78 NonNull::new(tm_ptr)
79 .map(|tm_unique| Self { tm_unique, phantom: PhantomData })
80 .ok_or_else(|| LlvmError::CreateTargetMachine { triple: SmallCStr::from(triple) })
81 }
82
83 pub fn raw(&self) -> &llvm::TargetMachine {
88 unsafe { self.tm_unique.as_ref() }
91 }
92}
93
94impl Drop for OwnedTargetMachine {
95 fn drop(&mut self) {
96 unsafe {
100 llvm::LLVMRustDisposeTargetMachine(self.tm_unique.as_mut());
101 }
102 }
103}