Skip to main content

rustc_codegen_llvm/
builder.rs

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