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