Skip to main content

rustc_codegen_llvm/
builder.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

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

                    #[warn(clippy :: suspicious_else_formatting)]
                    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.call_intrinsic("llvm.instrprof.increment", &[],
                &[fn_name, hash, num_counters, index]);
        }
    }
}#[instrument(level = "debug", skip(self))]
2220    pub(crate) fn instrprof_increment(
2221        &mut self,
2222        fn_name: &'ll Value,
2223        hash: &'ll Value,
2224        num_counters: &'ll Value,
2225        index: &'ll Value,
2226    ) {
2227        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
2228    }
2229}