Skip to main content

rustc_codegen_llvm/
builder.rs

1use std::borrow::{Borrow, Cow};
2use std::iter;
3use std::ops::Deref;
4
5use rustc_ast::expand::typetree::FncTree;
6pub(crate) mod autodiff;
7pub(crate) mod gpu_offload;
8
9use libc::{c_char, c_uint};
10use rustc_abi::{self as abi, Align, CanonAbi, Size, WrappingRange};
11use rustc_codegen_ssa::MemFlags;
12use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
13use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14use rustc_codegen_ssa::mir::place::PlaceRef;
15use rustc_codegen_ssa::traits::*;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::attrs::{AttributeKind, UnrollAttr};
18use rustc_hir::def_id::DefId;
19use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
20use rustc_middle::ty::layout::{
21    FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22    TyAndLayout,
23};
24use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
25use rustc_sanitizers::{cfi, kcfi};
26use rustc_session::config::OptLevel;
27use rustc_span::Span;
28use rustc_target::callconv::{FnAbi, PassMode};
29use rustc_target::spec::{Arch, HasTargetSpec, SanitizerSet, Target};
30use smallvec::SmallVec;
31use tracing::{debug, instrument};
32
33use crate::abi::FnAbiLlvmExt;
34use crate::attributes;
35use crate::common::Funclet;
36use crate::context::{CodegenCx, FullCx, GenericCx, SCx};
37use crate::llvm::{
38    self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, FromGeneric, GEPNoWrapFlags, Metadata, TRUE,
39    ToLlvmBool, Type, Value,
40};
41use crate::type_of::LayoutLlvmExt;
42
43#[must_use]
44pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
45    pub llbuilder: &'ll mut llvm::Builder<'ll>,
46    pub cx: &'a GenericCx<'ll, CX>,
47    pub span: rustc_span::Span,
48}
49
50pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
51pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
52
53impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
54    fn drop(&mut self) {
55        unsafe {
56            llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
57        }
58    }
59}
60
61impl<'a, 'll> SBuilder<'a, 'll> {
62    pub(crate) fn call(
63        &mut self,
64        llty: &'ll Type,
65        llfn: &'ll Value,
66        args: &[&'ll Value],
67        funclet: Option<&Funclet<'ll>>,
68    ) -> &'ll Value {
69        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:69",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(69u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
70
71        let args = self.check_call("call", llty, llfn, args);
72        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
73        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
74        if let Some(funclet_bundle) = funclet_bundle {
75            bundles.push(funclet_bundle);
76        }
77
78        let call = unsafe {
79            llvm::LLVMBuildCallWithOperandBundles(
80                self.llbuilder,
81                llty,
82                llfn,
83                args.as_ptr() as *const &llvm::Value,
84                args.len() as c_uint,
85                bundles.as_ptr(),
86                bundles.len() as c_uint,
87                c"".as_ptr(),
88            )
89        };
90        call
91    }
92}
93
94impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
95    fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
96        // Create a fresh builder from the simple context.
97        let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(scx.deref().borrow().llcx) };
98        GenericBuilder { llbuilder, cx: scx, span: rustc_span::DUMMY_SP }
99    }
100
101    pub(crate) fn append_block(
102        cx: &'a GenericCx<'ll, CX>,
103        llfn: &'ll Value,
104        name: &str,
105    ) -> &'ll BasicBlock {
106        unsafe {
107            let name = SmallCStr::new(name);
108            llvm::LLVMAppendBasicBlockInContext(cx.llcx(), llfn, name.as_ptr())
109        }
110    }
111
112    pub(crate) fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
113        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
114    }
115
116    pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
117        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
118    }
119
120    pub(crate) fn ret_void(&mut self) {
121        llvm::LLVMBuildRetVoid(self.llbuilder);
122    }
123
124    pub(crate) fn ret(&mut self, v: &'ll Value) {
125        unsafe {
126            llvm::LLVMBuildRet(self.llbuilder, v);
127        }
128    }
129
130    pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
131        let bx = Self::with_cx(cx);
132        unsafe {
133            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
134        }
135        bx
136    }
137
138    // The generic builder has less functionality and thus (unlike the other alloca) we can not
139    // easily jump to the beginning of the function to place our allocas there. We trust the user
140    // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to
141    // handle this.
142    pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
143        let val = unsafe {
144            let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
145            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
146            // Cast to default addrspace if necessary
147            llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
148        };
149        if name != "" {
150            let name = std::ffi::CString::new(name).unwrap();
151            llvm::set_value_name(val, &name.as_bytes());
152        }
153        val
154    }
155
156    pub(crate) fn inbounds_gep(
157        &mut self,
158        ty: &'ll Type,
159        ptr: &'ll Value,
160        indices: &[&'ll Value],
161    ) -> &'ll Value {
162        unsafe {
163            llvm::LLVMBuildGEPWithNoWrapFlags(
164                self.llbuilder,
165                ty,
166                ptr,
167                indices.as_ptr(),
168                indices.len() as c_uint,
169                UNNAMED,
170                GEPNoWrapFlags::InBounds,
171            )
172        }
173    }
174
175    pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
176        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:176",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(176u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
177        {
    match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
        (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!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
178        unsafe {
179            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
180            llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
181            store
182        }
183    }
184
185    pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
186        unsafe {
187            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
188            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
189            load
190        }
191    }
192}
193
194/// Empty string, to be used where LLVM expects an instruction name, indicating
195/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
196// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
197pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
198
199impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
200    type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
201    type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
202    type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
203
204    type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
205    type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
206    type FunctionSignature = <GenericCx<'ll, CX> as BackendTypes>::FunctionSignature;
207
208    type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
209    type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
210    type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
211}
212
213impl abi::HasDataLayout for Builder<'_, '_, '_> {
214    fn data_layout(&self) -> &abi::TargetDataLayout {
215        self.cx.data_layout()
216    }
217}
218
219impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
220    #[inline]
221    fn tcx(&self) -> TyCtxt<'tcx> {
222        self.cx.tcx
223    }
224}
225
226impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
227    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
228        self.cx.typing_env()
229    }
230}
231
232impl HasTargetSpec for Builder<'_, '_, '_> {
233    #[inline]
234    fn target_spec(&self) -> &Target {
235        self.cx.target_spec()
236    }
237}
238
239impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
240    #[inline]
241    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
242        self.cx.handle_layout_err(err, span, ty)
243    }
244}
245
246impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
247    #[inline]
248    fn handle_fn_abi_err(
249        &self,
250        err: FnAbiError<'tcx>,
251        span: Span,
252        fn_abi_request: FnAbiRequest<'tcx>,
253    ) -> ! {
254        self.cx.handle_fn_abi_err(err, span, fn_abi_request)
255    }
256}
257
258impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
259    type Target = CodegenCx<'ll, 'tcx>;
260
261    #[inline]
262    fn deref(&self) -> &Self::Target {
263        self.cx
264    }
265}
266
267macro_rules! math_builder_methods {
268    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
269        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
270            unsafe {
271                llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
272            }
273        })+
274    }
275}
276
277macro_rules! set_math_builder_methods {
278    ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
279        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
280            unsafe {
281                let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
282                llvm::$llvm_set_math(instr);
283                instr
284            }
285        })+
286    }
287}
288
289impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
290    type CodegenCx = CodegenCx<'ll, 'tcx>;
291
292    fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
293        let bx = Builder::with_cx(cx);
294        unsafe {
295            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
296        }
297        bx
298    }
299
300    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
301        self.cx
302    }
303
304    fn llbb(&self) -> &'ll BasicBlock {
305        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
306    }
307
308    fn set_span(&mut self, span: rustc_span::Span) {
309        self.span = span;
310    }
311
312    fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
313        unsafe {
314            let name = SmallCStr::new(name);
315            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
316        }
317    }
318
319    fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
320        Self::append_block(self.cx, self.llfn(), name)
321    }
322
323    fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
324        *self = Self::build(self.cx, llbb)
325    }
326
327    fn ret_void(&mut self) {
328        llvm::LLVMBuildRetVoid(self.llbuilder);
329    }
330
331    fn ret(&mut self, v: &'ll Value) {
332        unsafe {
333            llvm::LLVMBuildRet(self.llbuilder, v);
334        }
335    }
336
337    fn br(&mut self, dest: &'ll BasicBlock) {
338        unsafe {
339            llvm::LLVMBuildBr(self.llbuilder, dest);
340        }
341    }
342
343    fn br_with_attrs(&mut self, dest: &'ll BasicBlock, attributes: &[AttributeKind]) {
344        unsafe {
345            let val = llvm::LLVMBuildBr(self.llbuilder, dest);
346
347            let mut nodes = Vec::new();
348
349            for attribute in attributes {
350                let AttributeKind::Unroll(unroll) = attribute else {
351                    continue;
352                };
353                // UnrollAttr::Count needs a second operand, the provided count, but the other
354                // unroll hints do not.
355                let md_node = if let UnrollAttr::Count(count) = unroll {
356                    let unroll_meta = self.create_metadata("llvm.loop.unroll.count".as_bytes());
357                    let count = llvm::LLVMValueAsMetadata(self.get_const_i32(u64::from(*count)));
358                    self.md_node_in_context(&[unroll_meta, count])
359                } else {
360                    let metadata_str = match unroll {
361                        UnrollAttr::Hint => "llvm.loop.unroll.enable",
362                        UnrollAttr::Full => "llvm.loop.unroll.full",
363                        UnrollAttr::Never => "llvm.loop.unroll.disable",
364                        UnrollAttr::Count(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
365                    };
366                    let unroll_meta = self.create_metadata(metadata_str.as_bytes());
367                    self.md_node_in_context(&[unroll_meta])
368                };
369                nodes.push(md_node);
370            }
371
372            if let [first, ..] = nodes[..] {
373                nodes.insert(0, first);
374
375                // Create the loop metadata node
376                let loop_meta_mdnode = self.set_metadata_node(val, llvm::MD_loop, &nodes);
377
378                // Look up the metadata node as a value
379                let loop_meta_val = llvm::LLVMGetMetadata(val, llvm::MD_loop).unwrap();
380
381                // Replace the first entry with a reference to itself
382                // This is required by LLVM. See the LangRef page for llvm.loop metadata.
383                llvm::LLVMReplaceMDNodeOperandWith(loop_meta_val, 0, loop_meta_mdnode);
384            }
385        }
386    }
387
388    fn cond_br(
389        &mut self,
390        cond: &'ll Value,
391        then_llbb: &'ll BasicBlock,
392        else_llbb: &'ll BasicBlock,
393    ) {
394        unsafe {
395            llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
396        }
397    }
398
399    fn switch(
400        &mut self,
401        v: &'ll Value,
402        else_llbb: &'ll BasicBlock,
403        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
404    ) {
405        let switch =
406            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
407        for (on_val, dest) in cases {
408            let on_val = self.const_uint_big(self.val_ty(v), on_val);
409            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
410        }
411    }
412
413    fn switch_with_weights(
414        &mut self,
415        v: Self::Value,
416        else_llbb: Self::BasicBlock,
417        else_is_cold: bool,
418        cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
419    ) {
420        if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
421            self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
422            return;
423        }
424
425        let id = self.cx.create_metadata(b"branch_weights");
426
427        // For switch instructions with 2 targets, the `llvm.expect` intrinsic is used.
428        // This function handles switch instructions with more than 2 targets and it needs to
429        // emit branch weights metadata instead of using the intrinsic.
430        // The values 1 and 2000 are the same as the values used by the `llvm.expect` intrinsic.
431        let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
432        let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
433        let weight =
434            |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
435
436        let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
437        md.push(id);
438        md.push(weight(else_is_cold));
439
440        let switch =
441            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
442        for (on_val, dest, is_cold) in cases {
443            let on_val = self.const_uint_big(self.val_ty(v), on_val);
444            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
445            md.push(weight(is_cold));
446        }
447
448        self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
449    }
450
451    fn invoke(
452        &mut self,
453        llty: &'ll Type,
454        fn_attrs: Option<&CodegenFnAttrs>,
455        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
456        llfn: &'ll Value,
457        args: &[&'ll Value],
458        then: &'ll BasicBlock,
459        catch: &'ll BasicBlock,
460        funclet: Option<&Funclet<'ll>>,
461        instance: Option<Instance<'tcx>>,
462    ) -> &'ll Value {
463        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:463",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(463u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
464
465        let args = self.check_call("invoke", llty, llfn, args);
466        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
467        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
468        if let Some(funclet_bundle) = funclet_bundle {
469            bundles.push(funclet_bundle);
470        }
471
472        // Emit CFI pointer type membership test
473        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
474
475        // Emit KCFI operand bundle
476        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
477        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
478            bundles.push(kcfi_bundle);
479        }
480
481        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
482        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
483            bundles.push(p);
484        }
485
486        let invoke = unsafe {
487            llvm::LLVMBuildInvokeWithOperandBundles(
488                self.llbuilder,
489                llty,
490                llfn,
491                args.as_ptr(),
492                args.len() as c_uint,
493                then,
494                catch,
495                bundles.as_ptr(),
496                bundles.len() as c_uint,
497                UNNAMED,
498            )
499        };
500        if let Some(fn_abi) = fn_abi {
501            fn_abi.apply_attrs_callsite(self, invoke);
502        }
503        invoke
504    }
505
506    fn unreachable(&mut self) {
507        unsafe {
508            llvm::LLVMBuildUnreachable(self.llbuilder);
509        }
510    }
511
512    fn unchecked_umul(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, x, y, UNNAMED) }
}math_builder_methods! {
513        add(a, b) => LLVMBuildAdd,
514        fadd(a, b) => LLVMBuildFAdd,
515        sub(a, b) => LLVMBuildSub,
516        fsub(a, b) => LLVMBuildFSub,
517        mul(a, b) => LLVMBuildMul,
518        fmul(a, b) => LLVMBuildFMul,
519        udiv(a, b) => LLVMBuildUDiv,
520        exactudiv(a, b) => LLVMBuildExactUDiv,
521        sdiv(a, b) => LLVMBuildSDiv,
522        exactsdiv(a, b) => LLVMBuildExactSDiv,
523        fdiv(a, b) => LLVMBuildFDiv,
524        urem(a, b) => LLVMBuildURem,
525        srem(a, b) => LLVMBuildSRem,
526        frem(a, b) => LLVMBuildFRem,
527        shl(a, b) => LLVMBuildShl,
528        lshr(a, b) => LLVMBuildLShr,
529        ashr(a, b) => LLVMBuildAShr,
530        and(a, b) => LLVMBuildAnd,
531        or(a, b) => LLVMBuildOr,
532        xor(a, b) => LLVMBuildXor,
533        neg(x) => LLVMBuildNeg,
534        fneg(x) => LLVMBuildFNeg,
535        not(x) => LLVMBuildNot,
536        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
537        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
538        unchecked_ssub(x, y) => LLVMBuildNSWSub,
539        unchecked_usub(x, y) => LLVMBuildNUWSub,
540        unchecked_smul(x, y) => LLVMBuildNSWMul,
541        unchecked_umul(x, y) => LLVMBuildNUWMul,
542    }
543
544    fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
545        unsafe {
546            let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
547            if llvm::LLVMIsAInstruction(add).is_some() {
548                llvm::LLVMSetNUW(add, TRUE);
549                llvm::LLVMSetNSW(add, TRUE);
550            }
551            add
552        }
553    }
554    fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
555        unsafe {
556            let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
557            if llvm::LLVMIsAInstruction(sub).is_some() {
558                llvm::LLVMSetNUW(sub, TRUE);
559                llvm::LLVMSetNSW(sub, TRUE);
560            }
561            sub
562        }
563    }
564    fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
565        unsafe {
566            let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
567            if llvm::LLVMIsAInstruction(mul).is_some() {
568                llvm::LLVMSetNUW(mul, TRUE);
569                llvm::LLVMSetNSW(mul, TRUE);
570            }
571            mul
572        }
573    }
574
575    fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
576        unsafe {
577            let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
578
579            // If a and b are both values, then `or` is a value, rather than
580            // an instruction, so we need to check before setting the flag.
581            // (See also `LLVMBuildNUWNeg` which also needs a check.)
582            if llvm::LLVMIsAInstruction(or).is_some() {
583                llvm::LLVMSetIsDisjoint(or, TRUE);
584            }
585            or
586        }
587    }
588
589    fn frem_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFRem(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}set_math_builder_methods! {
590        fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
591        fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
592        fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
593        fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
594        frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
595        fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
596        fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
597        fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
598        fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
599        frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
600    }
601
602    fn checked_binop(
603        &mut self,
604        oop: OverflowOp,
605        ty: Ty<'tcx>,
606        lhs: Self::Value,
607        rhs: Self::Value,
608    ) -> (Self::Value, Self::Value) {
609        let (size, signed) = ty.int_size_and_signed(self.tcx);
610        let width = size.bits();
611
612        if !signed {
613            match oop {
614                OverflowOp::Sub => {
615                    // Emit sub and icmp instead of llvm.usub.with.overflow. LLVM considers these
616                    // to be the canonical form. It will attempt to reform llvm.usub.with.overflow
617                    // in the backend if profitable.
618                    let sub = self.sub(lhs, rhs);
619                    let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
620                    return (sub, cmp);
621                }
622                OverflowOp::Add => {
623                    // Like with sub above, using icmp is the preferred form. See
624                    // <https://rust-lang.zulipchat.com/#narrow/channel/187780-t-compiler.2Fllvm/topic/.60uadd.2Ewith.2Eoverflow.60.20.28again.29/near/533041085>
625                    let add = self.add(lhs, rhs);
626                    let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
627                    return (add, cmp);
628                }
629                OverflowOp::Mul => {}
630            }
631        }
632
633        let oop_str = match oop {
634            OverflowOp::Add => "add",
635            OverflowOp::Sub => "sub",
636            OverflowOp::Mul => "mul",
637        };
638
639        let name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.with.overflow",
                if signed { 's' } else { 'u' }, oop_str))
    })format!("llvm.{}{oop_str}.with.overflow", if signed { 's' } else { 'u' });
640
641        let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
642        (self.extract_value(res, 0), self.extract_value(res, 1))
643    }
644
645    fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
646        if self.cx().val_ty(val) == self.cx().type_i1() {
647            self.zext(val, self.cx().type_i8())
648        } else {
649            val
650        }
651    }
652
653    fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
654        if scalar.is_bool() {
655            return self.unchecked_utrunc(val, self.cx().type_i1());
656        }
657        val
658    }
659
660    fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
661        let mut bx = Builder::with_cx(self.cx);
662        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
663        let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
664        unsafe {
665            let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
666            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
667            // Cast to default addrspace if necessary
668            llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
669        }
670    }
671
672    fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value {
673        let mut bx = Builder::with_cx(self.cx);
674        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
675        let scalable_vector_ty = layout.llvm_type(self.cx);
676
677        unsafe {
678            let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, scalable_vector_ty, UNNAMED);
679            llvm::LLVMSetAlignment(alloca, layout.align.abi.bytes() as c_uint);
680            alloca
681        }
682    }
683
684    fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
685        unsafe {
686            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
687            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
688            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
689            load
690        }
691    }
692
693    fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
694        unsafe {
695            let load = self.load(ty, ptr, align);
696            llvm::LLVMSetVolatile(load, llvm::TRUE);
697            load
698        }
699    }
700
701    fn atomic_load(
702        &mut self,
703        ty: &'ll Type,
704        ptr: &'ll Value,
705        order: rustc_middle::ty::AtomicOrdering,
706        volatile: bool,
707        size: Size,
708    ) -> &'ll Value {
709        unsafe {
710            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
711            // Set atomic ordering
712            llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
713            if volatile {
714                llvm::LLVMSetVolatile(load, llvm::TRUE);
715            }
716            // LLVM requires the alignment of atomic loads to be at least the size of the type.
717            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
718            load
719        }
720    }
721
722    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("load_operand",
                                    "rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(722u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: OperandRef<'tcx, &'ll Value> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if place.layout.is_unsized() {
                let tail =
                    self.tcx.struct_tail_for_codegen(place.layout.ty,
                        self.typing_env());
                if #[allow(non_exhaustive_omitted_patterns)] match tail.kind()
                        {
                        ty::Foreign(..) => true,
                        _ => false,
                    } {
                    {
                        ::core::panicking::panic_fmt(format_args!("unsized locals must not be `extern` types"));
                    };
                }
            }
            {
                match (&place.val.llextra.is_some(),
                        &place.layout.is_unsized()) {
                    (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);
                        }
                    }
                }
            };
            if place.layout.is_zst() {
                return OperandRef::zero_sized(place.layout);
            }
            fn scalar_load_metadata<'a, 'll,
                'tcx>(bx: &mut Builder<'a, 'll, 'tcx>, load: &'ll Value,
                scalar: abi::Scalar, layout: TyAndLayout<'tcx>,
                offset: Size) {
                {}

                #[allow(clippy :: suspicious_else_formatting)]
                {
                    let __tracing_attr_span;
                    let __tracing_attr_guard;
                    if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() ||
                            { false } {
                        __tracing_attr_span =
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("scalar_load_metadata",
                                                    "rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(739u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                                    ::tracing_core::field::FieldSet::new(&[{
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("load")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("load");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("scalar")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("scalar");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("layout")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("layout");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("offset")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("offset");
                                                                        NAME.as_str()
                                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::SPAN)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let mut interest = ::tracing::subscriber::Interest::never();
                                if ::tracing::Level::TRACE <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::TRACE <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            { interest = __CALLSITE.interest(); !interest.is_never() }
                                        &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest) {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Span::new(meta,
                                        &{
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&load)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalar)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&layout)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&offset)
                                                                            as &dyn ::tracing::field::Value))])
                                            })
                                } else {
                                    let span =
                                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                                    {};
                                    span
                                }
                            };
                        __tracing_attr_guard = __tracing_attr_span.enter();
                    }

                    #[warn(clippy :: suspicious_else_formatting)]
                    {

                        #[allow(unknown_lints, unreachable_code, clippy ::
                        diverging_sub_expression, clippy :: empty_loop, clippy ::
                        let_unit_value, clippy :: let_with_type_underscore, clippy
                        :: needless_return, clippy :: unreachable)]
                        if false {
                            let __tracing_attr_fake_return: () = loop {};
                            return __tracing_attr_fake_return;
                        }
                        {
                            if bx.cx.sess().opts.optimize == OptLevel::No { return; }
                            if !scalar.is_uninit_valid() { bx.noundef_metadata(load); }
                            match scalar.primitive() {
                                abi::Primitive::Int(..) => {
                                    if !scalar.is_always_valid(bx) {
                                        bx.range_metadata(load, scalar.valid_range(bx));
                                    }
                                }
                                abi::Primitive::Pointer(_) => {
                                    if !scalar.valid_range(bx).contains(0) {
                                        bx.nonnull_metadata(load);
                                    }
                                    if let Some(pointee) = layout.pointee_info_at(bx, offset) &&
                                            pointee.align > Align::ONE {
                                        bx.align_metadata(load, pointee.align);
                                    }
                                }
                                abi::Primitive::Float(_) => {}
                            }
                        }
                    }
                }
            }
            let val =
                if let Some(_) = place.val.llextra {
                    OperandValue::Ref(place.val)
                } else if place.layout.backend_repr.is_scalar_or_simd() {
                    let mut const_llval = None;
                    let llty = place.layout.llvm_type(self);
                    if let Some(global) =
                            llvm::LLVMIsAGlobalVariable(place.val.llval) {
                        if llvm::LLVMIsGlobalConstant(global).is_true() {
                            if let Some(init) = llvm::LLVMGetInitializer(global) {
                                if self.val_ty(init) == llty { const_llval = Some(init); }
                            }
                        }
                    }
                    let llval =
                        const_llval.unwrap_or_else(||
                                {
                                    let load =
                                        self.load(llty, place.val.llval, place.val.align);
                                    if let abi::BackendRepr::Scalar(scalar) =
                                            place.layout.backend_repr {
                                        scalar_load_metadata(self, load, scalar, place.layout,
                                            Size::ZERO);
                                        self.to_immediate_scalar(load, scalar)
                                    } else { load }
                                });
                    OperandValue::Immediate(llval)
                } else if let abi::BackendRepr::ScalarPair { a, b, b_offset }
                        = place.layout.backend_repr {
                    let mut load =
                        |i, scalar: abi::Scalar, layout, align, offset|
                            {
                                let llptr =
                                    if i == 0 {
                                        place.val.llval
                                    } else {
                                        self.inbounds_ptradd(place.val.llval,
                                            self.const_usize(b_offset.bytes()))
                                    };
                                let llty =
                                    place.layout.scalar_pair_element_llvm_type(self, i, false);
                                let load = self.load(llty, llptr, align);
                                scalar_load_metadata(self, load, scalar, layout, offset);
                                self.to_immediate_scalar(load, scalar)
                            };
                    OperandValue::Pair(load(0, a, place.layout, place.val.align,
                            Size::ZERO),
                        load(1, b, place.layout,
                            place.val.align.restrict_for_offset(b_offset), b_offset))
                } else { OperandValue::Ref(place.val) };
            OperandRef { val, layout: place.layout, move_annotation: None }
        }
    }
}#[instrument(level = "trace", skip(self))]
723    fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
724        if place.layout.is_unsized() {
725            let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
726            if matches!(tail.kind(), ty::Foreign(..)) {
727                // Unsized locals and, at least conceptually, even unsized arguments must be copied
728                // around, which requires dynamically determining their size. Therefore, we cannot
729                // allow `extern` types here. Consult t-opsem before removing this check.
730                panic!("unsized locals must not be `extern` types");
731            }
732        }
733        assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
734
735        if place.layout.is_zst() {
736            return OperandRef::zero_sized(place.layout);
737        }
738
739        #[instrument(level = "trace", skip(bx))]
740        fn scalar_load_metadata<'a, 'll, 'tcx>(
741            bx: &mut Builder<'a, 'll, 'tcx>,
742            load: &'ll Value,
743            scalar: abi::Scalar,
744            layout: TyAndLayout<'tcx>,
745            offset: Size,
746        ) {
747            if bx.cx.sess().opts.optimize == OptLevel::No {
748                // Don't emit metadata we're not going to use
749                return;
750            }
751
752            if !scalar.is_uninit_valid() {
753                bx.noundef_metadata(load);
754            }
755
756            match scalar.primitive() {
757                abi::Primitive::Int(..) => {
758                    if !scalar.is_always_valid(bx) {
759                        bx.range_metadata(load, scalar.valid_range(bx));
760                    }
761                }
762                abi::Primitive::Pointer(_) => {
763                    if !scalar.valid_range(bx).contains(0) {
764                        bx.nonnull_metadata(load);
765                    }
766
767                    if let Some(pointee) = layout.pointee_info_at(bx, offset)
768                        && pointee.align > Align::ONE
769                    {
770                        bx.align_metadata(load, pointee.align);
771                    }
772                }
773                abi::Primitive::Float(_) => {}
774            }
775        }
776
777        let val = if let Some(_) = place.val.llextra {
778            // FIXME: Merge with the `else` below?
779            OperandValue::Ref(place.val)
780        } else if place.layout.backend_repr.is_scalar_or_simd() {
781            let mut const_llval = None;
782            let llty = place.layout.llvm_type(self);
783            if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
784                if llvm::LLVMIsGlobalConstant(global).is_true() {
785                    if let Some(init) = llvm::LLVMGetInitializer(global) {
786                        if self.val_ty(init) == llty {
787                            const_llval = Some(init);
788                        }
789                    }
790                }
791            }
792
793            let llval = const_llval.unwrap_or_else(|| {
794                let load = self.load(llty, place.val.llval, place.val.align);
795                if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
796                    scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
797                    self.to_immediate_scalar(load, scalar)
798                } else {
799                    load
800                }
801            });
802            OperandValue::Immediate(llval)
803        } else if let abi::BackendRepr::ScalarPair { a, b, b_offset } = place.layout.backend_repr {
804            let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
805                let llptr = if i == 0 {
806                    place.val.llval
807                } else {
808                    self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
809                };
810                let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
811                let load = self.load(llty, llptr, align);
812                scalar_load_metadata(self, load, scalar, layout, offset);
813                self.to_immediate_scalar(load, scalar)
814            };
815
816            OperandValue::Pair(
817                load(0, a, place.layout, place.val.align, Size::ZERO),
818                load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
819            )
820        } else {
821            OperandValue::Ref(place.val)
822        };
823
824        OperandRef { val, layout: place.layout, move_annotation: None }
825    }
826
827    fn write_operand_repeatedly(
828        &mut self,
829        cg_elem: OperandRef<'tcx, &'ll Value>,
830        count: u64,
831        dest: PlaceRef<'tcx, &'ll Value>,
832    ) {
833        if self.cx.sess().opts.optimize == OptLevel::No {
834            // To let debuggers single-step over lines like
835            //
836            //     let foo = ["bar"; 42];
837            //
838            // we need the debugger-friendly LLVM IR that `_unoptimized()`
839            // provides. The `_optimized()` version generates trickier LLVM IR.
840            // See PR #148058 for a failed attempt at handling that.
841            self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
842        } else {
843            self.write_operand_repeatedly_optimized(cg_elem, count, dest);
844        }
845    }
846
847    fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
848        if self.cx.sess().opts.optimize == OptLevel::No {
849            // Don't emit metadata we're not going to use
850            return;
851        }
852
853        let llty = self.cx.val_ty(load);
854        let md = [
855            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
856            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
857        ];
858        self.set_metadata_node(load, llvm::MD_range, &md);
859    }
860
861    fn nonnull_metadata(&mut self, load: &'ll Value) {
862        self.set_metadata_node(load, llvm::MD_nonnull, &[]);
863    }
864
865    fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
866        self.store_with_flags(val, ptr, align, MemFlags::empty())
867    }
868
869    fn store_with_flags(
870        &mut self,
871        val: &'ll Value,
872        ptr: &'ll Value,
873        align: Align,
874        flags: MemFlags,
875    ) -> &'ll Value {
876        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:876",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(876u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?} ({2:?})",
                                                    val, ptr, flags) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
877        {
    match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
        (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!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
878        unsafe {
879            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
880            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
881            let align = align.bytes() as c_uint;
882            llvm::LLVMSetAlignment(store, align);
883            if flags.contains(MemFlags::VOLATILE) {
884                llvm::LLVMSetVolatile(store, llvm::TRUE);
885            }
886            if flags.contains(MemFlags::NONTEMPORAL) {
887                // Make sure that the current target architectures supports "sane" non-temporal
888                // stores, i.e., non-temporal stores that are equivalent to regular stores except
889                // for performance. LLVM doesn't seem to care about this, and will happily treat
890                // `!nontemporal` stores as-if they were normal stores (for reordering optimizations
891                // etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
892                // regular stores but require special fences. So we keep a list of architectures
893                // where `!nontemporal` is known to be truly just a hint, and use regular stores
894                // everywhere else. (In the future, we could alternatively ensure that an sfence
895                // gets emitted after a sequence of movnt before any kind of synchronizing
896                // operation. But it's not clear how to do that with LLVM.)
897                // For more context, see <https://github.com/rust-lang/rust/issues/114582> and
898                // <https://github.com/llvm/llvm-project/issues/64521>.
899                let use_nontemporal = #[allow(non_exhaustive_omitted_patterns)] match self.cx.tcx.sess.target.arch {
    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64 => true,
    _ => false,
}matches!(
900                    self.cx.tcx.sess.target.arch,
901                    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
902                );
903                if use_nontemporal {
904                    // According to LLVM [1] building a nontemporal store must
905                    // *always* point to a metadata value of the integer 1.
906                    //
907                    // [1]: https://llvm.org/docs/LangRef.html#store-instruction
908                    let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
909                    self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
910                }
911            }
912            if flags.contains(MemFlags::CAPTURES_READ_ONLY)
913                && crate::llvm_util::get_version() >= (22, 0, 0)
914            {
915                if !(self.type_kind(self.val_ty(val)) == TypeKind::Pointer) {
    {
        ::core::panicking::panic_fmt(format_args!("CAPTURED_READ_ONLY is only supported on pointer stores"));
    }
};assert!(
916                    self.type_kind(self.val_ty(val)) == TypeKind::Pointer,
917                    "CAPTURED_READ_ONLY is only supported on pointer stores"
918                );
919                let args = [
920                    self.cx.create_metadata(b"address"),
921                    self.cx.create_metadata(b"read_provenance"),
922                ];
923                // FIXME: Switch this to use MD_captures once LLVM 22 is the minimum.
924                let id = self.get_md_kind_id("captures");
925                let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, args.as_ptr(), args.len());
926                self.set_metadata(store, id, md);
927            }
928            store
929        }
930    }
931
932    fn atomic_store(
933        &mut self,
934        val: &'ll Value,
935        ptr: &'ll Value,
936        order: rustc_middle::ty::AtomicOrdering,
937        volatile: bool,
938        size: Size,
939    ) {
940        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:940",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(940u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
941        {
    match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
        (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!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
942        unsafe {
943            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
944            // Set atomic ordering
945            llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
946            if volatile {
947                llvm::LLVMSetVolatile(store, llvm::TRUE);
948            }
949            // LLVM requires the alignment of atomic stores to be at least the size of the type.
950            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
951        }
952    }
953
954    fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
955        unsafe {
956            llvm::LLVMBuildGEPWithNoWrapFlags(
957                self.llbuilder,
958                ty,
959                ptr,
960                indices.as_ptr(),
961                indices.len() as c_uint,
962                UNNAMED,
963                GEPNoWrapFlags::default(),
964            )
965        }
966    }
967
968    fn inbounds_gep(
969        &mut self,
970        ty: &'ll Type,
971        ptr: &'ll Value,
972        indices: &[&'ll Value],
973    ) -> &'ll Value {
974        unsafe {
975            llvm::LLVMBuildGEPWithNoWrapFlags(
976                self.llbuilder,
977                ty,
978                ptr,
979                indices.as_ptr(),
980                indices.len() as c_uint,
981                UNNAMED,
982                GEPNoWrapFlags::InBounds,
983            )
984        }
985    }
986
987    fn inbounds_nuw_gep(
988        &mut self,
989        ty: &'ll Type,
990        ptr: &'ll Value,
991        indices: &[&'ll Value],
992    ) -> &'ll Value {
993        unsafe {
994            llvm::LLVMBuildGEPWithNoWrapFlags(
995                self.llbuilder,
996                ty,
997                ptr,
998                indices.as_ptr(),
999                indices.len() as c_uint,
1000                UNNAMED,
1001                GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
1002            )
1003        }
1004    }
1005
1006    /* Casts */
1007    fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1008        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1009    }
1010
1011    fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1012        if true {
    {
        match (&self.val_ty(val), &dest_ty) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(self.val_ty(val), dest_ty);
1013
1014        let trunc = self.trunc(val, dest_ty);
1015        unsafe {
1016            if llvm::LLVMIsAInstruction(trunc).is_some() {
1017                llvm::LLVMSetNUW(trunc, TRUE);
1018            }
1019        }
1020        trunc
1021    }
1022
1023    fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1024        if true {
    {
        match (&self.val_ty(val), &dest_ty) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(self.val_ty(val), dest_ty);
1025
1026        let trunc = self.trunc(val, dest_ty);
1027        unsafe {
1028            if llvm::LLVMIsAInstruction(trunc).is_some() {
1029                llvm::LLVMSetNSW(trunc, TRUE);
1030            }
1031        }
1032        trunc
1033    }
1034
1035    fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1036        unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
1037    }
1038
1039    fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1040        self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
1041    }
1042
1043    fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1044        self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
1045    }
1046
1047    fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1048        // On WebAssembly the `fptoui` and `fptosi` instructions currently have
1049        // poor codegen. The reason for this is that the corresponding wasm
1050        // instructions, `i32.trunc_f32_s` for example, will trap when the float
1051        // is out-of-bounds, infinity, or nan. This means that LLVM
1052        // automatically inserts control flow around `fptoui` and `fptosi`
1053        // because the LLVM instruction `fptoui` is defined as producing a
1054        // poison value, not having UB on out-of-bounds values.
1055        //
1056        // This method, however, is only used with non-saturating casts that
1057        // have UB on out-of-bounds values. This means that it's ok if we use
1058        // the raw wasm instruction since out-of-bounds values can do whatever
1059        // we like. To ensure that LLVM picks the right instruction we choose
1060        // the raw wasm intrinsic functions which avoid LLVM inserting all the
1061        // other control flow automatically.
1062        if self.sess().target.is_like_wasm {
1063            let src_ty = self.cx.val_ty(val);
1064            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1065                let float_width = self.cx.float_width(src_ty);
1066                let int_width = self.cx.int_width(dest_ty);
1067                if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
    (32 | 64, 32 | 64) => true,
    _ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1068                    return self.call_intrinsic(
1069                        "llvm.wasm.trunc.unsigned",
1070                        &[dest_ty, src_ty],
1071                        &[val],
1072                    );
1073                }
1074            }
1075        }
1076        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1077    }
1078
1079    fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1080        // see `fptoui` above for why wasm is different here
1081        if self.sess().target.is_like_wasm {
1082            let src_ty = self.cx.val_ty(val);
1083            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1084                let float_width = self.cx.float_width(src_ty);
1085                let int_width = self.cx.int_width(dest_ty);
1086                if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
    (32 | 64, 32 | 64) => true,
    _ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1087                    return self.call_intrinsic(
1088                        "llvm.wasm.trunc.signed",
1089                        &[dest_ty, src_ty],
1090                        &[val],
1091                    );
1092                }
1093            }
1094        }
1095        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1096    }
1097
1098    fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1099        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1100    }
1101
1102    fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1103        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1104    }
1105
1106    fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1107        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1108    }
1109
1110    fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1111        unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1112    }
1113
1114    fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1115        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1116    }
1117
1118    fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1119        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1120    }
1121
1122    fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1123        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1124    }
1125
1126    fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1127        unsafe {
1128            llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1129        }
1130    }
1131
1132    fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1133        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1134    }
1135
1136    /* Comparisons */
1137    fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1138        let op = llvm::IntPredicate::from_generic(op);
1139        unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1140    }
1141
1142    fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1143        let op = llvm::RealPredicate::from_generic(op);
1144        unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1145    }
1146
1147    fn three_way_compare(
1148        &mut self,
1149        ty: Ty<'tcx>,
1150        lhs: Self::Value,
1151        rhs: Self::Value,
1152    ) -> Self::Value {
1153        let size = ty.primitive_size(self.tcx);
1154        let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1155
1156        self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1157    }
1158
1159    /* Miscellaneous instructions */
1160    fn memcpy(
1161        &mut self,
1162        dst: &'ll Value,
1163        dst_align: Align,
1164        src: &'ll Value,
1165        src_align: Align,
1166        size: &'ll Value,
1167        flags: MemFlags,
1168        tt: Option<FncTree>,
1169    ) {
1170        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memcpy not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1171        let size = self.intcast(size, self.type_isize(), false);
1172        let is_volatile = flags.contains(MemFlags::VOLATILE);
1173        let memcpy = unsafe {
1174            llvm::LLVMRustBuildMemCpy(
1175                self.llbuilder,
1176                dst,
1177                dst_align.bytes() as c_uint,
1178                src,
1179                src_align.bytes() as c_uint,
1180                size,
1181                is_volatile,
1182            )
1183        };
1184
1185        // TypeTree metadata for memcpy is especially important: when Enzyme encounters
1186        // a memcpy during autodiff, it needs to know the structure of the data being
1187        // copied to properly track derivatives. For example, copying an array of floats
1188        // vs. copying a struct with mixed types requires different derivative handling.
1189        // The TypeTree tells Enzyme exactly what memory layout to expect.
1190        if let Some(tt) = tt {
1191            crate::typetree::add_tt(self, memcpy, tt);
1192        }
1193    }
1194
1195    fn memmove(
1196        &mut self,
1197        dst: &'ll Value,
1198        dst_align: Align,
1199        src: &'ll Value,
1200        src_align: Align,
1201        size: &'ll Value,
1202        flags: MemFlags,
1203    ) {
1204        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memmove not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1205        let size = self.intcast(size, self.type_isize(), false);
1206        let is_volatile = flags.contains(MemFlags::VOLATILE);
1207        unsafe {
1208            llvm::LLVMRustBuildMemMove(
1209                self.llbuilder,
1210                dst,
1211                dst_align.bytes() as c_uint,
1212                src,
1213                src_align.bytes() as c_uint,
1214                size,
1215                is_volatile,
1216            );
1217        }
1218    }
1219
1220    fn memset(
1221        &mut self,
1222        ptr: &'ll Value,
1223        fill_byte: &'ll Value,
1224        size: &'ll Value,
1225        align: Align,
1226        flags: MemFlags,
1227    ) {
1228        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memset not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1229        let is_volatile = flags.contains(MemFlags::VOLATILE);
1230        unsafe {
1231            llvm::LLVMRustBuildMemSet(
1232                self.llbuilder,
1233                ptr,
1234                align.bytes() as c_uint,
1235                fill_byte,
1236                size,
1237                is_volatile,
1238            );
1239        }
1240    }
1241
1242    fn vscale(&mut self, ty: &'ll Type) -> &'ll Value {
1243        unsafe { llvm::LLVMRustBuildVScale(self.llbuilder, ty) }
1244    }
1245
1246    fn select(
1247        &mut self,
1248        cond: &'ll Value,
1249        then_val: &'ll Value,
1250        else_val: &'ll Value,
1251    ) -> &'ll Value {
1252        unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1253    }
1254
1255    fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1256        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1257    }
1258
1259    fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1260        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1261    }
1262
1263    fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1264        unsafe {
1265            let elt_ty = self.cx.val_ty(elt);
1266            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1267            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1268            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1269            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1270        }
1271    }
1272
1273    fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1274        {
    match (&(idx as c_uint as u64), &idx) {
        (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!(idx as c_uint as u64, idx);
1275        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1276    }
1277
1278    fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1279        {
    match (&(idx as c_uint as u64), &idx) {
        (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!(idx as c_uint as u64, idx);
1280        unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1281    }
1282
1283    fn set_personality_fn(&mut self, personality: &'ll Value) {
1284        unsafe {
1285            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1286        }
1287    }
1288
1289    fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1290        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1291        let landing_pad = self.landing_pad(ty, pers_fn, 0);
1292        unsafe {
1293            llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1294        }
1295        (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1296    }
1297
1298    fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1299        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1300        let landing_pad = self.landing_pad(ty, pers_fn, 1);
1301        self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1302    }
1303
1304    fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1305        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1306        let mut exn = self.const_poison(ty);
1307        exn = self.insert_value(exn, exn0, 0);
1308        exn = self.insert_value(exn, exn1, 1);
1309        unsafe {
1310            llvm::LLVMBuildResume(self.llbuilder, exn);
1311        }
1312    }
1313
1314    fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1315        let ret = unsafe {
1316            llvm::LLVMBuildCleanupPad(
1317                self.llbuilder,
1318                parent,
1319                args.as_ptr(),
1320                args.len() as c_uint,
1321                c"cleanuppad".as_ptr(),
1322            )
1323        };
1324        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1325    }
1326
1327    fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1328        unsafe {
1329            llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1330                .expect("LLVM does not have support for cleanupret");
1331        }
1332    }
1333
1334    fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1335        let ret = unsafe {
1336            llvm::LLVMBuildCatchPad(
1337                self.llbuilder,
1338                parent,
1339                args.as_ptr(),
1340                args.len() as c_uint,
1341                c"catchpad".as_ptr(),
1342            )
1343        };
1344        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1345    }
1346
1347    fn catch_switch(
1348        &mut self,
1349        parent: Option<&'ll Value>,
1350        unwind: Option<&'ll BasicBlock>,
1351        handlers: &[&'ll BasicBlock],
1352    ) -> &'ll Value {
1353        let ret = unsafe {
1354            llvm::LLVMBuildCatchSwitch(
1355                self.llbuilder,
1356                parent,
1357                unwind,
1358                handlers.len() as c_uint,
1359                c"catchswitch".as_ptr(),
1360            )
1361        };
1362        let ret = ret.expect("LLVM does not have support for catchswitch");
1363        for handler in handlers {
1364            unsafe {
1365                llvm::LLVMAddHandler(ret, handler);
1366            }
1367        }
1368        ret
1369    }
1370
1371    fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> &'ll Value {
1372        funclet.cleanuppad()
1373    }
1374
1375    // Atomic Operations
1376    fn atomic_cmpxchg(
1377        &mut self,
1378        dst: &'ll Value,
1379        cmp: &'ll Value,
1380        src: &'ll Value,
1381        order: rustc_middle::ty::AtomicOrdering,
1382        failure_order: rustc_middle::ty::AtomicOrdering,
1383        weak: bool,
1384    ) -> (&'ll Value, &'ll Value) {
1385        unsafe {
1386            let value = llvm::LLVMBuildAtomicCmpXchg(
1387                self.llbuilder,
1388                dst,
1389                cmp,
1390                src,
1391                AtomicOrdering::from_generic(order),
1392                AtomicOrdering::from_generic(failure_order),
1393                llvm::FALSE, // SingleThreaded
1394            );
1395            llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1396            let val = self.extract_value(value, 0);
1397            let success = self.extract_value(value, 1);
1398            (val, success)
1399        }
1400    }
1401
1402    fn atomic_rmw(
1403        &mut self,
1404        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1405        dst: &'ll Value,
1406        src: &'ll Value,
1407        order: rustc_middle::ty::AtomicOrdering,
1408        ret_ptr: bool,
1409    ) -> &'ll Value {
1410        // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the
1411        // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not
1412        // currently support that (https://github.com/llvm/llvm-project/issues/120837).
1413        let mut res = unsafe {
1414            llvm::LLVMBuildAtomicRMW(
1415                self.llbuilder,
1416                AtomicRmwBinOp::from_generic(op),
1417                dst,
1418                src,
1419                AtomicOrdering::from_generic(order),
1420                llvm::FALSE, // SingleThreaded
1421            )
1422        };
1423        if ret_ptr && self.val_ty(res) != self.type_ptr() {
1424            res = self.inttoptr(res, self.type_ptr());
1425        }
1426        res
1427    }
1428
1429    fn atomic_fence(
1430        &mut self,
1431        order: rustc_middle::ty::AtomicOrdering,
1432        scope: SynchronizationScope,
1433    ) {
1434        let single_threaded = match scope {
1435            SynchronizationScope::SingleThread => true,
1436            SynchronizationScope::CrossThread => false,
1437        };
1438        unsafe {
1439            llvm::LLVMBuildFence(
1440                self.llbuilder,
1441                AtomicOrdering::from_generic(order),
1442                single_threaded.to_llvm_bool(),
1443                UNNAMED,
1444            );
1445        }
1446    }
1447
1448    fn set_invariant_load(&mut self, load: &'ll Value) {
1449        self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1450    }
1451
1452    fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1453        self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1454    }
1455
1456    fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1457        self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1458    }
1459
1460    fn call(
1461        &mut self,
1462        llty: &'ll Type,
1463        caller_attrs: Option<&CodegenFnAttrs>,
1464        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1465        llfn: &'ll Value,
1466        args: &[&'ll Value],
1467        funclet: Option<&Funclet<'ll>>,
1468        callee_instance: Option<Instance<'tcx>>,
1469    ) -> &'ll Value {
1470        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1470",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1470u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
1471
1472        let args = self.check_call("call", llty, llfn, args);
1473        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1474        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1475        if let Some(funclet_bundle) = funclet_bundle {
1476            bundles.push(funclet_bundle);
1477        }
1478
1479        // Emit CFI pointer type membership test
1480        self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1481
1482        // Emit KCFI operand bundle
1483        let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1484        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1485            bundles.push(kcfi_bundle);
1486        }
1487
1488        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1489        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1490            bundles.push(p);
1491        }
1492
1493        let call = unsafe {
1494            llvm::LLVMBuildCallWithOperandBundles(
1495                self.llbuilder,
1496                llty,
1497                llfn,
1498                args.as_ptr() as *const &llvm::Value,
1499                args.len() as c_uint,
1500                bundles.as_ptr(),
1501                bundles.len() as c_uint,
1502                c"".as_ptr(),
1503            )
1504        };
1505
1506        if let Some(callee_instance) = callee_instance {
1507            // Attributes on the function definition being called
1508            let callee_attrs = self.cx.tcx.codegen_fn_attrs(callee_instance.def_id());
1509
1510            if let Some(inlining_rule) =
1511                attributes::inline_attr(&self.cx, self.cx.tcx, callee_instance, callee_attrs)
1512            {
1513                attributes::apply_to_callsite(
1514                    call,
1515                    llvm::AttributePlace::Function,
1516                    &[inlining_rule],
1517                );
1518            }
1519        }
1520
1521        if let Some(fn_abi) = fn_abi {
1522            fn_abi.apply_attrs_callsite(self, call);
1523        }
1524        call
1525    }
1526
1527    fn tail_call(
1528        &mut self,
1529        llty: Self::Type,
1530        caller_attrs: Option<&CodegenFnAttrs>,
1531        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1532        llfn: Self::Value,
1533        args: &[Self::Value],
1534        funclet: Option<&Self::Funclet>,
1535        callee_instance: Option<Instance<'tcx>>,
1536    ) {
1537        let call =
1538            self.call(llty, caller_attrs, Some(fn_abi), llfn, args, funclet, callee_instance);
1539        llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1540
1541        match &fn_abi.ret.mode {
1542            PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1543            PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1544        }
1545    }
1546
1547    fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1548        unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1549    }
1550
1551    fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1552        // Cleanup is always the cold path.
1553        let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1554        attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1555    }
1556}
1557
1558impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1559    fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1560        // Forward to the `get_static` method of `CodegenCx`
1561        let global = self.cx().get_static(def_id);
1562        if self.cx().tcx.is_thread_local_static(def_id) {
1563            let pointer =
1564                self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1565            // Cast to default address space if globals are in a different addrspace
1566            self.pointercast(pointer, self.type_ptr())
1567        } else {
1568            // Cast to default address space if globals are in a different addrspace
1569            self.cx().const_pointercast(global, self.type_ptr())
1570        }
1571    }
1572}
1573
1574impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1575    pub(crate) fn llfn(&self) -> &'ll Value {
1576        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1577    }
1578
1579    fn generate_ubsan_cfi_diag_data(
1580        &mut self,
1581        span: rustc_span::Span,
1582        expected_ty: String,
1583        check_kind: u8,
1584    ) -> &'ll Value {
1585        let cx = self.cx();
1586        let tcx = cx.tcx;
1587
1588        let loc = tcx.sess.source_map().lookup_char_pos(span.lo());
1589
1590        let filename_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\0",
                loc.file.name.prefer_local_unconditionally()))
    })format!("{}\0", loc.file.name.prefer_local_unconditionally());
1591        let filename_val = cx.const_bytes(filename_str.as_bytes());
1592        let filename_ptr = cx.static_addr_of_impl(filename_val, Align::ONE, None);
1593
1594        // SourceLocation UBSan struct: { const char *filename, uint32_t line, uint32_t column }
1595        let source_location = cx.const_struct(
1596            &[
1597                filename_ptr,
1598                cx.const_u32(loc.line as u32),
1599                // UBSan columns are 1-based
1600                cx.const_u32(loc.col.0 as u32 + 1),
1601            ],
1602            false, // packed = false
1603        );
1604
1605        let ty_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\0", expected_ty))
    })format!("{}\0", expected_ty);
1606        let ty_name_val = cx.const_bytes(ty_name.as_bytes());
1607
1608        // TypeDescriptor UBSan struct: { uint16_t TypeKind, uint16_t TypeInfo, const char *TypeName }
1609        let type_descriptor =
1610            cx.const_struct(&[cx.const_i16(0xffffu16 as i16), cx.const_i16(0), ty_name_val], false);
1611
1612        let type_descriptor_ptr =
1613            cx.static_addr_of_impl(type_descriptor, Align::from_bytes(2).unwrap(), None);
1614
1615        // CFICheckFailData UBSan struct: { uint8_t CheckKind, SourceLocation Loc, TypeDescriptor *Type }
1616        let cfi_check_fail_data = cx
1617            .const_struct(&[cx.const_u8(check_kind), source_location, type_descriptor_ptr], false);
1618        let align = tcx.data_layout.aggregate_align;
1619
1620        // Returns the final opaque pointer to the struct to be passed to __ubsan_handle_cfi_check_fail
1621        cx.static_addr_of_mut(cfi_check_fail_data, align, Some("__ubsan_cfi_check_fail_data"))
1622    }
1623}
1624
1625impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1626    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1627        unsafe {
1628            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1629        }
1630    }
1631}
1632impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1633    fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1634        let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1635        self.set_metadata_node(load, llvm::MD_align, &md);
1636    }
1637
1638    fn noundef_metadata(&mut self, load: &'ll Value) {
1639        self.set_metadata_node(load, llvm::MD_noundef, &[]);
1640    }
1641
1642    pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1643        self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1644    }
1645
1646    fn write_operand_repeatedly_optimized(
1647        &mut self,
1648        cg_elem: OperandRef<'tcx, &'ll Value>,
1649        count: u64,
1650        dest: PlaceRef<'tcx, &'ll Value>,
1651    ) {
1652        let zero = self.const_usize(0);
1653        let count = self.const_usize(count);
1654
1655        let header_bb = self.append_sibling_block("repeat_loop_header");
1656        let body_bb = self.append_sibling_block("repeat_loop_body");
1657        let next_bb = self.append_sibling_block("repeat_loop_next");
1658
1659        self.br(header_bb);
1660
1661        let mut header_bx = Self::build(self.cx, header_bb);
1662        let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1663
1664        let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1665        header_bx.cond_br(keep_going, body_bb, next_bb);
1666
1667        let mut body_bx = Self::build(self.cx, body_bb);
1668        let dest_elem = dest.project_index(&mut body_bx, i);
1669        cg_elem.val.store(&mut body_bx, dest_elem);
1670
1671        let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1672        body_bx.br(header_bb);
1673        header_bx.add_incoming_to_phi(i, next, body_bb);
1674
1675        *self = Self::build(self.cx, next_bb);
1676    }
1677
1678    fn write_operand_repeatedly_unoptimized(
1679        &mut self,
1680        cg_elem: OperandRef<'tcx, &'ll Value>,
1681        count: u64,
1682        dest: PlaceRef<'tcx, &'ll Value>,
1683    ) {
1684        let zero = self.const_usize(0);
1685        let count = self.const_usize(count);
1686        let start = dest.project_index(self, zero).val.llval;
1687        let end = dest.project_index(self, count).val.llval;
1688
1689        let header_bb = self.append_sibling_block("repeat_loop_header");
1690        let body_bb = self.append_sibling_block("repeat_loop_body");
1691        let next_bb = self.append_sibling_block("repeat_loop_next");
1692
1693        self.br(header_bb);
1694
1695        let mut header_bx = Self::build(self.cx, header_bb);
1696        let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1697
1698        let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1699        header_bx.cond_br(keep_going, body_bb, next_bb);
1700
1701        let mut body_bx = Self::build(self.cx, body_bb);
1702        let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1703        cg_elem
1704            .val
1705            .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1706
1707        let next = body_bx.inbounds_gep(
1708            self.backend_type(cg_elem.layout),
1709            current,
1710            &[self.const_usize(1)],
1711        );
1712        body_bx.br(header_bb);
1713        header_bx.add_incoming_to_phi(current, next, body_bb);
1714
1715        *self = Self::build(self.cx, next_bb);
1716    }
1717
1718    pub(crate) fn minimum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1719        let call = self.call_intrinsic("llvm.minimumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1720        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1721        call
1722    }
1723
1724    pub(crate) fn maximum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1725        let call = self.call_intrinsic("llvm.maximumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1726        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1727        call
1728    }
1729
1730    pub(crate) fn insert_element(
1731        &mut self,
1732        vec: &'ll Value,
1733        elt: &'ll Value,
1734        idx: &'ll Value,
1735    ) -> &'ll Value {
1736        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1737    }
1738
1739    pub(crate) fn shuffle_vector(
1740        &mut self,
1741        v1: &'ll Value,
1742        v2: &'ll Value,
1743        mask: &'ll Value,
1744    ) -> &'ll Value {
1745        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1746    }
1747
1748    pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1749        self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1750    }
1751    pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1752        self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1753    }
1754    pub(crate) fn vector_reduce_fadd_reassoc(
1755        &mut self,
1756        acc: &'ll Value,
1757        src: &'ll Value,
1758    ) -> &'ll Value {
1759        unsafe {
1760            let instr =
1761                self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1762            llvm::LLVMRustSetAllowReassoc(instr);
1763            instr
1764        }
1765    }
1766    pub(crate) fn vector_reduce_fmul_reassoc(
1767        &mut self,
1768        acc: &'ll Value,
1769        src: &'ll Value,
1770    ) -> &'ll Value {
1771        unsafe {
1772            let instr =
1773                self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1774            llvm::LLVMRustSetAllowReassoc(instr);
1775            instr
1776        }
1777    }
1778    pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1779        self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1780    }
1781    pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1782        self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1783    }
1784    pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1785        self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1786    }
1787    pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1788        self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1789    }
1790    pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1791        self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1792    }
1793    pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1794        self.call_intrinsic(
1795            if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1796            &[self.val_ty(src)],
1797            &[src],
1798        )
1799    }
1800    pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1801        self.call_intrinsic(
1802            if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1803            &[self.val_ty(src)],
1804            &[src],
1805        )
1806    }
1807}
1808impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1809    pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1810        unsafe {
1811            llvm::LLVMAddClause(landing_pad, clause);
1812        }
1813    }
1814
1815    pub(crate) fn catch_ret(
1816        &mut self,
1817        funclet: &Funclet<'ll>,
1818        unwind: &'ll BasicBlock,
1819    ) -> &'ll Value {
1820        let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1821        ret.expect("LLVM does not have support for catchret")
1822    }
1823
1824    pub(crate) fn check_call<'b>(
1825        &mut self,
1826        typ: &str,
1827        fn_ty: &'ll Type,
1828        llfn: &'ll Value,
1829        args: &'b [&'ll Value],
1830    ) -> Cow<'b, [&'ll Value]> {
1831        if !(self.cx.type_kind(fn_ty) == TypeKind::Function) {
    {
        ::core::panicking::panic_fmt(format_args!("builder::{0} not passed a function, but {1:?}",
                typ, fn_ty));
    }
};assert!(
1832            self.cx.type_kind(fn_ty) == TypeKind::Function,
1833            "builder::{typ} not passed a function, but {fn_ty:?}"
1834        );
1835
1836        let param_tys = self.cx.func_params_types(fn_ty);
1837
1838        let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1839            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1840
1841        if all_args_match {
1842            return Cow::Borrowed(args);
1843        }
1844
1845        let casted_args: Vec<_> = iter::zip(param_tys, args)
1846            .enumerate()
1847            .map(|(i, (expected_ty, &actual_val))| {
1848                let actual_ty = self.cx.val_ty(actual_val);
1849                if expected_ty != actual_ty {
1850                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1850",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1850u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("type mismatch in function call of {0:?}. Expected {1:?} for param {2}, got {3:?}; injecting bitcast",
                                                    llfn, expected_ty, i, actual_ty) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1851                        "type mismatch in function call of {:?}. \
1852                            Expected {:?} for param {}, got {:?}; injecting bitcast",
1853                        llfn, expected_ty, i, actual_ty
1854                    );
1855                    self.bitcast(actual_val, expected_ty)
1856                } else {
1857                    actual_val
1858                }
1859            })
1860            .collect();
1861
1862        Cow::Owned(casted_args)
1863    }
1864
1865    pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1866        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1867    }
1868}
1869
1870impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1871    pub(crate) fn call_intrinsic(
1872        &mut self,
1873        base_name: impl Into<Cow<'static, str>>,
1874        type_params: &[&'ll Type],
1875        args: &[&'ll Value],
1876    ) -> &'ll Value {
1877        let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1878        self.call(ty, None, None, f, args, None, None)
1879    }
1880
1881    fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1882        let size = size.bytes();
1883        if size == 0 {
1884            return;
1885        }
1886
1887        if !self.cx().sess().emit_lifetime_markers() {
1888            return;
1889        }
1890
1891        if crate::llvm_util::get_version() >= (22, 0, 0) {
1892            // LLVM 22 requires the lifetime intrinsic to act directly on the alloca,
1893            // there can't be an addrspacecast in between.
1894            let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1895            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1896        } else {
1897            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1898        }
1899    }
1900}
1901impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1902    pub(crate) fn phi(
1903        &mut self,
1904        ty: &'ll Type,
1905        vals: &[&'ll Value],
1906        bbs: &[&'ll BasicBlock],
1907    ) -> &'ll Value {
1908        {
    match (&vals.len(), &bbs.len()) {
        (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!(vals.len(), bbs.len());
1909        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1910        unsafe {
1911            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1912            phi
1913        }
1914    }
1915
1916    fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1917        unsafe {
1918            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1919        }
1920    }
1921}
1922impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1923    pub(crate) fn landing_pad(
1924        &mut self,
1925        ty: &'ll Type,
1926        pers_fn: &'ll Value,
1927        num_clauses: usize,
1928    ) -> &'ll Value {
1929        // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1930        // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1931        // personality lives on the parent function anyway.
1932        self.set_personality_fn(pers_fn);
1933        unsafe {
1934            llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1935        }
1936    }
1937
1938    pub(crate) fn callbr(
1939        &mut self,
1940        llty: &'ll Type,
1941        fn_attrs: Option<&CodegenFnAttrs>,
1942        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1943        llfn: &'ll Value,
1944        args: &[&'ll Value],
1945        default_dest: &'ll BasicBlock,
1946        indirect_dest: &[&'ll BasicBlock],
1947        funclet: Option<&Funclet<'ll>>,
1948        instance: Option<Instance<'tcx>>,
1949    ) -> &'ll Value {
1950        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1950",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1950u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
1951
1952        let args = self.check_call("callbr", llty, llfn, args);
1953        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1954        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1955        if let Some(funclet_bundle) = funclet_bundle {
1956            bundles.push(funclet_bundle);
1957        }
1958
1959        // Emit CFI pointer type membership test
1960        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1961
1962        // Emit KCFI operand bundle
1963        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1964        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1965            bundles.push(kcfi_bundle);
1966        }
1967
1968        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1969        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1970            bundles.push(p);
1971        }
1972
1973        let callbr = unsafe {
1974            llvm::LLVMBuildCallBr(
1975                self.llbuilder,
1976                llty,
1977                llfn,
1978                default_dest,
1979                indirect_dest.as_ptr(),
1980                indirect_dest.len() as c_uint,
1981                args.as_ptr(),
1982                args.len() as c_uint,
1983                bundles.as_ptr(),
1984                bundles.len() as c_uint,
1985                UNNAMED,
1986            )
1987        };
1988        if let Some(fn_abi) = fn_abi {
1989            fn_abi.apply_attrs_callsite(self, callbr);
1990        }
1991        callbr
1992    }
1993
1994    // Emits CFI pointer type membership tests.
1995    fn cfi_type_test(
1996        &mut self,
1997        fn_attrs: Option<&CodegenFnAttrs>,
1998        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1999        instance: Option<Instance<'tcx>>,
2000        llfn: &'ll Value,
2001    ) {
2002        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2003        if self.tcx.sess.is_sanitizer_cfi_enabled()
2004            && let Some(fn_abi) = fn_abi
2005            && is_indirect_call
2006        {
2007            if let Some(fn_attrs) = fn_attrs
2008                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
2009            {
2010                return;
2011            }
2012
2013            let mut options = cfi::TypeIdOptions::empty();
2014            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2015                options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
2016            }
2017            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2018                options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
2019            }
2020
2021            let typeid = if let Some(instance) = instance {
2022                cfi::typeid_for_instance(self.tcx, instance, options)
2023            } else {
2024                cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2025            };
2026            let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
2027            let dbg_loc = self.get_dbg_loc();
2028
2029            // Test whether the function pointer is associated with the type identifier using the
2030            // llvm.type.test intrinsic. The LowerTypeTests link-time optimization pass replaces
2031            // calls to this intrinsic with code to test type membership.
2032            let typeid = self.get_metadata_value(typeid_metadata);
2033            let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
2034            let bb_pass = self.append_sibling_block("type_test.pass");
2035            let bb_fail = self.append_sibling_block("type_test.fail");
2036            self.cond_br(cond, bb_pass, bb_fail);
2037
2038            self.switch_to_block(bb_fail);
2039            if let Some(dbg_loc) = dbg_loc {
2040                self.set_dbg_loc(dbg_loc);
2041            }
2042
2043            let is_diag = self.tcx.sess.opts.unstable_opts.sanitizer_cfi_diag.unwrap_or(false);
2044            let is_recover =
2045                self.tcx.sess.opts.unstable_opts.sanitizer_cfi_recover.unwrap_or(false);
2046
2047            if is_diag || is_recover {
2048                let fty = self.cx.type_func(
2049                    &[self.cx.type_ptr(), self.cx.type_isize(), self.cx.type_isize()],
2050                    self.cx.type_void(),
2051                );
2052                let ubsan_handler = self.declare_cfn(
2053                    if is_recover {
2054                        "__ubsan_handle_cfi_check_fail"
2055                    } else {
2056                        "__ubsan_handle_cfi_check_fail_abort"
2057                    },
2058                    llvm::UnnamedAddr::Global,
2059                    fty,
2060                );
2061
2062                let mut expected_ty = String::from("fn(");
2063                for (i, arg) in fn_abi.args.iter().enumerate() {
2064                    if i > 0 {
2065                        expected_ty.push_str(", ");
2066                    }
2067                    use std::fmt::Write;
2068                    (&mut expected_ty).write_fmt(format_args!("{0}", arg.layout.ty))write!(&mut expected_ty, "{}", arg.layout.ty).unwrap();
2069                }
2070                expected_ty.push(')');
2071                if !fn_abi.ret.layout.ty.is_unit() {
2072                    use std::fmt::Write;
2073                    (&mut expected_ty).write_fmt(format_args!(" -> {0}", fn_abi.ret.layout.ty))write!(&mut expected_ty, " -> {}", fn_abi.ret.layout.ty).unwrap();
2074                }
2075
2076                // 4 for cfi-icall (indirect call)
2077                let check_kind = 4;
2078                let diag_data =
2079                    self.generate_ubsan_cfi_diag_data(self.span, expected_ty, check_kind);
2080
2081                let function_address = self.ptrtoint(llfn, self.cx.type_isize());
2082                self.call(
2083                    fty,
2084                    None,
2085                    None,
2086                    ubsan_handler,
2087                    &[diag_data, function_address, self.const_usize(0)],
2088                    None,
2089                    None,
2090                );
2091                if is_recover {
2092                    self.br(bb_pass);
2093                } else {
2094                    self.unreachable();
2095                }
2096            } else {
2097                self.abort();
2098                self.unreachable();
2099            }
2100
2101            self.switch_to_block(bb_pass);
2102            if let Some(dbg_loc) = dbg_loc {
2103                self.set_dbg_loc(dbg_loc);
2104            }
2105        }
2106    }
2107
2108    // Emits KCFI operand bundles.
2109    fn kcfi_operand_bundle(
2110        &mut self,
2111        fn_attrs: Option<&CodegenFnAttrs>,
2112        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2113        instance: Option<Instance<'tcx>>,
2114        llfn: &'ll Value,
2115    ) -> Option<llvm::OperandBundleBox<'ll>> {
2116        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2117        let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
2118            && let Some(fn_abi) = fn_abi
2119            && is_indirect_call
2120        {
2121            if let Some(fn_attrs) = fn_attrs
2122                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
2123            {
2124                return None;
2125            }
2126
2127            let mut options = kcfi::TypeIdOptions::empty();
2128            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2129                options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
2130            }
2131            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2132                options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
2133            }
2134
2135            let kcfi_typeid = if let Some(instance) = instance {
2136                kcfi::typeid_for_instance(self.tcx, instance, options)
2137            } else {
2138                kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2139            };
2140
2141            Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
2142        } else {
2143            None
2144        };
2145        kcfi_bundle
2146    }
2147
2148    // Emits pauth operand bundle.
2149    fn ptrauth_operand_bundle(
2150        &mut self,
2151        llfn: &'ll Value,
2152        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2153    ) -> Option<llvm::OperandBundleBox<'ll>> {
2154        if self.sess().pointer_authentication_functions().is_none() {
2155            return None;
2156        }
2157        // Pointer authentication support is currently limited to extern "C" calls; filter out other
2158        // ABIs.
2159        if fn_abi?.conv != CanonAbi::C {
2160            return None;
2161        }
2162        // Filter out LLVM intrinsics.
2163        if llvm::get_value_name(llfn).starts_with(b"llvm.") {
2164            return None;
2165        }
2166
2167        // FIXME(jchlanda) Operand bundles should only be attached to indirect function calls.
2168        // However, function pointer signing is currently performed in `get_fn_addr`, which causes
2169        // the logic to be applied too broadly, including to function values (not just pointers).
2170        // As a result, direct calls using signed function values must also receive operand
2171        // bundles.
2172        // Once this is resolved, we should analyze each call and skip direct calls. See the
2173        // discussion in the rust-lang issue: <https://github.com/rust-lang/rust/issues/152532>
2174        let key: u32 = 0;
2175        let discriminator: u64 = 0;
2176        Some(llvm::OperandBundleBox::new(
2177            "ptrauth",
2178            &[self.const_u32(key), self.const_u64(discriminator)],
2179        ))
2180    }
2181
2182    /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation.
2183    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("instrprof_increment",
                                    "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2183u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hash")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hash");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("num_counters")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("num_counters");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("index")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("index");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hash)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&num_counters)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&index)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.call_intrinsic("llvm.instrprof.increment", &[],
                &[fn_name, hash, num_counters, index]);
        }
    }
}#[instrument(level = "debug", skip(self))]
2184    pub(crate) fn instrprof_increment(
2185        &mut self,
2186        fn_name: &'ll Value,
2187        hash: &'ll Value,
2188        num_counters: &'ll Value,
2189        index: &'ll Value,
2190    ) {
2191        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
2192    }
2193}