rustc_codegen_llvm/llvm/
mod.rs

1#![allow(non_snake_case)]
2
3use std::ffi::{CStr, CString};
4use std::num::NonZero;
5use std::ptr;
6use std::string::FromUtf8Error;
7
8use libc::c_uint;
9use rustc_abi::{Align, Size, WrappingRange};
10use rustc_llvm::RustString;
11
12pub(crate) use self::CallConv::*;
13pub(crate) use self::CodeGenOptSize::*;
14pub(crate) use self::MetadataType::*;
15pub(crate) use self::ffi::*;
16use crate::common::AsCCharPtr;
17
18pub(crate) mod diagnostic;
19pub(crate) mod enzyme_ffi;
20mod ffi;
21
22pub(crate) use self::enzyme_ffi::*;
23
24impl LLVMRustResult {
25    pub(crate) fn into_result(self) -> Result<(), ()> {
26        match self {
27            LLVMRustResult::Success => Ok(()),
28            LLVMRustResult::Failure => Err(()),
29        }
30    }
31}
32
33pub(crate) fn AddFunctionAttributes<'ll>(
34    llfn: &'ll Value,
35    idx: AttributePlace,
36    attrs: &[&'ll Attribute],
37) {
38    unsafe {
39        LLVMRustAddFunctionAttributes(llfn, idx.as_uint(), attrs.as_ptr(), attrs.len());
40    }
41}
42
43pub(crate) fn AddCallSiteAttributes<'ll>(
44    callsite: &'ll Value,
45    idx: AttributePlace,
46    attrs: &[&'ll Attribute],
47) {
48    unsafe {
49        LLVMRustAddCallSiteAttributes(callsite, idx.as_uint(), attrs.as_ptr(), attrs.len());
50    }
51}
52
53pub(crate) fn CreateAttrStringValue<'ll>(
54    llcx: &'ll Context,
55    attr: &str,
56    value: &str,
57) -> &'ll Attribute {
58    unsafe {
59        LLVMCreateStringAttribute(
60            llcx,
61            attr.as_c_char_ptr(),
62            attr.len().try_into().unwrap(),
63            value.as_c_char_ptr(),
64            value.len().try_into().unwrap(),
65        )
66    }
67}
68
69pub(crate) fn CreateAttrString<'ll>(llcx: &'ll Context, attr: &str) -> &'ll Attribute {
70    unsafe {
71        LLVMCreateStringAttribute(
72            llcx,
73            attr.as_c_char_ptr(),
74            attr.len().try_into().unwrap(),
75            std::ptr::null(),
76            0,
77        )
78    }
79}
80
81pub(crate) fn CreateAlignmentAttr(llcx: &Context, bytes: u64) -> &Attribute {
82    unsafe { LLVMRustCreateAlignmentAttr(llcx, bytes) }
83}
84
85pub(crate) fn CreateDereferenceableAttr(llcx: &Context, bytes: u64) -> &Attribute {
86    unsafe { LLVMRustCreateDereferenceableAttr(llcx, bytes) }
87}
88
89pub(crate) fn CreateDereferenceableOrNullAttr(llcx: &Context, bytes: u64) -> &Attribute {
90    unsafe { LLVMRustCreateDereferenceableOrNullAttr(llcx, bytes) }
91}
92
93pub(crate) fn CreateByValAttr<'ll>(llcx: &'ll Context, ty: &'ll Type) -> &'ll Attribute {
94    unsafe { LLVMRustCreateByValAttr(llcx, ty) }
95}
96
97pub(crate) fn CreateStructRetAttr<'ll>(llcx: &'ll Context, ty: &'ll Type) -> &'ll Attribute {
98    unsafe { LLVMRustCreateStructRetAttr(llcx, ty) }
99}
100
101pub(crate) fn CreateUWTableAttr(llcx: &Context, async_: bool) -> &Attribute {
102    unsafe { LLVMRustCreateUWTableAttr(llcx, async_) }
103}
104
105pub(crate) fn CreateAllocSizeAttr(llcx: &Context, size_arg: u32) -> &Attribute {
106    unsafe { LLVMRustCreateAllocSizeAttr(llcx, size_arg) }
107}
108
109pub(crate) fn CreateAllocKindAttr(llcx: &Context, kind_arg: AllocKindFlags) -> &Attribute {
110    unsafe { LLVMRustCreateAllocKindAttr(llcx, kind_arg.bits()) }
111}
112
113pub(crate) fn CreateRangeAttr(llcx: &Context, size: Size, range: WrappingRange) -> &Attribute {
114    let lower = range.start;
115    let upper = range.end.wrapping_add(1);
116    let lower_words = [lower as u64, (lower >> 64) as u64];
117    let upper_words = [upper as u64, (upper >> 64) as u64];
118    unsafe {
119        LLVMRustCreateRangeAttribute(
120            llcx,
121            size.bits().try_into().unwrap(),
122            lower_words.as_ptr(),
123            upper_words.as_ptr(),
124        )
125    }
126}
127
128#[derive(Copy, Clone)]
129pub(crate) enum AttributePlace {
130    ReturnValue,
131    Argument(u32),
132    Function,
133}
134
135impl AttributePlace {
136    pub(crate) fn as_uint(self) -> c_uint {
137        match self {
138            AttributePlace::ReturnValue => 0,
139            AttributePlace::Argument(i) => 1 + i,
140            AttributePlace::Function => !0,
141        }
142    }
143}
144
145#[derive(Copy, Clone, PartialEq)]
146#[repr(C)]
147pub(crate) enum CodeGenOptSize {
148    CodeGenOptSizeNone = 0,
149    CodeGenOptSizeDefault = 1,
150    CodeGenOptSizeAggressive = 2,
151}
152
153pub(crate) fn SetInstructionCallConv(instr: &Value, cc: CallConv) {
154    unsafe {
155        LLVMSetInstructionCallConv(instr, cc as c_uint);
156    }
157}
158pub(crate) fn SetFunctionCallConv(fn_: &Value, cc: CallConv) {
159    unsafe {
160        LLVMSetFunctionCallConv(fn_, cc as c_uint);
161    }
162}
163
164// Externally visible symbols that might appear in multiple codegen units need to appear in
165// their own comdat section so that the duplicates can be discarded at link time. This can for
166// example happen for generics when using multiple codegen units. This function simply uses the
167// value's name as the comdat value to make sure that it is in a 1-to-1 relationship to the
168// function.
169// For more details on COMDAT sections see e.g., https://www.airs.com/blog/archives/52
170pub(crate) fn SetUniqueComdat(llmod: &Module, val: &Value) {
171    let name_buf = get_value_name(val);
172    let name =
173        CString::from_vec_with_nul(name_buf).or_else(|buf| CString::new(buf.into_bytes())).unwrap();
174    set_comdat(llmod, val, &name);
175}
176
177pub(crate) fn set_unnamed_address(global: &Value, unnamed: UnnamedAddr) {
178    LLVMSetUnnamedAddress(global, unnamed);
179}
180
181pub(crate) fn set_thread_local_mode(global: &Value, mode: ThreadLocalMode) {
182    unsafe {
183        LLVMSetThreadLocalMode(global, mode);
184    }
185}
186
187impl AttributeKind {
188    /// Create an LLVM Attribute with no associated value.
189    pub(crate) fn create_attr(self, llcx: &Context) -> &Attribute {
190        unsafe { LLVMRustCreateAttrNoValue(llcx, self) }
191    }
192}
193
194impl MemoryEffects {
195    /// Create an LLVM Attribute with these memory effects.
196    pub(crate) fn create_attr(self, llcx: &Context) -> &Attribute {
197        unsafe { LLVMRustCreateMemoryEffectsAttr(llcx, self) }
198    }
199}
200
201pub(crate) fn set_section(llglobal: &Value, section_name: &CStr) {
202    unsafe {
203        LLVMSetSection(llglobal, section_name.as_ptr());
204    }
205}
206
207pub(crate) fn add_global<'a>(llmod: &'a Module, ty: &'a Type, name_cstr: &CStr) -> &'a Value {
208    unsafe { LLVMAddGlobal(llmod, ty, name_cstr.as_ptr()) }
209}
210
211pub(crate) fn set_initializer(llglobal: &Value, constant_val: &Value) {
212    unsafe {
213        LLVMSetInitializer(llglobal, constant_val);
214    }
215}
216
217pub(crate) fn set_global_constant(llglobal: &Value, is_constant: bool) {
218    LLVMSetGlobalConstant(llglobal, if is_constant { ffi::True } else { ffi::False });
219}
220
221pub(crate) fn get_linkage(llglobal: &Value) -> Linkage {
222    unsafe { LLVMGetLinkage(llglobal) }.to_rust()
223}
224
225pub(crate) fn set_linkage(llglobal: &Value, linkage: Linkage) {
226    unsafe {
227        LLVMSetLinkage(llglobal, linkage);
228    }
229}
230
231pub(crate) fn is_declaration(llglobal: &Value) -> bool {
232    unsafe { LLVMIsDeclaration(llglobal) == ffi::True }
233}
234
235pub(crate) fn get_visibility(llglobal: &Value) -> Visibility {
236    unsafe { LLVMGetVisibility(llglobal) }.to_rust()
237}
238
239pub(crate) fn set_visibility(llglobal: &Value, visibility: Visibility) {
240    unsafe {
241        LLVMSetVisibility(llglobal, visibility);
242    }
243}
244
245pub(crate) fn set_alignment(llglobal: &Value, align: Align) {
246    unsafe {
247        ffi::LLVMSetAlignment(llglobal, align.bytes() as c_uint);
248    }
249}
250
251/// Get the `name`d comdat from `llmod` and assign it to `llglobal`.
252///
253/// Inserts the comdat into `llmod` if it does not exist.
254/// It is an error to call this if the target does not support comdat.
255pub(crate) fn set_comdat(llmod: &Module, llglobal: &Value, name: &CStr) {
256    unsafe {
257        let comdat = LLVMGetOrInsertComdat(llmod, name.as_ptr());
258        LLVMSetComdat(llglobal, comdat);
259    }
260}
261
262/// Safe wrapper around `LLVMGetParam`, because segfaults are no fun.
263pub(crate) fn get_param(llfn: &Value, index: c_uint) -> &Value {
264    unsafe {
265        assert!(
266            index < LLVMCountParams(llfn),
267            "out of bounds argument access: {} out of {} arguments",
268            index,
269            LLVMCountParams(llfn)
270        );
271        LLVMGetParam(llfn, index)
272    }
273}
274
275/// Safe wrapper for `LLVMGetValueName2`
276/// Needs to allocate the value, because `set_value_name` will invalidate
277/// the pointer.
278pub(crate) fn get_value_name(value: &Value) -> Vec<u8> {
279    unsafe {
280        let mut len = 0;
281        let data = LLVMGetValueName2(value, &mut len);
282        std::slice::from_raw_parts(data.cast(), len).to_vec()
283    }
284}
285
286#[derive(Debug, Copy, Clone)]
287pub(crate) struct Intrinsic {
288    id: NonZero<c_uint>,
289}
290
291impl Intrinsic {
292    pub(crate) fn lookup(name: &[u8]) -> Option<Self> {
293        let id = unsafe { LLVMLookupIntrinsicID(name.as_c_char_ptr(), name.len()) };
294        NonZero::new(id).map(|id| Self { id })
295    }
296
297    pub(crate) fn get_declaration<'ll>(
298        self,
299        llmod: &'ll Module,
300        type_params: &[&'ll Type],
301    ) -> &'ll Value {
302        unsafe {
303            LLVMGetIntrinsicDeclaration(llmod, self.id, type_params.as_ptr(), type_params.len())
304        }
305    }
306}
307
308/// Safe wrapper for `LLVMSetValueName2` from a byte slice
309pub(crate) fn set_value_name(value: &Value, name: &[u8]) {
310    unsafe {
311        let data = name.as_c_char_ptr();
312        LLVMSetValueName2(value, data, name.len());
313    }
314}
315
316pub(crate) fn build_string(f: impl FnOnce(&RustString)) -> Result<String, FromUtf8Error> {
317    String::from_utf8(RustString::build_byte_buffer(f))
318}
319
320pub(crate) fn build_byte_buffer(f: impl FnOnce(&RustString)) -> Vec<u8> {
321    RustString::build_byte_buffer(f)
322}
323
324pub(crate) fn twine_to_string(tr: &Twine) -> String {
325    unsafe {
326        build_string(|s| LLVMRustWriteTwineToString(tr, s)).expect("got a non-UTF8 Twine from LLVM")
327    }
328}
329
330pub(crate) fn last_error() -> Option<String> {
331    unsafe {
332        let cstr = LLVMRustGetLastError();
333        if cstr.is_null() {
334            None
335        } else {
336            let err = CStr::from_ptr(cstr).to_bytes();
337            let err = String::from_utf8_lossy(err).to_string();
338            libc::free(cstr as *mut _);
339            Some(err)
340        }
341    }
342}
343
344/// Owning pointer to an [`OperandBundle`] that will dispose of the bundle
345/// when dropped.
346pub(crate) struct OperandBundleBox<'a> {
347    raw: ptr::NonNull<OperandBundle<'a>>,
348}
349
350impl<'a> OperandBundleBox<'a> {
351    pub(crate) fn new(name: &str, vals: &[&'a Value]) -> Self {
352        let raw = unsafe {
353            LLVMCreateOperandBundle(
354                name.as_c_char_ptr(),
355                name.len(),
356                vals.as_ptr(),
357                vals.len() as c_uint,
358            )
359        };
360        Self { raw: ptr::NonNull::new(raw).unwrap() }
361    }
362
363    /// Dereferences to the underlying `&OperandBundle`.
364    ///
365    /// This can't be a `Deref` implementation because `OperandBundle` transitively
366    /// contains an extern type, which is incompatible with `Deref::Target: ?Sized`.
367    pub(crate) fn as_ref(&self) -> &OperandBundle<'a> {
368        // SAFETY: The returned reference is opaque and can only used for FFI.
369        // It is valid for as long as `&self` is.
370        unsafe { self.raw.as_ref() }
371    }
372}
373
374impl Drop for OperandBundleBox<'_> {
375    fn drop(&mut self) {
376        unsafe {
377            LLVMDisposeOperandBundle(self.raw);
378        }
379    }
380}
381
382pub(crate) fn add_module_flag_u32(
383    module: &Module,
384    merge_behavior: ModuleFlagMergeBehavior,
385    key: &str,
386    value: u32,
387) {
388    unsafe {
389        LLVMRustAddModuleFlagU32(module, merge_behavior, key.as_c_char_ptr(), key.len(), value);
390    }
391}
392
393pub(crate) fn add_module_flag_str(
394    module: &Module,
395    merge_behavior: ModuleFlagMergeBehavior,
396    key: &str,
397    value: &str,
398) {
399    unsafe {
400        LLVMRustAddModuleFlagString(
401            module,
402            merge_behavior,
403            key.as_c_char_ptr(),
404            key.len(),
405            value.as_c_char_ptr(),
406            value.len(),
407        );
408    }
409}
410
411pub(crate) fn set_dllimport_storage_class<'ll>(v: &'ll Value) {
412    unsafe {
413        LLVMSetDLLStorageClass(v, DLLStorageClass::DllImport);
414    }
415}
416
417pub(crate) fn set_dso_local<'ll>(v: &'ll Value) {
418    unsafe {
419        LLVMRustSetDSOLocal(v, true);
420    }
421}
422
423/// Safe wrapper for `LLVMAppendModuleInlineAsm`, which delegates to
424/// `Module::appendModuleInlineAsm`.
425pub(crate) fn append_module_inline_asm<'ll>(llmod: &'ll Module, asm: &[u8]) {
426    unsafe {
427        LLVMAppendModuleInlineAsm(llmod, asm.as_ptr(), asm.len());
428    }
429}