Skip to main content

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