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