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;
24
25pub(crate) use self::enzyme_ffi::*;
26
27impl LLVMRustResult {
28 pub(crate) fn into_result(self) -> Result<(), ()> {
29 match self {
30 LLVMRustResult::Success => Ok(()),
31 LLVMRustResult::Failure => Err(()),
32 }
33 }
34}
35
36pub(crate) fn AddFunctionAttributes<'ll>(
37 llfn: &'ll Value,
38 idx: AttributePlace,
39 attrs: &[&'ll Attribute],
40) {
41 unsafe {
42 LLVMRustAddFunctionAttributes(llfn, idx.as_uint(), attrs.as_ptr(), attrs.len());
43 }
44}
45
46pub(crate) fn HasStringAttribute<'ll>(llfn: &'ll Value, name: &str) -> bool {
47 unsafe { LLVMRustHasFnAttribute(llfn, name.as_c_char_ptr(), name.len()) }
48}
49
50pub(crate) fn RemoveStringAttrFromFn<'ll>(llfn: &'ll Value, name: &str) {
51 unsafe { LLVMRustRemoveFnAttribute(llfn, name.as_c_char_ptr(), name.len()) }
52}
53
54pub(crate) fn AddCallSiteAttributes<'ll>(
55 callsite: &'ll Value,
56 idx: AttributePlace,
57 attrs: &[&'ll Attribute],
58) {
59 unsafe {
60 LLVMRustAddCallSiteAttributes(callsite, idx.as_uint(), attrs.as_ptr(), attrs.len());
61 }
62}
63
64pub(crate) fn CreateAttrStringValue<'ll>(
65 llcx: &'ll Context,
66 attr: &str,
67 value: &str,
68) -> &'ll Attribute {
69 unsafe {
70 LLVMCreateStringAttribute(
71 llcx,
72 attr.as_c_char_ptr(),
73 attr.len().try_into().unwrap(),
74 value.as_c_char_ptr(),
75 value.len().try_into().unwrap(),
76 )
77 }
78}
79pub(crate) fn CreateAttrStringValueFromCStr<'ll>(
80 llcx: &'ll Context,
81 attr: &std::ffi::CStr,
82 value: &std::ffi::CStr,
83) -> &'ll Attribute {
84 unsafe {
85 LLVMCreateStringAttribute(
86 llcx,
87 (*attr).as_ptr(),
88 (*attr).to_bytes().len() as c_uint,
89 (*value).as_ptr(),
90 (*value).to_bytes().len() as c_uint,
91 )
92 }
93}
94
95pub(crate) fn CreateAttrString<'ll>(llcx: &'ll Context, attr: &str) -> &'ll Attribute {
96 unsafe {
97 LLVMCreateStringAttribute(
98 llcx,
99 attr.as_c_char_ptr(),
100 attr.len().try_into().unwrap(),
101 std::ptr::null(),
102 0,
103 )
104 }
105}
106
107pub(crate) fn CreateAlignmentAttr(llcx: &Context, bytes: u64) -> &Attribute {
108 unsafe { LLVMRustCreateAlignmentAttr(llcx, bytes) }
109}
110
111pub(crate) fn CreateDereferenceableAttr(llcx: &Context, bytes: u64) -> &Attribute {
112 unsafe { LLVMRustCreateDereferenceableAttr(llcx, bytes) }
113}
114
115pub(crate) fn CreateDereferenceableOrNullAttr(llcx: &Context, bytes: u64) -> &Attribute {
116 unsafe { LLVMRustCreateDereferenceableOrNullAttr(llcx, bytes) }
117}
118
119pub(crate) fn CreateByValAttr<'ll>(llcx: &'ll Context, ty: &'ll Type) -> &'ll Attribute {
120 unsafe { LLVMRustCreateByValAttr(llcx, ty) }
121}
122
123pub(crate) fn CreateStructRetAttr<'ll>(llcx: &'ll Context, ty: &'ll Type) -> &'ll Attribute {
124 unsafe { LLVMRustCreateStructRetAttr(llcx, ty) }
125}
126
127pub(crate) fn CreateUWTableAttr(llcx: &Context, async_: bool) -> &Attribute {
128 unsafe { LLVMRustCreateUWTableAttr(llcx, async_) }
129}
130
131pub(crate) fn CreateAllocSizeAttr(llcx: &Context, size_arg: u32) -> &Attribute {
132 unsafe { LLVMRustCreateAllocSizeAttr(llcx, size_arg) }
133}
134
135pub(crate) fn CreateAllocKindAttr(llcx: &Context, kind_arg: AllocKindFlags) -> &Attribute {
136 unsafe { LLVMRustCreateAllocKindAttr(llcx, kind_arg.bits()) }
137}
138
139pub(crate) fn CreateRangeAttr(llcx: &Context, size: Size, range: WrappingRange) -> &Attribute {
140 let lower = range.start;
141 let upper = range.end.wrapping_add(1);
143
144 let as_u64_array = |x: u128| [x as u64, (x >> 64) as u64];
146 let lower_words: [u64; 2] = as_u64_array(lower);
147 let upper_words: [u64; 2] = as_u64_array(upper);
148
149 let size_bits = size.bits();
152 if !(size_bits <= 128) {
::core::panicking::panic("assertion failed: size_bits <= 128")
};assert!(size_bits <= 128);
153 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());
156 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());
157 let size_bits = c_uint::try_from(size_bits).unwrap();
158
159 unsafe {
160 LLVMRustCreateRangeAttribute(llcx, size_bits, lower_words.as_ptr(), upper_words.as_ptr())
161 }
162}
163
164#[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)]
165pub(crate) enum AttributePlace {
166 ReturnValue,
167 Argument(u32),
168 Function,
169}
170
171impl AttributePlace {
172 pub(crate) fn as_uint(self) -> c_uint {
173 match self {
174 AttributePlace::ReturnValue => 0,
175 AttributePlace::Argument(i) => 1 + i,
176 AttributePlace::Function => !0,
177 }
178 }
179}
180
181#[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)]
182#[repr(C)]
183pub(crate) enum CodeGenOptSize {
184 CodeGenOptSizeNone = 0,
185 CodeGenOptSizeDefault = 1,
186 CodeGenOptSizeAggressive = 2,
187}
188
189pub(crate) fn SetInstructionCallConv(instr: &Value, cc: CallConv) {
190 unsafe {
191 LLVMSetInstructionCallConv(instr, cc as c_uint);
192 }
193}
194pub(crate) fn SetFunctionCallConv(fn_: &Value, cc: CallConv) {
195 unsafe {
196 LLVMSetFunctionCallConv(fn_, cc as c_uint);
197 }
198}
199
200pub(crate) fn SetUniqueComdat(llmod: &Module, val: &Value) {
207 let name_buf = get_value_name(val);
208 let name =
209 CString::from_vec_with_nul(name_buf).or_else(|buf| CString::new(buf.into_bytes())).unwrap();
210 set_comdat(llmod, val, &name);
211}
212
213pub(crate) fn set_unnamed_address(global: &Value, unnamed: UnnamedAddr) {
214 LLVMSetUnnamedAddress(global, unnamed);
215}
216
217pub(crate) fn set_thread_local_mode(global: &Value, mode: ThreadLocalMode) {
218 unsafe {
219 LLVMSetThreadLocalMode(global, mode);
220 }
221}
222
223impl AttributeKind {
224 pub(crate) fn create_attr(self, llcx: &Context) -> &Attribute {
226 unsafe { LLVMRustCreateAttrNoValue(llcx, self) }
227 }
228}
229
230impl MemoryEffects {
231 pub(crate) fn create_attr(self, llcx: &Context) -> &Attribute {
233 unsafe { LLVMRustCreateMemoryEffectsAttr(llcx, self) }
234 }
235}
236
237pub(crate) fn set_section(llglobal: &Value, section_name: &CStr) {
238 unsafe {
239 LLVMSetSection(llglobal, section_name.as_ptr());
240 }
241}
242
243pub(crate) fn add_global<'a>(llmod: &'a Module, ty: &'a Type, name_cstr: &CStr) -> &'a Value {
244 unsafe { LLVMAddGlobal(llmod, ty, name_cstr.as_ptr()) }
245}
246
247pub(crate) fn set_initializer(llglobal: &Value, constant_val: &Value) {
248 unsafe {
249 LLVMSetInitializer(llglobal, constant_val);
250 }
251}
252
253pub(crate) fn set_global_constant(llglobal: &Value, is_constant: bool) {
254 LLVMSetGlobalConstant(llglobal, is_constant.to_llvm_bool());
255}
256
257pub(crate) fn get_linkage(llglobal: &Value) -> Linkage {
258 unsafe { LLVMGetLinkage(llglobal) }.to_rust()
259}
260
261pub(crate) fn set_linkage(llglobal: &Value, linkage: Linkage) {
262 unsafe {
263 LLVMSetLinkage(llglobal, linkage);
264 }
265}
266
267pub(crate) fn is_declaration(llglobal: &Value) -> bool {
268 unsafe { LLVMIsDeclaration(llglobal) }.is_true()
269}
270
271pub(crate) fn get_visibility(llglobal: &Value) -> Visibility {
272 unsafe { LLVMGetVisibility(llglobal) }.to_rust()
273}
274
275pub(crate) fn set_visibility(llglobal: &Value, visibility: Visibility) {
276 unsafe {
277 LLVMSetVisibility(llglobal, visibility);
278 }
279}
280
281pub(crate) fn set_alignment(llglobal: &Value, align: Align) {
282 unsafe {
283 ffi::LLVMSetAlignment(llglobal, align.bytes() as c_uint);
284 }
285}
286
287pub(crate) fn set_externally_initialized(llglobal: &Value, is_ext_init: bool) {
288 LLVMSetExternallyInitialized(llglobal, is_ext_init.to_llvm_bool());
289}
290
291pub(crate) fn set_comdat(llmod: &Module, llglobal: &Value, name: &CStr) {
296 unsafe {
297 let comdat = LLVMGetOrInsertComdat(llmod, name.as_ptr());
298 LLVMSetComdat(llglobal, comdat);
299 }
300}
301
302pub(crate) fn count_params(llfn: &Value) -> c_uint {
303 LLVMCountParams(llfn)
304}
305
306pub(crate) fn get_param(llfn: &Value, index: c_uint) -> &Value {
308 unsafe {
309 if !(index < LLVMCountParams(llfn)) {
{
::core::panicking::panic_fmt(format_args!("out of bounds argument access: {0} out of {1} arguments",
index, LLVMCountParams(llfn)));
}
};assert!(
310 index < LLVMCountParams(llfn),
311 "out of bounds argument access: {} out of {} arguments",
312 index,
313 LLVMCountParams(llfn)
314 );
315 LLVMGetParam(llfn, index)
316 }
317}
318
319pub(crate) fn get_value_name(value: &Value) -> Vec<u8> {
323 unsafe {
324 let mut len = 0;
325 let data = LLVMGetValueName2(value, &mut len);
326 std::slice::from_raw_parts(data.cast(), len).to_vec()
327 }
328}
329
330#[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)]
331pub(crate) struct Intrinsic {
332 id: NonZero<c_uint>,
333}
334
335impl Intrinsic {
336 pub(crate) fn lookup(name: &[u8]) -> Option<Self> {
337 let id = unsafe { LLVMLookupIntrinsicID(name.as_c_char_ptr(), name.len()) };
338 NonZero::new(id).map(|id| Self { id })
339 }
340
341 pub(crate) fn is_overloaded(self) -> bool {
342 unsafe { LLVMIntrinsicIsOverloaded(self.id).is_true() }
343 }
344
345 pub(crate) fn is_target_specific(self) -> bool {
346 unsafe { LLVMRustIsTargetIntrinsic(self.id) }
347 }
348
349 pub(crate) fn get_declaration<'ll>(
350 self,
351 llmod: &'ll Module,
352 type_params: &[&'ll Type],
353 ) -> &'ll Value {
354 unsafe {
355 LLVMGetIntrinsicDeclaration(llmod, self.id, type_params.as_ptr(), type_params.len())
356 }
357 }
358}
359
360pub(crate) fn set_value_name(value: &Value, name: &[u8]) {
362 unsafe {
363 let data = name.as_c_char_ptr();
364 LLVMSetValueName2(value, data, name.len());
365 }
366}
367
368pub(crate) fn build_string(f: impl FnOnce(&RustString)) -> Result<String, FromUtf8Error> {
369 String::from_utf8(RustString::build_byte_buffer(f))
370}
371
372pub(crate) fn build_byte_buffer(f: impl FnOnce(&RustString)) -> Vec<u8> {
373 RustString::build_byte_buffer(f)
374}
375
376pub(crate) fn twine_to_string(tr: &Twine) -> String {
377 unsafe {
378 build_string(|s| LLVMRustWriteTwineToString(tr, s)).expect("got a non-UTF8 Twine from LLVM")
379 }
380}
381
382pub(crate) fn last_error() -> Option<String> {
383 unsafe {
384 let cstr = LLVMRustGetLastError();
385 if cstr.is_null() {
386 None
387 } else {
388 let err = CStr::from_ptr(cstr).to_bytes();
389 let err = String::from_utf8_lossy(err).to_string();
390 libc::free(cstr as *mut _);
391 Some(err)
392 }
393 }
394}
395
396pub(crate) struct OperandBundleBox<'a> {
399 raw: ptr::NonNull<OperandBundle<'a>>,
400}
401
402impl<'a> OperandBundleBox<'a> {
403 pub(crate) fn new(name: &str, vals: &[&'a Value]) -> Self {
404 let raw = unsafe {
405 LLVMCreateOperandBundle(
406 name.as_c_char_ptr(),
407 name.len(),
408 vals.as_ptr(),
409 vals.len() as c_uint,
410 )
411 };
412 Self { raw: ptr::NonNull::new(raw).unwrap() }
413 }
414
415 pub(crate) fn as_ref(&self) -> &OperandBundle<'a> {
420 unsafe { self.raw.as_ref() }
423 }
424}
425
426impl Drop for OperandBundleBox<'_> {
427 fn drop(&mut self) {
428 unsafe {
429 LLVMDisposeOperandBundle(self.raw);
430 }
431 }
432}
433
434pub(crate) fn add_module_flag_u32(
435 module: &Module,
436 merge_behavior: ModuleFlagMergeBehavior,
437 key: &str,
438 value: u32,
439) {
440 unsafe {
441 LLVMRustAddModuleFlagU32(module, merge_behavior, key.as_c_char_ptr(), key.len(), value);
442 }
443}
444
445pub(crate) fn add_module_flag_str(
446 module: &Module,
447 merge_behavior: ModuleFlagMergeBehavior,
448 key: &str,
449 value: &str,
450) {
451 unsafe {
452 LLVMRustAddModuleFlagString(
453 module,
454 merge_behavior,
455 key.as_c_char_ptr(),
456 key.len(),
457 value.as_c_char_ptr(),
458 value.len(),
459 );
460 }
461}
462
463pub(crate) fn set_dllimport_storage_class<'ll>(v: &'ll Value) {
464 unsafe {
465 LLVMSetDLLStorageClass(v, DLLStorageClass::DllImport);
466 }
467}
468
469pub(crate) fn set_dso_local<'ll>(v: &'ll Value) {
470 unsafe {
471 LLVMRustSetDSOLocal(v, true);
472 }
473}
474
475pub(crate) fn append_module_inline_asm<'ll>(llmod: &'ll Module, asm: &[u8]) {
478 unsafe {
479 LLVMAppendModuleInlineAsm(llmod, asm.as_ptr(), asm.len());
480 }
481}
482
483pub(crate) fn add_alias<'ll>(
485 module: &'ll Module,
486 ty: &Type,
487 address_space: AddressSpace,
488 aliasee: &Value,
489 name: &CStr,
490) -> &'ll Value {
491 unsafe { LLVMAddAlias2(module, ty, address_space.0, aliasee, name.as_ptr()) }
492}
493
494pub(crate) fn const_ptr_auth<'ll>(
496 ptr: &'ll Value,
497 key: u32,
498 disc: u64,
499 addr_diversity: Option<&'ll Value>,
500) -> &'ll Value {
501 unsafe {
502 let addr_div_ptr = addr_diversity.map_or(std::ptr::null(), |v| v as *const Value);
503 let deactivation_symbol = std::ptr::null();
504 let result =
505 LLVMRustConstPtrAuth(ptr as *const Value, key, disc, addr_div_ptr, deactivation_symbol);
506 &*result
507 }
508}