rustc_codegen_llvm/llvm/
ffi.rs

1//! Bindings to the LLVM-C API (`LLVM*`), and to our own `extern "C"` wrapper
2//! functions around the unstable LLVM C++ API (`LLVMRust*`).
3//!
4//! ## Passing pointer/length strings as `*const c_uchar` (PTR_LEN_STR)
5//!
6//! Normally it's a good idea for Rust-side bindings to match the corresponding
7//! C-side function declarations as closely as possible. But when passing `&str`
8//! or `&[u8]` data as a pointer/length pair, it's more convenient to declare
9//! the Rust-side pointer as `*const c_uchar` instead of `*const c_char`.
10//! Both pointer types have the same ABI, and using `*const c_uchar` avoids
11//! the need for an extra cast from `*const u8` on the Rust side.
12
13#![allow(non_camel_case_types)]
14
15use std::fmt::{self, Debug};
16use std::marker::PhantomData;
17use std::num::NonZero;
18use std::ptr;
19
20use bitflags::bitflags;
21use libc::{c_char, c_int, c_uchar, c_uint, c_ulonglong, c_void, size_t};
22
23use super::RustString;
24use super::debuginfo::{
25    DIArray, DIBuilder, DIDerivedType, DIDescriptor, DIEnumerator, DIFile, DIFlags, DILocation,
26    DISPFlags, DIScope, DISubprogram, DITemplateTypeParameter, DIType, DebugEmissionKind,
27    DebugNameTableKind,
28};
29use crate::llvm::MetadataKindId;
30use crate::{TryFromU32, llvm};
31
32/// In the LLVM-C API, boolean values are passed as `typedef int LLVMBool`,
33/// which has a different ABI from Rust or C++ `bool`.
34///
35/// This wrapper does not implement `PartialEq`.
36/// To test the underlying boolean value, use [`Self::is_true`].
37#[derive(Clone, Copy)]
38#[repr(transparent)]
39pub(crate) struct Bool {
40    value: c_int,
41}
42
43pub(crate) const TRUE: Bool = Bool::TRUE;
44pub(crate) const FALSE: Bool = Bool::FALSE;
45
46impl Bool {
47    pub(crate) const TRUE: Self = Self { value: 1 };
48    pub(crate) const FALSE: Self = Self { value: 0 };
49
50    pub(crate) const fn from_bool(rust_bool: bool) -> Self {
51        if rust_bool { Self::TRUE } else { Self::FALSE }
52    }
53
54    /// Converts this LLVM-C boolean to a Rust `bool`
55    pub(crate) fn is_true(self) -> bool {
56        // Since we're interacting with a C API, follow the C convention of
57        // treating any nonzero value as true.
58        self.value != Self::FALSE.value
59    }
60}
61
62impl Debug for Bool {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        match self.value {
65            0 => f.write_str("FALSE"),
66            1 => f.write_str("TRUE"),
67            // As with `Self::is_true`, treat any nonzero value as true.
68            v => write!(f, "TRUE ({v})"),
69        }
70    }
71}
72
73/// Convenience trait to convert `bool` to `llvm::Bool` with an explicit method call.
74///
75/// Being able to write `b.to_llvm_bool()` is less noisy than `llvm::Bool::from(b)`,
76/// while being more explicit and less mistake-prone than something like `b.into()`.
77pub(crate) trait ToLlvmBool: Copy {
78    fn to_llvm_bool(self) -> llvm::Bool;
79}
80
81impl ToLlvmBool for bool {
82    #[inline(always)]
83    fn to_llvm_bool(self) -> llvm::Bool {
84        llvm::Bool::from_bool(self)
85    }
86}
87
88/// Wrapper for a raw enum value returned from LLVM's C APIs.
89///
90/// For C enums returned by LLVM, it's risky to use a Rust enum as the return
91/// type, because it would be UB if a later version of LLVM adds a new enum
92/// value and returns it. Instead, return this raw wrapper, then convert to the
93/// Rust-side enum explicitly.
94#[repr(transparent)]
95pub(crate) struct RawEnum<T> {
96    value: u32,
97    /// We don't own or consume a `T`, but we can produce one.
98    _rust_side_type: PhantomData<fn() -> T>,
99}
100
101impl<T: TryFrom<u32>> RawEnum<T> {
102    #[track_caller]
103    pub(crate) fn to_rust(self) -> T
104    where
105        T::Error: Debug,
106    {
107        // If this fails, the Rust-side enum is out of sync with LLVM's enum.
108        T::try_from(self.value).expect("enum value returned by LLVM should be known")
109    }
110}
111
112#[derive(Copy, Clone, PartialEq)]
113#[repr(C)]
114#[allow(dead_code)] // Variants constructed by C++.
115pub(crate) enum LLVMRustResult {
116    Success,
117    Failure,
118}
119
120/// Must match the layout of `LLVMRustModuleFlagMergeBehavior`.
121///
122/// When merging modules (e.g. during LTO), their metadata flags are combined. Conflicts are
123/// resolved according to the merge behaviors specified here. Flags differing only in merge
124/// behavior are still considered to be in conflict.
125///
126/// In order for Rust-C LTO to work, we must specify behaviors compatible with Clang. Notably,
127/// 'Error' and 'Warning' cannot be mixed for a given flag.
128///
129/// There is a stable LLVM-C version of this enum (`LLVMModuleFlagBehavior`),
130/// but as of LLVM 19 it does not support all of the enum values in the unstable
131/// C++ API.
132#[derive(Copy, Clone, PartialEq)]
133#[repr(C)]
134pub(crate) enum ModuleFlagMergeBehavior {
135    Error = 1,
136    Warning = 2,
137    Require = 3,
138    Override = 4,
139    Append = 5,
140    AppendUnique = 6,
141    Max = 7,
142    Min = 8,
143}
144
145// Consts for the LLVM CallConv type, pre-cast to usize.
146
147/// Must match the layout of `LLVMTailCallKind`.
148#[derive(Copy, Clone, PartialEq, Debug)]
149#[repr(C)]
150#[allow(dead_code)]
151pub(crate) enum TailCallKind {
152    None = 0,
153    Tail = 1,
154    MustTail = 2,
155    NoTail = 3,
156}
157
158/// LLVM CallingConv::ID. Should we wrap this?
159///
160/// See <https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/IR/CallingConv.h>
161#[derive(Copy, Clone, PartialEq, Debug, TryFromU32)]
162#[repr(C)]
163pub(crate) enum CallConv {
164    CCallConv = 0,
165    FastCallConv = 8,
166    ColdCallConv = 9,
167    PreserveMost = 14,
168    PreserveAll = 15,
169    Tail = 18,
170    X86StdcallCallConv = 64,
171    X86FastcallCallConv = 65,
172    ArmAapcsCallConv = 67,
173    Msp430Intr = 69,
174    X86_ThisCall = 70,
175    PtxKernel = 71,
176    X86_64_SysV = 78,
177    X86_64_Win64 = 79,
178    X86_VectorCall = 80,
179    X86_Intr = 83,
180    AvrNonBlockingInterrupt = 84,
181    AvrInterrupt = 85,
182    AmdgpuKernel = 91,
183}
184
185/// Must match the layout of `LLVMLinkage`.
186#[derive(Copy, Clone, PartialEq, TryFromU32)]
187#[repr(C)]
188pub(crate) enum Linkage {
189    ExternalLinkage = 0,
190    AvailableExternallyLinkage = 1,
191    LinkOnceAnyLinkage = 2,
192    LinkOnceODRLinkage = 3,
193    #[deprecated = "marked obsolete by LLVM"]
194    LinkOnceODRAutoHideLinkage = 4,
195    WeakAnyLinkage = 5,
196    WeakODRLinkage = 6,
197    AppendingLinkage = 7,
198    InternalLinkage = 8,
199    PrivateLinkage = 9,
200    #[deprecated = "marked obsolete by LLVM"]
201    DLLImportLinkage = 10,
202    #[deprecated = "marked obsolete by LLVM"]
203    DLLExportLinkage = 11,
204    ExternalWeakLinkage = 12,
205    #[deprecated = "marked obsolete by LLVM"]
206    GhostLinkage = 13,
207    CommonLinkage = 14,
208    LinkerPrivateLinkage = 15,
209    LinkerPrivateWeakLinkage = 16,
210}
211
212/// Must match the layout of `LLVMVisibility`.
213#[repr(C)]
214#[derive(Copy, Clone, PartialEq, TryFromU32)]
215pub(crate) enum Visibility {
216    Default = 0,
217    Hidden = 1,
218    Protected = 2,
219}
220
221/// LLVMUnnamedAddr
222#[repr(C)]
223pub(crate) enum UnnamedAddr {
224    No,
225    #[expect(dead_code)]
226    Local,
227    Global,
228}
229
230/// LLVMDLLStorageClass
231#[derive(Copy, Clone)]
232#[repr(C)]
233pub(crate) enum DLLStorageClass {
234    #[allow(dead_code)]
235    Default = 0,
236    DllImport = 1, // Function to be imported from DLL.
237    #[allow(dead_code)]
238    DllExport = 2, // Function to be accessible from DLL.
239}
240
241/// Must match the layout of `LLVMRustAttributeKind`.
242/// Semantically a subset of the C++ enum llvm::Attribute::AttrKind,
243/// though it is not ABI compatible (since it's a C++ enum)
244#[repr(C)]
245#[derive(Copy, Clone, Debug)]
246#[expect(dead_code, reason = "Some variants are unused, but are kept to match the C++")]
247pub(crate) enum AttributeKind {
248    AlwaysInline = 0,
249    ByVal = 1,
250    Cold = 2,
251    InlineHint = 3,
252    MinSize = 4,
253    Naked = 5,
254    NoAlias = 6,
255    CapturesAddress = 7,
256    NoInline = 8,
257    NonNull = 9,
258    NoRedZone = 10,
259    NoReturn = 11,
260    NoUnwind = 12,
261    OptimizeForSize = 13,
262    ReadOnly = 14,
263    SExt = 15,
264    StructRet = 16,
265    UWTable = 17,
266    ZExt = 18,
267    InReg = 19,
268    SanitizeThread = 20,
269    SanitizeAddress = 21,
270    SanitizeMemory = 22,
271    NonLazyBind = 23,
272    OptimizeNone = 24,
273    ReadNone = 26,
274    SanitizeHWAddress = 28,
275    WillReturn = 29,
276    StackProtectReq = 30,
277    StackProtectStrong = 31,
278    StackProtect = 32,
279    NoUndef = 33,
280    SanitizeMemTag = 34,
281    NoCfCheck = 35,
282    ShadowCallStack = 36,
283    AllocSize = 37,
284    AllocatedPointer = 38,
285    AllocAlign = 39,
286    SanitizeSafeStack = 40,
287    FnRetThunkExtern = 41,
288    Writable = 42,
289    DeadOnUnwind = 43,
290    DeadOnReturn = 44,
291    CapturesReadOnly = 45,
292    CapturesNone = 46,
293    SanitizeRealtimeNonblocking = 47,
294    SanitizeRealtimeBlocking = 48,
295}
296
297/// LLVMIntPredicate
298#[derive(Copy, Clone)]
299#[repr(C)]
300pub(crate) enum IntPredicate {
301    IntEQ = 32,
302    IntNE = 33,
303    IntUGT = 34,
304    IntUGE = 35,
305    IntULT = 36,
306    IntULE = 37,
307    IntSGT = 38,
308    IntSGE = 39,
309    IntSLT = 40,
310    IntSLE = 41,
311}
312
313/// LLVMRealPredicate
314#[derive(Copy, Clone)]
315#[repr(C)]
316pub(crate) enum RealPredicate {
317    RealPredicateFalse = 0,
318    RealOEQ = 1,
319    RealOGT = 2,
320    RealOGE = 3,
321    RealOLT = 4,
322    RealOLE = 5,
323    RealONE = 6,
324    RealORD = 7,
325    RealUNO = 8,
326    RealUEQ = 9,
327    RealUGT = 10,
328    RealUGE = 11,
329    RealULT = 12,
330    RealULE = 13,
331    RealUNE = 14,
332    RealPredicateTrue = 15,
333}
334
335/// Must match the layout of `LLVMTypeKind`.
336///
337/// Use [`RawEnum<TypeKind>`] for values of `LLVMTypeKind` returned from LLVM,
338/// to avoid risk of UB if LLVM adds new enum values.
339///
340/// All of LLVM's variants should be declared here, even if no Rust-side code refers
341/// to them, because unknown variants will cause [`RawEnum::to_rust`] to panic.
342#[derive(Copy, Clone, PartialEq, Debug, TryFromU32)]
343#[repr(C)]
344pub(crate) enum TypeKind {
345    Void = 0,
346    Half = 1,
347    Float = 2,
348    Double = 3,
349    X86_FP80 = 4,
350    FP128 = 5,
351    PPC_FP128 = 6,
352    Label = 7,
353    Integer = 8,
354    Function = 9,
355    Struct = 10,
356    Array = 11,
357    Pointer = 12,
358    Vector = 13,
359    Metadata = 14,
360    Token = 16,
361    ScalableVector = 17,
362    BFloat = 18,
363    X86_AMX = 19,
364}
365
366impl TypeKind {
367    pub(crate) fn to_generic(self) -> rustc_codegen_ssa::common::TypeKind {
368        use rustc_codegen_ssa::common::TypeKind as Common;
369        match self {
370            Self::Void => Common::Void,
371            Self::Half => Common::Half,
372            Self::Float => Common::Float,
373            Self::Double => Common::Double,
374            Self::X86_FP80 => Common::X86_FP80,
375            Self::FP128 => Common::FP128,
376            Self::PPC_FP128 => Common::PPC_FP128,
377            Self::Label => Common::Label,
378            Self::Integer => Common::Integer,
379            Self::Function => Common::Function,
380            Self::Struct => Common::Struct,
381            Self::Array => Common::Array,
382            Self::Pointer => Common::Pointer,
383            Self::Vector => Common::Vector,
384            Self::Metadata => Common::Metadata,
385            Self::Token => Common::Token,
386            Self::ScalableVector => Common::ScalableVector,
387            Self::BFloat => Common::BFloat,
388            Self::X86_AMX => Common::X86_AMX,
389        }
390    }
391}
392
393/// LLVMAtomicRmwBinOp
394#[derive(Copy, Clone)]
395#[repr(C)]
396pub(crate) enum AtomicRmwBinOp {
397    AtomicXchg = 0,
398    AtomicAdd = 1,
399    AtomicSub = 2,
400    AtomicAnd = 3,
401    AtomicNand = 4,
402    AtomicOr = 5,
403    AtomicXor = 6,
404    AtomicMax = 7,
405    AtomicMin = 8,
406    AtomicUMax = 9,
407    AtomicUMin = 10,
408}
409
410/// LLVMAtomicOrdering
411#[derive(Copy, Clone)]
412#[repr(C)]
413pub(crate) enum AtomicOrdering {
414    #[allow(dead_code)]
415    NotAtomic = 0,
416    #[allow(dead_code)]
417    Unordered = 1,
418    Monotonic = 2,
419    // Consume = 3,  // Not specified yet.
420    Acquire = 4,
421    Release = 5,
422    AcquireRelease = 6,
423    SequentiallyConsistent = 7,
424}
425
426/// LLVMRustFileType
427#[derive(Copy, Clone)]
428#[repr(C)]
429pub(crate) enum FileType {
430    AssemblyFile,
431    ObjectFile,
432}
433
434/// Must match the layout of `LLVMInlineAsmDialect`.
435#[derive(Copy, Clone, PartialEq)]
436#[repr(C)]
437pub(crate) enum AsmDialect {
438    Att,
439    Intel,
440}
441
442/// LLVMRustCodeGenOptLevel
443#[derive(Copy, Clone, PartialEq)]
444#[repr(C)]
445pub(crate) enum CodeGenOptLevel {
446    None,
447    Less,
448    Default,
449    Aggressive,
450}
451
452/// LLVMRustPassBuilderOptLevel
453#[repr(C)]
454pub(crate) enum PassBuilderOptLevel {
455    O0,
456    O1,
457    O2,
458    O3,
459    Os,
460    Oz,
461}
462
463/// LLVMRustOptStage
464#[derive(PartialEq)]
465#[repr(C)]
466pub(crate) enum OptStage {
467    PreLinkNoLTO,
468    PreLinkThinLTO,
469    PreLinkFatLTO,
470    ThinLTO,
471    FatLTO,
472}
473
474/// LLVMRustSanitizerOptions
475#[repr(C)]
476pub(crate) struct SanitizerOptions {
477    pub sanitize_address: bool,
478    pub sanitize_address_recover: bool,
479    pub sanitize_cfi: bool,
480    pub sanitize_dataflow: bool,
481    pub sanitize_dataflow_abilist: *const *const c_char,
482    pub sanitize_dataflow_abilist_len: size_t,
483    pub sanitize_kcfi: bool,
484    pub sanitize_memory: bool,
485    pub sanitize_memory_recover: bool,
486    pub sanitize_memory_track_origins: c_int,
487    pub sanitize_realtime: bool,
488    pub sanitize_thread: bool,
489    pub sanitize_hwaddress: bool,
490    pub sanitize_hwaddress_recover: bool,
491    pub sanitize_kernel_address: bool,
492    pub sanitize_kernel_address_recover: bool,
493}
494
495/// LLVMRustRelocModel
496#[derive(Copy, Clone, PartialEq)]
497#[repr(C)]
498pub(crate) enum RelocModel {
499    Static,
500    PIC,
501    DynamicNoPic,
502    ROPI,
503    RWPI,
504    ROPI_RWPI,
505}
506
507/// LLVMRustFloatABI
508#[derive(Copy, Clone, PartialEq)]
509#[repr(C)]
510pub(crate) enum FloatAbi {
511    Default,
512    Soft,
513    Hard,
514}
515
516/// LLVMRustCodeModel
517#[derive(Copy, Clone)]
518#[repr(C)]
519pub(crate) enum CodeModel {
520    Tiny,
521    Small,
522    Kernel,
523    Medium,
524    Large,
525    None,
526}
527
528/// LLVMRustDiagnosticKind
529#[derive(Copy, Clone)]
530#[repr(C)]
531#[allow(dead_code)] // Variants constructed by C++.
532pub(crate) enum DiagnosticKind {
533    Other,
534    InlineAsm,
535    StackSize,
536    DebugMetadataVersion,
537    SampleProfile,
538    OptimizationRemark,
539    OptimizationRemarkMissed,
540    OptimizationRemarkAnalysis,
541    OptimizationRemarkAnalysisFPCommute,
542    OptimizationRemarkAnalysisAliasing,
543    OptimizationRemarkOther,
544    OptimizationFailure,
545    PGOProfile,
546    Linker,
547    Unsupported,
548    SrcMgr,
549}
550
551/// LLVMRustDiagnosticLevel
552#[derive(Copy, Clone)]
553#[repr(C)]
554#[allow(dead_code)] // Variants constructed by C++.
555pub(crate) enum DiagnosticLevel {
556    Error,
557    Warning,
558    Note,
559    Remark,
560}
561
562unsafe extern "C" {
563    // LLVMRustThinLTOData
564    pub(crate) type ThinLTOData;
565
566    // LLVMRustThinLTOBuffer
567    pub(crate) type ThinLTOBuffer;
568}
569
570/// LLVMRustThinLTOModule
571#[repr(C)]
572pub(crate) struct ThinLTOModule {
573    pub identifier: *const c_char,
574    pub data: *const u8,
575    pub len: usize,
576}
577
578/// LLVMThreadLocalMode
579#[derive(Copy, Clone)]
580#[repr(C)]
581pub(crate) enum ThreadLocalMode {
582    #[expect(dead_code)]
583    NotThreadLocal,
584    GeneralDynamic,
585    LocalDynamic,
586    InitialExec,
587    LocalExec,
588}
589
590/// LLVMRustChecksumKind
591#[derive(Copy, Clone)]
592#[repr(C)]
593pub(crate) enum ChecksumKind {
594    None,
595    MD5,
596    SHA1,
597    SHA256,
598}
599
600/// LLVMRustMemoryEffects
601#[derive(Copy, Clone)]
602#[repr(C)]
603pub(crate) enum MemoryEffects {
604    None,
605    ReadOnly,
606    InaccessibleMemOnly,
607    ReadOnlyNotPure,
608}
609
610/// LLVMOpcode
611#[derive(Copy, Clone, PartialEq, Eq)]
612#[repr(C)]
613#[expect(dead_code, reason = "Some variants are unused, but are kept to match LLVM-C")]
614pub(crate) enum Opcode {
615    Ret = 1,
616    Br = 2,
617    Switch = 3,
618    IndirectBr = 4,
619    Invoke = 5,
620    Unreachable = 7,
621    CallBr = 67,
622    FNeg = 66,
623    Add = 8,
624    FAdd = 9,
625    Sub = 10,
626    FSub = 11,
627    Mul = 12,
628    FMul = 13,
629    UDiv = 14,
630    SDiv = 15,
631    FDiv = 16,
632    URem = 17,
633    SRem = 18,
634    FRem = 19,
635    Shl = 20,
636    LShr = 21,
637    AShr = 22,
638    And = 23,
639    Or = 24,
640    Xor = 25,
641    Alloca = 26,
642    Load = 27,
643    Store = 28,
644    GetElementPtr = 29,
645    Trunc = 30,
646    ZExt = 31,
647    SExt = 32,
648    FPToUI = 33,
649    FPToSI = 34,
650    UIToFP = 35,
651    SIToFP = 36,
652    FPTrunc = 37,
653    FPExt = 38,
654    PtrToInt = 39,
655    IntToPtr = 40,
656    BitCast = 41,
657    AddrSpaceCast = 60,
658    ICmp = 42,
659    FCmp = 43,
660    PHI = 44,
661    Call = 45,
662    Select = 46,
663    UserOp1 = 47,
664    UserOp2 = 48,
665    VAArg = 49,
666    ExtractElement = 50,
667    InsertElement = 51,
668    ShuffleVector = 52,
669    ExtractValue = 53,
670    InsertValue = 54,
671    Freeze = 68,
672    Fence = 55,
673    AtomicCmpXchg = 56,
674    AtomicRMW = 57,
675    Resume = 58,
676    LandingPad = 59,
677    CleanupRet = 61,
678    CatchRet = 62,
679    CatchPad = 63,
680    CleanupPad = 64,
681    CatchSwitch = 65,
682}
683
684/// Must match the layout of `LLVMRustCompressionKind`.
685#[derive(Copy, Clone)]
686#[repr(C)]
687pub(crate) enum CompressionKind {
688    None = 0,
689    Zlib = 1,
690    Zstd = 2,
691}
692
693unsafe extern "C" {
694    type Opaque;
695}
696#[repr(C)]
697struct InvariantOpaque<'a> {
698    _marker: PhantomData<&'a mut &'a ()>,
699    _opaque: Opaque,
700}
701
702// Opaque pointer types
703unsafe extern "C" {
704    pub(crate) type Module;
705    pub(crate) type Context;
706    pub(crate) type Type;
707    pub(crate) type Value;
708    pub(crate) type ConstantInt;
709    pub(crate) type Attribute;
710    pub(crate) type Metadata;
711    pub(crate) type BasicBlock;
712    pub(crate) type Comdat;
713    /// `&'ll DbgRecord` represents `LLVMDbgRecordRef`.
714    pub(crate) type DbgRecord;
715}
716#[repr(C)]
717pub(crate) struct Builder<'a>(InvariantOpaque<'a>);
718#[repr(C)]
719pub(crate) struct PassManager<'a>(InvariantOpaque<'a>);
720unsafe extern "C" {
721    pub type TargetMachine;
722}
723unsafe extern "C" {
724    pub(crate) type Twine;
725    pub(crate) type DiagnosticInfo;
726    pub(crate) type SMDiagnostic;
727}
728/// Opaque pointee of `LLVMOperandBundleRef`.
729#[repr(C)]
730pub(crate) struct OperandBundle<'a>(InvariantOpaque<'a>);
731#[repr(C)]
732pub(crate) struct Linker<'a>(InvariantOpaque<'a>);
733
734unsafe extern "C" {
735    pub(crate) type DiagnosticHandler;
736}
737
738pub(crate) type DiagnosticHandlerTy = unsafe extern "C" fn(&DiagnosticInfo, *mut c_void);
739
740pub(crate) mod debuginfo {
741    use std::ptr;
742
743    use bitflags::bitflags;
744
745    use super::{InvariantOpaque, Metadata};
746    use crate::llvm::{self, Module};
747
748    /// Opaque target type for references to an LLVM debuginfo builder.
749    ///
750    /// `&'_ DIBuilder<'ll>` corresponds to `LLVMDIBuilderRef`, which is the
751    /// LLVM-C wrapper for `DIBuilder *`.
752    ///
753    /// Debuginfo builders are created and destroyed during codegen, so the
754    /// builder reference typically has a shorter lifetime than the LLVM
755    /// session (`'ll`) that it participates in.
756    #[repr(C)]
757    pub(crate) struct DIBuilder<'ll>(InvariantOpaque<'ll>);
758
759    /// Owning pointer to a `DIBuilder<'ll>` that will dispose of the builder
760    /// when dropped. Use `.as_ref()` to get the underlying `&DIBuilder`
761    /// needed for debuginfo FFI calls.
762    pub(crate) struct DIBuilderBox<'ll> {
763        raw: ptr::NonNull<DIBuilder<'ll>>,
764    }
765
766    impl<'ll> DIBuilderBox<'ll> {
767        pub(crate) fn new(llmod: &'ll Module) -> Self {
768            let raw = unsafe { llvm::LLVMCreateDIBuilder(llmod) };
769            let raw = ptr::NonNull::new(raw).unwrap();
770            Self { raw }
771        }
772
773        pub(crate) fn as_ref(&self) -> &DIBuilder<'ll> {
774            // SAFETY: This is an owning pointer, so `&DIBuilder` is valid
775            // for as long as `&self` is.
776            unsafe { self.raw.as_ref() }
777        }
778    }
779
780    impl<'ll> Drop for DIBuilderBox<'ll> {
781        fn drop(&mut self) {
782            unsafe { llvm::LLVMDisposeDIBuilder(self.raw) };
783        }
784    }
785
786    pub(crate) type DIDescriptor = Metadata;
787    pub(crate) type DILocation = Metadata;
788    pub(crate) type DIScope = DIDescriptor;
789    pub(crate) type DIFile = DIScope;
790    pub(crate) type DILexicalBlock = DIScope;
791    pub(crate) type DISubprogram = DIScope;
792    pub(crate) type DIType = DIDescriptor;
793    pub(crate) type DIBasicType = DIType;
794    pub(crate) type DIDerivedType = DIType;
795    pub(crate) type DICompositeType = DIDerivedType;
796    pub(crate) type DIVariable = DIDescriptor;
797    pub(crate) type DIArray = DIDescriptor;
798    pub(crate) type DIEnumerator = DIDescriptor;
799    pub(crate) type DITemplateTypeParameter = DIDescriptor;
800
801    bitflags! {
802        /// Must match the layout of `LLVMDIFlags` in the LLVM-C API.
803        ///
804        /// Each value declared here must also be covered by the static
805        /// assertions in `RustWrapper.cpp` used by `fromRust(LLVMDIFlags)`.
806        #[repr(transparent)]
807        #[derive(Clone, Copy, Default)]
808        pub(crate) struct DIFlags: u32 {
809            const FlagZero                = 0;
810            const FlagPrivate             = 1;
811            const FlagProtected           = 2;
812            const FlagPublic              = 3;
813            const FlagFwdDecl             = (1 << 2);
814            const FlagAppleBlock          = (1 << 3);
815            const FlagReservedBit4        = (1 << 4);
816            const FlagVirtual             = (1 << 5);
817            const FlagArtificial          = (1 << 6);
818            const FlagExplicit            = (1 << 7);
819            const FlagPrototyped          = (1 << 8);
820            const FlagObjcClassComplete   = (1 << 9);
821            const FlagObjectPointer       = (1 << 10);
822            const FlagVector              = (1 << 11);
823            const FlagStaticMember        = (1 << 12);
824            const FlagLValueReference     = (1 << 13);
825            const FlagRValueReference     = (1 << 14);
826            const FlagReserved            = (1 << 15);
827            const FlagSingleInheritance   = (1 << 16);
828            const FlagMultipleInheritance = (2 << 16);
829            const FlagVirtualInheritance  = (3 << 16);
830            const FlagIntroducedVirtual   = (1 << 18);
831            const FlagBitField            = (1 << 19);
832            const FlagNoReturn            = (1 << 20);
833            // The bit at (1 << 21) is unused, but was `LLVMDIFlagMainSubprogram`.
834            const FlagTypePassByValue     = (1 << 22);
835            const FlagTypePassByReference = (1 << 23);
836            const FlagEnumClass           = (1 << 24);
837            const FlagThunk               = (1 << 25);
838            const FlagNonTrivial          = (1 << 26);
839            const FlagBigEndian           = (1 << 27);
840            const FlagLittleEndian        = (1 << 28);
841        }
842    }
843
844    // These values **must** match with LLVMRustDISPFlags!!
845    bitflags! {
846        #[repr(transparent)]
847        #[derive(Clone, Copy, Default)]
848        pub(crate) struct DISPFlags: u32 {
849            const SPFlagZero              = 0;
850            const SPFlagVirtual           = 1;
851            const SPFlagPureVirtual       = 2;
852            const SPFlagLocalToUnit       = (1 << 2);
853            const SPFlagDefinition        = (1 << 3);
854            const SPFlagOptimized         = (1 << 4);
855            const SPFlagMainSubprogram    = (1 << 5);
856        }
857    }
858
859    /// LLVMRustDebugEmissionKind
860    #[derive(Copy, Clone)]
861    #[repr(C)]
862    pub(crate) enum DebugEmissionKind {
863        NoDebug,
864        FullDebug,
865        LineTablesOnly,
866        DebugDirectivesOnly,
867    }
868
869    /// LLVMRustDebugNameTableKind
870    #[derive(Clone, Copy)]
871    #[repr(C)]
872    pub(crate) enum DebugNameTableKind {
873        Default,
874        #[expect(dead_code)]
875        Gnu,
876        None,
877    }
878}
879
880// These values **must** match with LLVMRustAllocKindFlags
881bitflags! {
882    #[repr(transparent)]
883    #[derive(Default)]
884    pub(crate) struct AllocKindFlags : u64 {
885        const Unknown = 0;
886        const Alloc = 1;
887        const Realloc = 1 << 1;
888        const Free = 1 << 2;
889        const Uninitialized = 1 << 3;
890        const Zeroed = 1 << 4;
891        const Aligned = 1 << 5;
892    }
893}
894
895// These values **must** match with LLVMGEPNoWrapFlags
896bitflags! {
897    #[repr(transparent)]
898    #[derive(Default)]
899    pub struct GEPNoWrapFlags : c_uint {
900        const InBounds = 1 << 0;
901        const NUSW = 1 << 1;
902        const NUW = 1 << 2;
903    }
904}
905
906unsafe extern "C" {
907    pub(crate) type ModuleBuffer;
908}
909
910pub(crate) type SelfProfileBeforePassCallback =
911    unsafe extern "C" fn(*mut c_void, *const c_char, *const c_char);
912pub(crate) type SelfProfileAfterPassCallback = unsafe extern "C" fn(*mut c_void);
913
914pub(crate) type GetSymbolsCallback =
915    unsafe extern "C" fn(*mut c_void, *const c_char) -> *mut c_void;
916pub(crate) type GetSymbolsErrorCallback = unsafe extern "C" fn(*const c_char) -> *mut c_void;
917
918unsafe extern "C" {
919    // Create and destroy contexts.
920    pub(crate) fn LLVMContextCreate() -> &'static mut Context;
921    pub(crate) fn LLVMContextDispose(C: &'static mut Context);
922    pub(crate) fn LLVMContextSetDiscardValueNames(C: &Context, Discard: Bool);
923    pub(crate) fn LLVMGetMDKindIDInContext(
924        C: &Context,
925        Name: *const c_char,
926        SLen: c_uint,
927    ) -> MetadataKindId;
928
929    pub(crate) fn LLVMDisposeTargetMachine(T: ptr::NonNull<TargetMachine>);
930
931    // Create modules.
932    pub(crate) fn LLVMModuleCreateWithNameInContext(
933        ModuleID: *const c_char,
934        C: &Context,
935    ) -> &Module;
936    pub(crate) safe fn LLVMCloneModule(M: &Module) -> &Module;
937
938    /// Data layout. See Module::getDataLayout.
939    pub(crate) fn LLVMGetDataLayoutStr(M: &Module) -> *const c_char;
940    pub(crate) fn LLVMSetDataLayout(M: &Module, Triple: *const c_char);
941
942    /// Append inline assembly to a module. See `Module::appendModuleInlineAsm`.
943    pub(crate) fn LLVMAppendModuleInlineAsm(
944        M: &Module,
945        Asm: *const c_uchar, // See "PTR_LEN_STR".
946        Len: size_t,
947    );
948
949    /// Create the specified uniqued inline asm string. See `InlineAsm::get()`.
950    pub(crate) fn LLVMGetInlineAsm<'ll>(
951        Ty: &'ll Type,
952        AsmString: *const c_uchar, // See "PTR_LEN_STR".
953        AsmStringSize: size_t,
954        Constraints: *const c_uchar, // See "PTR_LEN_STR".
955        ConstraintsSize: size_t,
956        HasSideEffects: llvm::Bool,
957        IsAlignStack: llvm::Bool,
958        Dialect: AsmDialect,
959        CanThrow: llvm::Bool,
960    ) -> &'ll Value;
961
962    pub(crate) safe fn LLVMGetTypeKind(Ty: &Type) -> RawEnum<TypeKind>;
963
964    // Operations on integer types
965    pub(crate) fn LLVMInt1TypeInContext(C: &Context) -> &Type;
966    pub(crate) fn LLVMInt8TypeInContext(C: &Context) -> &Type;
967    pub(crate) fn LLVMInt16TypeInContext(C: &Context) -> &Type;
968    pub(crate) fn LLVMInt32TypeInContext(C: &Context) -> &Type;
969    pub(crate) fn LLVMInt64TypeInContext(C: &Context) -> &Type;
970    pub(crate) safe fn LLVMIntTypeInContext(C: &Context, NumBits: c_uint) -> &Type;
971
972    pub(crate) fn LLVMGetIntTypeWidth(IntegerTy: &Type) -> c_uint;
973
974    // Operations on real types
975    pub(crate) fn LLVMHalfTypeInContext(C: &Context) -> &Type;
976    pub(crate) fn LLVMFloatTypeInContext(C: &Context) -> &Type;
977    pub(crate) fn LLVMDoubleTypeInContext(C: &Context) -> &Type;
978    pub(crate) fn LLVMFP128TypeInContext(C: &Context) -> &Type;
979
980    // Operations on function types
981    pub(crate) fn LLVMFunctionType<'a>(
982        ReturnType: &'a Type,
983        ParamTypes: *const &'a Type,
984        ParamCount: c_uint,
985        IsVarArg: Bool,
986    ) -> &'a Type;
987    pub(crate) fn LLVMCountParamTypes(FunctionTy: &Type) -> c_uint;
988    pub(crate) fn LLVMGetParamTypes<'a>(FunctionTy: &'a Type, Dest: *mut &'a Type);
989
990    // Operations on struct types
991    pub(crate) fn LLVMStructTypeInContext<'a>(
992        C: &'a Context,
993        ElementTypes: *const &'a Type,
994        ElementCount: c_uint,
995        Packed: Bool,
996    ) -> &'a Type;
997
998    // Operations on array, pointer, and vector types (sequence types)
999    pub(crate) safe fn LLVMPointerTypeInContext(C: &Context, AddressSpace: c_uint) -> &Type;
1000    pub(crate) fn LLVMVectorType(ElementType: &Type, ElementCount: c_uint) -> &Type;
1001
1002    pub(crate) fn LLVMGetElementType(Ty: &Type) -> &Type;
1003    pub(crate) fn LLVMGetVectorSize(VectorTy: &Type) -> c_uint;
1004
1005    // Operations on other types
1006    pub(crate) fn LLVMVoidTypeInContext(C: &Context) -> &Type;
1007
1008    // Operations on all values
1009    pub(crate) fn LLVMTypeOf(Val: &Value) -> &Type;
1010    pub(crate) fn LLVMGetValueName2(Val: &Value, Length: *mut size_t) -> *const c_char;
1011    pub(crate) fn LLVMSetValueName2(Val: &Value, Name: *const c_char, NameLen: size_t);
1012    pub(crate) fn LLVMReplaceAllUsesWith<'a>(OldVal: &'a Value, NewVal: &'a Value);
1013    pub(crate) safe fn LLVMSetMetadata<'a>(Val: &'a Value, KindID: MetadataKindId, Node: &'a Value);
1014    pub(crate) fn LLVMGlobalSetMetadata<'a>(
1015        Val: &'a Value,
1016        KindID: MetadataKindId,
1017        Metadata: &'a Metadata,
1018    );
1019    pub(crate) safe fn LLVMValueAsMetadata(Node: &Value) -> &Metadata;
1020
1021    // Operations on constants of any type
1022    pub(crate) fn LLVMConstNull(Ty: &Type) -> &Value;
1023    pub(crate) fn LLVMGetUndef(Ty: &Type) -> &Value;
1024    pub(crate) fn LLVMGetPoison(Ty: &Type) -> &Value;
1025
1026    // Operations on metadata
1027    pub(crate) fn LLVMMDStringInContext2(
1028        C: &Context,
1029        Str: *const c_char,
1030        SLen: size_t,
1031    ) -> &Metadata;
1032    pub(crate) fn LLVMMDNodeInContext2<'a>(
1033        C: &'a Context,
1034        Vals: *const &'a Metadata,
1035        Count: size_t,
1036    ) -> &'a Metadata;
1037    pub(crate) fn LLVMAddNamedMetadataOperand<'a>(
1038        M: &'a Module,
1039        Name: *const c_char,
1040        Val: &'a Value,
1041    );
1042
1043    // Operations on scalar constants
1044    pub(crate) fn LLVMConstInt(IntTy: &Type, N: c_ulonglong, SignExtend: Bool) -> &Value;
1045    pub(crate) fn LLVMConstIntOfArbitraryPrecision(
1046        IntTy: &Type,
1047        Wn: c_uint,
1048        Ws: *const u64,
1049    ) -> &Value;
1050    pub(crate) fn LLVMConstReal(RealTy: &Type, N: f64) -> &Value;
1051
1052    // Operations on composite constants
1053    pub(crate) fn LLVMConstArray2<'a>(
1054        ElementTy: &'a Type,
1055        ConstantVals: *const &'a Value,
1056        Length: u64,
1057    ) -> &'a Value;
1058    pub(crate) fn LLVMArrayType2(ElementType: &Type, ElementCount: u64) -> &Type;
1059    pub(crate) fn LLVMConstStringInContext2(
1060        C: &Context,
1061        Str: *const c_char,
1062        Length: size_t,
1063        DontNullTerminate: Bool,
1064    ) -> &Value;
1065    pub(crate) fn LLVMConstStructInContext<'a>(
1066        C: &'a Context,
1067        ConstantVals: *const &'a Value,
1068        Count: c_uint,
1069        Packed: Bool,
1070    ) -> &'a Value;
1071    pub(crate) fn LLVMConstNamedStruct<'a>(
1072        StructTy: &'a Type,
1073        ConstantVals: *const &'a Value,
1074        Count: c_uint,
1075    ) -> &'a Value;
1076    pub(crate) fn LLVMConstVector(ScalarConstantVals: *const &Value, Size: c_uint) -> &Value;
1077
1078    // Constant expressions
1079    pub(crate) fn LLVMConstInBoundsGEP2<'a>(
1080        ty: &'a Type,
1081        ConstantVal: &'a Value,
1082        ConstantIndices: *const &'a Value,
1083        NumIndices: c_uint,
1084    ) -> &'a Value;
1085    pub(crate) fn LLVMConstPtrToInt<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1086    pub(crate) fn LLVMConstIntToPtr<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1087    pub(crate) fn LLVMConstBitCast<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1088    pub(crate) fn LLVMConstPointerCast<'a>(ConstantVal: &'a Value, ToType: &'a Type) -> &'a Value;
1089    pub(crate) fn LLVMGetAggregateElement(ConstantVal: &Value, Idx: c_uint) -> Option<&Value>;
1090    pub(crate) fn LLVMGetConstOpcode(ConstantVal: &Value) -> Opcode;
1091    pub(crate) fn LLVMIsAConstantExpr(Val: &Value) -> Option<&Value>;
1092
1093    // Operations on global variables, functions, and aliases (globals)
1094    pub(crate) fn LLVMIsDeclaration(Global: &Value) -> Bool;
1095    pub(crate) fn LLVMGetLinkage(Global: &Value) -> RawEnum<Linkage>;
1096    pub(crate) fn LLVMSetLinkage(Global: &Value, RustLinkage: Linkage);
1097    pub(crate) fn LLVMSetSection(Global: &Value, Section: *const c_char);
1098    pub(crate) fn LLVMGetVisibility(Global: &Value) -> RawEnum<Visibility>;
1099    pub(crate) fn LLVMSetVisibility(Global: &Value, Viz: Visibility);
1100    pub(crate) fn LLVMGetAlignment(Global: &Value) -> c_uint;
1101    pub(crate) fn LLVMSetAlignment(Global: &Value, Bytes: c_uint);
1102    pub(crate) fn LLVMSetDLLStorageClass(V: &Value, C: DLLStorageClass);
1103    pub(crate) fn LLVMGlobalGetValueType(Global: &Value) -> &Type;
1104
1105    // Operations on global variables
1106    pub(crate) safe fn LLVMIsAGlobalVariable(GlobalVar: &Value) -> Option<&Value>;
1107    pub(crate) fn LLVMAddGlobal<'a>(M: &'a Module, Ty: &'a Type, Name: *const c_char) -> &'a Value;
1108    pub(crate) fn LLVMGetNamedGlobal(M: &Module, Name: *const c_char) -> Option<&Value>;
1109    pub(crate) fn LLVMGetFirstGlobal(M: &Module) -> Option<&Value>;
1110    pub(crate) fn LLVMGetNextGlobal(GlobalVar: &Value) -> Option<&Value>;
1111    pub(crate) fn LLVMDeleteGlobal(GlobalVar: &Value);
1112    pub(crate) safe fn LLVMGetInitializer(GlobalVar: &Value) -> Option<&Value>;
1113    pub(crate) fn LLVMSetInitializer<'a>(GlobalVar: &'a Value, ConstantVal: &'a Value);
1114    pub(crate) safe fn LLVMIsThreadLocal(GlobalVar: &Value) -> Bool;
1115    pub(crate) fn LLVMSetThreadLocalMode(GlobalVar: &Value, Mode: ThreadLocalMode);
1116    pub(crate) safe fn LLVMIsGlobalConstant(GlobalVar: &Value) -> Bool;
1117    pub(crate) safe fn LLVMSetGlobalConstant(GlobalVar: &Value, IsConstant: Bool);
1118    pub(crate) safe fn LLVMSetTailCall(CallInst: &Value, IsTailCall: Bool);
1119    pub(crate) safe fn LLVMSetTailCallKind(CallInst: &Value, kind: TailCallKind);
1120    pub(crate) safe fn LLVMSetExternallyInitialized(GlobalVar: &Value, IsExtInit: Bool);
1121
1122    // Operations on attributes
1123    pub(crate) fn LLVMCreateStringAttribute(
1124        C: &Context,
1125        Name: *const c_char,
1126        NameLen: c_uint,
1127        Value: *const c_char,
1128        ValueLen: c_uint,
1129    ) -> &Attribute;
1130
1131    // Operations on functions
1132    pub(crate) fn LLVMSetFunctionCallConv(Fn: &Value, CC: c_uint);
1133    pub(crate) fn LLVMAddFunction<'a>(
1134        Mod: &'a Module,
1135        Name: *const c_char,
1136        FunctionTy: &'a Type,
1137    ) -> &'a Value;
1138    pub(crate) fn LLVMDeleteFunction(Fn: &Value);
1139
1140    // Operations about llvm intrinsics
1141    pub(crate) fn LLVMLookupIntrinsicID(Name: *const c_char, NameLen: size_t) -> c_uint;
1142    pub(crate) fn LLVMGetIntrinsicDeclaration<'a>(
1143        Mod: &'a Module,
1144        ID: NonZero<c_uint>,
1145        ParamTypes: *const &'a Type,
1146        ParamCount: size_t,
1147    ) -> &'a Value;
1148
1149    // Operations on parameters
1150    pub(crate) fn LLVMIsAArgument(Val: &Value) -> Option<&Value>;
1151    pub(crate) safe fn LLVMCountParams(Fn: &Value) -> c_uint;
1152    pub(crate) fn LLVMGetParam(Fn: &Value, Index: c_uint) -> &Value;
1153
1154    // Operations on basic blocks
1155    pub(crate) fn LLVMGetBasicBlockParent(BB: &BasicBlock) -> &Value;
1156    pub(crate) fn LLVMAppendBasicBlockInContext<'a>(
1157        C: &'a Context,
1158        Fn: &'a Value,
1159        Name: *const c_char,
1160    ) -> &'a BasicBlock;
1161
1162    // Operations on instructions
1163    pub(crate) fn LLVMIsAInstruction(Val: &Value) -> Option<&Value>;
1164    pub(crate) fn LLVMGetFirstBasicBlock(Fn: &Value) -> &BasicBlock;
1165    pub(crate) fn LLVMGetOperand(Val: &Value, Index: c_uint) -> Option<&Value>;
1166
1167    // Operations on call sites
1168    pub(crate) fn LLVMSetInstructionCallConv(Instr: &Value, CC: c_uint);
1169
1170    // Operations on load/store instructions (only)
1171    pub(crate) fn LLVMSetVolatile(MemoryAccessInst: &Value, volatile: Bool);
1172    pub(crate) fn LLVMSetOrdering(MemoryAccessInst: &Value, Ordering: AtomicOrdering);
1173
1174    // Operations on phi nodes
1175    pub(crate) fn LLVMAddIncoming<'a>(
1176        PhiNode: &'a Value,
1177        IncomingValues: *const &'a Value,
1178        IncomingBlocks: *const &'a BasicBlock,
1179        Count: c_uint,
1180    );
1181
1182    // Instruction builders
1183    pub(crate) fn LLVMCreateBuilderInContext(C: &Context) -> &mut Builder<'_>;
1184    pub(crate) fn LLVMPositionBuilderAtEnd<'a>(Builder: &Builder<'a>, Block: &'a BasicBlock);
1185    pub(crate) fn LLVMGetInsertBlock<'a>(Builder: &Builder<'a>) -> &'a BasicBlock;
1186    pub(crate) fn LLVMDisposeBuilder<'a>(Builder: &'a mut Builder<'a>);
1187
1188    // Metadata
1189    pub(crate) fn LLVMSetCurrentDebugLocation2<'a>(Builder: &Builder<'a>, Loc: *const Metadata);
1190    pub(crate) fn LLVMGetCurrentDebugLocation2<'a>(Builder: &Builder<'a>) -> Option<&'a Metadata>;
1191
1192    // Terminators
1193    pub(crate) safe fn LLVMBuildRetVoid<'a>(B: &Builder<'a>) -> &'a Value;
1194    pub(crate) fn LLVMBuildRet<'a>(B: &Builder<'a>, V: &'a Value) -> &'a Value;
1195    pub(crate) fn LLVMBuildBr<'a>(B: &Builder<'a>, Dest: &'a BasicBlock) -> &'a Value;
1196    pub(crate) fn LLVMBuildCondBr<'a>(
1197        B: &Builder<'a>,
1198        If: &'a Value,
1199        Then: &'a BasicBlock,
1200        Else: &'a BasicBlock,
1201    ) -> &'a Value;
1202    pub(crate) fn LLVMBuildSwitch<'a>(
1203        B: &Builder<'a>,
1204        V: &'a Value,
1205        Else: &'a BasicBlock,
1206        NumCases: c_uint,
1207    ) -> &'a Value;
1208    pub(crate) fn LLVMBuildLandingPad<'a>(
1209        B: &Builder<'a>,
1210        Ty: &'a Type,
1211        PersFn: Option<&'a Value>,
1212        NumClauses: c_uint,
1213        Name: *const c_char,
1214    ) -> &'a Value;
1215    pub(crate) fn LLVMBuildResume<'a>(B: &Builder<'a>, Exn: &'a Value) -> &'a Value;
1216    pub(crate) fn LLVMBuildUnreachable<'a>(B: &Builder<'a>) -> &'a Value;
1217
1218    pub(crate) fn LLVMBuildCleanupPad<'a>(
1219        B: &Builder<'a>,
1220        ParentPad: Option<&'a Value>,
1221        Args: *const &'a Value,
1222        NumArgs: c_uint,
1223        Name: *const c_char,
1224    ) -> Option<&'a Value>;
1225    pub(crate) fn LLVMBuildCleanupRet<'a>(
1226        B: &Builder<'a>,
1227        CleanupPad: &'a Value,
1228        BB: Option<&'a BasicBlock>,
1229    ) -> Option<&'a Value>;
1230    pub(crate) fn LLVMBuildCatchPad<'a>(
1231        B: &Builder<'a>,
1232        ParentPad: &'a Value,
1233        Args: *const &'a Value,
1234        NumArgs: c_uint,
1235        Name: *const c_char,
1236    ) -> Option<&'a Value>;
1237    pub(crate) fn LLVMBuildCatchRet<'a>(
1238        B: &Builder<'a>,
1239        CatchPad: &'a Value,
1240        BB: &'a BasicBlock,
1241    ) -> Option<&'a Value>;
1242    pub(crate) fn LLVMBuildCatchSwitch<'a>(
1243        Builder: &Builder<'a>,
1244        ParentPad: Option<&'a Value>,
1245        UnwindBB: Option<&'a BasicBlock>,
1246        NumHandlers: c_uint,
1247        Name: *const c_char,
1248    ) -> Option<&'a Value>;
1249    pub(crate) fn LLVMAddHandler<'a>(CatchSwitch: &'a Value, Dest: &'a BasicBlock);
1250    pub(crate) fn LLVMSetPersonalityFn<'a>(Func: &'a Value, Pers: &'a Value);
1251
1252    // Add a case to the switch instruction
1253    pub(crate) fn LLVMAddCase<'a>(Switch: &'a Value, OnVal: &'a Value, Dest: &'a BasicBlock);
1254
1255    // Add a clause to the landing pad instruction
1256    pub(crate) fn LLVMAddClause<'a>(LandingPad: &'a Value, ClauseVal: &'a Value);
1257
1258    // Set the cleanup on a landing pad instruction
1259    pub(crate) fn LLVMSetCleanup(LandingPad: &Value, Val: Bool);
1260
1261    // Arithmetic
1262    pub(crate) fn LLVMBuildAdd<'a>(
1263        B: &Builder<'a>,
1264        LHS: &'a Value,
1265        RHS: &'a Value,
1266        Name: *const c_char,
1267    ) -> &'a Value;
1268    pub(crate) fn LLVMBuildFAdd<'a>(
1269        B: &Builder<'a>,
1270        LHS: &'a Value,
1271        RHS: &'a Value,
1272        Name: *const c_char,
1273    ) -> &'a Value;
1274    pub(crate) fn LLVMBuildSub<'a>(
1275        B: &Builder<'a>,
1276        LHS: &'a Value,
1277        RHS: &'a Value,
1278        Name: *const c_char,
1279    ) -> &'a Value;
1280    pub(crate) fn LLVMBuildFSub<'a>(
1281        B: &Builder<'a>,
1282        LHS: &'a Value,
1283        RHS: &'a Value,
1284        Name: *const c_char,
1285    ) -> &'a Value;
1286    pub(crate) fn LLVMBuildMul<'a>(
1287        B: &Builder<'a>,
1288        LHS: &'a Value,
1289        RHS: &'a Value,
1290        Name: *const c_char,
1291    ) -> &'a Value;
1292    pub(crate) fn LLVMBuildFMul<'a>(
1293        B: &Builder<'a>,
1294        LHS: &'a Value,
1295        RHS: &'a Value,
1296        Name: *const c_char,
1297    ) -> &'a Value;
1298    pub(crate) fn LLVMBuildUDiv<'a>(
1299        B: &Builder<'a>,
1300        LHS: &'a Value,
1301        RHS: &'a Value,
1302        Name: *const c_char,
1303    ) -> &'a Value;
1304    pub(crate) fn LLVMBuildExactUDiv<'a>(
1305        B: &Builder<'a>,
1306        LHS: &'a Value,
1307        RHS: &'a Value,
1308        Name: *const c_char,
1309    ) -> &'a Value;
1310    pub(crate) fn LLVMBuildSDiv<'a>(
1311        B: &Builder<'a>,
1312        LHS: &'a Value,
1313        RHS: &'a Value,
1314        Name: *const c_char,
1315    ) -> &'a Value;
1316    pub(crate) fn LLVMBuildExactSDiv<'a>(
1317        B: &Builder<'a>,
1318        LHS: &'a Value,
1319        RHS: &'a Value,
1320        Name: *const c_char,
1321    ) -> &'a Value;
1322    pub(crate) fn LLVMBuildFDiv<'a>(
1323        B: &Builder<'a>,
1324        LHS: &'a Value,
1325        RHS: &'a Value,
1326        Name: *const c_char,
1327    ) -> &'a Value;
1328    pub(crate) fn LLVMBuildURem<'a>(
1329        B: &Builder<'a>,
1330        LHS: &'a Value,
1331        RHS: &'a Value,
1332        Name: *const c_char,
1333    ) -> &'a Value;
1334    pub(crate) fn LLVMBuildSRem<'a>(
1335        B: &Builder<'a>,
1336        LHS: &'a Value,
1337        RHS: &'a Value,
1338        Name: *const c_char,
1339    ) -> &'a Value;
1340    pub(crate) fn LLVMBuildFRem<'a>(
1341        B: &Builder<'a>,
1342        LHS: &'a Value,
1343        RHS: &'a Value,
1344        Name: *const c_char,
1345    ) -> &'a Value;
1346    pub(crate) fn LLVMBuildShl<'a>(
1347        B: &Builder<'a>,
1348        LHS: &'a Value,
1349        RHS: &'a Value,
1350        Name: *const c_char,
1351    ) -> &'a Value;
1352    pub(crate) fn LLVMBuildLShr<'a>(
1353        B: &Builder<'a>,
1354        LHS: &'a Value,
1355        RHS: &'a Value,
1356        Name: *const c_char,
1357    ) -> &'a Value;
1358    pub(crate) fn LLVMBuildAShr<'a>(
1359        B: &Builder<'a>,
1360        LHS: &'a Value,
1361        RHS: &'a Value,
1362        Name: *const c_char,
1363    ) -> &'a Value;
1364    pub(crate) fn LLVMBuildNSWAdd<'a>(
1365        B: &Builder<'a>,
1366        LHS: &'a Value,
1367        RHS: &'a Value,
1368        Name: *const c_char,
1369    ) -> &'a Value;
1370    pub(crate) fn LLVMBuildNUWAdd<'a>(
1371        B: &Builder<'a>,
1372        LHS: &'a Value,
1373        RHS: &'a Value,
1374        Name: *const c_char,
1375    ) -> &'a Value;
1376    pub(crate) fn LLVMBuildNSWSub<'a>(
1377        B: &Builder<'a>,
1378        LHS: &'a Value,
1379        RHS: &'a Value,
1380        Name: *const c_char,
1381    ) -> &'a Value;
1382    pub(crate) fn LLVMBuildNUWSub<'a>(
1383        B: &Builder<'a>,
1384        LHS: &'a Value,
1385        RHS: &'a Value,
1386        Name: *const c_char,
1387    ) -> &'a Value;
1388    pub(crate) fn LLVMBuildNSWMul<'a>(
1389        B: &Builder<'a>,
1390        LHS: &'a Value,
1391        RHS: &'a Value,
1392        Name: *const c_char,
1393    ) -> &'a Value;
1394    pub(crate) fn LLVMBuildNUWMul<'a>(
1395        B: &Builder<'a>,
1396        LHS: &'a Value,
1397        RHS: &'a Value,
1398        Name: *const c_char,
1399    ) -> &'a Value;
1400    pub(crate) fn LLVMBuildAnd<'a>(
1401        B: &Builder<'a>,
1402        LHS: &'a Value,
1403        RHS: &'a Value,
1404        Name: *const c_char,
1405    ) -> &'a Value;
1406    pub(crate) fn LLVMBuildOr<'a>(
1407        B: &Builder<'a>,
1408        LHS: &'a Value,
1409        RHS: &'a Value,
1410        Name: *const c_char,
1411    ) -> &'a Value;
1412    pub(crate) fn LLVMBuildXor<'a>(
1413        B: &Builder<'a>,
1414        LHS: &'a Value,
1415        RHS: &'a Value,
1416        Name: *const c_char,
1417    ) -> &'a Value;
1418    pub(crate) fn LLVMBuildNeg<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char)
1419    -> &'a Value;
1420    pub(crate) fn LLVMBuildFNeg<'a>(
1421        B: &Builder<'a>,
1422        V: &'a Value,
1423        Name: *const c_char,
1424    ) -> &'a Value;
1425    pub(crate) fn LLVMBuildNot<'a>(B: &Builder<'a>, V: &'a Value, Name: *const c_char)
1426    -> &'a Value;
1427
1428    // Extra flags on arithmetic
1429    pub(crate) fn LLVMSetIsDisjoint(Instr: &Value, IsDisjoint: Bool);
1430    pub(crate) fn LLVMSetNUW(ArithInst: &Value, HasNUW: Bool);
1431    pub(crate) fn LLVMSetNSW(ArithInst: &Value, HasNSW: Bool);
1432
1433    // Memory
1434    pub(crate) fn LLVMBuildAlloca<'a>(
1435        B: &Builder<'a>,
1436        Ty: &'a Type,
1437        Name: *const c_char,
1438    ) -> &'a Value;
1439    pub(crate) fn LLVMBuildLoad2<'a>(
1440        B: &Builder<'a>,
1441        Ty: &'a Type,
1442        PointerVal: &'a Value,
1443        Name: *const c_char,
1444    ) -> &'a Value;
1445
1446    pub(crate) fn LLVMBuildStore<'a>(B: &Builder<'a>, Val: &'a Value, Ptr: &'a Value) -> &'a Value;
1447
1448    pub(crate) fn LLVMBuildGEPWithNoWrapFlags<'a>(
1449        B: &Builder<'a>,
1450        Ty: &'a Type,
1451        Pointer: &'a Value,
1452        Indices: *const &'a Value,
1453        NumIndices: c_uint,
1454        Name: *const c_char,
1455        Flags: GEPNoWrapFlags,
1456    ) -> &'a Value;
1457
1458    // Casts
1459    pub(crate) fn LLVMBuildTrunc<'a>(
1460        B: &Builder<'a>,
1461        Val: &'a Value,
1462        DestTy: &'a Type,
1463        Name: *const c_char,
1464    ) -> &'a Value;
1465    pub(crate) fn LLVMBuildZExt<'a>(
1466        B: &Builder<'a>,
1467        Val: &'a Value,
1468        DestTy: &'a Type,
1469        Name: *const c_char,
1470    ) -> &'a Value;
1471    pub(crate) fn LLVMBuildSExt<'a>(
1472        B: &Builder<'a>,
1473        Val: &'a Value,
1474        DestTy: &'a Type,
1475        Name: *const c_char,
1476    ) -> &'a Value;
1477    pub(crate) fn LLVMBuildFPToUI<'a>(
1478        B: &Builder<'a>,
1479        Val: &'a Value,
1480        DestTy: &'a Type,
1481        Name: *const c_char,
1482    ) -> &'a Value;
1483    pub(crate) fn LLVMBuildFPToSI<'a>(
1484        B: &Builder<'a>,
1485        Val: &'a Value,
1486        DestTy: &'a Type,
1487        Name: *const c_char,
1488    ) -> &'a Value;
1489    pub(crate) fn LLVMBuildUIToFP<'a>(
1490        B: &Builder<'a>,
1491        Val: &'a Value,
1492        DestTy: &'a Type,
1493        Name: *const c_char,
1494    ) -> &'a Value;
1495    pub(crate) fn LLVMBuildSIToFP<'a>(
1496        B: &Builder<'a>,
1497        Val: &'a Value,
1498        DestTy: &'a Type,
1499        Name: *const c_char,
1500    ) -> &'a Value;
1501    pub(crate) fn LLVMBuildFPTrunc<'a>(
1502        B: &Builder<'a>,
1503        Val: &'a Value,
1504        DestTy: &'a Type,
1505        Name: *const c_char,
1506    ) -> &'a Value;
1507    pub(crate) fn LLVMBuildFPExt<'a>(
1508        B: &Builder<'a>,
1509        Val: &'a Value,
1510        DestTy: &'a Type,
1511        Name: *const c_char,
1512    ) -> &'a Value;
1513    pub(crate) fn LLVMBuildPtrToInt<'a>(
1514        B: &Builder<'a>,
1515        Val: &'a Value,
1516        DestTy: &'a Type,
1517        Name: *const c_char,
1518    ) -> &'a Value;
1519    pub(crate) fn LLVMBuildIntToPtr<'a>(
1520        B: &Builder<'a>,
1521        Val: &'a Value,
1522        DestTy: &'a Type,
1523        Name: *const c_char,
1524    ) -> &'a Value;
1525    pub(crate) fn LLVMBuildBitCast<'a>(
1526        B: &Builder<'a>,
1527        Val: &'a Value,
1528        DestTy: &'a Type,
1529        Name: *const c_char,
1530    ) -> &'a Value;
1531    pub(crate) fn LLVMBuildPointerCast<'a>(
1532        B: &Builder<'a>,
1533        Val: &'a Value,
1534        DestTy: &'a Type,
1535        Name: *const c_char,
1536    ) -> &'a Value;
1537    pub(crate) fn LLVMBuildIntCast2<'a>(
1538        B: &Builder<'a>,
1539        Val: &'a Value,
1540        DestTy: &'a Type,
1541        IsSigned: Bool,
1542        Name: *const c_char,
1543    ) -> &'a Value;
1544
1545    // Comparisons
1546    pub(crate) fn LLVMBuildICmp<'a>(
1547        B: &Builder<'a>,
1548        Op: c_uint,
1549        LHS: &'a Value,
1550        RHS: &'a Value,
1551        Name: *const c_char,
1552    ) -> &'a Value;
1553    pub(crate) fn LLVMBuildFCmp<'a>(
1554        B: &Builder<'a>,
1555        Op: c_uint,
1556        LHS: &'a Value,
1557        RHS: &'a Value,
1558        Name: *const c_char,
1559    ) -> &'a Value;
1560
1561    // Miscellaneous instructions
1562    pub(crate) fn LLVMBuildPhi<'a>(B: &Builder<'a>, Ty: &'a Type, Name: *const c_char)
1563    -> &'a Value;
1564    pub(crate) fn LLVMBuildSelect<'a>(
1565        B: &Builder<'a>,
1566        If: &'a Value,
1567        Then: &'a Value,
1568        Else: &'a Value,
1569        Name: *const c_char,
1570    ) -> &'a Value;
1571    pub(crate) fn LLVMBuildVAArg<'a>(
1572        B: &Builder<'a>,
1573        list: &'a Value,
1574        Ty: &'a Type,
1575        Name: *const c_char,
1576    ) -> &'a Value;
1577    pub(crate) fn LLVMBuildExtractElement<'a>(
1578        B: &Builder<'a>,
1579        VecVal: &'a Value,
1580        Index: &'a Value,
1581        Name: *const c_char,
1582    ) -> &'a Value;
1583    pub(crate) fn LLVMBuildInsertElement<'a>(
1584        B: &Builder<'a>,
1585        VecVal: &'a Value,
1586        EltVal: &'a Value,
1587        Index: &'a Value,
1588        Name: *const c_char,
1589    ) -> &'a Value;
1590    pub(crate) fn LLVMBuildShuffleVector<'a>(
1591        B: &Builder<'a>,
1592        V1: &'a Value,
1593        V2: &'a Value,
1594        Mask: &'a Value,
1595        Name: *const c_char,
1596    ) -> &'a Value;
1597    pub(crate) fn LLVMBuildExtractValue<'a>(
1598        B: &Builder<'a>,
1599        AggVal: &'a Value,
1600        Index: c_uint,
1601        Name: *const c_char,
1602    ) -> &'a Value;
1603    pub(crate) fn LLVMBuildInsertValue<'a>(
1604        B: &Builder<'a>,
1605        AggVal: &'a Value,
1606        EltVal: &'a Value,
1607        Index: c_uint,
1608        Name: *const c_char,
1609    ) -> &'a Value;
1610
1611    // Atomic Operations
1612    pub(crate) fn LLVMBuildAtomicCmpXchg<'a>(
1613        B: &Builder<'a>,
1614        LHS: &'a Value,
1615        CMP: &'a Value,
1616        RHS: &'a Value,
1617        Order: AtomicOrdering,
1618        FailureOrder: AtomicOrdering,
1619        SingleThreaded: Bool,
1620    ) -> &'a Value;
1621
1622    pub(crate) fn LLVMSetWeak(CmpXchgInst: &Value, IsWeak: Bool);
1623
1624    pub(crate) fn LLVMBuildAtomicRMW<'a>(
1625        B: &Builder<'a>,
1626        Op: AtomicRmwBinOp,
1627        LHS: &'a Value,
1628        RHS: &'a Value,
1629        Order: AtomicOrdering,
1630        SingleThreaded: Bool,
1631    ) -> &'a Value;
1632
1633    pub(crate) fn LLVMBuildFence<'a>(
1634        B: &Builder<'a>,
1635        Order: AtomicOrdering,
1636        SingleThreaded: Bool,
1637        Name: *const c_char,
1638    ) -> &'a Value;
1639
1640    /// Writes a module to the specified path. Returns 0 on success.
1641    pub(crate) fn LLVMWriteBitcodeToFile(M: &Module, Path: *const c_char) -> c_int;
1642
1643    /// Creates a legacy pass manager -- only used for final codegen.
1644    pub(crate) fn LLVMCreatePassManager<'a>() -> &'a mut PassManager<'a>;
1645
1646    pub(crate) fn LLVMAddAnalysisPasses<'a>(T: &'a TargetMachine, PM: &PassManager<'a>);
1647
1648    pub(crate) fn LLVMGetHostCPUFeatures() -> *mut c_char;
1649
1650    pub(crate) fn LLVMDisposeMessage(message: *mut c_char);
1651
1652    pub(crate) fn LLVMIsMultithreaded() -> Bool;
1653
1654    pub(crate) fn LLVMStructCreateNamed(C: &Context, Name: *const c_char) -> &Type;
1655
1656    pub(crate) fn LLVMStructSetBody<'a>(
1657        StructTy: &'a Type,
1658        ElementTypes: *const &'a Type,
1659        ElementCount: c_uint,
1660        Packed: Bool,
1661    );
1662
1663    pub(crate) safe fn LLVMMetadataAsValue<'a>(C: &'a Context, MD: &'a Metadata) -> &'a Value;
1664
1665    pub(crate) safe fn LLVMSetUnnamedAddress(Global: &Value, UnnamedAddr: UnnamedAddr);
1666
1667    pub(crate) fn LLVMIsAConstantInt(value_ref: &Value) -> Option<&ConstantInt>;
1668
1669    pub(crate) fn LLVMGetOrInsertComdat(M: &Module, Name: *const c_char) -> &Comdat;
1670    pub(crate) fn LLVMSetComdat(V: &Value, C: &Comdat);
1671
1672    pub(crate) fn LLVMCreateOperandBundle(
1673        Tag: *const c_char,
1674        TagLen: size_t,
1675        Args: *const &'_ Value,
1676        NumArgs: c_uint,
1677    ) -> *mut OperandBundle<'_>;
1678    pub(crate) fn LLVMDisposeOperandBundle(Bundle: ptr::NonNull<OperandBundle<'_>>);
1679
1680    pub(crate) fn LLVMBuildCallWithOperandBundles<'a>(
1681        B: &Builder<'a>,
1682        Ty: &'a Type,
1683        Fn: &'a Value,
1684        Args: *const &'a Value,
1685        NumArgs: c_uint,
1686        Bundles: *const &OperandBundle<'a>,
1687        NumBundles: c_uint,
1688        Name: *const c_char,
1689    ) -> &'a Value;
1690    pub(crate) fn LLVMBuildInvokeWithOperandBundles<'a>(
1691        B: &Builder<'a>,
1692        Ty: &'a Type,
1693        Fn: &'a Value,
1694        Args: *const &'a Value,
1695        NumArgs: c_uint,
1696        Then: &'a BasicBlock,
1697        Catch: &'a BasicBlock,
1698        Bundles: *const &OperandBundle<'a>,
1699        NumBundles: c_uint,
1700        Name: *const c_char,
1701    ) -> &'a Value;
1702    pub(crate) fn LLVMBuildCallBr<'a>(
1703        B: &Builder<'a>,
1704        Ty: &'a Type,
1705        Fn: &'a Value,
1706        DefaultDest: &'a BasicBlock,
1707        IndirectDests: *const &'a BasicBlock,
1708        NumIndirectDests: c_uint,
1709        Args: *const &'a Value,
1710        NumArgs: c_uint,
1711        Bundles: *const &OperandBundle<'a>,
1712        NumBundles: c_uint,
1713        Name: *const c_char,
1714    ) -> &'a Value;
1715}
1716
1717#[cfg(feature = "llvm_offload")]
1718pub(crate) use self::Offload::*;
1719
1720#[cfg(feature = "llvm_offload")]
1721mod Offload {
1722    use super::*;
1723    unsafe extern "C" {
1724        /// Processes the module and writes it in an offload compatible way into a "host.out" file.
1725        pub(crate) fn LLVMRustBundleImages<'a>(M: &'a Module, TM: &'a TargetMachine) -> bool;
1726        pub(crate) fn LLVMRustOffloadMapper<'a>(OldFn: &'a Value, NewFn: &'a Value);
1727    }
1728}
1729
1730#[cfg(not(feature = "llvm_offload"))]
1731pub(crate) use self::Offload_fallback::*;
1732
1733#[cfg(not(feature = "llvm_offload"))]
1734mod Offload_fallback {
1735    use super::*;
1736    /// Processes the module and writes it in an offload compatible way into a "host.out" file.
1737    /// Marked as unsafe to match the real offload wrapper which is unsafe due to FFI.
1738    #[allow(unused_unsafe)]
1739    pub(crate) unsafe fn LLVMRustBundleImages<'a>(_M: &'a Module, _TM: &'a TargetMachine) -> bool {
1740        unimplemented!("This rustc version was not built with LLVM Offload support!");
1741    }
1742    #[allow(unused_unsafe)]
1743    pub(crate) unsafe fn LLVMRustOffloadMapper<'a>(_OldFn: &'a Value, _NewFn: &'a Value) {
1744        unimplemented!("This rustc version was not built with LLVM Offload support!");
1745    }
1746}
1747
1748// FFI bindings for `DIBuilder` functions in the LLVM-C API.
1749// Try to keep these in the same order as in `llvm/include/llvm-c/DebugInfo.h`.
1750//
1751// FIXME(#134001): Audit all `Option` parameters, especially in lists, to check
1752// that they really are nullable on the C/C++ side. LLVM doesn't appear to
1753// actually document which ones are nullable.
1754unsafe extern "C" {
1755    pub(crate) fn LLVMCreateDIBuilder<'ll>(M: &'ll Module) -> *mut DIBuilder<'ll>;
1756    pub(crate) fn LLVMDisposeDIBuilder<'ll>(Builder: ptr::NonNull<DIBuilder<'ll>>);
1757
1758    pub(crate) fn LLVMDIBuilderFinalize<'ll>(Builder: &DIBuilder<'ll>);
1759
1760    pub(crate) fn LLVMDIBuilderCreateNameSpace<'ll>(
1761        Builder: &DIBuilder<'ll>,
1762        ParentScope: Option<&'ll Metadata>,
1763        Name: *const c_uchar, // See "PTR_LEN_STR".
1764        NameLen: size_t,
1765        ExportSymbols: llvm::Bool,
1766    ) -> &'ll Metadata;
1767
1768    pub(crate) fn LLVMDIBuilderCreateLexicalBlock<'ll>(
1769        Builder: &DIBuilder<'ll>,
1770        Scope: &'ll Metadata,
1771        File: &'ll Metadata,
1772        Line: c_uint,
1773        Column: c_uint,
1774    ) -> &'ll Metadata;
1775
1776    pub(crate) fn LLVMDIBuilderCreateLexicalBlockFile<'ll>(
1777        Builder: &DIBuilder<'ll>,
1778        Scope: &'ll Metadata,
1779        File: &'ll Metadata,
1780        Discriminator: c_uint, // (optional "DWARF path discriminator"; default is 0)
1781    ) -> &'ll Metadata;
1782
1783    pub(crate) fn LLVMDIBuilderCreateDebugLocation<'ll>(
1784        Ctx: &'ll Context,
1785        Line: c_uint,
1786        Column: c_uint,
1787        Scope: &'ll Metadata,
1788        InlinedAt: Option<&'ll Metadata>,
1789    ) -> &'ll Metadata;
1790
1791    pub(crate) fn LLVMDIBuilderCreateSubroutineType<'ll>(
1792        Builder: &DIBuilder<'ll>,
1793        File: Option<&'ll Metadata>, // (ignored and has no effect)
1794        ParameterTypes: *const Option<&'ll Metadata>,
1795        NumParameterTypes: c_uint,
1796        Flags: DIFlags, // (default is `DIFlags::DIFlagZero`)
1797    ) -> &'ll Metadata;
1798
1799    pub(crate) fn LLVMDIBuilderCreateUnionType<'ll>(
1800        Builder: &DIBuilder<'ll>,
1801        Scope: Option<&'ll Metadata>,
1802        Name: *const c_uchar, // See "PTR_LEN_STR".
1803        NameLen: size_t,
1804        File: &'ll Metadata,
1805        LineNumber: c_uint,
1806        SizeInBits: u64,
1807        AlignInBits: u32,
1808        Flags: DIFlags,
1809        Elements: *const Option<&'ll Metadata>,
1810        NumElements: c_uint,
1811        RunTimeLang: c_uint, // (optional Objective-C runtime version; default is 0)
1812        UniqueId: *const c_uchar, // See "PTR_LEN_STR".
1813        UniqueIdLen: size_t,
1814    ) -> &'ll Metadata;
1815
1816    pub(crate) fn LLVMDIBuilderCreateArrayType<'ll>(
1817        Builder: &DIBuilder<'ll>,
1818        Size: u64,
1819        Align: u32,
1820        Ty: &'ll Metadata,
1821        Subscripts: *const &'ll Metadata,
1822        NumSubscripts: c_uint,
1823    ) -> &'ll Metadata;
1824
1825    pub(crate) fn LLVMDIBuilderCreateBasicType<'ll>(
1826        Builder: &DIBuilder<'ll>,
1827        Name: *const c_uchar, // See "PTR_LEN_STR".
1828        NameLen: size_t,
1829        SizeInBits: u64,
1830        Encoding: c_uint, // (`LLVMDWARFTypeEncoding`)
1831        Flags: DIFlags,   // (default is `DIFlags::DIFlagZero`)
1832    ) -> &'ll Metadata;
1833
1834    pub(crate) fn LLVMDIBuilderCreatePointerType<'ll>(
1835        Builder: &DIBuilder<'ll>,
1836        PointeeTy: &'ll Metadata,
1837        SizeInBits: u64,
1838        AlignInBits: u32,
1839        AddressSpace: c_uint, // (optional DWARF address space; default is 0)
1840        Name: *const c_uchar, // See "PTR_LEN_STR".
1841        NameLen: size_t,
1842    ) -> &'ll Metadata;
1843
1844    pub(crate) fn LLVMDIBuilderCreateStructType<'ll>(
1845        Builder: &DIBuilder<'ll>,
1846        Scope: Option<&'ll Metadata>,
1847        Name: *const c_uchar, // See "PTR_LEN_STR".
1848        NameLen: size_t,
1849        File: &'ll Metadata,
1850        LineNumber: c_uint,
1851        SizeInBits: u64,
1852        AlignInBits: u32,
1853        Flags: DIFlags,
1854        DerivedFrom: Option<&'ll Metadata>,
1855        Elements: *const Option<&'ll Metadata>,
1856        NumElements: c_uint,
1857        RunTimeLang: c_uint, // (optional Objective-C runtime version; default is 0)
1858        VTableHolder: Option<&'ll Metadata>,
1859        UniqueId: *const c_uchar, // See "PTR_LEN_STR".
1860        UniqueIdLen: size_t,
1861    ) -> &'ll Metadata;
1862
1863    pub(crate) fn LLVMDIBuilderCreateMemberType<'ll>(
1864        Builder: &DIBuilder<'ll>,
1865        Scope: &'ll Metadata,
1866        Name: *const c_uchar, // See "PTR_LEN_STR".
1867        NameLen: size_t,
1868        File: &'ll Metadata,
1869        LineNo: c_uint,
1870        SizeInBits: u64,
1871        AlignInBits: u32,
1872        OffsetInBits: u64,
1873        Flags: DIFlags,
1874        Ty: &'ll Metadata,
1875    ) -> &'ll Metadata;
1876
1877    pub(crate) fn LLVMDIBuilderCreateStaticMemberType<'ll>(
1878        Builder: &DIBuilder<'ll>,
1879        Scope: &'ll Metadata,
1880        Name: *const c_uchar, // See "PTR_LEN_STR".
1881        NameLen: size_t,
1882        File: &'ll Metadata,
1883        LineNumber: c_uint,
1884        Type: &'ll Metadata,
1885        Flags: DIFlags,
1886        ConstantVal: Option<&'ll Value>,
1887        AlignInBits: u32,
1888    ) -> &'ll Metadata;
1889
1890    /// Creates a "qualified type" in the C/C++ sense, by adding modifiers
1891    /// like `const` or `volatile`.
1892    pub(crate) fn LLVMDIBuilderCreateQualifiedType<'ll>(
1893        Builder: &DIBuilder<'ll>,
1894        Tag: c_uint, // (DWARF tag, e.g. `DW_TAG_const_type`)
1895        Type: &'ll Metadata,
1896    ) -> &'ll Metadata;
1897
1898    pub(crate) fn LLVMDIBuilderCreateTypedef<'ll>(
1899        Builder: &DIBuilder<'ll>,
1900        Type: &'ll Metadata,
1901        Name: *const c_uchar, // See "PTR_LEN_STR".
1902        NameLen: size_t,
1903        File: &'ll Metadata,
1904        LineNo: c_uint,
1905        Scope: Option<&'ll Metadata>,
1906        AlignInBits: u32, // (optional; default is 0)
1907    ) -> &'ll Metadata;
1908
1909    pub(crate) fn LLVMDIBuilderGetOrCreateSubrange<'ll>(
1910        Builder: &DIBuilder<'ll>,
1911        LowerBound: i64,
1912        Count: i64,
1913    ) -> &'ll Metadata;
1914
1915    pub(crate) fn LLVMDIBuilderGetOrCreateArray<'ll>(
1916        Builder: &DIBuilder<'ll>,
1917        Data: *const Option<&'ll Metadata>,
1918        NumElements: size_t,
1919    ) -> &'ll Metadata;
1920
1921    pub(crate) fn LLVMDIBuilderCreateExpression<'ll>(
1922        Builder: &DIBuilder<'ll>,
1923        Addr: *const u64,
1924        Length: size_t,
1925    ) -> &'ll Metadata;
1926
1927    pub(crate) fn LLVMDIBuilderCreateGlobalVariableExpression<'ll>(
1928        Builder: &DIBuilder<'ll>,
1929        Scope: Option<&'ll Metadata>,
1930        Name: *const c_uchar, // See "PTR_LEN_STR".
1931        NameLen: size_t,
1932        Linkage: *const c_uchar, // See "PTR_LEN_STR".
1933        LinkLen: size_t,
1934        File: &'ll Metadata,
1935        LineNo: c_uint,
1936        Ty: &'ll Metadata,
1937        LocalToUnit: llvm::Bool,
1938        Expr: &'ll Metadata,
1939        Decl: Option<&'ll Metadata>,
1940        AlignInBits: u32,
1941    ) -> &'ll Metadata;
1942
1943    pub(crate) fn LLVMDIBuilderInsertDeclareRecordAtEnd<'ll>(
1944        Builder: &DIBuilder<'ll>,
1945        Storage: &'ll Value,
1946        VarInfo: &'ll Metadata,
1947        Expr: &'ll Metadata,
1948        DebugLoc: &'ll Metadata,
1949        Block: &'ll BasicBlock,
1950    ) -> &'ll DbgRecord;
1951
1952    pub(crate) fn LLVMDIBuilderInsertDbgValueRecordAtEnd<'ll>(
1953        Builder: &DIBuilder<'ll>,
1954        Val: &'ll Value,
1955        VarInfo: &'ll Metadata,
1956        Expr: &'ll Metadata,
1957        DebugLoc: &'ll Metadata,
1958        Block: &'ll BasicBlock,
1959    ) -> &'ll DbgRecord;
1960
1961    pub(crate) fn LLVMDIBuilderCreateAutoVariable<'ll>(
1962        Builder: &DIBuilder<'ll>,
1963        Scope: &'ll Metadata,
1964        Name: *const c_uchar, // See "PTR_LEN_STR".
1965        NameLen: size_t,
1966        File: &'ll Metadata,
1967        LineNo: c_uint,
1968        Ty: &'ll Metadata,
1969        AlwaysPreserve: llvm::Bool, // "If true, this descriptor will survive optimizations."
1970        Flags: DIFlags,
1971        AlignInBits: u32,
1972    ) -> &'ll Metadata;
1973
1974    pub(crate) fn LLVMDIBuilderCreateParameterVariable<'ll>(
1975        Builder: &DIBuilder<'ll>,
1976        Scope: &'ll Metadata,
1977        Name: *const c_uchar, // See "PTR_LEN_STR".
1978        NameLen: size_t,
1979        ArgNo: c_uint,
1980        File: &'ll Metadata,
1981        LineNo: c_uint,
1982        Ty: &'ll Metadata,
1983        AlwaysPreserve: llvm::Bool, // "If true, this descriptor will survive optimizations."
1984        Flags: DIFlags,
1985    ) -> &'ll Metadata;
1986}
1987
1988#[link(name = "llvm-wrapper", kind = "static")]
1989unsafe extern "C" {
1990    pub(crate) fn LLVMRustInstallErrorHandlers();
1991    pub(crate) fn LLVMRustDisableSystemDialogsOnCrash();
1992
1993    // Operations on all values
1994    pub(crate) fn LLVMRustGlobalAddMetadata<'a>(
1995        Val: &'a Value,
1996        KindID: MetadataKindId,
1997        Metadata: &'a Metadata,
1998    );
1999    pub(crate) fn LLVMRustIsNonGVFunctionPointerTy(Val: &Value) -> bool;
2000
2001    // Operations on scalar constants
2002    pub(crate) fn LLVMRustConstIntGetZExtValue(ConstantVal: &ConstantInt, Value: &mut u64) -> bool;
2003    pub(crate) fn LLVMRustConstInt128Get(
2004        ConstantVal: &ConstantInt,
2005        SExt: bool,
2006        high: &mut u64,
2007        low: &mut u64,
2008    ) -> bool;
2009
2010    // Operations on global variables, functions, and aliases (globals)
2011    pub(crate) fn LLVMRustSetDSOLocal(Global: &Value, is_dso_local: bool);
2012
2013    // Operations on global variables
2014    pub(crate) fn LLVMRustGetOrInsertGlobal<'a>(
2015        M: &'a Module,
2016        Name: *const c_char,
2017        NameLen: size_t,
2018        T: &'a Type,
2019    ) -> &'a Value;
2020    pub(crate) fn LLVMRustGetNamedValue(
2021        M: &Module,
2022        Name: *const c_char,
2023        NameLen: size_t,
2024    ) -> Option<&Value>;
2025
2026    // Operations on attributes
2027    pub(crate) fn LLVMRustCreateAttrNoValue(C: &Context, attr: AttributeKind) -> &Attribute;
2028    pub(crate) fn LLVMRustCreateAlignmentAttr(C: &Context, bytes: u64) -> &Attribute;
2029    pub(crate) fn LLVMRustCreateDereferenceableAttr(C: &Context, bytes: u64) -> &Attribute;
2030    pub(crate) fn LLVMRustCreateDereferenceableOrNullAttr(C: &Context, bytes: u64) -> &Attribute;
2031    pub(crate) fn LLVMRustCreateByValAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
2032    pub(crate) fn LLVMRustCreateStructRetAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
2033    pub(crate) fn LLVMRustCreateElementTypeAttr<'a>(C: &'a Context, ty: &'a Type) -> &'a Attribute;
2034    pub(crate) fn LLVMRustCreateUWTableAttr(C: &Context, async_: bool) -> &Attribute;
2035    pub(crate) fn LLVMRustCreateAllocSizeAttr(C: &Context, size_arg: u32) -> &Attribute;
2036    pub(crate) fn LLVMRustCreateAllocKindAttr(C: &Context, size_arg: u64) -> &Attribute;
2037    pub(crate) fn LLVMRustCreateMemoryEffectsAttr(
2038        C: &Context,
2039        effects: MemoryEffects,
2040    ) -> &Attribute;
2041    /// ## Safety
2042    /// - Each of `LowerWords` and `UpperWords` must point to an array that is
2043    ///   long enough to fully define an integer of size `NumBits`, i.e. each
2044    ///   pointer must point to `NumBits.div_ceil(64)` elements or more.
2045    /// - The implementation will make its own copy of the pointed-to `u64`
2046    ///   values, so the pointers only need to outlive this function call.
2047    pub(crate) fn LLVMRustCreateRangeAttribute(
2048        C: &Context,
2049        NumBits: c_uint,
2050        LowerWords: *const u64,
2051        UpperWords: *const u64,
2052    ) -> &Attribute;
2053
2054    // Operations on functions
2055    pub(crate) fn LLVMRustGetOrInsertFunction<'a>(
2056        M: &'a Module,
2057        Name: *const c_char,
2058        NameLen: size_t,
2059        FunctionTy: &'a Type,
2060    ) -> &'a Value;
2061    pub(crate) fn LLVMRustAddFunctionAttributes<'a>(
2062        Fn: &'a Value,
2063        index: c_uint,
2064        Attrs: *const &'a Attribute,
2065        AttrsLen: size_t,
2066    );
2067
2068    // Operations on call sites
2069    pub(crate) fn LLVMRustAddCallSiteAttributes<'a>(
2070        Instr: &'a Value,
2071        index: c_uint,
2072        Attrs: *const &'a Attribute,
2073        AttrsLen: size_t,
2074    );
2075
2076    pub(crate) fn LLVMRustSetFastMath(Instr: &Value);
2077    pub(crate) fn LLVMRustSetAlgebraicMath(Instr: &Value);
2078    pub(crate) fn LLVMRustSetAllowReassoc(Instr: &Value);
2079
2080    // Miscellaneous instructions
2081    pub(crate) fn LLVMRustBuildMemCpy<'a>(
2082        B: &Builder<'a>,
2083        Dst: &'a Value,
2084        DstAlign: c_uint,
2085        Src: &'a Value,
2086        SrcAlign: c_uint,
2087        Size: &'a Value,
2088        IsVolatile: bool,
2089    ) -> &'a Value;
2090    pub(crate) fn LLVMRustBuildMemMove<'a>(
2091        B: &Builder<'a>,
2092        Dst: &'a Value,
2093        DstAlign: c_uint,
2094        Src: &'a Value,
2095        SrcAlign: c_uint,
2096        Size: &'a Value,
2097        IsVolatile: bool,
2098    ) -> &'a Value;
2099    pub(crate) fn LLVMRustBuildMemSet<'a>(
2100        B: &Builder<'a>,
2101        Dst: &'a Value,
2102        DstAlign: c_uint,
2103        Val: &'a Value,
2104        Size: &'a Value,
2105        IsVolatile: bool,
2106    ) -> &'a Value;
2107
2108    pub(crate) fn LLVMRustTimeTraceProfilerInitialize();
2109
2110    pub(crate) fn LLVMRustTimeTraceProfilerFinishThread();
2111
2112    pub(crate) fn LLVMRustTimeTraceProfilerFinish(FileName: *const c_char);
2113
2114    /// Returns a string describing the last error caused by an LLVMRust* call.
2115    pub(crate) fn LLVMRustGetLastError() -> *const c_char;
2116
2117    /// Prints the timing information collected by `-Ztime-llvm-passes`.
2118    pub(crate) fn LLVMRustPrintPassTimings(OutStr: &RustString);
2119
2120    /// Prints the statistics collected by `-Zprint-codegen-stats`.
2121    pub(crate) fn LLVMRustPrintStatistics(OutStr: &RustString);
2122
2123    pub(crate) fn LLVMRustInlineAsmVerify(
2124        Ty: &Type,
2125        Constraints: *const c_uchar, // See "PTR_LEN_STR".
2126        ConstraintsLen: size_t,
2127    ) -> bool;
2128
2129    /// A list of pointer-length strings is passed as two pointer-length slices,
2130    /// one slice containing pointers and one slice containing their corresponding
2131    /// lengths. The implementation will check that both slices have the same length.
2132    pub(crate) fn LLVMRustCoverageWriteFilenamesToBuffer(
2133        Filenames: *const *const c_uchar, // See "PTR_LEN_STR".
2134        FilenamesLen: size_t,
2135        Lengths: *const size_t,
2136        LengthsLen: size_t,
2137        BufferOut: &RustString,
2138    );
2139
2140    pub(crate) fn LLVMRustCoverageWriteFunctionMappingsToBuffer(
2141        VirtualFileMappingIDs: *const c_uint,
2142        NumVirtualFileMappingIDs: size_t,
2143        Expressions: *const crate::coverageinfo::ffi::CounterExpression,
2144        NumExpressions: size_t,
2145        CodeRegions: *const crate::coverageinfo::ffi::CodeRegion,
2146        NumCodeRegions: size_t,
2147        ExpansionRegions: *const crate::coverageinfo::ffi::ExpansionRegion,
2148        NumExpansionRegions: size_t,
2149        BranchRegions: *const crate::coverageinfo::ffi::BranchRegion,
2150        NumBranchRegions: size_t,
2151        BufferOut: &RustString,
2152    );
2153
2154    pub(crate) fn LLVMRustCoverageCreatePGOFuncNameVar(
2155        F: &Value,
2156        FuncName: *const c_uchar, // See "PTR_LEN_STR".
2157        FuncNameLen: size_t,
2158    ) -> &Value;
2159    pub(crate) fn LLVMRustCoverageHashBytes(
2160        Bytes: *const c_uchar, // See "PTR_LEN_STR".
2161        NumBytes: size_t,
2162    ) -> u64;
2163
2164    pub(crate) safe fn LLVMRustCoverageWriteCovmapSectionNameToString(
2165        M: &Module,
2166        OutStr: &RustString,
2167    );
2168    pub(crate) safe fn LLVMRustCoverageWriteCovfunSectionNameToString(
2169        M: &Module,
2170        OutStr: &RustString,
2171    );
2172    pub(crate) safe fn LLVMRustCoverageWriteCovmapVarNameToString(OutStr: &RustString);
2173
2174    pub(crate) safe fn LLVMRustCoverageMappingVersion() -> u32;
2175    pub(crate) fn LLVMRustDebugMetadataVersion() -> u32;
2176    pub(crate) fn LLVMRustVersionMajor() -> u32;
2177    pub(crate) fn LLVMRustVersionMinor() -> u32;
2178    pub(crate) fn LLVMRustVersionPatch() -> u32;
2179
2180    /// Add LLVM module flags.
2181    ///
2182    /// In order for Rust-C LTO to work, module flags must be compatible with Clang. What
2183    /// "compatible" means depends on the merge behaviors involved.
2184    pub(crate) fn LLVMRustAddModuleFlagU32(
2185        M: &Module,
2186        MergeBehavior: ModuleFlagMergeBehavior,
2187        Name: *const c_char,
2188        NameLen: size_t,
2189        Value: u32,
2190    );
2191
2192    pub(crate) fn LLVMRustAddModuleFlagString(
2193        M: &Module,
2194        MergeBehavior: ModuleFlagMergeBehavior,
2195        Name: *const c_char,
2196        NameLen: size_t,
2197        Value: *const c_char,
2198        ValueLen: size_t,
2199    );
2200
2201    pub(crate) fn LLVMRustDIBuilderCreateCompileUnit<'a>(
2202        Builder: &DIBuilder<'a>,
2203        Lang: c_uint,
2204        File: &'a DIFile,
2205        Producer: *const c_char,
2206        ProducerLen: size_t,
2207        isOptimized: bool,
2208        Flags: *const c_char,
2209        RuntimeVer: c_uint,
2210        SplitName: *const c_char,
2211        SplitNameLen: size_t,
2212        kind: DebugEmissionKind,
2213        DWOId: u64,
2214        SplitDebugInlining: bool,
2215        DebugNameTableKind: DebugNameTableKind,
2216    ) -> &'a DIDescriptor;
2217
2218    pub(crate) fn LLVMRustDIBuilderCreateFile<'a>(
2219        Builder: &DIBuilder<'a>,
2220        Filename: *const c_char,
2221        FilenameLen: size_t,
2222        Directory: *const c_char,
2223        DirectoryLen: size_t,
2224        CSKind: ChecksumKind,
2225        Checksum: *const c_char,
2226        ChecksumLen: size_t,
2227        Source: *const c_char,
2228        SourceLen: size_t,
2229    ) -> &'a DIFile;
2230
2231    pub(crate) fn LLVMRustDIBuilderCreateFunction<'a>(
2232        Builder: &DIBuilder<'a>,
2233        Scope: &'a DIDescriptor,
2234        Name: *const c_char,
2235        NameLen: size_t,
2236        LinkageName: *const c_char,
2237        LinkageNameLen: size_t,
2238        File: &'a DIFile,
2239        LineNo: c_uint,
2240        Ty: &'a DIType,
2241        ScopeLine: c_uint,
2242        Flags: DIFlags,
2243        SPFlags: DISPFlags,
2244        MaybeFn: Option<&'a Value>,
2245        TParam: &'a DIArray,
2246        Decl: Option<&'a DIDescriptor>,
2247    ) -> &'a DISubprogram;
2248
2249    pub(crate) fn LLVMRustDIBuilderCreateMethod<'a>(
2250        Builder: &DIBuilder<'a>,
2251        Scope: &'a DIDescriptor,
2252        Name: *const c_char,
2253        NameLen: size_t,
2254        LinkageName: *const c_char,
2255        LinkageNameLen: size_t,
2256        File: &'a DIFile,
2257        LineNo: c_uint,
2258        Ty: &'a DIType,
2259        Flags: DIFlags,
2260        SPFlags: DISPFlags,
2261        TParam: &'a DIArray,
2262    ) -> &'a DISubprogram;
2263
2264    pub(crate) fn LLVMRustDIBuilderCreateVariantMemberType<'a>(
2265        Builder: &DIBuilder<'a>,
2266        Scope: &'a DIScope,
2267        Name: *const c_char,
2268        NameLen: size_t,
2269        File: &'a DIFile,
2270        LineNumber: c_uint,
2271        SizeInBits: u64,
2272        AlignInBits: u32,
2273        OffsetInBits: u64,
2274        Discriminant: Option<&'a Value>,
2275        Flags: DIFlags,
2276        Ty: &'a DIType,
2277    ) -> &'a DIType;
2278
2279    pub(crate) fn LLVMRustDIBuilderCreateEnumerator<'a>(
2280        Builder: &DIBuilder<'a>,
2281        Name: *const c_char,
2282        NameLen: size_t,
2283        Value: *const u64,
2284        SizeInBits: c_uint,
2285        IsUnsigned: bool,
2286    ) -> &'a DIEnumerator;
2287
2288    pub(crate) fn LLVMRustDIBuilderCreateEnumerationType<'a>(
2289        Builder: &DIBuilder<'a>,
2290        Scope: &'a DIScope,
2291        Name: *const c_char,
2292        NameLen: size_t,
2293        File: &'a DIFile,
2294        LineNumber: c_uint,
2295        SizeInBits: u64,
2296        AlignInBits: u32,
2297        Elements: &'a DIArray,
2298        ClassType: &'a DIType,
2299        IsScoped: bool,
2300    ) -> &'a DIType;
2301
2302    pub(crate) fn LLVMRustDIBuilderCreateVariantPart<'a>(
2303        Builder: &DIBuilder<'a>,
2304        Scope: &'a DIScope,
2305        Name: *const c_char,
2306        NameLen: size_t,
2307        File: &'a DIFile,
2308        LineNo: c_uint,
2309        SizeInBits: u64,
2310        AlignInBits: u32,
2311        Flags: DIFlags,
2312        Discriminator: Option<&'a DIDerivedType>,
2313        Elements: &'a DIArray,
2314        UniqueId: *const c_char,
2315        UniqueIdLen: size_t,
2316    ) -> &'a DIDerivedType;
2317
2318    pub(crate) fn LLVMRustDIBuilderCreateTemplateTypeParameter<'a>(
2319        Builder: &DIBuilder<'a>,
2320        Scope: Option<&'a DIScope>,
2321        Name: *const c_char,
2322        NameLen: size_t,
2323        Ty: &'a DIType,
2324    ) -> &'a DITemplateTypeParameter;
2325
2326    pub(crate) fn LLVMRustDICompositeTypeReplaceArrays<'a>(
2327        Builder: &DIBuilder<'a>,
2328        CompositeType: &'a DIType,
2329        Elements: Option<&'a DIArray>,
2330        Params: Option<&'a DIArray>,
2331    );
2332
2333    pub(crate) fn LLVMRustDILocationCloneWithBaseDiscriminator<'a>(
2334        Location: &'a DILocation,
2335        BD: c_uint,
2336    ) -> Option<&'a DILocation>;
2337
2338    pub(crate) fn LLVMRustWriteTypeToString(Type: &Type, s: &RustString);
2339    pub(crate) fn LLVMRustWriteValueToString(value_ref: &Value, s: &RustString);
2340
2341    pub(crate) fn LLVMRustHasFeature(T: &TargetMachine, s: *const c_char) -> bool;
2342
2343    pub(crate) fn LLVMRustPrintTargetCPUs(TM: &TargetMachine, OutStr: &RustString);
2344    pub(crate) fn LLVMRustGetTargetFeaturesCount(T: &TargetMachine) -> size_t;
2345    pub(crate) fn LLVMRustGetTargetFeature(
2346        T: &TargetMachine,
2347        Index: size_t,
2348        Feature: &mut *const c_char,
2349        Desc: &mut *const c_char,
2350    );
2351
2352    pub(crate) fn LLVMRustGetHostCPUName(LenOut: &mut size_t) -> *const u8;
2353
2354    // This function makes copies of pointed to data, so the data's lifetime may end after this
2355    // function returns.
2356    pub(crate) fn LLVMRustCreateTargetMachine(
2357        Triple: *const c_char,
2358        CPU: *const c_char,
2359        Features: *const c_char,
2360        Abi: *const c_char,
2361        Model: CodeModel,
2362        Reloc: RelocModel,
2363        Level: CodeGenOptLevel,
2364        FloatABIType: FloatAbi,
2365        FunctionSections: bool,
2366        DataSections: bool,
2367        UniqueSectionNames: bool,
2368        TrapUnreachable: bool,
2369        Singlethread: bool,
2370        VerboseAsm: bool,
2371        EmitStackSizeSection: bool,
2372        RelaxELFRelocations: bool,
2373        UseInitArray: bool,
2374        SplitDwarfFile: *const c_char,
2375        OutputObjFile: *const c_char,
2376        DebugInfoCompression: CompressionKind,
2377        UseEmulatedTls: bool,
2378        UseWasmEH: bool,
2379    ) -> *mut TargetMachine;
2380
2381    pub(crate) fn LLVMRustAddLibraryInfo<'a>(
2382        PM: &PassManager<'a>,
2383        M: &'a Module,
2384        DisableSimplifyLibCalls: bool,
2385    );
2386    pub(crate) fn LLVMRustWriteOutputFile<'a>(
2387        T: &'a TargetMachine,
2388        PM: *mut PassManager<'a>,
2389        M: &'a Module,
2390        Output: *const c_char,
2391        DwoOutput: *const c_char,
2392        FileType: FileType,
2393        VerifyIR: bool,
2394    ) -> LLVMRustResult;
2395    pub(crate) fn LLVMRustOptimize<'a>(
2396        M: &'a Module,
2397        TM: &'a TargetMachine,
2398        OptLevel: PassBuilderOptLevel,
2399        OptStage: OptStage,
2400        IsLinkerPluginLTO: bool,
2401        NoPrepopulatePasses: bool,
2402        VerifyIR: bool,
2403        LintIR: bool,
2404        ThinLTOBuffer: Option<&mut *mut ThinLTOBuffer>,
2405        EmitThinLTO: bool,
2406        EmitThinLTOSummary: bool,
2407        MergeFunctions: bool,
2408        UnrollLoops: bool,
2409        SLPVectorize: bool,
2410        LoopVectorize: bool,
2411        DisableSimplifyLibCalls: bool,
2412        EmitLifetimeMarkers: bool,
2413        RunEnzyme: bool,
2414        PrintBeforeEnzyme: bool,
2415        PrintAfterEnzyme: bool,
2416        PrintPasses: bool,
2417        SanitizerOptions: Option<&SanitizerOptions>,
2418        PGOGenPath: *const c_char,
2419        PGOUsePath: *const c_char,
2420        InstrumentCoverage: bool,
2421        InstrProfileOutput: *const c_char,
2422        PGOSampleUsePath: *const c_char,
2423        DebugInfoForProfiling: bool,
2424        llvm_selfprofiler: *mut c_void,
2425        begin_callback: SelfProfileBeforePassCallback,
2426        end_callback: SelfProfileAfterPassCallback,
2427        ExtraPasses: *const c_char,
2428        ExtraPassesLen: size_t,
2429        LLVMPlugins: *const c_char,
2430        LLVMPluginsLen: size_t,
2431    ) -> LLVMRustResult;
2432    pub(crate) fn LLVMRustPrintModule(
2433        M: &Module,
2434        Output: *const c_char,
2435        Demangle: extern "C" fn(*const c_char, size_t, *mut c_char, size_t) -> size_t,
2436    ) -> LLVMRustResult;
2437    pub(crate) fn LLVMRustSetLLVMOptions(Argc: c_int, Argv: *const *const c_char);
2438    pub(crate) fn LLVMRustPrintPasses();
2439    pub(crate) fn LLVMRustSetNormalizedTarget(M: &Module, triple: *const c_char);
2440    pub(crate) fn LLVMRustRunRestrictionPass(M: &Module, syms: *const *const c_char, len: size_t);
2441
2442    pub(crate) fn LLVMRustWriteTwineToString(T: &Twine, s: &RustString);
2443
2444    pub(crate) fn LLVMRustUnpackOptimizationDiagnostic<'a>(
2445        DI: &'a DiagnosticInfo,
2446        pass_name_out: &RustString,
2447        function_out: &mut Option<&'a Value>,
2448        loc_line_out: &mut c_uint,
2449        loc_column_out: &mut c_uint,
2450        loc_filename_out: &RustString,
2451        message_out: &RustString,
2452    );
2453
2454    pub(crate) fn LLVMRustUnpackInlineAsmDiagnostic<'a>(
2455        DI: &'a DiagnosticInfo,
2456        level_out: &mut DiagnosticLevel,
2457        cookie_out: &mut u64,
2458        message_out: &mut Option<&'a Twine>,
2459    );
2460
2461    pub(crate) fn LLVMRustWriteDiagnosticInfoToString(DI: &DiagnosticInfo, s: &RustString);
2462    pub(crate) fn LLVMRustGetDiagInfoKind(DI: &DiagnosticInfo) -> DiagnosticKind;
2463
2464    pub(crate) fn LLVMRustGetSMDiagnostic<'a>(
2465        DI: &'a DiagnosticInfo,
2466        cookie_out: &mut u64,
2467    ) -> &'a SMDiagnostic;
2468
2469    pub(crate) fn LLVMRustUnpackSMDiagnostic(
2470        d: &SMDiagnostic,
2471        message_out: &RustString,
2472        buffer_out: &RustString,
2473        level_out: &mut DiagnosticLevel,
2474        loc_out: &mut c_uint,
2475        ranges_out: *mut c_uint,
2476        num_ranges: &mut usize,
2477    ) -> bool;
2478
2479    pub(crate) fn LLVMRustSetDataLayoutFromTargetMachine<'a>(M: &'a Module, TM: &'a TargetMachine);
2480
2481    pub(crate) fn LLVMRustPositionBuilderPastAllocas<'a>(B: &Builder<'a>, Fn: &'a Value);
2482    pub(crate) fn LLVMRustPositionBuilderAtStart<'a>(B: &Builder<'a>, BB: &'a BasicBlock);
2483    pub(crate) fn LLVMRustGetInsertPoint<'a>(B: &Builder<'a>) -> &'a Value;
2484    pub(crate) fn LLVMRustRestoreInsertPoint<'a>(B: &Builder<'a>, IP: &'a Value);
2485
2486    pub(crate) fn LLVMRustSetModulePICLevel(M: &Module);
2487    pub(crate) fn LLVMRustSetModulePIELevel(M: &Module);
2488    pub(crate) fn LLVMRustSetModuleCodeModel(M: &Module, Model: CodeModel);
2489    pub(crate) fn LLVMRustModuleBufferCreate(M: &Module) -> &'static mut ModuleBuffer;
2490    pub(crate) fn LLVMRustModuleBufferPtr(p: &ModuleBuffer) -> *const u8;
2491    pub(crate) fn LLVMRustModuleBufferLen(p: &ModuleBuffer) -> usize;
2492    pub(crate) fn LLVMRustModuleBufferFree(p: &'static mut ModuleBuffer);
2493    pub(crate) fn LLVMRustModuleCost(M: &Module) -> u64;
2494    pub(crate) fn LLVMRustModuleInstructionStats(M: &Module, Str: &RustString);
2495
2496    pub(crate) fn LLVMRustThinLTOBufferCreate(
2497        M: &Module,
2498        is_thin: bool,
2499    ) -> &'static mut ThinLTOBuffer;
2500    pub(crate) fn LLVMRustThinLTOBufferFree(M: &'static mut ThinLTOBuffer);
2501    pub(crate) fn LLVMRustThinLTOBufferPtr(M: &ThinLTOBuffer) -> *const c_char;
2502    pub(crate) fn LLVMRustThinLTOBufferLen(M: &ThinLTOBuffer) -> size_t;
2503    pub(crate) fn LLVMRustThinLTOBufferThinLinkDataPtr(M: &ThinLTOBuffer) -> *const c_char;
2504    pub(crate) fn LLVMRustThinLTOBufferThinLinkDataLen(M: &ThinLTOBuffer) -> size_t;
2505    pub(crate) fn LLVMRustCreateThinLTOData(
2506        Modules: *const ThinLTOModule,
2507        NumModules: size_t,
2508        PreservedSymbols: *const *const c_char,
2509        PreservedSymbolsLen: size_t,
2510    ) -> Option<&'static mut ThinLTOData>;
2511    pub(crate) fn LLVMRustPrepareThinLTORename(
2512        Data: &ThinLTOData,
2513        Module: &Module,
2514        Target: &TargetMachine,
2515    );
2516    pub(crate) fn LLVMRustPrepareThinLTOResolveWeak(Data: &ThinLTOData, Module: &Module) -> bool;
2517    pub(crate) fn LLVMRustPrepareThinLTOInternalize(Data: &ThinLTOData, Module: &Module) -> bool;
2518    pub(crate) fn LLVMRustPrepareThinLTOImport(
2519        Data: &ThinLTOData,
2520        Module: &Module,
2521        Target: &TargetMachine,
2522    ) -> bool;
2523    pub(crate) fn LLVMRustFreeThinLTOData(Data: &'static mut ThinLTOData);
2524    pub(crate) fn LLVMRustParseBitcodeForLTO(
2525        Context: &Context,
2526        Data: *const u8,
2527        len: usize,
2528        Identifier: *const c_char,
2529    ) -> Option<&Module>;
2530
2531    pub(crate) fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>;
2532    pub(crate) fn LLVMRustLinkerAdd(
2533        linker: &Linker<'_>,
2534        bytecode: *const c_char,
2535        bytecode_len: usize,
2536    ) -> bool;
2537    pub(crate) fn LLVMRustLinkerFree<'a>(linker: &'a mut Linker<'a>);
2538    pub(crate) fn LLVMRustComputeLTOCacheKey(
2539        key_out: &RustString,
2540        mod_id: *const c_char,
2541        data: &ThinLTOData,
2542    );
2543
2544    pub(crate) fn LLVMRustContextGetDiagnosticHandler(
2545        Context: &Context,
2546    ) -> Option<&DiagnosticHandler>;
2547    pub(crate) fn LLVMRustContextSetDiagnosticHandler(
2548        context: &Context,
2549        diagnostic_handler: Option<&DiagnosticHandler>,
2550    );
2551    pub(crate) fn LLVMRustContextConfigureDiagnosticHandler(
2552        context: &Context,
2553        diagnostic_handler_callback: DiagnosticHandlerTy,
2554        diagnostic_handler_context: *mut c_void,
2555        remark_all_passes: bool,
2556        remark_passes: *const *const c_char,
2557        remark_passes_len: usize,
2558        remark_file: *const c_char,
2559        pgo_available: bool,
2560    );
2561
2562    pub(crate) fn LLVMRustGetMangledName(V: &Value, out: &RustString);
2563
2564    pub(crate) fn LLVMRustGetElementTypeArgIndex(CallSite: &Value) -> i32;
2565
2566    pub(crate) safe fn LLVMRustLLVMHasZlibCompression() -> bool;
2567    pub(crate) safe fn LLVMRustLLVMHasZstdCompression() -> bool;
2568
2569    pub(crate) fn LLVMRustGetSymbols(
2570        buf_ptr: *const u8,
2571        buf_len: usize,
2572        state: *mut c_void,
2573        callback: GetSymbolsCallback,
2574        error_callback: GetSymbolsErrorCallback,
2575    ) -> *mut c_void;
2576
2577    pub(crate) fn LLVMRustIs64BitSymbolicFile(buf_ptr: *const u8, buf_len: usize) -> bool;
2578
2579    pub(crate) fn LLVMRustIsECObject(buf_ptr: *const u8, buf_len: usize) -> bool;
2580
2581    pub(crate) fn LLVMRustIsAnyArm64Coff(buf_ptr: *const u8, buf_len: usize) -> bool;
2582
2583    pub(crate) fn LLVMRustSetNoSanitizeAddress(Global: &Value);
2584    pub(crate) fn LLVMRustSetNoSanitizeHWAddress(Global: &Value);
2585}