Skip to main content

rustc_codegen_llvm/
consts.rs

1use std::ops::Range;
2
3use rustc_abi::{Align, ExternAbi, HasDataLayout, Primitive, Scalar, Size, WrappingRange};
4use rustc_codegen_ssa::common;
5use rustc_codegen_ssa::traits::*;
6use rustc_hir::LangItem;
7use rustc_hir::attrs::Linkage;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::{DefId, LOCAL_CRATE};
10use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
11use rustc_middle::mir::interpret::{
12    Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, Scalar as InterpScalar,
13    read_target_uint,
14};
15use rustc_middle::mono::MonoItem;
16use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf};
17use rustc_middle::ty::{self, Instance};
18use rustc_middle::{bug, span_bug};
19use rustc_span::Symbol;
20use rustc_target::spec::{Arch, LlvmAbi};
21use tracing::{debug, instrument, trace};
22
23use crate::common::CodegenCx;
24use crate::errors::SymbolAlreadyDefined;
25use crate::llvm::{self, Type, Value, const_ptr_auth};
26use crate::type_of::LayoutLlvmExt;
27use crate::{base, debuginfo};
28
29/// Indicates whether a value originates from a `static`.
30pub(crate) enum IsStatic {
31    Yes,
32    No,
33}
34/// Indicates whether a symbol is part of `.init_array` or `.fini_array`.
35pub(crate) enum IsInitOrFini {
36    Yes,
37    No,
38}
39pub(crate) fn const_alloc_to_llvm<'ll>(
40    cx: &CodegenCx<'ll, '_>,
41    alloc: &Allocation,
42    is_static: IsStatic,
43    is_init_fini: IsInitOrFini,
44) -> &'ll Value {
45    // We expect that callers of const_alloc_to_llvm will instead directly codegen a pointer or
46    // integer for any &ZST where the ZST is a constant (i.e. not a static). We should never be
47    // producing empty LLVM allocations as they're just adding noise to binaries and forcing less
48    // optimal codegen.
49    //
50    // Statics have a guaranteed meaningful address so it's less clear that we want to do
51    // something like this; it's also harder.
52    if #[allow(non_exhaustive_omitted_patterns)] match is_static {
    IsStatic::No => true,
    _ => false,
}matches!(is_static, IsStatic::No) {
53        if !(alloc.len() != 0) {
    ::core::panicking::panic("assertion failed: alloc.len() != 0")
};assert!(alloc.len() != 0);
54    }
55    let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
56    let dl = cx.data_layout();
57    let pointer_size = dl.pointer_size();
58    let pointer_size_bytes = pointer_size.bytes() as usize;
59
60    // Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`, so `range`
61    // must be within the bounds of `alloc` and not contain or overlap a pointer provenance.
62    fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
63        llvals: &mut Vec<&'ll Value>,
64        cx: &'a CodegenCx<'ll, 'b>,
65        alloc: &'a Allocation,
66        range: Range<usize>,
67    ) {
68        let chunks = alloc.init_mask().range_as_init_chunks(range.clone().into());
69
70        let chunk_to_llval = move |chunk| match chunk {
71            InitChunk::Init(range) => {
72                let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
73                let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
74                cx.const_bytes(bytes)
75            }
76            InitChunk::Uninit(range) => {
77                let len = range.end.bytes() - range.start.bytes();
78                cx.const_undef(cx.type_array(cx.type_i8(), len))
79            }
80        };
81
82        // Generating partially-uninit consts is limited to small numbers of chunks,
83        // to avoid the cost of generating large complex const expressions.
84        // For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element, and
85        // would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
86        let max = cx.sess().opts.unstable_opts.uninit_const_chunk_threshold;
87        let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
88
89        if allow_uninit_chunks {
90            llvals.extend(chunks.map(chunk_to_llval));
91        } else {
92            // If this allocation contains any uninit bytes, codegen as if it was initialized
93            // (using some arbitrary value for uninit bytes).
94            let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
95            llvals.push(cx.const_bytes(bytes));
96        }
97    }
98
99    let mut next_offset = 0;
100    for &(offset, prov) in alloc.provenance().ptrs().iter() {
101        let offset = offset.bytes();
102        {
    match (&(offset as usize as u64), &offset) {
        (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!(offset as usize as u64, offset);
103        let offset = offset as usize;
104        if offset > next_offset {
105            // This `inspect` is okay since we have checked that there is no provenance, it
106            // is within the bounds of the allocation, and it doesn't affect interpreter execution
107            // (we inspect the result after interpreter execution).
108            append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
109        }
110        let ptr_offset = read_target_uint(
111            dl.endian,
112            // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
113            // affect interpreter execution (we inspect the result after interpreter execution),
114            // and we properly interpret the provenance as a relocation pointer offset.
115            alloc.inspect_with_uninit_and_ptr_outside_interpreter(
116                offset..(offset + pointer_size_bytes),
117            ),
118        )
119        .expect("const_alloc_to_llvm: could not read relocation pointer")
120            as u64;
121
122        let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx);
123        // Under pointer authentication, function pointers stored in init/fini arrays need special
124        // handling.
125        let pac_metadata = Some(
126            if cx.sess().target.llvm_abiname == LlvmAbi::Pauthtest
127                && #[allow(non_exhaustive_omitted_patterns)] match is_init_fini {
    IsInitOrFini::Yes => true,
    _ => false,
}matches!(is_init_fini, IsInitOrFini::Yes)
128            {
129                PacMetadata {
130                    // Must correspond to ptrauth_key_init_fini_pointer from `ptrauth.h`.
131                    key: 0,
132                    // ptrauth_string_discriminator("init_fini")
133                    disc: 0xd9d4,
134                    addr_diversity: AddressDiversity::Synthetic(1),
135                }
136            } else {
137                PacMetadata::default()
138            },
139        );
140        llvals.push(cx.scalar_to_backend_with_pac(
141            InterpScalar::from_pointer(Pointer::new(prov, Size::from_bytes(ptr_offset)), &cx.tcx),
142            Scalar::Initialized {
143                value: Primitive::Pointer(address_space),
144                valid_range: WrappingRange::full(pointer_size),
145            },
146            cx.type_ptr_ext(address_space),
147            pac_metadata,
148        ));
149        next_offset = offset + pointer_size_bytes;
150    }
151    if alloc.len() >= next_offset {
152        let range = next_offset..alloc.len();
153        // This `inspect` is okay since we have check that it is after all provenance, it is
154        // within the bounds of the allocation, and it doesn't affect interpreter execution (we
155        // inspect the result after interpreter execution).
156        append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
157    }
158
159    // Avoid wrapping in a struct if there is only a single value. This ensures
160    // that LLVM is able to perform the string merging optimization if the constant
161    // is a valid C string. LLVM only considers bare arrays for this optimization,
162    // not arrays wrapped in a struct. LLVM handles this at:
163    // https://github.com/rust-lang/llvm-project/blob/acaea3d2bb8f351b740db7ebce7d7a40b9e21488/llvm/lib/Target/TargetLoweringObjectFile.cpp#L249-L280
164    if let &[data] = &*llvals { data } else { cx.const_struct(&llvals, true) }
165}
166
167fn codegen_static_initializer<'ll, 'tcx>(
168    cx: &CodegenCx<'ll, 'tcx>,
169    def_id: DefId,
170) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> {
171    let alloc = cx.tcx.eval_static_initializer(def_id)?;
172    let attrs = cx.tcx.codegen_fn_attrs(def_id);
173    // FIXME(jchlanda) Decide if this could be better served by `ctor` crate. See the discussion
174    // here: <https://github.com/rust-lang/rust/pull/155722#discussion_r3320477047>
175    let is_in_init_fini: IsInitOrFini = attrs
176        .link_section
177        .map(|link_section| {
178            let s = link_section.as_str();
179            if s.starts_with(".init_array") || s.starts_with(".fini_array") {
180                IsInitOrFini::Yes
181            } else {
182                IsInitOrFini::No
183            }
184        })
185        .unwrap_or(IsInitOrFini::No);
186    Ok((const_alloc_to_llvm(cx, alloc.inner(), IsStatic::Yes, is_in_init_fini), alloc))
187}
188
189fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
190    // The target may require greater alignment for globals than the type does.
191    // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
192    // which can force it to be smaller. Rust doesn't support this yet.
193    if let Some(min_global) = cx.sess().target.min_global_align {
194        align = Ord::max(align, min_global);
195    }
196    llvm::set_alignment(gv, align);
197}
198
199fn check_and_apply_linkage<'ll, 'tcx>(
200    cx: &CodegenCx<'ll, 'tcx>,
201    attrs: &CodegenFnAttrs,
202    llty: &'ll Type,
203    sym: &str,
204    def_id: DefId,
205) -> &'ll Value {
206    if let Some(linkage) = attrs.import_linkage {
207        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/consts.rs:207",
                        "rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/consts.rs"),
                        ::tracing_core::__macro_support::Option::Some(207u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("get_static: sym={0} linkage={1:?}",
                                                    sym, linkage) as &dyn Value))])
            });
    } else { ; }
};debug!("get_static: sym={} linkage={:?}", sym, linkage);
208
209        let mut should_sign = false;
210        // Declare a symbol `foo`. If `foo` is an extern_weak symbol, we declare
211        // an extern_weak function, otherwise a global with the desired linkage.
212        let g1 = if #[allow(non_exhaustive_omitted_patterns)] match attrs.import_linkage {
    Some(Linkage::ExternalWeak) => true,
    _ => false,
}matches!(attrs.import_linkage, Some(Linkage::ExternalWeak)) {
213            // An `extern_weak` function is represented as an `Option<unsafe extern ...>`,
214            // we extract the function signature and declare it as an extern_weak function
215            // instead of an extern_weak i8.
216            let instance = Instance::mono(cx.tcx, def_id);
217            if let ty::Adt(struct_def, args) = instance.ty(cx.tcx, cx.typing_env()).kind()
218                && cx.tcx.is_lang_item(struct_def.did(), LangItem::Option)
219                && let ty::FnPtr(sig, header) = args.type_at(0).kind()
220            {
221                let fn_sig = sig.with(*header);
222                let fn_abi = cx.fn_abi_of_fn_ptr(fn_sig, ty::List::empty());
223                // Decide if the initializer needs to be signed
224                if cx.sess().target.llvm_abiname == LlvmAbi::Pauthtest
225                    && #[allow(non_exhaustive_omitted_patterns)] match fn_sig.abi() {
    ExternAbi::C { .. } | ExternAbi::System { .. } => true,
    _ => false,
}matches!(fn_sig.abi(), ExternAbi::C { .. } | ExternAbi::System { .. })
226                {
227                    should_sign = true;
228                }
229                cx.declare_fn(sym, &fn_abi, None)
230            } else {
231                cx.declare_global(sym, cx.type_i8())
232            }
233        } else {
234            cx.declare_global(sym, cx.type_i8())
235        };
236        llvm::set_linkage(g1, base::linkage_to_llvm(linkage));
237
238        // Normally this is done in `get_static_inner`, but when as we generate an internal global,
239        // it will apply the dso_local to the internal global instead, so do it here, too.
240        cx.assume_dso_local(g1, true);
241
242        // Declare an internal global `extern_with_linkage_foo` which
243        // is initialized with the address of `foo`. If `foo` is
244        // discarded during linking (for example, if `foo` has weak
245        // linkage and there are no definitions), then
246        // `extern_with_linkage_foo` will instead be initialized to
247        // zero.
248        let real_name =
249            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("_rust_extern_with_linkage_{0:016x}_{1}",
                cx.tcx.stable_crate_id(LOCAL_CRATE), sym))
    })format!("_rust_extern_with_linkage_{:016x}_{sym}", cx.tcx.stable_crate_id(LOCAL_CRATE));
250        let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
251            cx.sess().dcx().emit_fatal(SymbolAlreadyDefined {
252                span: cx.tcx.def_span(def_id),
253                symbol_name: sym,
254            })
255        });
256        llvm::set_linkage(g2, llvm::Linkage::InternalLinkage);
257        llvm::set_unnamed_address(g2, llvm::UnnamedAddr::Global);
258
259        // Sign the function pointer that is used to initialize the global
260        let initializer = if should_sign {
261            let key: u32 = 0;
262            let discriminator: u64 = 0;
263
264            const_ptr_auth(
265                cx.const_bitcast(g1, llty),
266                key,
267                discriminator,
268                None, /* address_diversity */
269            )
270        } else {
271            g1
272        };
273
274        llvm::set_initializer(g2, initializer);
275
276        g2
277    } else if cx.tcx.sess.target.arch == Arch::X86
278        && common::is_mingw_gnu_toolchain(&cx.tcx.sess.target)
279        && let Some(dllimport) = crate::common::get_dllimport(cx.tcx, def_id, sym)
280    {
281        cx.declare_global(&common::i686_decorated_name(dllimport, true, true, false), llty)
282    } else {
283        // Generate an external declaration.
284        // FIXME(nagisa): investigate whether it can be changed into define_global
285        cx.declare_global(sym, llty)
286    }
287}
288
289impl<'ll> CodegenCx<'ll, '_> {
290    pub(crate) fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
291        unsafe { llvm::LLVMConstBitCast(val, ty) }
292    }
293
294    pub(crate) fn const_pointercast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
295        unsafe { llvm::LLVMConstPointerCast(val, ty) }
296    }
297
298    /// Create a global variable.
299    ///
300    /// The returned global variable is a pointer in the default address space for globals.
301    /// Fails if a symbol with the given name already exists.
302    pub(crate) fn static_addr_of_mut(
303        &self,
304        cv: &'ll Value,
305        align: Align,
306        kind: Option<&str>,
307    ) -> &'ll Value {
308        let gv = match kind {
309            Some(kind) if !self.tcx.sess.fewer_names() => {
310                let name = self.generate_local_symbol_name(kind);
311                let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| {
312                    ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        name));bug!("symbol `{}` is already defined", name);
313                });
314                gv
315            }
316            _ => self.define_global("", self.val_ty(cv)).unwrap_or_else(|| {
317                ::rustc_middle::util::bug::bug_fmt(format_args!("anonymous global symbol is already defined"));bug!("anonymous global symbol is already defined");
318            }),
319        };
320        llvm::set_linkage(gv, llvm::Linkage::PrivateLinkage);
321        llvm::set_initializer(gv, cv);
322        set_global_alignment(self, gv, align);
323        llvm::set_unnamed_address(gv, llvm::UnnamedAddr::Global);
324        gv
325    }
326
327    /// Create a global constant.
328    ///
329    /// The returned global variable is a pointer in the default address space for globals.
330    pub(crate) fn static_addr_of_impl(
331        &self,
332        cv: &'ll Value,
333        align: Align,
334        kind: Option<&str>,
335    ) -> &'ll Value {
336        if let Some(&gv) = self.const_globals.borrow().get(&cv) {
337            unsafe {
338                // Upgrade the alignment in cases where the same constant is used with different
339                // alignment requirements
340                let llalign = align.bytes() as u32;
341                if llalign > llvm::LLVMGetAlignment(gv) {
342                    llvm::LLVMSetAlignment(gv, llalign);
343                }
344            }
345            return gv;
346        }
347        let gv = self.static_addr_of_mut(cv, align, kind);
348        llvm::set_global_constant(gv, true);
349
350        self.const_globals.borrow_mut().insert(cv, gv);
351        gv
352    }
353
354    #[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("get_static",
                                    "rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(354u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'ll Value = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let instance = Instance::mono(self.tcx, def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/consts.rs:357",
                                    "rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(357u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&["instance"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&instance)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let DefKind::Static { nested, .. } =
                self.tcx.def_kind(def_id) else {
                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                };
            let llty =
                if nested {
                    self.type_i8()
                } else {
                    let ty = instance.ty(self.tcx, self.typing_env());
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/consts.rs:366",
                                            "rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/consts.rs"),
                                            ::tracing_core::__macro_support::Option::Some(366u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                            ::tracing_core::field::FieldSet::new(&["ty"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&ty) as
                                                                &dyn Value))])
                                });
                        } else { ; }
                    };
                    self.layout_of(ty).llvm_type(self)
                };
            self.get_static_inner(def_id, llty)
        }
    }
}#[instrument(level = "debug", skip(self))]
355    pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
356        let instance = Instance::mono(self.tcx, def_id);
357        trace!(?instance);
358
359        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
360        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
361        // out the llvm type from the actual evaluated initializer.
362        let llty = if nested {
363            self.type_i8()
364        } else {
365            let ty = instance.ty(self.tcx, self.typing_env());
366            trace!(?ty);
367            self.layout_of(ty).llvm_type(self)
368        };
369        self.get_static_inner(def_id, llty)
370    }
371
372    #[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("get_static_inner",
                                    "rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(372u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'ll Value = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let instance = Instance::mono(self.tcx, def_id);
            if let Some(&g) = self.instances.borrow().get(&instance) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/consts.rs:376",
                                        "rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/consts.rs"),
                                        ::tracing_core::__macro_support::Option::Some(376u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("used cached value")
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                return g;
            }
            let defined_in_current_codegen_unit =
                self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
            if !!defined_in_current_codegen_unit {
                {
                    ::core::panicking::panic_fmt(format_args!("consts::get_static() should always hit the cache for statics defined in the same CGU, but did not for `{0:?}`",
                            def_id));
                }
            };
            let sym = self.tcx.symbol_name(instance).name;
            let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/consts.rs:391",
                                    "rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(391u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&["sym", "fn_attrs"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&sym) as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&fn_attrs)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let g =
                if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
                    if let Some(g) = self.get_declared_value(sym) {
                        if self.val_ty(g) != self.type_ptr() {
                            ::rustc_middle::util::bug::span_bug_fmt(self.tcx.def_span(def_id),
                                format_args!("Conflicting types for static"));
                        }
                    }
                    let g = self.declare_global(sym, llty);
                    if !self.tcx.is_reachable_non_generic(def_id) {
                        llvm::set_visibility(g, llvm::Visibility::Hidden);
                    }
                    g
                } else if let Some(classname) = fn_attrs.objc_class {
                    self.get_objc_classref(classname)
                } else if let Some(methname) = fn_attrs.objc_selector {
                    self.get_objc_selref(methname)
                } else {
                    check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
                };
            if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
                llvm::set_thread_local_mode(g, self.tls_model);
            }
            let dso_local = self.assume_dso_local(g, true);
            if !def_id.is_local() {
                let needs_dll_storage_attr =
                    self.use_dll_storage_attrs &&
                                !self.tcx.is_foreign_item(def_id) && !dso_local &&
                        !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
                if !!(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
                                        self.tcx.sess.target.is_like_windows &&
                                    self.tcx.sess.opts.cg.prefer_dynamic) {
                    ::core::panicking::panic("assertion failed: !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() &&\n                self.tcx.sess.target.is_like_windows &&\n            self.tcx.sess.opts.cg.prefer_dynamic)")
                };
                if needs_dll_storage_attr {
                    if !self.tcx.is_codegened_item(def_id) {
                        llvm::set_dllimport_storage_class(g);
                    }
                }
            }
            if self.use_dll_storage_attrs &&
                        let Some(library) = self.tcx.native_library(def_id) &&
                    library.kind.is_dllimport() {
                llvm::set_dllimport_storage_class(g);
            }
            self.instances.borrow_mut().insert(instance, g);
            g
        }
    }
}#[instrument(level = "debug", skip(self, llty))]
373    fn get_static_inner(&self, def_id: DefId, llty: &'ll Type) -> &'ll Value {
374        let instance = Instance::mono(self.tcx, def_id);
375        if let Some(&g) = self.instances.borrow().get(&instance) {
376            trace!("used cached value");
377            return g;
378        }
379
380        let defined_in_current_codegen_unit =
381            self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
382        assert!(
383            !defined_in_current_codegen_unit,
384            "consts::get_static() should always hit the cache for \
385                 statics defined in the same CGU, but did not for `{def_id:?}`"
386        );
387
388        let sym = self.tcx.symbol_name(instance).name;
389        let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
390
391        debug!(?sym, ?fn_attrs);
392
393        let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
394            if let Some(g) = self.get_declared_value(sym) {
395                if self.val_ty(g) != self.type_ptr() {
396                    span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
397                }
398            }
399
400            let g = self.declare_global(sym, llty);
401
402            if !self.tcx.is_reachable_non_generic(def_id) {
403                llvm::set_visibility(g, llvm::Visibility::Hidden);
404            }
405
406            g
407        } else if let Some(classname) = fn_attrs.objc_class {
408            self.get_objc_classref(classname)
409        } else if let Some(methname) = fn_attrs.objc_selector {
410            self.get_objc_selref(methname)
411        } else {
412            check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
413        };
414
415        // Thread-local statics in some other crate need to *always* be linked
416        // against in a thread-local fashion, so we need to be sure to apply the
417        // thread-local attribute locally if it was present remotely. If we
418        // don't do this then linker errors can be generated where the linker
419        // complains that one object files has a thread local version of the
420        // symbol and another one doesn't.
421        if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
422            llvm::set_thread_local_mode(g, self.tls_model);
423        }
424
425        let dso_local = self.assume_dso_local(g, true);
426
427        if !def_id.is_local() {
428            let needs_dll_storage_attr = self.use_dll_storage_attrs
429                && !self.tcx.is_foreign_item(def_id)
430                // Local definitions can never be imported, so we must not apply
431                // the DLLImport annotation.
432                && !dso_local
433                // Linker plugin ThinLTO doesn't create the self-dllimport Rust uses for rlibs
434                // as the code generation happens out of process. Instead we assume static linkage
435                // and disallow dynamic linking when linker plugin based LTO is enabled.
436                // Regular in-process ThinLTO doesn't need this workaround.
437                && !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
438
439            // If this assertion triggers, there's something wrong with commandline
440            // argument validation.
441            assert!(
442                !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
443                    && self.tcx.sess.target.is_like_windows
444                    && self.tcx.sess.opts.cg.prefer_dynamic)
445            );
446
447            if needs_dll_storage_attr {
448                // This item is external but not foreign, i.e., it originates from an external Rust
449                // crate. Since we don't know whether this crate will be linked dynamically or
450                // statically in the final application, we always mark such symbols as 'dllimport'.
451                // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
452                // to make things work.
453                //
454                // However, in some scenarios we defer emission of statics to downstream
455                // crates, so there are cases where a static with an upstream DefId
456                // is actually present in the current crate. We can find out via the
457                // is_codegened_item query.
458                if !self.tcx.is_codegened_item(def_id) {
459                    llvm::set_dllimport_storage_class(g);
460                }
461            }
462        }
463
464        if self.use_dll_storage_attrs
465            && let Some(library) = self.tcx.native_library(def_id)
466            && library.kind.is_dllimport()
467        {
468            // For foreign (native) libs we know the exact storage type to use.
469            llvm::set_dllimport_storage_class(g);
470        }
471
472        self.instances.borrow_mut().insert(instance, g);
473        g
474    }
475
476    fn codegen_static_item(&mut self, def_id: DefId) {
477        if !llvm::LLVMGetInitializer(self.instances.borrow().get(&Instance::mono(self.tcx,
                                def_id)).unwrap()).is_none() {
    ::core::panicking::panic("assertion failed: llvm::LLVMGetInitializer(self.instances.borrow().get(&Instance::mono(self.tcx,\n                        def_id)).unwrap()).is_none()")
};assert!(
478            llvm::LLVMGetInitializer(
479                self.instances.borrow().get(&Instance::mono(self.tcx, def_id)).unwrap()
480            )
481            .is_none()
482        );
483        let attrs = self.tcx.codegen_fn_attrs(def_id);
484
485        let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
486            // Error has already been reported
487            return;
488        };
489        let alloc = alloc.inner();
490
491        let val_llty = self.val_ty(v);
492
493        let g = self.get_static_inner(def_id, val_llty);
494        let llty = self.get_type_of_global(g);
495
496        let g = if val_llty == llty {
497            g
498        } else {
499            // codegen_static_initializer creates the global value just from the
500            // `Allocation` data by generating one big struct value that is just
501            // all the bytes and pointers after each other. This will almost never
502            // match the type that the static was declared with. Unfortunately
503            // we can't just LLVMConstBitCast our way out of it because that has very
504            // specific rules on what can be cast. So instead of adding a new way to
505            // generate static initializers that match the static's type, we picked
506            // the easier option and retroactively change the type of the static item itself.
507            let name = String::from_utf8(llvm::get_value_name(g))
508                .expect("we declare our statics with a utf8-valid name");
509            llvm::set_value_name(g, b"");
510
511            let linkage = llvm::get_linkage(g);
512            let visibility = llvm::get_visibility(g);
513
514            let new_g = self.declare_global(&name, val_llty);
515
516            llvm::set_linkage(new_g, linkage);
517            llvm::set_visibility(new_g, visibility);
518
519            // The old global has had its name removed but is returned by
520            // get_static since it is in the instance cache. Provide an
521            // alternative lookup that points to the new global so that
522            // global_asm! can compute the correct mangled symbol name
523            // for the global.
524            self.renamed_statics.borrow_mut().insert(def_id, new_g);
525
526            // To avoid breaking any invariants, we leave around the old
527            // global for the moment; we'll replace all references to it
528            // with the new global later. (See base::codegen_backend.)
529            self.statics_to_rauw.borrow_mut().push((g, new_g));
530            new_g
531        };
532
533        // NOTE: Alignment from attributes has already been applied to the allocation.
534        set_global_alignment(self, g, alloc.align);
535        llvm::set_initializer(g, v);
536
537        self.assume_dso_local(g, true);
538
539        // Forward the allocation's mutability (picked by the const interner) to LLVM.
540        if alloc.mutability.is_not() {
541            llvm::set_global_constant(g, true);
542        }
543
544        debuginfo::build_global_var_di_node(self, def_id, g);
545
546        if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
547            llvm::set_thread_local_mode(g, self.tls_model);
548        }
549
550        // Wasm statics with custom link sections get special treatment as they
551        // go into custom sections of the wasm executable. The exception to this
552        // is the `.init_array` section which are treated specially by the wasm linker.
553        if self.tcx.sess.target.is_like_wasm
554            && attrs
555                .link_section
556                .map(|link_section| !link_section.as_str().starts_with(".init_array"))
557                .unwrap_or(true)
558        {
559            if let Some(section) = attrs.link_section {
560                let section = self.create_metadata(section.as_str().as_bytes());
561                if !alloc.provenance().ptrs().is_empty() {
    ::core::panicking::panic("assertion failed: alloc.provenance().ptrs().is_empty()")
};assert!(alloc.provenance().ptrs().is_empty());
562
563                // The `inspect` method is okay here because we checked for provenance, and
564                // because we are doing this access to inspect the final interpreter state (not
565                // as part of the interpreter execution).
566                let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
567                let alloc = self.create_metadata(bytes);
568                let data = [section, alloc];
569                self.module_add_named_metadata_node(self.llmod(), c"wasm.custom_sections", &data);
570            }
571        } else {
572            base::set_link_section(g, attrs);
573        }
574
575        base::set_variable_sanitizer_attrs(g, attrs);
576
577        if attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
578            // `USED` and `USED_LINKER` can't be used together.
579            if !!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
    ::core::panicking::panic("assertion failed: !attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)")
};assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER));
580
581            // The semantics of #[used] in Rust only require the symbol to make it into the
582            // object file. It is explicitly allowed for the linker to strip the symbol if it
583            // is dead, which means we are allowed to use `llvm.compiler.used` instead of
584            // `llvm.used` here.
585            //
586            // Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
587            // sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
588            // in the handling of `.init_array` (the static constructor list) in versions of
589            // the gold linker (prior to the one released with binutils 2.36).
590            //
591            // That said, we only ever emit these when `#[used(compiler)]` is explicitly
592            // requested. This is to avoid similar breakage on other targets, in particular
593            // MachO targets have *their* static constructor lists broken if `llvm.compiler.used`
594            // is emitted rather than `llvm.used`. However, that check happens when assigning
595            // the `CodegenFnAttrFlags` in the `codegen_fn_attrs` query, so we don't need to
596            // take care of it here.
597            self.add_compiler_used_global(g);
598        }
599        if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
600            // `USED` and `USED_LINKER` can't be used together.
601            if !!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
    ::core::panicking::panic("assertion failed: !attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)")
};assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER));
602
603            self.add_used_global(g);
604        }
605    }
606
607    /// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr.
608    pub(crate) fn add_used_global(&mut self, global: &'ll Value) {
609        self.used_statics.push(global);
610    }
611
612    /// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
613    /// an array of ptr.
614    pub(crate) fn add_compiler_used_global(&self, global: &'ll Value) {
615        self.compiler_used_statics.borrow_mut().push(global);
616    }
617
618    // We do our best here to match what Clang does when compiling Objective-C natively.
619    // See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
620    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
621    fn define_objc_classname(&self, classname: &str) -> &'ll Value {
622        {
    match (&self.objc_abi_version(), &1) {
        (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.objc_abi_version(), 1);
623
624        let llval = self.null_terminate_const_bytes(classname.as_bytes());
625        let llty = self.val_ty(llval);
626        let sym = self.generate_local_symbol_name("OBJC_CLASS_NAME_");
627        let g = self.define_global(&sym, llty).unwrap_or_else(|| {
628            ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
629        });
630        set_global_alignment(self, g, self.tcx.data_layout.i8_align);
631        llvm::set_initializer(g, llval);
632        llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
633        llvm::set_section(g, c"__TEXT,__cstring,cstring_literals");
634        llvm::LLVMSetGlobalConstant(g, llvm::TRUE);
635        llvm::LLVMSetUnnamedAddress(g, llvm::UnnamedAddr::Global);
636        self.add_compiler_used_global(g);
637
638        g
639    }
640
641    // We do our best here to match what Clang does when compiling Objective-C natively.
642    // See Clang's `ObjCNonFragileABITypesHelper`:
643    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L6052
644    fn get_objc_class_t(&self) -> &'ll Type {
645        if let Some(class_t) = self.objc_class_t.get() {
646            return class_t;
647        }
648
649        {
    match (&self.objc_abi_version(), &2) {
        (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.objc_abi_version(), 2);
650
651        // struct _class_t {
652        //     struct _class_t* isa;
653        //     struct _class_t* const superclass;
654        //     void* cache;
655        //     IMP* vtable;
656        //     struct class_ro_t* ro;
657        // }
658
659        let class_t = self.type_named_struct("struct._class_t");
660        let els = [self.type_ptr(); 5];
661        let packed = false;
662        self.set_struct_body(class_t, &els, packed);
663
664        self.objc_class_t.set(Some(class_t));
665        class_t
666    }
667
668    // We do our best here to match what Clang does when compiling Objective-C natively. We
669    // deduplicate references within a CGU, but we need a reference definition in each referencing
670    // CGU. All attempts at using external references to a single reference definition result in
671    // linker errors.
672    fn get_objc_classref(&self, classname: Symbol) -> &'ll Value {
673        let mut classrefs = self.objc_classrefs.borrow_mut();
674        if let Some(classref) = classrefs.get(&classname).copied() {
675            return classref;
676        }
677
678        let g = match self.objc_abi_version() {
679            1 => {
680                // See Clang's `CGObjCMac::EmitClassRefFromId`:
681                // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5205
682                let llval = self.define_objc_classname(classname.as_str());
683                let llty = self.type_ptr();
684                let sym = self.generate_local_symbol_name("OBJC_CLASS_REFERENCES_");
685                let g = self.define_global(&sym, llty).unwrap_or_else(|| {
686                    ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
687                });
688                set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
689                llvm::set_initializer(g, llval);
690                llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
691                llvm::set_section(g, c"__OBJC,__cls_refs,literal_pointers,no_dead_strip");
692                self.add_compiler_used_global(g);
693                g
694            }
695            2 => {
696                // See Clang's `CGObjCNonFragileABIMac::EmitClassRefFromId`:
697                // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7423
698                let llval = {
699                    let extern_sym = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("OBJC_CLASS_$_{0}",
                classname.as_str()))
    })format!("OBJC_CLASS_$_{}", classname.as_str());
700                    let extern_llty = self.get_objc_class_t();
701                    self.declare_global(&extern_sym, extern_llty)
702                };
703                let llty = self.type_ptr();
704                let sym = self.generate_local_symbol_name("OBJC_CLASSLIST_REFERENCES_$_");
705                let g = self.define_global(&sym, llty).unwrap_or_else(|| {
706                    ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
707                });
708                set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
709                llvm::set_initializer(g, llval);
710                llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
711                llvm::set_section(g, c"__DATA,__objc_classrefs,regular,no_dead_strip");
712                self.add_compiler_used_global(g);
713                g
714            }
715            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
716        };
717
718        classrefs.insert(classname, g);
719        g
720    }
721
722    // We do our best here to match what Clang does when compiling Objective-C natively. We
723    // deduplicate references within a CGU, but we need a reference definition in each referencing
724    // CGU. All attempts at using external references to a single reference definition result in
725    // linker errors.
726    //
727    // Newer versions of Apple Clang generate calls to `@"objc_msgSend$methname"` selector stub
728    // functions. We don't currently do that. The code we generate is closer to what Apple Clang
729    // generates with the `-fno-objc-msgsend-selector-stubs` option.
730    fn get_objc_selref(&self, methname: Symbol) -> &'ll Value {
731        let mut selrefs = self.objc_selrefs.borrow_mut();
732        if let Some(selref) = selrefs.get(&methname).copied() {
733            return selref;
734        }
735
736        let abi_version = self.objc_abi_version();
737
738        // See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
739        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
740        let methname_llval = self.null_terminate_const_bytes(methname.as_str().as_bytes());
741        let methname_llty = self.val_ty(methname_llval);
742        let methname_sym = self.generate_local_symbol_name("OBJC_METH_VAR_NAME_");
743        let methname_g = self.define_global(&methname_sym, methname_llty).unwrap_or_else(|| {
744            ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        methname_sym));bug!("symbol `{}` is already defined", methname_sym);
745        });
746        set_global_alignment(self, methname_g, self.tcx.data_layout.i8_align);
747        llvm::set_initializer(methname_g, methname_llval);
748        llvm::set_linkage(methname_g, llvm::Linkage::PrivateLinkage);
749        llvm::set_section(
750            methname_g,
751            match abi_version {
752                1 => c"__TEXT,__cstring,cstring_literals",
753                2 => c"__TEXT,__objc_methname,cstring_literals",
754                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
755            },
756        );
757        llvm::LLVMSetGlobalConstant(methname_g, llvm::TRUE);
758        llvm::LLVMSetUnnamedAddress(methname_g, llvm::UnnamedAddr::Global);
759        self.add_compiler_used_global(methname_g);
760
761        // See Clang's `CGObjCMac::EmitSelectorAddr`:
762        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5243
763        // And Clang's `CGObjCNonFragileABIMac::EmitSelectorAddr`:
764        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7586
765        let selref_llval = methname_g;
766        let selref_llty = self.type_ptr();
767        let selref_sym = self.generate_local_symbol_name("OBJC_SELECTOR_REFERENCES_");
768        let selref_g = self.define_global(&selref_sym, selref_llty).unwrap_or_else(|| {
769            ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        selref_sym));bug!("symbol `{}` is already defined", selref_sym);
770        });
771        set_global_alignment(self, selref_g, self.tcx.data_layout.pointer_align().abi);
772        llvm::set_initializer(selref_g, selref_llval);
773        llvm::set_externally_initialized(selref_g, true);
774        llvm::set_linkage(
775            selref_g,
776            match abi_version {
777                1 => llvm::Linkage::PrivateLinkage,
778                2 => llvm::Linkage::InternalLinkage,
779                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
780            },
781        );
782        llvm::set_section(
783            selref_g,
784            match abi_version {
785                1 => c"__OBJC,__message_refs,literal_pointers,no_dead_strip",
786                2 => c"__DATA,__objc_selrefs,literal_pointers,no_dead_strip",
787                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
788            },
789        );
790        self.add_compiler_used_global(selref_g);
791
792        selrefs.insert(methname, selref_g);
793        selref_g
794    }
795
796    // We do our best here to match what Clang does when compiling Objective-C natively.
797    // See Clang's `ObjCTypesHelper`:
798    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5936
799    // And Clang's `CGObjCMac::EmitModuleInfo`:
800    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5151
801    pub(crate) fn define_objc_module_info(&mut self) {
802        {
    match (&self.objc_abi_version(), &1) {
        (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.objc_abi_version(), 1);
803
804        // struct _objc_module {
805        //     long version;                // Hardcoded to 7 in Clang.
806        //     long size;                   // sizeof(struct _objc_module)
807        //     char* name;                  // Hardcoded to classname "" in Clang.
808        //     struct _objc_symtab* symtab; // Null without class or category definitions.
809        //  }
810
811        let llty = self.type_named_struct("struct._objc_module");
812        let i32_llty = self.type_i32();
813        let ptr_llty = self.type_ptr();
814        let packed = false;
815        self.set_struct_body(llty, &[i32_llty, i32_llty, ptr_llty, ptr_llty], packed);
816
817        let version = self.const_uint(i32_llty, 7);
818        let size = self.const_uint(i32_llty, 16);
819        let name = self.define_objc_classname("");
820        let symtab = self.const_null(ptr_llty);
821        let llval = crate::common::named_struct(llty, &[version, size, name, symtab]);
822
823        let sym = "OBJC_MODULES";
824        let g = self.define_global(&sym, llty).unwrap_or_else(|| {
825            ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
826        });
827        set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
828        llvm::set_initializer(g, llval);
829        llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
830        llvm::set_section(g, c"__OBJC,__module_info,regular,no_dead_strip");
831
832        self.add_compiler_used_global(g);
833    }
834}
835
836impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> {
837    /// Get a pointer to a global variable.
838    ///
839    /// The pointer will always be in the default address space. If global variables default to a
840    /// different address space, an addrspacecast is inserted.
841    fn static_addr_of(&self, alloc: ConstAllocation<'_>, kind: Option<&str>) -> &'ll Value {
842        // FIXME: should we cache `const_alloc_to_llvm` to avoid repeating this for the
843        // same `ConstAllocation`?
844        let cv = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No);
845
846        let gv = self.static_addr_of_impl(cv, alloc.inner().align, kind);
847        // static_addr_of_impl returns the bare global variable, which might not be in the default
848        // address space. Cast to the default address space if necessary.
849        self.const_pointercast(gv, self.type_ptr())
850    }
851
852    fn codegen_static(&mut self, def_id: DefId) {
853        self.codegen_static_item(def_id)
854    }
855}