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, 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::def_id::DefId;
18use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
19use rustc_middle::ty::layout::{
20    FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
21    TyAndLayout,
22};
23use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
24use rustc_sanitizers::{cfi, kcfi};
25use rustc_session::config::OptLevel;
26use rustc_span::Span;
27use rustc_target::callconv::{FnAbi, PassMode};
28use rustc_target::spec::{Arch, HasTargetSpec, SanitizerSet, Target};
29use smallvec::SmallVec;
30use tracing::{debug, instrument};
31
32use crate::abi::FnAbiLlvmExt;
33use crate::attributes;
34use crate::common::Funclet;
35use crate::context::{CodegenCx, FullCx, GenericCx, SCx};
36use crate::llvm::{
37    self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, FromGeneric, GEPNoWrapFlags, Metadata, TRUE,
38    ToLlvmBool, Type, Value,
39};
40use crate::type_of::LayoutLlvmExt;
41
42#[must_use]
43pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
44    pub llbuilder: &'ll mut llvm::Builder<'ll>,
45    pub cx: &'a GenericCx<'ll, CX>,
46}
47
48pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
49pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
50
51impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
52    fn drop(&mut self) {
53        unsafe {
54            llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
55        }
56    }
57}
58
59impl<'a, 'll> SBuilder<'a, 'll> {
60    pub(crate) fn call(
61        &mut self,
62        llty: &'ll Type,
63        llfn: &'ll Value,
64        args: &[&'ll Value],
65        funclet: Option<&Funclet<'ll>>,
66    ) -> &'ll Value {
67        {
    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:67",
                        "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(67u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
68
69        let args = self.check_call("call", llty, llfn, args);
70        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
71        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
72        if let Some(funclet_bundle) = funclet_bundle {
73            bundles.push(funclet_bundle);
74        }
75
76        let call = unsafe {
77            llvm::LLVMBuildCallWithOperandBundles(
78                self.llbuilder,
79                llty,
80                llfn,
81                args.as_ptr() as *const &llvm::Value,
82                args.len() as c_uint,
83                bundles.as_ptr(),
84                bundles.len() as c_uint,
85                c"".as_ptr(),
86            )
87        };
88        call
89    }
90}
91
92impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
93    fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
94        // Create a fresh builder from the simple context.
95        let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(scx.deref().borrow().llcx) };
96        GenericBuilder { llbuilder, cx: scx }
97    }
98
99    pub(crate) fn append_block(
100        cx: &'a GenericCx<'ll, CX>,
101        llfn: &'ll Value,
102        name: &str,
103    ) -> &'ll BasicBlock {
104        unsafe {
105            let name = SmallCStr::new(name);
106            llvm::LLVMAppendBasicBlockInContext(cx.llcx(), llfn, name.as_ptr())
107        }
108    }
109
110    pub(crate) fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
111        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
112    }
113
114    pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
115        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
116    }
117
118    pub(crate) fn ret_void(&mut self) {
119        llvm::LLVMBuildRetVoid(self.llbuilder);
120    }
121
122    pub(crate) fn ret(&mut self, v: &'ll Value) {
123        unsafe {
124            llvm::LLVMBuildRet(self.llbuilder, v);
125        }
126    }
127
128    pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
129        let bx = Self::with_cx(cx);
130        unsafe {
131            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
132        }
133        bx
134    }
135
136    // The generic builder has less functionality and thus (unlike the other alloca) we can not
137    // easily jump to the beginning of the function to place our allocas there. We trust the user
138    // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to
139    // handle this.
140    pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
141        let val = unsafe {
142            let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
143            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
144            // Cast to default addrspace if necessary
145            llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
146        };
147        if name != "" {
148            let name = std::ffi::CString::new(name).unwrap();
149            llvm::set_value_name(val, &name.as_bytes());
150        }
151        val
152    }
153
154    pub(crate) fn inbounds_gep(
155        &mut self,
156        ty: &'ll Type,
157        ptr: &'ll Value,
158        indices: &[&'ll Value],
159    ) -> &'ll Value {
160        unsafe {
161            llvm::LLVMBuildGEPWithNoWrapFlags(
162                self.llbuilder,
163                ty,
164                ptr,
165                indices.as_ptr(),
166                indices.len() as c_uint,
167                UNNAMED,
168                GEPNoWrapFlags::InBounds,
169            )
170        }
171    }
172
173    pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
174        {
    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:174",
                        "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(174u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
175        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);
176        unsafe {
177            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
178            llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
179            store
180        }
181    }
182
183    pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
184        unsafe {
185            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
186            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
187            load
188        }
189    }
190}
191
192/// Empty string, to be used where LLVM expects an instruction name, indicating
193/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
194// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
195pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
196
197impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
198    type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
199    type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
200    type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
201
202    type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
203    type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
204    type FunctionSignature = <GenericCx<'ll, CX> as BackendTypes>::FunctionSignature;
205
206    type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
207    type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
208    type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
209}
210
211impl abi::HasDataLayout for Builder<'_, '_, '_> {
212    fn data_layout(&self) -> &abi::TargetDataLayout {
213        self.cx.data_layout()
214    }
215}
216
217impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
218    #[inline]
219    fn tcx(&self) -> TyCtxt<'tcx> {
220        self.cx.tcx
221    }
222}
223
224impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
225    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
226        self.cx.typing_env()
227    }
228}
229
230impl HasTargetSpec for Builder<'_, '_, '_> {
231    #[inline]
232    fn target_spec(&self) -> &Target {
233        self.cx.target_spec()
234    }
235}
236
237impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
238    #[inline]
239    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
240        self.cx.handle_layout_err(err, span, ty)
241    }
242}
243
244impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
245    #[inline]
246    fn handle_fn_abi_err(
247        &self,
248        err: FnAbiError<'tcx>,
249        span: Span,
250        fn_abi_request: FnAbiRequest<'tcx>,
251    ) -> ! {
252        self.cx.handle_fn_abi_err(err, span, fn_abi_request)
253    }
254}
255
256impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
257    type Target = CodegenCx<'ll, 'tcx>;
258
259    #[inline]
260    fn deref(&self) -> &Self::Target {
261        self.cx
262    }
263}
264
265macro_rules! math_builder_methods {
266    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
267        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
268            unsafe {
269                llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
270            }
271        })+
272    }
273}
274
275macro_rules! set_math_builder_methods {
276    ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
277        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
278            unsafe {
279                let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
280                llvm::$llvm_set_math(instr);
281                instr
282            }
283        })+
284    }
285}
286
287impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
288    type CodegenCx = CodegenCx<'ll, 'tcx>;
289
290    fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
291        let bx = Builder::with_cx(cx);
292        unsafe {
293            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
294        }
295        bx
296    }
297
298    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
299        self.cx
300    }
301
302    fn llbb(&self) -> &'ll BasicBlock {
303        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
304    }
305
306    fn set_span(&mut self, _span: Span) {}
307
308    fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
309        unsafe {
310            let name = SmallCStr::new(name);
311            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
312        }
313    }
314
315    fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
316        Self::append_block(self.cx, self.llfn(), name)
317    }
318
319    fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
320        *self = Self::build(self.cx, llbb)
321    }
322
323    fn ret_void(&mut self) {
324        llvm::LLVMBuildRetVoid(self.llbuilder);
325    }
326
327    fn ret(&mut self, v: &'ll Value) {
328        unsafe {
329            llvm::LLVMBuildRet(self.llbuilder, v);
330        }
331    }
332
333    fn br(&mut self, dest: &'ll BasicBlock) {
334        unsafe {
335            llvm::LLVMBuildBr(self.llbuilder, dest);
336        }
337    }
338
339    fn cond_br(
340        &mut self,
341        cond: &'ll Value,
342        then_llbb: &'ll BasicBlock,
343        else_llbb: &'ll BasicBlock,
344    ) {
345        unsafe {
346            llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
347        }
348    }
349
350    fn switch(
351        &mut self,
352        v: &'ll Value,
353        else_llbb: &'ll BasicBlock,
354        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
355    ) {
356        let switch =
357            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
358        for (on_val, dest) in cases {
359            let on_val = self.const_uint_big(self.val_ty(v), on_val);
360            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
361        }
362    }
363
364    fn switch_with_weights(
365        &mut self,
366        v: Self::Value,
367        else_llbb: Self::BasicBlock,
368        else_is_cold: bool,
369        cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
370    ) {
371        if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
372            self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
373            return;
374        }
375
376        let id = self.cx.create_metadata(b"branch_weights");
377
378        // For switch instructions with 2 targets, the `llvm.expect` intrinsic is used.
379        // This function handles switch instructions with more than 2 targets and it needs to
380        // emit branch weights metadata instead of using the intrinsic.
381        // The values 1 and 2000 are the same as the values used by the `llvm.expect` intrinsic.
382        let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
383        let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
384        let weight =
385            |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
386
387        let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
388        md.push(id);
389        md.push(weight(else_is_cold));
390
391        let switch =
392            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
393        for (on_val, dest, is_cold) in cases {
394            let on_val = self.const_uint_big(self.val_ty(v), on_val);
395            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
396            md.push(weight(is_cold));
397        }
398
399        self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
400    }
401
402    fn invoke(
403        &mut self,
404        llty: &'ll Type,
405        fn_attrs: Option<&CodegenFnAttrs>,
406        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
407        llfn: &'ll Value,
408        args: &[&'ll Value],
409        then: &'ll BasicBlock,
410        catch: &'ll BasicBlock,
411        funclet: Option<&Funclet<'ll>>,
412        instance: Option<Instance<'tcx>>,
413    ) -> &'ll Value {
414        {
    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:414",
                        "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(414u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
415
416        let args = self.check_call("invoke", llty, llfn, args);
417        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
418        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
419        if let Some(funclet_bundle) = funclet_bundle {
420            bundles.push(funclet_bundle);
421        }
422
423        // Emit CFI pointer type membership test
424        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
425
426        // Emit KCFI operand bundle
427        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
428        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
429            bundles.push(kcfi_bundle);
430        }
431
432        let invoke = unsafe {
433            llvm::LLVMBuildInvokeWithOperandBundles(
434                self.llbuilder,
435                llty,
436                llfn,
437                args.as_ptr(),
438                args.len() as c_uint,
439                then,
440                catch,
441                bundles.as_ptr(),
442                bundles.len() as c_uint,
443                UNNAMED,
444            )
445        };
446        if let Some(fn_abi) = fn_abi {
447            fn_abi.apply_attrs_callsite(self, invoke);
448        }
449        invoke
450    }
451
452    fn unreachable(&mut self) {
453        unsafe {
454            llvm::LLVMBuildUnreachable(self.llbuilder);
455        }
456    }
457
458    fn unchecked_umul(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, x, y, UNNAMED) }
}math_builder_methods! {
459        add(a, b) => LLVMBuildAdd,
460        fadd(a, b) => LLVMBuildFAdd,
461        sub(a, b) => LLVMBuildSub,
462        fsub(a, b) => LLVMBuildFSub,
463        mul(a, b) => LLVMBuildMul,
464        fmul(a, b) => LLVMBuildFMul,
465        udiv(a, b) => LLVMBuildUDiv,
466        exactudiv(a, b) => LLVMBuildExactUDiv,
467        sdiv(a, b) => LLVMBuildSDiv,
468        exactsdiv(a, b) => LLVMBuildExactSDiv,
469        fdiv(a, b) => LLVMBuildFDiv,
470        urem(a, b) => LLVMBuildURem,
471        srem(a, b) => LLVMBuildSRem,
472        frem(a, b) => LLVMBuildFRem,
473        shl(a, b) => LLVMBuildShl,
474        lshr(a, b) => LLVMBuildLShr,
475        ashr(a, b) => LLVMBuildAShr,
476        and(a, b) => LLVMBuildAnd,
477        or(a, b) => LLVMBuildOr,
478        xor(a, b) => LLVMBuildXor,
479        neg(x) => LLVMBuildNeg,
480        fneg(x) => LLVMBuildFNeg,
481        not(x) => LLVMBuildNot,
482        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
483        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
484        unchecked_ssub(x, y) => LLVMBuildNSWSub,
485        unchecked_usub(x, y) => LLVMBuildNUWSub,
486        unchecked_smul(x, y) => LLVMBuildNSWMul,
487        unchecked_umul(x, y) => LLVMBuildNUWMul,
488    }
489
490    fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
491        unsafe {
492            let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
493            if llvm::LLVMIsAInstruction(add).is_some() {
494                llvm::LLVMSetNUW(add, TRUE);
495                llvm::LLVMSetNSW(add, TRUE);
496            }
497            add
498        }
499    }
500    fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
501        unsafe {
502            let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
503            if llvm::LLVMIsAInstruction(sub).is_some() {
504                llvm::LLVMSetNUW(sub, TRUE);
505                llvm::LLVMSetNSW(sub, TRUE);
506            }
507            sub
508        }
509    }
510    fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
511        unsafe {
512            let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
513            if llvm::LLVMIsAInstruction(mul).is_some() {
514                llvm::LLVMSetNUW(mul, TRUE);
515                llvm::LLVMSetNSW(mul, TRUE);
516            }
517            mul
518        }
519    }
520
521    fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
522        unsafe {
523            let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
524
525            // If a and b are both values, then `or` is a value, rather than
526            // an instruction, so we need to check before setting the flag.
527            // (See also `LLVMBuildNUWNeg` which also needs a check.)
528            if llvm::LLVMIsAInstruction(or).is_some() {
529                llvm::LLVMSetIsDisjoint(or, TRUE);
530            }
531            or
532        }
533    }
534
535    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! {
536        fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
537        fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
538        fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
539        fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
540        frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
541        fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
542        fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
543        fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
544        fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
545        frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
546    }
547
548    fn checked_binop(
549        &mut self,
550        oop: OverflowOp,
551        ty: Ty<'tcx>,
552        lhs: Self::Value,
553        rhs: Self::Value,
554    ) -> (Self::Value, Self::Value) {
555        let (size, signed) = ty.int_size_and_signed(self.tcx);
556        let width = size.bits();
557
558        if !signed {
559            match oop {
560                OverflowOp::Sub => {
561                    // Emit sub and icmp instead of llvm.usub.with.overflow. LLVM considers these
562                    // to be the canonical form. It will attempt to reform llvm.usub.with.overflow
563                    // in the backend if profitable.
564                    let sub = self.sub(lhs, rhs);
565                    let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
566                    return (sub, cmp);
567                }
568                OverflowOp::Add => {
569                    // Like with sub above, using icmp is the preferred form. See
570                    // <https://rust-lang.zulipchat.com/#narrow/channel/187780-t-compiler.2Fllvm/topic/.60uadd.2Ewith.2Eoverflow.60.20.28again.29/near/533041085>
571                    let add = self.add(lhs, rhs);
572                    let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
573                    return (add, cmp);
574                }
575                OverflowOp::Mul => {}
576            }
577        }
578
579        let oop_str = match oop {
580            OverflowOp::Add => "add",
581            OverflowOp::Sub => "sub",
582            OverflowOp::Mul => "mul",
583        };
584
585        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' });
586
587        let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
588        (self.extract_value(res, 0), self.extract_value(res, 1))
589    }
590
591    fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
592        if self.cx().val_ty(val) == self.cx().type_i1() {
593            self.zext(val, self.cx().type_i8())
594        } else {
595            val
596        }
597    }
598
599    fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
600        if scalar.is_bool() {
601            return self.unchecked_utrunc(val, self.cx().type_i1());
602        }
603        val
604    }
605
606    fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
607        let mut bx = Builder::with_cx(self.cx);
608        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
609        let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
610        unsafe {
611            let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
612            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
613            // Cast to default addrspace if necessary
614            llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
615        }
616    }
617
618    fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value {
619        let mut bx = Builder::with_cx(self.cx);
620        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
621        let scalable_vector_ty = layout.llvm_type(self.cx);
622
623        unsafe {
624            let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, scalable_vector_ty, UNNAMED);
625            llvm::LLVMSetAlignment(alloca, layout.align.abi.bytes() as c_uint);
626            alloca
627        }
628    }
629
630    fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
631        unsafe {
632            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
633            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
634            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
635            load
636        }
637    }
638
639    fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value) -> &'ll Value {
640        unsafe {
641            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
642            llvm::LLVMSetVolatile(load, llvm::TRUE);
643            load
644        }
645    }
646
647    fn atomic_load(
648        &mut self,
649        ty: &'ll Type,
650        ptr: &'ll Value,
651        order: rustc_middle::ty::AtomicOrdering,
652        size: Size,
653    ) -> &'ll Value {
654        unsafe {
655            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
656            // Set atomic ordering
657            llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
658            // LLVM requires the alignment of atomic loads to be at least the size of the type.
659            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
660            load
661        }
662    }
663
664    #[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(664u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&["place"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn 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(681u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                                    ::tracing_core::field::FieldSet::new(&["load", "scalar",
                                                                    "layout", "offset"],
                                                        ::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};
                                                let mut iter = meta.fields().iter();
                                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&load)
                                                                            as &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalar)
                                                                            as &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&layout)
                                                                            as &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&offset)
                                                                            as &dyn 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.is_llvm_immediate() {
                    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) =
                        place.layout.backend_repr {
                    let b_offset = a.size(self).align_to(b.align(self).abi);
                    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))]
665    fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
666        if place.layout.is_unsized() {
667            let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
668            if matches!(tail.kind(), ty::Foreign(..)) {
669                // Unsized locals and, at least conceptually, even unsized arguments must be copied
670                // around, which requires dynamically determining their size. Therefore, we cannot
671                // allow `extern` types here. Consult t-opsem before removing this check.
672                panic!("unsized locals must not be `extern` types");
673            }
674        }
675        assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
676
677        if place.layout.is_zst() {
678            return OperandRef::zero_sized(place.layout);
679        }
680
681        #[instrument(level = "trace", skip(bx))]
682        fn scalar_load_metadata<'a, 'll, 'tcx>(
683            bx: &mut Builder<'a, 'll, 'tcx>,
684            load: &'ll Value,
685            scalar: abi::Scalar,
686            layout: TyAndLayout<'tcx>,
687            offset: Size,
688        ) {
689            if bx.cx.sess().opts.optimize == OptLevel::No {
690                // Don't emit metadata we're not going to use
691                return;
692            }
693
694            if !scalar.is_uninit_valid() {
695                bx.noundef_metadata(load);
696            }
697
698            match scalar.primitive() {
699                abi::Primitive::Int(..) => {
700                    if !scalar.is_always_valid(bx) {
701                        bx.range_metadata(load, scalar.valid_range(bx));
702                    }
703                }
704                abi::Primitive::Pointer(_) => {
705                    if !scalar.valid_range(bx).contains(0) {
706                        bx.nonnull_metadata(load);
707                    }
708
709                    if let Some(pointee) = layout.pointee_info_at(bx, offset)
710                        && pointee.align > Align::ONE
711                    {
712                        bx.align_metadata(load, pointee.align);
713                    }
714                }
715                abi::Primitive::Float(_) => {}
716            }
717        }
718
719        let val = if let Some(_) = place.val.llextra {
720            // FIXME: Merge with the `else` below?
721            OperandValue::Ref(place.val)
722        } else if place.layout.is_llvm_immediate() {
723            let mut const_llval = None;
724            let llty = place.layout.llvm_type(self);
725            if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
726                if llvm::LLVMIsGlobalConstant(global).is_true() {
727                    if let Some(init) = llvm::LLVMGetInitializer(global) {
728                        if self.val_ty(init) == llty {
729                            const_llval = Some(init);
730                        }
731                    }
732                }
733            }
734
735            let llval = const_llval.unwrap_or_else(|| {
736                let load = self.load(llty, place.val.llval, place.val.align);
737                if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
738                    scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
739                    self.to_immediate_scalar(load, scalar)
740                } else {
741                    load
742                }
743            });
744            OperandValue::Immediate(llval)
745        } else if let abi::BackendRepr::ScalarPair(a, b) = place.layout.backend_repr {
746            let b_offset = a.size(self).align_to(b.align(self).abi);
747
748            let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
749                let llptr = if i == 0 {
750                    place.val.llval
751                } else {
752                    self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
753                };
754                let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
755                let load = self.load(llty, llptr, align);
756                scalar_load_metadata(self, load, scalar, layout, offset);
757                self.to_immediate_scalar(load, scalar)
758            };
759
760            OperandValue::Pair(
761                load(0, a, place.layout, place.val.align, Size::ZERO),
762                load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
763            )
764        } else {
765            OperandValue::Ref(place.val)
766        };
767
768        OperandRef { val, layout: place.layout, move_annotation: None }
769    }
770
771    fn write_operand_repeatedly(
772        &mut self,
773        cg_elem: OperandRef<'tcx, &'ll Value>,
774        count: u64,
775        dest: PlaceRef<'tcx, &'ll Value>,
776    ) {
777        if self.cx.sess().opts.optimize == OptLevel::No {
778            // To let debuggers single-step over lines like
779            //
780            //     let foo = ["bar"; 42];
781            //
782            // we need the debugger-friendly LLVM IR that `_unoptimized()`
783            // provides. The `_optimized()` version generates trickier LLVM IR.
784            // See PR #148058 for a failed attempt at handling that.
785            self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
786        } else {
787            self.write_operand_repeatedly_optimized(cg_elem, count, dest);
788        }
789    }
790
791    fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
792        if self.cx.sess().opts.optimize == OptLevel::No {
793            // Don't emit metadata we're not going to use
794            return;
795        }
796
797        let llty = self.cx.val_ty(load);
798        let md = [
799            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
800            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
801        ];
802        self.set_metadata_node(load, llvm::MD_range, &md);
803    }
804
805    fn nonnull_metadata(&mut self, load: &'ll Value) {
806        self.set_metadata_node(load, llvm::MD_nonnull, &[]);
807    }
808
809    fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
810        self.store_with_flags(val, ptr, align, MemFlags::empty())
811    }
812
813    fn store_with_flags(
814        &mut self,
815        val: &'ll Value,
816        ptr: &'ll Value,
817        align: Align,
818        flags: MemFlags,
819    ) -> &'ll Value {
820        {
    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:820",
                        "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(820u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?} ({2:?})",
                                                    val, ptr, flags) as &dyn Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
821        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);
822        unsafe {
823            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
824            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
825            let align =
826                if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
827            llvm::LLVMSetAlignment(store, align);
828            if flags.contains(MemFlags::VOLATILE) {
829                llvm::LLVMSetVolatile(store, llvm::TRUE);
830            }
831            if flags.contains(MemFlags::NONTEMPORAL) {
832                // Make sure that the current target architectures supports "sane" non-temporal
833                // stores, i.e., non-temporal stores that are equivalent to regular stores except
834                // for performance. LLVM doesn't seem to care about this, and will happily treat
835                // `!nontemporal` stores as-if they were normal stores (for reordering optimizations
836                // etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
837                // regular stores but require special fences. So we keep a list of architectures
838                // where `!nontemporal` is known to be truly just a hint, and use regular stores
839                // everywhere else. (In the future, we could alternatively ensure that an sfence
840                // gets emitted after a sequence of movnt before any kind of synchronizing
841                // operation. But it's not clear how to do that with LLVM.)
842                // For more context, see <https://github.com/rust-lang/rust/issues/114582> and
843                // <https://github.com/llvm/llvm-project/issues/64521>.
844                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!(
845                    self.cx.tcx.sess.target.arch,
846                    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
847                );
848                if use_nontemporal {
849                    // According to LLVM [1] building a nontemporal store must
850                    // *always* point to a metadata value of the integer 1.
851                    //
852                    // [1]: https://llvm.org/docs/LangRef.html#store-instruction
853                    let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
854                    self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
855                }
856            }
857            if flags.contains(MemFlags::CAPTURES_READ_ONLY)
858                && crate::llvm_util::get_version() >= (22, 0, 0)
859            {
860                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!(
861                    self.type_kind(self.val_ty(val)) == TypeKind::Pointer,
862                    "CAPTURED_READ_ONLY is only supported on pointer stores"
863                );
864                let args = [
865                    self.cx.create_metadata(b"address"),
866                    self.cx.create_metadata(b"read_provenance"),
867                ];
868                // FIXME: Switch this to use MD_captures once LLVM 22 is the minimum.
869                let id = self.get_md_kind_id("captures");
870                let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, args.as_ptr(), args.len());
871                self.set_metadata(store, id, md);
872            }
873            store
874        }
875    }
876
877    fn atomic_store(
878        &mut self,
879        val: &'ll Value,
880        ptr: &'ll Value,
881        order: rustc_middle::ty::AtomicOrdering,
882        size: Size,
883    ) {
884        {
    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:884",
                        "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(884u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
885        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);
886        unsafe {
887            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
888            // Set atomic ordering
889            llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
890            // LLVM requires the alignment of atomic stores to be at least the size of the type.
891            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
892        }
893    }
894
895    fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
896        unsafe {
897            llvm::LLVMBuildGEPWithNoWrapFlags(
898                self.llbuilder,
899                ty,
900                ptr,
901                indices.as_ptr(),
902                indices.len() as c_uint,
903                UNNAMED,
904                GEPNoWrapFlags::default(),
905            )
906        }
907    }
908
909    fn inbounds_gep(
910        &mut self,
911        ty: &'ll Type,
912        ptr: &'ll Value,
913        indices: &[&'ll Value],
914    ) -> &'ll Value {
915        unsafe {
916            llvm::LLVMBuildGEPWithNoWrapFlags(
917                self.llbuilder,
918                ty,
919                ptr,
920                indices.as_ptr(),
921                indices.len() as c_uint,
922                UNNAMED,
923                GEPNoWrapFlags::InBounds,
924            )
925        }
926    }
927
928    fn inbounds_nuw_gep(
929        &mut self,
930        ty: &'ll Type,
931        ptr: &'ll Value,
932        indices: &[&'ll Value],
933    ) -> &'ll Value {
934        unsafe {
935            llvm::LLVMBuildGEPWithNoWrapFlags(
936                self.llbuilder,
937                ty,
938                ptr,
939                indices.as_ptr(),
940                indices.len() as c_uint,
941                UNNAMED,
942                GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
943            )
944        }
945    }
946
947    /* Casts */
948    fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
949        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
950    }
951
952    fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
953        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);
954
955        let trunc = self.trunc(val, dest_ty);
956        unsafe {
957            if llvm::LLVMIsAInstruction(trunc).is_some() {
958                llvm::LLVMSetNUW(trunc, TRUE);
959            }
960        }
961        trunc
962    }
963
964    fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
965        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);
966
967        let trunc = self.trunc(val, dest_ty);
968        unsafe {
969            if llvm::LLVMIsAInstruction(trunc).is_some() {
970                llvm::LLVMSetNSW(trunc, TRUE);
971            }
972        }
973        trunc
974    }
975
976    fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
977        unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
978    }
979
980    fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
981        self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
982    }
983
984    fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
985        self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
986    }
987
988    fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
989        // On WebAssembly the `fptoui` and `fptosi` instructions currently have
990        // poor codegen. The reason for this is that the corresponding wasm
991        // instructions, `i32.trunc_f32_s` for example, will trap when the float
992        // is out-of-bounds, infinity, or nan. This means that LLVM
993        // automatically inserts control flow around `fptoui` and `fptosi`
994        // because the LLVM instruction `fptoui` is defined as producing a
995        // poison value, not having UB on out-of-bounds values.
996        //
997        // This method, however, is only used with non-saturating casts that
998        // have UB on out-of-bounds values. This means that it's ok if we use
999        // the raw wasm instruction since out-of-bounds values can do whatever
1000        // we like. To ensure that LLVM picks the right instruction we choose
1001        // the raw wasm intrinsic functions which avoid LLVM inserting all the
1002        // other control flow automatically.
1003        if self.sess().target.is_like_wasm {
1004            let src_ty = self.cx.val_ty(val);
1005            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1006                let float_width = self.cx.float_width(src_ty);
1007                let int_width = self.cx.int_width(dest_ty);
1008                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)) {
1009                    return self.call_intrinsic(
1010                        "llvm.wasm.trunc.unsigned",
1011                        &[dest_ty, src_ty],
1012                        &[val],
1013                    );
1014                }
1015            }
1016        }
1017        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1018    }
1019
1020    fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1021        // see `fptoui` above for why wasm is different here
1022        if self.sess().target.is_like_wasm {
1023            let src_ty = self.cx.val_ty(val);
1024            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1025                let float_width = self.cx.float_width(src_ty);
1026                let int_width = self.cx.int_width(dest_ty);
1027                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)) {
1028                    return self.call_intrinsic(
1029                        "llvm.wasm.trunc.signed",
1030                        &[dest_ty, src_ty],
1031                        &[val],
1032                    );
1033                }
1034            }
1035        }
1036        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1037    }
1038
1039    fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1040        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1041    }
1042
1043    fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1044        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1045    }
1046
1047    fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1048        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1049    }
1050
1051    fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1052        unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1053    }
1054
1055    fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1056        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1057    }
1058
1059    fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1060        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1061    }
1062
1063    fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1064        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1065    }
1066
1067    fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1068        unsafe {
1069            llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1070        }
1071    }
1072
1073    fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1074        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1075    }
1076
1077    /* Comparisons */
1078    fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1079        let op = llvm::IntPredicate::from_generic(op);
1080        unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1081    }
1082
1083    fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1084        let op = llvm::RealPredicate::from_generic(op);
1085        unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1086    }
1087
1088    fn three_way_compare(
1089        &mut self,
1090        ty: Ty<'tcx>,
1091        lhs: Self::Value,
1092        rhs: Self::Value,
1093    ) -> Self::Value {
1094        let size = ty.primitive_size(self.tcx);
1095        let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1096
1097        self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1098    }
1099
1100    /* Miscellaneous instructions */
1101    fn memcpy(
1102        &mut self,
1103        dst: &'ll Value,
1104        dst_align: Align,
1105        src: &'ll Value,
1106        src_align: Align,
1107        size: &'ll Value,
1108        flags: MemFlags,
1109        tt: Option<FncTree>,
1110    ) {
1111        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");
1112        let size = self.intcast(size, self.type_isize(), false);
1113        let is_volatile = flags.contains(MemFlags::VOLATILE);
1114        let memcpy = unsafe {
1115            llvm::LLVMRustBuildMemCpy(
1116                self.llbuilder,
1117                dst,
1118                dst_align.bytes() as c_uint,
1119                src,
1120                src_align.bytes() as c_uint,
1121                size,
1122                is_volatile,
1123            )
1124        };
1125
1126        // TypeTree metadata for memcpy is especially important: when Enzyme encounters
1127        // a memcpy during autodiff, it needs to know the structure of the data being
1128        // copied to properly track derivatives. For example, copying an array of floats
1129        // vs. copying a struct with mixed types requires different derivative handling.
1130        // The TypeTree tells Enzyme exactly what memory layout to expect.
1131        if let Some(tt) = tt {
1132            crate::typetree::add_tt(self.cx().llmod, self.cx().llcx, memcpy, tt);
1133        }
1134    }
1135
1136    fn memmove(
1137        &mut self,
1138        dst: &'ll Value,
1139        dst_align: Align,
1140        src: &'ll Value,
1141        src_align: Align,
1142        size: &'ll Value,
1143        flags: MemFlags,
1144    ) {
1145        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");
1146        let size = self.intcast(size, self.type_isize(), false);
1147        let is_volatile = flags.contains(MemFlags::VOLATILE);
1148        unsafe {
1149            llvm::LLVMRustBuildMemMove(
1150                self.llbuilder,
1151                dst,
1152                dst_align.bytes() as c_uint,
1153                src,
1154                src_align.bytes() as c_uint,
1155                size,
1156                is_volatile,
1157            );
1158        }
1159    }
1160
1161    fn memset(
1162        &mut self,
1163        ptr: &'ll Value,
1164        fill_byte: &'ll Value,
1165        size: &'ll Value,
1166        align: Align,
1167        flags: MemFlags,
1168    ) {
1169        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");
1170        let is_volatile = flags.contains(MemFlags::VOLATILE);
1171        unsafe {
1172            llvm::LLVMRustBuildMemSet(
1173                self.llbuilder,
1174                ptr,
1175                align.bytes() as c_uint,
1176                fill_byte,
1177                size,
1178                is_volatile,
1179            );
1180        }
1181    }
1182
1183    fn select(
1184        &mut self,
1185        cond: &'ll Value,
1186        then_val: &'ll Value,
1187        else_val: &'ll Value,
1188    ) -> &'ll Value {
1189        unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1190    }
1191
1192    fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1193        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1194    }
1195
1196    fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1197        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1198    }
1199
1200    fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1201        unsafe {
1202            let elt_ty = self.cx.val_ty(elt);
1203            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1204            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1205            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1206            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1207        }
1208    }
1209
1210    fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1211        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);
1212        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1213    }
1214
1215    fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1216        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);
1217        unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1218    }
1219
1220    fn set_personality_fn(&mut self, personality: &'ll Value) {
1221        unsafe {
1222            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1223        }
1224    }
1225
1226    fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1227        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1228        let landing_pad = self.landing_pad(ty, pers_fn, 0);
1229        unsafe {
1230            llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1231        }
1232        (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1233    }
1234
1235    fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1236        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1237        let landing_pad = self.landing_pad(ty, pers_fn, 1);
1238        self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1239    }
1240
1241    fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1242        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1243        let mut exn = self.const_poison(ty);
1244        exn = self.insert_value(exn, exn0, 0);
1245        exn = self.insert_value(exn, exn1, 1);
1246        unsafe {
1247            llvm::LLVMBuildResume(self.llbuilder, exn);
1248        }
1249    }
1250
1251    fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1252        let ret = unsafe {
1253            llvm::LLVMBuildCleanupPad(
1254                self.llbuilder,
1255                parent,
1256                args.as_ptr(),
1257                args.len() as c_uint,
1258                c"cleanuppad".as_ptr(),
1259            )
1260        };
1261        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1262    }
1263
1264    fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1265        unsafe {
1266            llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1267                .expect("LLVM does not have support for cleanupret");
1268        }
1269    }
1270
1271    fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1272        let ret = unsafe {
1273            llvm::LLVMBuildCatchPad(
1274                self.llbuilder,
1275                parent,
1276                args.as_ptr(),
1277                args.len() as c_uint,
1278                c"catchpad".as_ptr(),
1279            )
1280        };
1281        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1282    }
1283
1284    fn catch_switch(
1285        &mut self,
1286        parent: Option<&'ll Value>,
1287        unwind: Option<&'ll BasicBlock>,
1288        handlers: &[&'ll BasicBlock],
1289    ) -> &'ll Value {
1290        let ret = unsafe {
1291            llvm::LLVMBuildCatchSwitch(
1292                self.llbuilder,
1293                parent,
1294                unwind,
1295                handlers.len() as c_uint,
1296                c"catchswitch".as_ptr(),
1297            )
1298        };
1299        let ret = ret.expect("LLVM does not have support for catchswitch");
1300        for handler in handlers {
1301            unsafe {
1302                llvm::LLVMAddHandler(ret, handler);
1303            }
1304        }
1305        ret
1306    }
1307
1308    fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> &'ll Value {
1309        funclet.cleanuppad()
1310    }
1311
1312    // Atomic Operations
1313    fn atomic_cmpxchg(
1314        &mut self,
1315        dst: &'ll Value,
1316        cmp: &'ll Value,
1317        src: &'ll Value,
1318        order: rustc_middle::ty::AtomicOrdering,
1319        failure_order: rustc_middle::ty::AtomicOrdering,
1320        weak: bool,
1321    ) -> (&'ll Value, &'ll Value) {
1322        unsafe {
1323            let value = llvm::LLVMBuildAtomicCmpXchg(
1324                self.llbuilder,
1325                dst,
1326                cmp,
1327                src,
1328                AtomicOrdering::from_generic(order),
1329                AtomicOrdering::from_generic(failure_order),
1330                llvm::FALSE, // SingleThreaded
1331            );
1332            llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1333            let val = self.extract_value(value, 0);
1334            let success = self.extract_value(value, 1);
1335            (val, success)
1336        }
1337    }
1338
1339    fn atomic_rmw(
1340        &mut self,
1341        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1342        dst: &'ll Value,
1343        src: &'ll Value,
1344        order: rustc_middle::ty::AtomicOrdering,
1345        ret_ptr: bool,
1346    ) -> &'ll Value {
1347        // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the
1348        // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not
1349        // currently support that (https://github.com/llvm/llvm-project/issues/120837).
1350        let mut res = unsafe {
1351            llvm::LLVMBuildAtomicRMW(
1352                self.llbuilder,
1353                AtomicRmwBinOp::from_generic(op),
1354                dst,
1355                src,
1356                AtomicOrdering::from_generic(order),
1357                llvm::FALSE, // SingleThreaded
1358            )
1359        };
1360        if ret_ptr && self.val_ty(res) != self.type_ptr() {
1361            res = self.inttoptr(res, self.type_ptr());
1362        }
1363        res
1364    }
1365
1366    fn atomic_fence(
1367        &mut self,
1368        order: rustc_middle::ty::AtomicOrdering,
1369        scope: SynchronizationScope,
1370    ) {
1371        let single_threaded = match scope {
1372            SynchronizationScope::SingleThread => true,
1373            SynchronizationScope::CrossThread => false,
1374        };
1375        unsafe {
1376            llvm::LLVMBuildFence(
1377                self.llbuilder,
1378                AtomicOrdering::from_generic(order),
1379                single_threaded.to_llvm_bool(),
1380                UNNAMED,
1381            );
1382        }
1383    }
1384
1385    fn set_invariant_load(&mut self, load: &'ll Value) {
1386        self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1387    }
1388
1389    fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1390        self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1391    }
1392
1393    fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1394        self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1395    }
1396
1397    fn call(
1398        &mut self,
1399        llty: &'ll Type,
1400        caller_attrs: Option<&CodegenFnAttrs>,
1401        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1402        llfn: &'ll Value,
1403        args: &[&'ll Value],
1404        funclet: Option<&Funclet<'ll>>,
1405        callee_instance: Option<Instance<'tcx>>,
1406    ) -> &'ll Value {
1407        {
    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:1407",
                        "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(1407u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
1408
1409        let args = self.check_call("call", llty, llfn, args);
1410        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1411        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1412        if let Some(funclet_bundle) = funclet_bundle {
1413            bundles.push(funclet_bundle);
1414        }
1415
1416        // Emit CFI pointer type membership test
1417        self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1418
1419        // Emit KCFI operand bundle
1420        let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1421        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1422            bundles.push(kcfi_bundle);
1423        }
1424
1425        let call = unsafe {
1426            llvm::LLVMBuildCallWithOperandBundles(
1427                self.llbuilder,
1428                llty,
1429                llfn,
1430                args.as_ptr() as *const &llvm::Value,
1431                args.len() as c_uint,
1432                bundles.as_ptr(),
1433                bundles.len() as c_uint,
1434                c"".as_ptr(),
1435            )
1436        };
1437
1438        if let Some(callee_instance) = callee_instance {
1439            // Attributes on the function definition being called
1440            let callee_attrs = self.cx.tcx.codegen_fn_attrs(callee_instance.def_id());
1441
1442            if let Some(inlining_rule) =
1443                attributes::inline_attr(&self.cx, self.cx.tcx, callee_instance, callee_attrs)
1444            {
1445                attributes::apply_to_callsite(
1446                    call,
1447                    llvm::AttributePlace::Function,
1448                    &[inlining_rule],
1449                );
1450            }
1451        }
1452
1453        if let Some(fn_abi) = fn_abi {
1454            fn_abi.apply_attrs_callsite(self, call);
1455        }
1456        call
1457    }
1458
1459    fn tail_call(
1460        &mut self,
1461        llty: Self::Type,
1462        caller_attrs: Option<&CodegenFnAttrs>,
1463        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1464        llfn: Self::Value,
1465        args: &[Self::Value],
1466        funclet: Option<&Self::Funclet>,
1467        callee_instance: Option<Instance<'tcx>>,
1468    ) {
1469        let call =
1470            self.call(llty, caller_attrs, Some(fn_abi), llfn, args, funclet, callee_instance);
1471        llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1472
1473        match &fn_abi.ret.mode {
1474            PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1475            PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1476        }
1477    }
1478
1479    fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1480        unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1481    }
1482
1483    fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1484        // Cleanup is always the cold path.
1485        let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1486        attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1487    }
1488}
1489
1490impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1491    fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1492        // Forward to the `get_static` method of `CodegenCx`
1493        let global = self.cx().get_static(def_id);
1494        if self.cx().tcx.is_thread_local_static(def_id) {
1495            let pointer =
1496                self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1497            // Cast to default address space if globals are in a different addrspace
1498            self.pointercast(pointer, self.type_ptr())
1499        } else {
1500            // Cast to default address space if globals are in a different addrspace
1501            self.cx().const_pointercast(global, self.type_ptr())
1502        }
1503    }
1504}
1505
1506impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1507    pub(crate) fn llfn(&self) -> &'ll Value {
1508        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1509    }
1510}
1511
1512impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1513    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1514        unsafe {
1515            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1516        }
1517    }
1518}
1519impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1520    fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1521        let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1522        self.set_metadata_node(load, llvm::MD_align, &md);
1523    }
1524
1525    fn noundef_metadata(&mut self, load: &'ll Value) {
1526        self.set_metadata_node(load, llvm::MD_noundef, &[]);
1527    }
1528
1529    pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1530        self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1531    }
1532
1533    fn write_operand_repeatedly_optimized(
1534        &mut self,
1535        cg_elem: OperandRef<'tcx, &'ll Value>,
1536        count: u64,
1537        dest: PlaceRef<'tcx, &'ll Value>,
1538    ) {
1539        let zero = self.const_usize(0);
1540        let count = self.const_usize(count);
1541
1542        let header_bb = self.append_sibling_block("repeat_loop_header");
1543        let body_bb = self.append_sibling_block("repeat_loop_body");
1544        let next_bb = self.append_sibling_block("repeat_loop_next");
1545
1546        self.br(header_bb);
1547
1548        let mut header_bx = Self::build(self.cx, header_bb);
1549        let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1550
1551        let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1552        header_bx.cond_br(keep_going, body_bb, next_bb);
1553
1554        let mut body_bx = Self::build(self.cx, body_bb);
1555        let dest_elem = dest.project_index(&mut body_bx, i);
1556        cg_elem.val.store(&mut body_bx, dest_elem);
1557
1558        let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1559        body_bx.br(header_bb);
1560        header_bx.add_incoming_to_phi(i, next, body_bb);
1561
1562        *self = Self::build(self.cx, next_bb);
1563    }
1564
1565    fn write_operand_repeatedly_unoptimized(
1566        &mut self,
1567        cg_elem: OperandRef<'tcx, &'ll Value>,
1568        count: u64,
1569        dest: PlaceRef<'tcx, &'ll Value>,
1570    ) {
1571        let zero = self.const_usize(0);
1572        let count = self.const_usize(count);
1573        let start = dest.project_index(self, zero).val.llval;
1574        let end = dest.project_index(self, count).val.llval;
1575
1576        let header_bb = self.append_sibling_block("repeat_loop_header");
1577        let body_bb = self.append_sibling_block("repeat_loop_body");
1578        let next_bb = self.append_sibling_block("repeat_loop_next");
1579
1580        self.br(header_bb);
1581
1582        let mut header_bx = Self::build(self.cx, header_bb);
1583        let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1584
1585        let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1586        header_bx.cond_br(keep_going, body_bb, next_bb);
1587
1588        let mut body_bx = Self::build(self.cx, body_bb);
1589        let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1590        cg_elem
1591            .val
1592            .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1593
1594        let next = body_bx.inbounds_gep(
1595            self.backend_type(cg_elem.layout),
1596            current,
1597            &[self.const_usize(1)],
1598        );
1599        body_bx.br(header_bb);
1600        header_bx.add_incoming_to_phi(current, next, body_bb);
1601
1602        *self = Self::build(self.cx, next_bb);
1603    }
1604
1605    pub(crate) fn minimum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1606        let call = self.call_intrinsic("llvm.minimumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1607        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1608        call
1609    }
1610
1611    pub(crate) fn maximum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1612        let call = self.call_intrinsic("llvm.maximumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1613        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1614        call
1615    }
1616
1617    pub(crate) fn insert_element(
1618        &mut self,
1619        vec: &'ll Value,
1620        elt: &'ll Value,
1621        idx: &'ll Value,
1622    ) -> &'ll Value {
1623        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1624    }
1625
1626    pub(crate) fn shuffle_vector(
1627        &mut self,
1628        v1: &'ll Value,
1629        v2: &'ll Value,
1630        mask: &'ll Value,
1631    ) -> &'ll Value {
1632        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1633    }
1634
1635    pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1636        self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1637    }
1638    pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1639        self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1640    }
1641    pub(crate) fn vector_reduce_fadd_reassoc(
1642        &mut self,
1643        acc: &'ll Value,
1644        src: &'ll Value,
1645    ) -> &'ll Value {
1646        unsafe {
1647            let instr =
1648                self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1649            llvm::LLVMRustSetAllowReassoc(instr);
1650            instr
1651        }
1652    }
1653    pub(crate) fn vector_reduce_fmul_reassoc(
1654        &mut self,
1655        acc: &'ll Value,
1656        src: &'ll Value,
1657    ) -> &'ll Value {
1658        unsafe {
1659            let instr =
1660                self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1661            llvm::LLVMRustSetAllowReassoc(instr);
1662            instr
1663        }
1664    }
1665    pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1666        self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1667    }
1668    pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1669        self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1670    }
1671    pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1672        self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1673    }
1674    pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1675        self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1676    }
1677    pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1678        self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1679    }
1680    pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1681        self.call_intrinsic(
1682            if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1683            &[self.val_ty(src)],
1684            &[src],
1685        )
1686    }
1687    pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1688        self.call_intrinsic(
1689            if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1690            &[self.val_ty(src)],
1691            &[src],
1692        )
1693    }
1694}
1695impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1696    pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1697        unsafe {
1698            llvm::LLVMAddClause(landing_pad, clause);
1699        }
1700    }
1701
1702    pub(crate) fn catch_ret(
1703        &mut self,
1704        funclet: &Funclet<'ll>,
1705        unwind: &'ll BasicBlock,
1706    ) -> &'ll Value {
1707        let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1708        ret.expect("LLVM does not have support for catchret")
1709    }
1710
1711    pub(crate) fn check_call<'b>(
1712        &mut self,
1713        typ: &str,
1714        fn_ty: &'ll Type,
1715        llfn: &'ll Value,
1716        args: &'b [&'ll Value],
1717    ) -> Cow<'b, [&'ll Value]> {
1718        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!(
1719            self.cx.type_kind(fn_ty) == TypeKind::Function,
1720            "builder::{typ} not passed a function, but {fn_ty:?}"
1721        );
1722
1723        let param_tys = self.cx.func_params_types(fn_ty);
1724
1725        let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1726            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1727
1728        if all_args_match {
1729            return Cow::Borrowed(args);
1730        }
1731
1732        let casted_args: Vec<_> = iter::zip(param_tys, args)
1733            .enumerate()
1734            .map(|(i, (expected_ty, &actual_val))| {
1735                let actual_ty = self.cx.val_ty(actual_val);
1736                if expected_ty != actual_ty {
1737                    {
    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:1737",
                        "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(1737u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::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 Value))])
            });
    } else { ; }
};debug!(
1738                        "type mismatch in function call of {:?}. \
1739                            Expected {:?} for param {}, got {:?}; injecting bitcast",
1740                        llfn, expected_ty, i, actual_ty
1741                    );
1742                    self.bitcast(actual_val, expected_ty)
1743                } else {
1744                    actual_val
1745                }
1746            })
1747            .collect();
1748
1749        Cow::Owned(casted_args)
1750    }
1751
1752    pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1753        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1754    }
1755}
1756
1757impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1758    pub(crate) fn call_intrinsic(
1759        &mut self,
1760        base_name: impl Into<Cow<'static, str>>,
1761        type_params: &[&'ll Type],
1762        args: &[&'ll Value],
1763    ) -> &'ll Value {
1764        let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1765        self.call(ty, None, None, f, args, None, None)
1766    }
1767
1768    fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1769        let size = size.bytes();
1770        if size == 0 {
1771            return;
1772        }
1773
1774        if !self.cx().sess().emit_lifetime_markers() {
1775            return;
1776        }
1777
1778        if crate::llvm_util::get_version() >= (22, 0, 0) {
1779            // LLVM 22 requires the lifetime intrinsic to act directly on the alloca,
1780            // there can't be an addrspacecast in between.
1781            let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1782            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1783        } else {
1784            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1785        }
1786    }
1787}
1788impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1789    pub(crate) fn phi(
1790        &mut self,
1791        ty: &'ll Type,
1792        vals: &[&'ll Value],
1793        bbs: &[&'ll BasicBlock],
1794    ) -> &'ll Value {
1795        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());
1796        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1797        unsafe {
1798            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1799            phi
1800        }
1801    }
1802
1803    fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1804        unsafe {
1805            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1806        }
1807    }
1808}
1809impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1810    pub(crate) fn landing_pad(
1811        &mut self,
1812        ty: &'ll Type,
1813        pers_fn: &'ll Value,
1814        num_clauses: usize,
1815    ) -> &'ll Value {
1816        // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1817        // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1818        // personality lives on the parent function anyway.
1819        self.set_personality_fn(pers_fn);
1820        unsafe {
1821            llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1822        }
1823    }
1824
1825    pub(crate) fn callbr(
1826        &mut self,
1827        llty: &'ll Type,
1828        fn_attrs: Option<&CodegenFnAttrs>,
1829        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1830        llfn: &'ll Value,
1831        args: &[&'ll Value],
1832        default_dest: &'ll BasicBlock,
1833        indirect_dest: &[&'ll BasicBlock],
1834        funclet: Option<&Funclet<'ll>>,
1835        instance: Option<Instance<'tcx>>,
1836    ) -> &'ll Value {
1837        {
    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:1837",
                        "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(1837u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
1838
1839        let args = self.check_call("callbr", llty, llfn, args);
1840        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1841        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1842        if let Some(funclet_bundle) = funclet_bundle {
1843            bundles.push(funclet_bundle);
1844        }
1845
1846        // Emit CFI pointer type membership test
1847        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1848
1849        // Emit KCFI operand bundle
1850        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1851        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1852            bundles.push(kcfi_bundle);
1853        }
1854
1855        let callbr = unsafe {
1856            llvm::LLVMBuildCallBr(
1857                self.llbuilder,
1858                llty,
1859                llfn,
1860                default_dest,
1861                indirect_dest.as_ptr(),
1862                indirect_dest.len() as c_uint,
1863                args.as_ptr(),
1864                args.len() as c_uint,
1865                bundles.as_ptr(),
1866                bundles.len() as c_uint,
1867                UNNAMED,
1868            )
1869        };
1870        if let Some(fn_abi) = fn_abi {
1871            fn_abi.apply_attrs_callsite(self, callbr);
1872        }
1873        callbr
1874    }
1875
1876    // Emits CFI pointer type membership tests.
1877    fn cfi_type_test(
1878        &mut self,
1879        fn_attrs: Option<&CodegenFnAttrs>,
1880        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1881        instance: Option<Instance<'tcx>>,
1882        llfn: &'ll Value,
1883    ) {
1884        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1885        if self.tcx.sess.is_sanitizer_cfi_enabled()
1886            && let Some(fn_abi) = fn_abi
1887            && is_indirect_call
1888        {
1889            if let Some(fn_attrs) = fn_attrs
1890                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
1891            {
1892                return;
1893            }
1894
1895            let mut options = cfi::TypeIdOptions::empty();
1896            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1897                options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1898            }
1899            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1900                options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1901            }
1902
1903            let typeid = if let Some(instance) = instance {
1904                cfi::typeid_for_instance(self.tcx, instance, options)
1905            } else {
1906                cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1907            };
1908            let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1909            let dbg_loc = self.get_dbg_loc();
1910
1911            // Test whether the function pointer is associated with the type identifier using the
1912            // llvm.type.test intrinsic. The LowerTypeTests link-time optimization pass replaces
1913            // calls to this intrinsic with code to test type membership.
1914            let typeid = self.get_metadata_value(typeid_metadata);
1915            let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1916            let bb_pass = self.append_sibling_block("type_test.pass");
1917            let bb_fail = self.append_sibling_block("type_test.fail");
1918            self.cond_br(cond, bb_pass, bb_fail);
1919
1920            self.switch_to_block(bb_fail);
1921            if let Some(dbg_loc) = dbg_loc {
1922                self.set_dbg_loc(dbg_loc);
1923            }
1924            self.abort();
1925            self.unreachable();
1926
1927            self.switch_to_block(bb_pass);
1928            if let Some(dbg_loc) = dbg_loc {
1929                self.set_dbg_loc(dbg_loc);
1930            }
1931        }
1932    }
1933
1934    // Emits KCFI operand bundles.
1935    fn kcfi_operand_bundle(
1936        &mut self,
1937        fn_attrs: Option<&CodegenFnAttrs>,
1938        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1939        instance: Option<Instance<'tcx>>,
1940        llfn: &'ll Value,
1941    ) -> Option<llvm::OperandBundleBox<'ll>> {
1942        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1943        let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
1944            && let Some(fn_abi) = fn_abi
1945            && is_indirect_call
1946        {
1947            if let Some(fn_attrs) = fn_attrs
1948                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
1949            {
1950                return None;
1951            }
1952
1953            let mut options = kcfi::TypeIdOptions::empty();
1954            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1955                options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
1956            }
1957            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1958                options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
1959            }
1960
1961            let kcfi_typeid = if let Some(instance) = instance {
1962                kcfi::typeid_for_instance(self.tcx, instance, options)
1963            } else {
1964                kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1965            };
1966
1967            Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
1968        } else {
1969            None
1970        };
1971        kcfi_bundle
1972    }
1973
1974    /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation.
1975    #[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(1975u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&["fn_name", "hash",
                                                    "num_counters", "index"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hash)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&num_counters)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&index)
                                                            as &dyn 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))]
1976    pub(crate) fn instrprof_increment(
1977        &mut self,
1978        fn_name: &'ll Value,
1979        hash: &'ll Value,
1980        num_counters: &'ll Value,
1981        index: &'ll Value,
1982    ) {
1983        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
1984    }
1985}