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;
21use tracing::{debug, instrument, trace};
22
23use crate::common::CodegenCx;
24use crate::diagnostics::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`.
35#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for IsInitOrFini {
    #[inline]
    fn eq(&self, other: &IsInitOrFini) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
36pub(crate) enum IsInitOrFini {
37    Yes,
38    No,
39}
40pub(crate) fn const_alloc_to_llvm<'ll>(
41    cx: &CodegenCx<'ll, '_>,
42    alloc: &Allocation,
43    is_static: IsStatic,
44    is_init_fini: IsInitOrFini,
45) -> &'ll Value {
46    // We expect that callers of const_alloc_to_llvm will instead directly codegen a pointer or
47    // integer for any &ZST where the ZST is a constant (i.e. not a static). We should never be
48    // producing empty LLVM allocations as they're just adding noise to binaries and forcing less
49    // optimal codegen.
50    //
51    // Statics have a guaranteed meaningful address so it's less clear that we want to do
52    // something like this; it's also harder.
53    if #[allow(non_exhaustive_omitted_patterns)] match is_static {
    IsStatic::No => true,
    _ => false,
}matches!(is_static, IsStatic::No) {
54        if !(alloc.len() != 0) {
    ::core::panicking::panic("assertion failed: alloc.len() != 0")
};assert!(alloc.len() != 0);
55    }
56    let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
57    let dl = cx.data_layout();
58    let pointer_size = dl.pointer_size();
59    let pointer_size_bytes = pointer_size.bytes() as usize;
60
61    // Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`, so `range`
62    // must be within the bounds of `alloc` and not contain or overlap a pointer provenance.
63    fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
64        llvals: &mut Vec<&'ll Value>,
65        cx: &'a CodegenCx<'ll, 'b>,
66        alloc: &'a Allocation,
67        range: Range<usize>,
68    ) {
69        let chunks = alloc.init_mask().range_as_init_chunks(range.clone().into());
70
71        let chunk_to_llval = move |chunk| match chunk {
72            InitChunk::Init(range) => {
73                let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
74                let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
75                cx.const_bytes(bytes)
76            }
77            InitChunk::Uninit(range) => {
78                let len = range.end.bytes() - range.start.bytes();
79                cx.const_undef(cx.type_array(cx.type_i8(), len))
80            }
81        };
82
83        // Generating partially-uninit consts is limited to small numbers of chunks,
84        // to avoid the cost of generating large complex const expressions.
85        // For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element, and
86        // would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
87        let max = cx.sess().opts.unstable_opts.uninit_const_chunk_threshold;
88        let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
89
90        if allow_uninit_chunks {
91            llvals.extend(chunks.map(chunk_to_llval));
92        } else {
93            // If this allocation contains any uninit bytes, codegen as if it was initialized
94            // (using some arbitrary value for uninit bytes).
95            let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
96            llvals.push(cx.const_bytes(bytes));
97        }
98    }
99
100    let mut next_offset = 0;
101    for &(offset, prov) in alloc.provenance().ptrs().iter() {
102        let offset = offset.bytes();
103        {
    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);
104        let offset = offset as usize;
105        if offset > next_offset {
106            // This `inspect` is okay since we have checked that there is no provenance, it
107            // is within the bounds of the allocation, and it doesn't affect interpreter execution
108            // (we inspect the result after interpreter execution).
109            append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
110        }
111        let ptr_offset = read_target_uint(
112            dl.endian,
113            // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
114            // affect interpreter execution (we inspect the result after interpreter execution),
115            // and we properly interpret the provenance as a relocation pointer offset.
116            alloc.inspect_with_uninit_and_ptr_outside_interpreter(
117                offset..(offset + pointer_size_bytes),
118            ),
119        )
120        .expect("const_alloc_to_llvm: could not read relocation pointer")
121            as u64;
122
123        let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx);
124        let schema = if cx.sess().pointer_authentication() {
125            match is_init_fini {
126                IsInitOrFini::Yes => cx.sess().pointer_authentication_init_fini(),
127                IsInitOrFini::No => cx.sess().pointer_authentication_functions(),
128            }
129        } else {
130            None
131        };
132        llvals.push(cx.scalar_to_backend_with_pac(
133            InterpScalar::from_pointer(Pointer::new(prov, Size::from_bytes(ptr_offset)), &cx.tcx),
134            Scalar::Initialized {
135                value: Primitive::Pointer(address_space),
136                valid_range: WrappingRange::full(pointer_size),
137            },
138            cx.type_ptr_ext(address_space),
139            schema,
140        ));
141        next_offset = offset + pointer_size_bytes;
142    }
143    if alloc.len() >= next_offset {
144        let range = next_offset..alloc.len();
145        // This `inspect` is okay since we have check that it is after all provenance, it is
146        // within the bounds of the allocation, and it doesn't affect interpreter execution (we
147        // inspect the result after interpreter execution).
148        append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
149    }
150
151    // Avoid wrapping in a struct if there is only a single value. This ensures
152    // that LLVM is able to perform the string merging optimization if the constant
153    // is a valid C string. LLVM only considers bare arrays for this optimization,
154    // not arrays wrapped in a struct. LLVM handles this at:
155    // https://github.com/rust-lang/llvm-project/blob/acaea3d2bb8f351b740db7ebce7d7a40b9e21488/llvm/lib/Target/TargetLoweringObjectFile.cpp#L249-L280
156    if let &[data] = &*llvals { data } else { cx.const_struct(&llvals, true) }
157}
158
159fn codegen_static_initializer<'ll, 'tcx>(
160    cx: &CodegenCx<'ll, 'tcx>,
161    def_id: DefId,
162) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> {
163    let alloc = cx.tcx.eval_static_initializer(def_id)?;
164    let attrs = cx.tcx.codegen_fn_attrs(def_id);
165    // FIXME(jchlanda) Decide if this could be better served by `ctor` crate. See the discussion
166    // here: <https://github.com/rust-lang/rust/pull/155722#discussion_r3320477047>
167    let is_in_init_fini: IsInitOrFini = attrs
168        .link_section
169        .map(|link_section| {
170            let s = link_section.as_str();
171            if s.starts_with(".init_array") || s.starts_with(".fini_array") {
172                IsInitOrFini::Yes
173            } else {
174                IsInitOrFini::No
175            }
176        })
177        .unwrap_or(IsInitOrFini::No);
178    Ok((const_alloc_to_llvm(cx, alloc.inner(), IsStatic::Yes, is_in_init_fini), alloc))
179}
180
181fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
182    // The target may require greater alignment for globals than the type does.
183    // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
184    // which can force it to be smaller. Rust doesn't support this yet.
185    if let Some(min_global) = cx.sess().target.min_global_align {
186        align = Ord::max(align, min_global);
187    }
188    llvm::set_alignment(gv, align);
189}
190
191fn check_and_apply_linkage<'ll, 'tcx>(
192    cx: &CodegenCx<'ll, 'tcx>,
193    attrs: &CodegenFnAttrs,
194    llty: &'ll Type,
195    sym: &str,
196    def_id: DefId,
197) -> &'ll Value {
198    if let Some(linkage) = attrs.import_linkage {
199        {
    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:199",
                        "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(199u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_static: sym={0} linkage={1:?}",
                                                    sym, linkage) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("get_static: sym={} linkage={:?}", sym, linkage);
200
201        let mut should_sign = false;
202        // Declare a symbol `foo`. If `foo` is an extern_weak symbol, we declare
203        // an extern_weak function, otherwise a global with the desired linkage.
204        let g1 = if #[allow(non_exhaustive_omitted_patterns)] match attrs.import_linkage {
    Some(Linkage::ExternalWeak) => true,
    _ => false,
}matches!(attrs.import_linkage, Some(Linkage::ExternalWeak)) {
205            // An `extern_weak` function is represented as an `Option<unsafe extern ...>`,
206            // we extract the function signature and declare it as an extern_weak function
207            // instead of an extern_weak i8.
208            let instance = Instance::mono(cx.tcx, def_id);
209            if let ty::Adt(struct_def, args) = instance.ty(cx.tcx, cx.typing_env()).kind()
210                && cx.tcx.is_lang_item(struct_def.did(), LangItem::Option)
211                && let ty::FnPtr(sig, header) = args.type_at(0).kind()
212            {
213                let fn_sig = sig.with(*header);
214                let fn_abi = cx.fn_abi_of_fn_ptr(fn_sig, ty::List::empty());
215                // Decide if the initializer needs to be signed
216                if cx.sess().pointer_authentication()
217                    && #[allow(non_exhaustive_omitted_patterns)] match fn_sig.abi() {
    ExternAbi::C { .. } | ExternAbi::System { .. } => true,
    _ => false,
}matches!(fn_sig.abi(), ExternAbi::C { .. } | ExternAbi::System { .. })
218                {
219                    should_sign = true;
220                }
221                cx.declare_fn(sym, &fn_abi, None)
222            } else {
223                cx.declare_global(sym, cx.type_i8())
224            }
225        } else {
226            cx.declare_global(sym, cx.type_i8())
227        };
228        llvm::set_linkage(g1, base::linkage_to_llvm(linkage));
229
230        // Normally this is done in `get_static_inner`, but when as we generate an internal global,
231        // it will apply the dso_local to the internal global instead, so do it here, too.
232        cx.assume_dso_local(g1, true);
233
234        // Declare an internal global `extern_with_linkage_foo` which
235        // is initialized with the address of `foo`. If `foo` is
236        // discarded during linking (for example, if `foo` has weak
237        // linkage and there are no definitions), then
238        // `extern_with_linkage_foo` will instead be initialized to
239        // zero.
240        let real_name =
241            ::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));
242        let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
243            cx.sess().dcx().emit_fatal(SymbolAlreadyDefined {
244                span: cx.tcx.def_span(def_id),
245                symbol_name: sym,
246            })
247        });
248        llvm::set_linkage(g2, llvm::Linkage::InternalLinkage);
249        llvm::set_unnamed_address(g2, llvm::UnnamedAddr::Global);
250
251        // Sign the function pointer that is used to initialize the global
252        let initializer = if should_sign {
253            let key: u32 = 0;
254            let discriminator: u64 = 0;
255
256            const_ptr_auth(
257                cx.const_bitcast(g1, llty),
258                key,
259                discriminator,
260                None, /* address_diversity */
261            )
262        } else {
263            g1
264        };
265
266        llvm::set_initializer(g2, initializer);
267
268        g2
269    } else if cx.tcx.sess.target.arch == Arch::X86
270        && common::is_mingw_gnu_toolchain(&cx.tcx.sess.target)
271        && let Some(dllimport) = crate::common::get_dllimport(cx.tcx, def_id, sym)
272    {
273        cx.declare_global(&common::i686_decorated_name(dllimport, true, true, false), llty)
274    } else {
275        // Generate an external declaration.
276        // FIXME(nagisa): investigate whether it can be changed into define_global
277        cx.declare_global(sym, llty)
278    }
279}
280
281impl<'ll> CodegenCx<'ll, '_> {
282    pub(crate) fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
283        unsafe { llvm::LLVMConstBitCast(val, ty) }
284    }
285
286    pub(crate) fn const_pointercast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
287        unsafe { llvm::LLVMConstPointerCast(val, ty) }
288    }
289
290    /// Create a global variable.
291    ///
292    /// The returned global variable is a pointer in the default address space for globals.
293    /// Fails if a symbol with the given name already exists.
294    pub(crate) fn static_addr_of_mut(
295        &self,
296        cv: &'ll Value,
297        align: Align,
298        kind: Option<&str>,
299    ) -> &'ll Value {
300        let gv = match kind {
301            Some(kind) if !self.tcx.sess.fewer_names() => {
302                let name = self.generate_local_symbol_name(kind);
303                let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| {
304                    ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        name));bug!("symbol `{}` is already defined", name);
305                });
306                gv
307            }
308            _ => self.define_global("", self.val_ty(cv)).unwrap_or_else(|| {
309                ::rustc_middle::util::bug::bug_fmt(format_args!("anonymous global symbol is already defined"));bug!("anonymous global symbol is already defined");
310            }),
311        };
312        llvm::set_linkage(gv, llvm::Linkage::PrivateLinkage);
313        llvm::set_initializer(gv, cv);
314        set_global_alignment(self, gv, align);
315        llvm::set_unnamed_address(gv, llvm::UnnamedAddr::Global);
316        gv
317    }
318
319    /// Create a global constant.
320    ///
321    /// The returned global variable is a pointer in the default address space for globals.
322    pub(crate) fn static_addr_of_impl(
323        &self,
324        cv: &'ll Value,
325        align: Align,
326        kind: Option<&str>,
327    ) -> &'ll Value {
328        if let Some(&gv) = self.const_globals.borrow().get(&cv) {
329            unsafe {
330                // Upgrade the alignment in cases where the same constant is used with different
331                // alignment requirements
332                let llalign = align.bytes() as u32;
333                if llalign > llvm::LLVMGetAlignment(gv) {
334                    llvm::LLVMSetAlignment(gv, llalign);
335                }
336            }
337            return gv;
338        }
339        let gv = self.static_addr_of_mut(cv, align, kind);
340        llvm::set_global_constant(gv, true);
341
342        self.const_globals.borrow_mut().insert(cv, gv);
343        gv
344    }
345
346    #[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(346u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        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(&def_id)
                                                            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: &'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:349",
                                    "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(349u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                        as &dyn ::tracing::field::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:358",
                                            "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(358u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("ty")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("ty");
                                                                NAME.as_str()
                                                            }], ::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};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    self.layout_of(ty).llvm_type(self)
                };
            self.get_static_inner(def_id, llty)
        }
    }
}#[instrument(level = "debug", skip(self))]
347    pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
348        let instance = Instance::mono(self.tcx, def_id);
349        trace!(?instance);
350
351        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
352        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
353        // out the llvm type from the actual evaluated initializer.
354        let llty = if nested {
355            self.type_i8()
356        } else {
357            let ty = instance.ty(self.tcx, self.typing_env());
358            trace!(?ty);
359            self.layout_of(ty).llvm_type(self)
360        };
361        self.get_static_inner(def_id, llty)
362    }
363
364    #[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(364u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        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(&def_id)
                                                            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: &'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:368",
                                        "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(368u32),
                                        ::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};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("used cached value")
                                                            as &dyn ::tracing::field::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:383",
                                    "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(383u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sym")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sym");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_attrs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_attrs");
                                                        NAME.as_str()
                                                    }], ::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(&::tracing::field::debug(&sym)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_attrs)
                                                        as &dyn ::tracing::field::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 is_eii =
                    fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
                let needs_dll_storage_attr =
                    self.use_dll_storage_attrs &&
                                (!self.tcx.is_foreign_item(def_id) || is_eii) && !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))]
365    fn get_static_inner(&self, def_id: DefId, llty: &'ll Type) -> &'ll Value {
366        let instance = Instance::mono(self.tcx, def_id);
367        if let Some(&g) = self.instances.borrow().get(&instance) {
368            trace!("used cached value");
369            return g;
370        }
371
372        let defined_in_current_codegen_unit =
373            self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
374        assert!(
375            !defined_in_current_codegen_unit,
376            "consts::get_static() should always hit the cache for \
377                 statics defined in the same CGU, but did not for `{def_id:?}`"
378        );
379
380        let sym = self.tcx.symbol_name(instance).name;
381        let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
382
383        debug!(?sym, ?fn_attrs);
384
385        let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
386            if let Some(g) = self.get_declared_value(sym) {
387                if self.val_ty(g) != self.type_ptr() {
388                    span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
389                }
390            }
391
392            let g = self.declare_global(sym, llty);
393
394            if !self.tcx.is_reachable_non_generic(def_id) {
395                llvm::set_visibility(g, llvm::Visibility::Hidden);
396            }
397
398            g
399        } else if let Some(classname) = fn_attrs.objc_class {
400            self.get_objc_classref(classname)
401        } else if let Some(methname) = fn_attrs.objc_selector {
402            self.get_objc_selref(methname)
403        } else {
404            check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
405        };
406
407        // Thread-local statics in some other crate need to *always* be linked
408        // against in a thread-local fashion, so we need to be sure to apply the
409        // thread-local attribute locally if it was present remotely. If we
410        // don't do this then linker errors can be generated where the linker
411        // complains that one object files has a thread local version of the
412        // symbol and another one doesn't.
413        if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
414            llvm::set_thread_local_mode(g, self.tls_model);
415        }
416
417        let dso_local = self.assume_dso_local(g, true);
418
419        if !def_id.is_local() {
420            let is_eii = fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
421            let needs_dll_storage_attr = self.use_dll_storage_attrs
422                // EII static declarations are encoded as foreign items, but their symbols are
423                // resolved by Rust crates, not native libraries.
424                && (!self.tcx.is_foreign_item(def_id) || is_eii)
425                // Local definitions can never be imported, so we must not apply
426                // the DLLImport annotation.
427                && !dso_local
428                // Linker plugin ThinLTO doesn't create the self-dllimport Rust uses for rlibs
429                // as the code generation happens out of process. Instead we assume static linkage
430                // and disallow dynamic linking when linker plugin based LTO is enabled.
431                // Regular in-process ThinLTO doesn't need this workaround.
432                && !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
433
434            // If this assertion triggers, there's something wrong with commandline
435            // argument validation.
436            assert!(
437                !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
438                    && self.tcx.sess.target.is_like_windows
439                    && self.tcx.sess.opts.cg.prefer_dynamic)
440            );
441
442            if needs_dll_storage_attr {
443                // This item is external but not foreign, i.e., it originates from an external Rust
444                // crate. EII static declarations are handled the same way, even though they are
445                // represented as foreign items. Since we don't know whether this crate will be
446                // linked dynamically or statically in the final application, we always mark such
447                // symbols as 'dllimport'. If final linkage happens to be static, we rely on
448                // compiler-emitted __imp_ stubs to make things work.
449                //
450                // However, in some scenarios we defer emission of statics to downstream
451                // crates, so there are cases where a static with an upstream DefId
452                // is actually present in the current crate. We can find out via the
453                // is_codegened_item query.
454                if !self.tcx.is_codegened_item(def_id) {
455                    llvm::set_dllimport_storage_class(g);
456                }
457            }
458        }
459
460        if self.use_dll_storage_attrs
461            && let Some(library) = self.tcx.native_library(def_id)
462            && library.kind.is_dllimport()
463        {
464            // For foreign (native) libs we know the exact storage type to use.
465            llvm::set_dllimport_storage_class(g);
466        }
467
468        self.instances.borrow_mut().insert(instance, g);
469        g
470    }
471
472    fn codegen_static_item(&mut self, def_id: DefId) {
473        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!(
474            llvm::LLVMGetInitializer(
475                self.instances.borrow().get(&Instance::mono(self.tcx, def_id)).unwrap()
476            )
477            .is_none()
478        );
479        let attrs = self.tcx.codegen_fn_attrs(def_id);
480
481        let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
482            // Error has already been reported
483            return;
484        };
485        let alloc = alloc.inner();
486
487        let val_llty = self.val_ty(v);
488
489        let g = self.get_static_inner(def_id, val_llty);
490        let llty = self.get_type_of_global(g);
491
492        let g = if val_llty == llty {
493            g
494        } else {
495            // codegen_static_initializer creates the global value just from the
496            // `Allocation` data by generating one big struct value that is just
497            // all the bytes and pointers after each other. This will almost never
498            // match the type that the static was declared with. Unfortunately
499            // we can't just LLVMConstBitCast our way out of it because that has very
500            // specific rules on what can be cast. So instead of adding a new way to
501            // generate static initializers that match the static's type, we picked
502            // the easier option and retroactively change the type of the static item itself.
503            let name = String::from_utf8(llvm::get_value_name(g))
504                .expect("we declare our statics with a utf8-valid name");
505            llvm::set_value_name(g, b"");
506
507            let linkage = llvm::get_linkage(g);
508            let visibility = llvm::get_visibility(g);
509
510            let new_g = self.declare_global(&name, val_llty);
511
512            llvm::set_linkage(new_g, linkage);
513            llvm::set_visibility(new_g, visibility);
514
515            // The old global has had its name removed but is returned by
516            // get_static since it is in the instance cache. Provide an
517            // alternative lookup that points to the new global so that
518            // global_asm! can compute the correct mangled symbol name
519            // for the global.
520            self.renamed_statics.borrow_mut().insert(def_id, new_g);
521
522            // To avoid breaking any invariants, we leave around the old
523            // global for the moment; we'll replace all references to it
524            // with the new global later. (See base::codegen_backend.)
525            self.statics_to_rauw.borrow_mut().push((g, new_g));
526            new_g
527        };
528
529        // NOTE: Alignment from attributes has already been applied to the allocation.
530        set_global_alignment(self, g, alloc.align);
531        llvm::set_initializer(g, v);
532
533        self.assume_dso_local(g, true);
534
535        // Forward the allocation's mutability (picked by the const interner) to LLVM.
536        if alloc.mutability.is_not() {
537            llvm::set_global_constant(g, true);
538        }
539
540        debuginfo::build_global_var_di_node(self, def_id, g);
541
542        if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
543            llvm::set_thread_local_mode(g, self.tls_model);
544        }
545
546        // Wasm statics with custom link sections get special treatment as they
547        // go into custom sections of the wasm executable. The exception to this
548        // is the `.init_array` section which are treated specially by the wasm linker.
549        if self.tcx.sess.target.is_like_wasm
550            && attrs
551                .link_section
552                .map(|link_section| !link_section.as_str().starts_with(".init_array"))
553                .unwrap_or(true)
554        {
555            if let Some(section) = attrs.link_section {
556                let section = self.create_metadata(section.as_str().as_bytes());
557                if !alloc.provenance().ptrs().is_empty() {
    ::core::panicking::panic("assertion failed: alloc.provenance().ptrs().is_empty()")
};assert!(alloc.provenance().ptrs().is_empty());
558
559                // The `inspect` method is okay here because we checked for provenance, and
560                // because we are doing this access to inspect the final interpreter state (not
561                // as part of the interpreter execution).
562                let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
563                let alloc = self.create_metadata(bytes);
564                let data = [section, alloc];
565                self.module_add_named_metadata_node(self.llmod(), c"wasm.custom_sections", &data);
566            }
567        } else {
568            base::set_link_section(g, attrs);
569        }
570
571        base::set_variable_sanitizer_attrs(g, attrs);
572
573        if attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
574            // `USED` and `USED_LINKER` can't be used together.
575            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));
576
577            // The semantics of #[used] in Rust only require the symbol to make it into the
578            // object file. It is explicitly allowed for the linker to strip the symbol if it
579            // is dead, which means we are allowed to use `llvm.compiler.used` instead of
580            // `llvm.used` here.
581            //
582            // Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
583            // sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
584            // in the handling of `.init_array` (the static constructor list) in versions of
585            // the gold linker (prior to the one released with binutils 2.36).
586            //
587            // That said, we only ever emit these when `#[used(compiler)]` is explicitly
588            // requested. This is to avoid similar breakage on other targets, in particular
589            // MachO targets have *their* static constructor lists broken if `llvm.compiler.used`
590            // is emitted rather than `llvm.used`. However, that check happens when assigning
591            // the `CodegenFnAttrFlags` in the `codegen_fn_attrs` query, so we don't need to
592            // take care of it here.
593            self.add_compiler_used_global(g);
594        }
595        if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
596            // `USED` and `USED_LINKER` can't be used together.
597            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));
598
599            self.add_used_global(g);
600        }
601    }
602
603    /// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr.
604    pub(crate) fn add_used_global(&mut self, global: &'ll Value) {
605        self.used_statics.push(global);
606    }
607
608    /// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
609    /// an array of ptr.
610    pub(crate) fn add_compiler_used_global(&self, global: &'ll Value) {
611        self.compiler_used_statics.borrow_mut().push(global);
612    }
613
614    // We do our best here to match what Clang does when compiling Objective-C natively.
615    // See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
616    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
617    fn define_objc_classname(&self, classname: &str) -> &'ll Value {
618        {
    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);
619
620        let llval = self.null_terminate_const_bytes(classname.as_bytes());
621        let llty = self.val_ty(llval);
622        let sym = self.generate_local_symbol_name("OBJC_CLASS_NAME_");
623        let g = self.define_global(&sym, llty).unwrap_or_else(|| {
624            ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
625        });
626        set_global_alignment(self, g, self.tcx.data_layout.i8_align);
627        llvm::set_initializer(g, llval);
628        llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
629        llvm::set_section(g, c"__TEXT,__cstring,cstring_literals");
630        llvm::LLVMSetGlobalConstant(g, llvm::TRUE);
631        llvm::LLVMSetUnnamedAddress(g, llvm::UnnamedAddr::Global);
632        self.add_compiler_used_global(g);
633
634        g
635    }
636
637    // We do our best here to match what Clang does when compiling Objective-C natively.
638    // See Clang's `ObjCNonFragileABITypesHelper`:
639    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L6052
640    fn get_objc_class_t(&self) -> &'ll Type {
641        if let Some(class_t) = self.objc_class_t.get() {
642            return class_t;
643        }
644
645        {
    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);
646
647        // struct _class_t {
648        //     struct _class_t* isa;
649        //     struct _class_t* const superclass;
650        //     void* cache;
651        //     IMP* vtable;
652        //     struct class_ro_t* ro;
653        // }
654
655        let class_t = self.type_named_struct("struct._class_t");
656        let els = [self.type_ptr(); 5];
657        let packed = false;
658        self.set_struct_body(class_t, &els, packed);
659
660        self.objc_class_t.set(Some(class_t));
661        class_t
662    }
663
664    // We do our best here to match what Clang does when compiling Objective-C natively. We
665    // deduplicate references within a CGU, but we need a reference definition in each referencing
666    // CGU. All attempts at using external references to a single reference definition result in
667    // linker errors.
668    fn get_objc_classref(&self, classname: Symbol) -> &'ll Value {
669        let mut classrefs = self.objc_classrefs.borrow_mut();
670        if let Some(classref) = classrefs.get(&classname).copied() {
671            return classref;
672        }
673
674        let g = match self.objc_abi_version() {
675            1 => {
676                // See Clang's `CGObjCMac::EmitClassRefFromId`:
677                // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5205
678                let llval = self.define_objc_classname(classname.as_str());
679                let llty = self.type_ptr();
680                let sym = self.generate_local_symbol_name("OBJC_CLASS_REFERENCES_");
681                let g = self.define_global(&sym, llty).unwrap_or_else(|| {
682                    ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
683                });
684                set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
685                llvm::set_initializer(g, llval);
686                llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
687                llvm::set_section(g, c"__OBJC,__cls_refs,literal_pointers,no_dead_strip");
688                self.add_compiler_used_global(g);
689                g
690            }
691            2 => {
692                // See Clang's `CGObjCNonFragileABIMac::EmitClassRefFromId`:
693                // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7423
694                let llval = {
695                    let extern_sym = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("OBJC_CLASS_$_{0}",
                classname.as_str()))
    })format!("OBJC_CLASS_$_{}", classname.as_str());
696                    let extern_llty = self.get_objc_class_t();
697                    self.declare_global(&extern_sym, extern_llty)
698                };
699                let llty = self.type_ptr();
700                let sym = self.generate_local_symbol_name("OBJC_CLASSLIST_REFERENCES_$_");
701                let g = self.define_global(&sym, llty).unwrap_or_else(|| {
702                    ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
703                });
704                set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
705                llvm::set_initializer(g, llval);
706                llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
707                llvm::set_section(g, c"__DATA,__objc_classrefs,regular,no_dead_strip");
708                self.add_compiler_used_global(g);
709                g
710            }
711            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
712        };
713
714        classrefs.insert(classname, g);
715        g
716    }
717
718    // We do our best here to match what Clang does when compiling Objective-C natively. We
719    // deduplicate references within a CGU, but we need a reference definition in each referencing
720    // CGU. All attempts at using external references to a single reference definition result in
721    // linker errors.
722    //
723    // Newer versions of Apple Clang generate calls to `@"objc_msgSend$methname"` selector stub
724    // functions. We don't currently do that. The code we generate is closer to what Apple Clang
725    // generates with the `-fno-objc-msgsend-selector-stubs` option.
726    fn get_objc_selref(&self, methname: Symbol) -> &'ll Value {
727        let mut selrefs = self.objc_selrefs.borrow_mut();
728        if let Some(selref) = selrefs.get(&methname).copied() {
729            return selref;
730        }
731
732        let abi_version = self.objc_abi_version();
733
734        // See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
735        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
736        let methname_llval = self.null_terminate_const_bytes(methname.as_str().as_bytes());
737        let methname_llty = self.val_ty(methname_llval);
738        let methname_sym = self.generate_local_symbol_name("OBJC_METH_VAR_NAME_");
739        let methname_g = self.define_global(&methname_sym, methname_llty).unwrap_or_else(|| {
740            ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        methname_sym));bug!("symbol `{}` is already defined", methname_sym);
741        });
742        set_global_alignment(self, methname_g, self.tcx.data_layout.i8_align);
743        llvm::set_initializer(methname_g, methname_llval);
744        llvm::set_linkage(methname_g, llvm::Linkage::PrivateLinkage);
745        llvm::set_section(
746            methname_g,
747            match abi_version {
748                1 => c"__TEXT,__cstring,cstring_literals",
749                2 => c"__TEXT,__objc_methname,cstring_literals",
750                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
751            },
752        );
753        llvm::LLVMSetGlobalConstant(methname_g, llvm::TRUE);
754        llvm::LLVMSetUnnamedAddress(methname_g, llvm::UnnamedAddr::Global);
755        self.add_compiler_used_global(methname_g);
756
757        // See Clang's `CGObjCMac::EmitSelectorAddr`:
758        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5243
759        // And Clang's `CGObjCNonFragileABIMac::EmitSelectorAddr`:
760        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7586
761        let selref_llval = methname_g;
762        let selref_llty = self.type_ptr();
763        let selref_sym = self.generate_local_symbol_name("OBJC_SELECTOR_REFERENCES_");
764        let selref_g = self.define_global(&selref_sym, selref_llty).unwrap_or_else(|| {
765            ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        selref_sym));bug!("symbol `{}` is already defined", selref_sym);
766        });
767        set_global_alignment(self, selref_g, self.tcx.data_layout.pointer_align().abi);
768        llvm::set_initializer(selref_g, selref_llval);
769        llvm::set_externally_initialized(selref_g, true);
770        llvm::set_linkage(
771            selref_g,
772            match abi_version {
773                1 => llvm::Linkage::PrivateLinkage,
774                2 => llvm::Linkage::InternalLinkage,
775                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
776            },
777        );
778        llvm::set_section(
779            selref_g,
780            match abi_version {
781                1 => c"__OBJC,__message_refs,literal_pointers,no_dead_strip",
782                2 => c"__DATA,__objc_selrefs,literal_pointers,no_dead_strip",
783                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
784            },
785        );
786        self.add_compiler_used_global(selref_g);
787
788        selrefs.insert(methname, selref_g);
789        selref_g
790    }
791
792    // We do our best here to match what Clang does when compiling Objective-C natively.
793    // See Clang's `ObjCTypesHelper`:
794    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5936
795    // And Clang's `CGObjCMac::EmitModuleInfo`:
796    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5151
797    pub(crate) fn define_objc_module_info(&mut self) {
798        {
    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);
799
800        // struct _objc_module {
801        //     long version;                // Hardcoded to 7 in Clang.
802        //     long size;                   // sizeof(struct _objc_module)
803        //     char* name;                  // Hardcoded to classname "" in Clang.
804        //     struct _objc_symtab* symtab; // Null without class or category definitions.
805        //  }
806
807        let llty = self.type_named_struct("struct._objc_module");
808        let i32_llty = self.type_i32();
809        let ptr_llty = self.type_ptr();
810        let packed = false;
811        self.set_struct_body(llty, &[i32_llty, i32_llty, ptr_llty, ptr_llty], packed);
812
813        let version = self.const_uint(i32_llty, 7);
814        let size = self.const_uint(i32_llty, 16);
815        let name = self.define_objc_classname("");
816        let symtab = self.const_null(ptr_llty);
817        let llval = crate::common::named_struct(llty, &[version, size, name, symtab]);
818
819        let sym = "OBJC_MODULES";
820        let g = self.define_global(&sym, llty).unwrap_or_else(|| {
821            ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
822        });
823        set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
824        llvm::set_initializer(g, llval);
825        llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
826        llvm::set_section(g, c"__OBJC,__module_info,regular,no_dead_strip");
827
828        self.add_compiler_used_global(g);
829    }
830}
831
832impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> {
833    /// Get a pointer to a global variable.
834    ///
835    /// The pointer will always be in the default address space. If global variables default to a
836    /// different address space, an addrspacecast is inserted.
837    fn static_addr_of(&self, alloc: ConstAllocation<'_>, kind: Option<&str>) -> &'ll Value {
838        // FIXME: should we cache `const_alloc_to_llvm` to avoid repeating this for the
839        // same `ConstAllocation`?
840        let cv = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No);
841
842        let gv = self.static_addr_of_impl(cv, alloc.inner().align, kind);
843        // static_addr_of_impl returns the bare global variable, which might not be in the default
844        // address space. Cast to the default address space if necessary.
845        self.const_pointercast(gv, self.type_ptr())
846    }
847
848    fn codegen_static(&mut self, def_id: DefId) {
849        self.codegen_static_item(def_id)
850    }
851}