1use std::ops::Range;
23use rustc_abi::{Align, 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::{
12Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, Scalaras InterpScalar,
13read_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};
2223use crate::common::CodegenCx;
24use crate::errors::SymbolAlreadyDefined;
25use crate::llvm::{self, Type, Value};
26use crate::type_of::LayoutLlvmExt;
27use crate::{base, debuginfo};
2829pub(crate) fn const_alloc_to_llvm<'ll>(
30 cx: &CodegenCx<'ll, '_>,
31 alloc: &Allocation,
32 is_static: bool,
33) -> &'ll Value {
34// We expect that callers of const_alloc_to_llvm will instead directly codegen a pointer or
35 // integer for any &ZST where the ZST is a constant (i.e. not a static). We should never be
36 // producing empty LLVM allocations as they're just adding noise to binaries and forcing less
37 // optimal codegen.
38 //
39 // Statics have a guaranteed meaningful address so it's less clear that we want to do
40 // something like this; it's also harder.
41if !is_static {
42if !(alloc.len() != 0) {
::core::panicking::panic("assertion failed: alloc.len() != 0")
};assert!(alloc.len() != 0);
43 }
44let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
45let dl = cx.data_layout();
46let pointer_size = dl.pointer_size();
47let pointer_size_bytes = pointer_size.bytes() as usize;
4849// Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`, so `range`
50 // must be within the bounds of `alloc` and not contain or overlap a pointer provenance.
51fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
52 llvals: &mut Vec<&'ll Value>,
53 cx: &'a CodegenCx<'ll, 'b>,
54 alloc: &'a Allocation,
55 range: Range<usize>,
56 ) {
57let chunks = alloc.init_mask().range_as_init_chunks(range.clone().into());
5859let chunk_to_llval = move |chunk| match chunk {
60 InitChunk::Init(range) => {
61let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
62let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
63cx.const_bytes(bytes)
64 }
65 InitChunk::Uninit(range) => {
66let len = range.end.bytes() - range.start.bytes();
67cx.const_undef(cx.type_array(cx.type_i8(), len))
68 }
69 };
7071// Generating partially-uninit consts is limited to small numbers of chunks,
72 // to avoid the cost of generating large complex const expressions.
73 // For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element, and
74 // would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
75let max = cx.sess().opts.unstable_opts.uninit_const_chunk_threshold;
76let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
7778if allow_uninit_chunks {
79llvals.extend(chunks.map(chunk_to_llval));
80 } else {
81// If this allocation contains any uninit bytes, codegen as if it was initialized
82 // (using some arbitrary value for uninit bytes).
83let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
84llvals.push(cx.const_bytes(bytes));
85 }
86 }
8788let mut next_offset = 0;
89for &(offset, prov) in alloc.provenance().ptrs().iter() {
90let offset = offset.bytes();
91match (&(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);
92let offset = offset as usize;
93if offset > next_offset {
94// This `inspect` is okay since we have checked that there is no provenance, it
95 // is within the bounds of the allocation, and it doesn't affect interpreter execution
96 // (we inspect the result after interpreter execution).
97append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
98 }
99let ptr_offset = read_target_uint(
100 dl.endian,
101// This `inspect` is okay since it is within the bounds of the allocation, it doesn't
102 // affect interpreter execution (we inspect the result after interpreter execution),
103 // and we properly interpret the provenance as a relocation pointer offset.
104alloc.inspect_with_uninit_and_ptr_outside_interpreter(
105 offset..(offset + pointer_size_bytes),
106 ),
107 )
108 .expect("const_alloc_to_llvm: could not read relocation pointer")
109as u64;
110111let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx);
112113 llvals.push(cx.scalar_to_backend(
114 InterpScalar::from_pointer(Pointer::new(prov, Size::from_bytes(ptr_offset)), &cx.tcx),
115 Scalar::Initialized {
116 value: Primitive::Pointer(address_space),
117 valid_range: WrappingRange::full(pointer_size),
118 },
119 cx.type_ptr_ext(address_space),
120 ));
121 next_offset = offset + pointer_size_bytes;
122 }
123if alloc.len() >= next_offset {
124let range = next_offset..alloc.len();
125// This `inspect` is okay since we have check that it is after all provenance, it is
126 // within the bounds of the allocation, and it doesn't affect interpreter execution (we
127 // inspect the result after interpreter execution).
128append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
129 }
130131// Avoid wrapping in a struct if there is only a single value. This ensures
132 // that LLVM is able to perform the string merging optimization if the constant
133 // is a valid C string. LLVM only considers bare arrays for this optimization,
134 // not arrays wrapped in a struct. LLVM handles this at:
135 // https://github.com/rust-lang/llvm-project/blob/acaea3d2bb8f351b740db7ebce7d7a40b9e21488/llvm/lib/Target/TargetLoweringObjectFile.cpp#L249-L280
136if let &[data] = &*llvals { data } else { cx.const_struct(&llvals, true) }
137}
138139fn codegen_static_initializer<'ll, 'tcx>(
140 cx: &CodegenCx<'ll, 'tcx>,
141 def_id: DefId,
142) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> {
143let alloc = cx.tcx.eval_static_initializer(def_id)?;
144Ok((const_alloc_to_llvm(cx, alloc.inner(), /*static*/ true), alloc))
145}
146147fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
148// The target may require greater alignment for globals than the type does.
149 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
150 // which can force it to be smaller. Rust doesn't support this yet.
151if let Some(min_global) = cx.sess().target.min_global_align {
152align = Ord::max(align, min_global);
153 }
154 llvm::set_alignment(gv, align);
155}
156157fn check_and_apply_linkage<'ll, 'tcx>(
158 cx: &CodegenCx<'ll, 'tcx>,
159 attrs: &CodegenFnAttrs,
160 llty: &'ll Type,
161 sym: &str,
162 def_id: DefId,
163) -> &'ll Value {
164if let Some(linkage) = attrs.import_linkage {
165{
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:165",
"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(165u32),
::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);
166167// Declare a symbol `foo`. If `foo` is an extern_weak symbol, we declare
168 // an extern_weak function, otherwise a global with the desired linkage.
169let g1 = if #[allow(non_exhaustive_omitted_patterns)] match attrs.import_linkage {
Some(Linkage::ExternalWeak) => true,
_ => false,
}matches!(attrs.import_linkage, Some(Linkage::ExternalWeak)) {
170// An `extern_weak` function is represented as an `Option<unsafe extern ...>`,
171 // we extract the function signature and declare it as an extern_weak function
172 // instead of an extern_weak i8.
173let instance = Instance::mono(cx.tcx, def_id);
174if let ty::Adt(struct_def, args) = instance.ty(cx.tcx, cx.typing_env()).kind()
175 && cx.tcx.is_lang_item(struct_def.did(), LangItem::Option)
176 && let ty::FnPtr(sig, header) = args.type_at(0).kind()
177 {
178let fn_sig = sig.with(*header);
179180let fn_abi = cx.fn_abi_of_fn_ptr(fn_sig, ty::List::empty());
181cx.declare_fn(sym, &fn_abi, None)
182 } else {
183cx.declare_global(sym, cx.type_i8())
184 }
185 } else {
186cx.declare_global(sym, cx.type_i8())
187 };
188 llvm::set_linkage(g1, base::linkage_to_llvm(linkage));
189190// Normally this is done in `get_static_inner`, but when as we generate an internal global,
191 // it will apply the dso_local to the internal global instead, so do it here, too.
192cx.assume_dso_local(g1, true);
193194// Declare an internal global `extern_with_linkage_foo` which
195 // is initialized with the address of `foo`. If `foo` is
196 // discarded during linking (for example, if `foo` has weak
197 // linkage and there are no definitions), then
198 // `extern_with_linkage_foo` will instead be initialized to
199 // zero.
200let real_name =
201::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));
202let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
203cx.sess().dcx().emit_fatal(SymbolAlreadyDefined {
204 span: cx.tcx.def_span(def_id),
205 symbol_name: sym,
206 })
207 });
208 llvm::set_linkage(g2, llvm::Linkage::InternalLinkage);
209 llvm::set_unnamed_address(g2, llvm::UnnamedAddr::Global);
210 llvm::set_initializer(g2, g1);
211g2212 } else if cx.tcx.sess.target.arch == Arch::X86213 && common::is_mingw_gnu_toolchain(&cx.tcx.sess.target)
214 && let Some(dllimport) = crate::common::get_dllimport(cx.tcx, def_id, sym)
215 {
216cx.declare_global(&common::i686_decorated_name(dllimport, true, true, false), llty)
217 } else {
218// Generate an external declaration.
219 // FIXME(nagisa): investigate whether it can be changed into define_global
220cx.declare_global(sym, llty)
221 }
222}
223224impl<'ll> CodegenCx<'ll, '_> {
225pub(crate) fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
226unsafe { llvm::LLVMConstBitCast(val, ty) }
227 }
228229pub(crate) fn const_pointercast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
230unsafe { llvm::LLVMConstPointerCast(val, ty) }
231 }
232233/// Create a global variable.
234 ///
235 /// The returned global variable is a pointer in the default address space for globals.
236 /// Fails if a symbol with the given name already exists.
237pub(crate) fn static_addr_of_mut(
238&self,
239 cv: &'ll Value,
240 align: Align,
241 kind: Option<&str>,
242 ) -> &'ll Value {
243let gv = match kind {
244Some(kind) if !self.tcx.sess.fewer_names() => {
245let name = self.generate_local_symbol_name(kind);
246let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| {
247::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
name));bug!("symbol `{}` is already defined", name);
248 });
249gv250 }
251_ => self.define_global("", self.val_ty(cv)).unwrap_or_else(|| {
252::rustc_middle::util::bug::bug_fmt(format_args!("anonymous global symbol is already defined"));bug!("anonymous global symbol is already defined");
253 }),
254 };
255 llvm::set_linkage(gv, llvm::Linkage::PrivateLinkage);
256 llvm::set_initializer(gv, cv);
257set_global_alignment(self, gv, align);
258 llvm::set_unnamed_address(gv, llvm::UnnamedAddr::Global);
259gv260 }
261262/// Create a global constant.
263 ///
264 /// The returned global variable is a pointer in the default address space for globals.
265pub(crate) fn static_addr_of_impl(
266&self,
267 cv: &'ll Value,
268 align: Align,
269 kind: Option<&str>,
270 ) -> &'ll Value {
271if let Some(&gv) = self.const_globals.borrow().get(&cv) {
272unsafe {
273// Upgrade the alignment in cases where the same constant is used with different
274 // alignment requirements
275let llalign = align.bytes() as u32;
276if llalign > llvm::LLVMGetAlignment(gv) {
277 llvm::LLVMSetAlignment(gv, llalign);
278 }
279 }
280return gv;
281 }
282let gv = self.static_addr_of_mut(cv, align, kind);
283 llvm::set_global_constant(gv, true);
284285self.const_globals.borrow_mut().insert(cv, gv);
286gv287 }
288289#[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(289u32),
::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:292",
"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(292u32),
::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:301",
"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(301u32),
::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))]290pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
291let instance = Instance::mono(self.tcx, def_id);
292trace!(?instance);
293294let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
295// Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
296 // out the llvm type from the actual evaluated initializer.
297let llty = if nested {
298self.type_i8()
299 } else {
300let ty = instance.ty(self.tcx, self.typing_env());
301trace!(?ty);
302self.layout_of(ty).llvm_type(self)
303 };
304self.get_static_inner(def_id, llty)
305 }
306307#[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(307u32),
::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:311",
"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(311u32),
::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:326",
"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(326u32),
::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))]308fn get_static_inner(&self, def_id: DefId, llty: &'ll Type) -> &'ll Value {
309let instance = Instance::mono(self.tcx, def_id);
310if let Some(&g) = self.instances.borrow().get(&instance) {
311trace!("used cached value");
312return g;
313 }
314315let defined_in_current_codegen_unit =
316self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
317assert!(
318 !defined_in_current_codegen_unit,
319"consts::get_static() should always hit the cache for \
320 statics defined in the same CGU, but did not for `{def_id:?}`"
321);
322323let sym = self.tcx.symbol_name(instance).name;
324let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
325326debug!(?sym, ?fn_attrs);
327328let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
329if let Some(g) = self.get_declared_value(sym) {
330if self.val_ty(g) != self.type_ptr() {
331span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
332 }
333 }
334335let g = self.declare_global(sym, llty);
336337if !self.tcx.is_reachable_non_generic(def_id) {
338 llvm::set_visibility(g, llvm::Visibility::Hidden);
339 }
340341 g
342 } else if let Some(classname) = fn_attrs.objc_class {
343self.get_objc_classref(classname)
344 } else if let Some(methname) = fn_attrs.objc_selector {
345self.get_objc_selref(methname)
346 } else {
347 check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
348 };
349350// Thread-local statics in some other crate need to *always* be linked
351 // against in a thread-local fashion, so we need to be sure to apply the
352 // thread-local attribute locally if it was present remotely. If we
353 // don't do this then linker errors can be generated where the linker
354 // complains that one object files has a thread local version of the
355 // symbol and another one doesn't.
356if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
357 llvm::set_thread_local_mode(g, self.tls_model);
358 }
359360let dso_local = self.assume_dso_local(g, true);
361362if !def_id.is_local() {
363let needs_dll_storage_attr = self.use_dll_storage_attrs
364 && !self.tcx.is_foreign_item(def_id)
365// Local definitions can never be imported, so we must not apply
366 // the DLLImport annotation.
367&& !dso_local
368// Linker plugin ThinLTO doesn't create the self-dllimport Rust uses for rlibs
369 // as the code generation happens out of process. Instead we assume static linkage
370 // and disallow dynamic linking when linker plugin based LTO is enabled.
371 // Regular in-process ThinLTO doesn't need this workaround.
372&& !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
373374// If this assertion triggers, there's something wrong with commandline
375 // argument validation.
376assert!(
377 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
378 && self.tcx.sess.target.is_like_windows
379 && self.tcx.sess.opts.cg.prefer_dynamic)
380 );
381382if needs_dll_storage_attr {
383// This item is external but not foreign, i.e., it originates from an external Rust
384 // crate. Since we don't know whether this crate will be linked dynamically or
385 // statically in the final application, we always mark such symbols as 'dllimport'.
386 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
387 // to make things work.
388 //
389 // However, in some scenarios we defer emission of statics to downstream
390 // crates, so there are cases where a static with an upstream DefId
391 // is actually present in the current crate. We can find out via the
392 // is_codegened_item query.
393if !self.tcx.is_codegened_item(def_id) {
394 llvm::set_dllimport_storage_class(g);
395 }
396 }
397 }
398399if self.use_dll_storage_attrs
400 && let Some(library) = self.tcx.native_library(def_id)
401 && library.kind.is_dllimport()
402 {
403// For foreign (native) libs we know the exact storage type to use.
404llvm::set_dllimport_storage_class(g);
405 }
406407self.instances.borrow_mut().insert(instance, g);
408 g
409 }
410411fn codegen_static_item(&mut self, def_id: DefId) {
412if !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!(
413 llvm::LLVMGetInitializer(
414self.instances.borrow().get(&Instance::mono(self.tcx, def_id)).unwrap()
415 )
416 .is_none()
417 );
418let attrs = self.tcx.codegen_fn_attrs(def_id);
419420let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
421// Error has already been reported
422return;
423 };
424let alloc = alloc.inner();
425426let val_llty = self.val_ty(v);
427428let g = self.get_static_inner(def_id, val_llty);
429let llty = self.get_type_of_global(g);
430431let g = if val_llty == llty {
432g433 } else {
434// codegen_static_initializer creates the global value just from the
435 // `Allocation` data by generating one big struct value that is just
436 // all the bytes and pointers after each other. This will almost never
437 // match the type that the static was declared with. Unfortunately
438 // we can't just LLVMConstBitCast our way out of it because that has very
439 // specific rules on what can be cast. So instead of adding a new way to
440 // generate static initializers that match the static's type, we picked
441 // the easier option and retroactively change the type of the static item itself.
442let name = String::from_utf8(llvm::get_value_name(g))
443 .expect("we declare our statics with a utf8-valid name");
444 llvm::set_value_name(g, b"");
445446let linkage = llvm::get_linkage(g);
447let visibility = llvm::get_visibility(g);
448449let new_g = self.declare_global(&name, val_llty);
450451 llvm::set_linkage(new_g, linkage);
452 llvm::set_visibility(new_g, visibility);
453454// The old global has had its name removed but is returned by
455 // get_static since it is in the instance cache. Provide an
456 // alternative lookup that points to the new global so that
457 // global_asm! can compute the correct mangled symbol name
458 // for the global.
459self.renamed_statics.borrow_mut().insert(def_id, new_g);
460461// To avoid breaking any invariants, we leave around the old
462 // global for the moment; we'll replace all references to it
463 // with the new global later. (See base::codegen_backend.)
464self.statics_to_rauw.borrow_mut().push((g, new_g));
465new_g466 };
467468// NOTE: Alignment from attributes has already been applied to the allocation.
469set_global_alignment(self, g, alloc.align);
470 llvm::set_initializer(g, v);
471472self.assume_dso_local(g, true);
473474// Forward the allocation's mutability (picked by the const interner) to LLVM.
475if alloc.mutability.is_not() {
476 llvm::set_global_constant(g, true);
477 }
478479 debuginfo::build_global_var_di_node(self, def_id, g);
480481if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
482 llvm::set_thread_local_mode(g, self.tls_model);
483 }
484485// Wasm statics with custom link sections get special treatment as they
486 // go into custom sections of the wasm executable. The exception to this
487 // is the `.init_array` section which are treated specially by the wasm linker.
488if self.tcx.sess.target.is_like_wasm
489 && attrs490 .link_section
491 .map(|link_section| !link_section.as_str().starts_with(".init_array"))
492 .unwrap_or(true)
493 {
494if let Some(section) = attrs.link_section {
495let section = self.create_metadata(section.as_str().as_bytes());
496if !alloc.provenance().ptrs().is_empty() {
::core::panicking::panic("assertion failed: alloc.provenance().ptrs().is_empty()")
};assert!(alloc.provenance().ptrs().is_empty());
497498// The `inspect` method is okay here because we checked for provenance, and
499 // because we are doing this access to inspect the final interpreter state (not
500 // as part of the interpreter execution).
501let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
502let alloc = self.create_metadata(bytes);
503let data = [section, alloc];
504self.module_add_named_metadata_node(self.llmod(), c"wasm.custom_sections", &data);
505 }
506 } else {
507 base::set_link_section(g, attrs);
508 }
509510 base::set_variable_sanitizer_attrs(g, attrs);
511512if attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
513// `USED` and `USED_LINKER` can't be used together.
514if !!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
::core::panicking::panic("assertion failed: !attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)")
};assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER));
515516// The semantics of #[used] in Rust only require the symbol to make it into the
517 // object file. It is explicitly allowed for the linker to strip the symbol if it
518 // is dead, which means we are allowed to use `llvm.compiler.used` instead of
519 // `llvm.used` here.
520 //
521 // Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
522 // sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
523 // in the handling of `.init_array` (the static constructor list) in versions of
524 // the gold linker (prior to the one released with binutils 2.36).
525 //
526 // That said, we only ever emit these when `#[used(compiler)]` is explicitly
527 // requested. This is to avoid similar breakage on other targets, in particular
528 // MachO targets have *their* static constructor lists broken if `llvm.compiler.used`
529 // is emitted rather than `llvm.used`. However, that check happens when assigning
530 // the `CodegenFnAttrFlags` in the `codegen_fn_attrs` query, so we don't need to
531 // take care of it here.
532self.add_compiler_used_global(g);
533 }
534if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
535// `USED` and `USED_LINKER` can't be used together.
536if !!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
::core::panicking::panic("assertion failed: !attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)")
};assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER));
537538self.add_used_global(g);
539 }
540 }
541542/// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr.
543pub(crate) fn add_used_global(&mut self, global: &'ll Value) {
544self.used_statics.push(global);
545 }
546547/// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
548 /// an array of ptr.
549pub(crate) fn add_compiler_used_global(&self, global: &'ll Value) {
550self.compiler_used_statics.borrow_mut().push(global);
551 }
552553// We do our best here to match what Clang does when compiling Objective-C natively.
554 // See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
555 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
556fn define_objc_classname(&self, classname: &str) -> &'ll Value {
557match (&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);
558559let llval = self.null_terminate_const_bytes(classname.as_bytes());
560let llty = self.val_ty(llval);
561let sym = self.generate_local_symbol_name("OBJC_CLASS_NAME_");
562let g = self.define_global(&sym, llty).unwrap_or_else(|| {
563::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
sym));bug!("symbol `{}` is already defined", sym);
564 });
565set_global_alignment(self, g, self.tcx.data_layout.i8_align);
566 llvm::set_initializer(g, llval);
567 llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
568 llvm::set_section(g, c"__TEXT,__cstring,cstring_literals");
569 llvm::LLVMSetGlobalConstant(g, llvm::TRUE);
570 llvm::LLVMSetUnnamedAddress(g, llvm::UnnamedAddr::Global);
571self.add_compiler_used_global(g);
572573g574 }
575576// We do our best here to match what Clang does when compiling Objective-C natively.
577 // See Clang's `ObjCNonFragileABITypesHelper`:
578 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L6052
579fn get_objc_class_t(&self) -> &'ll Type {
580if let Some(class_t) = self.objc_class_t.get() {
581return class_t;
582 }
583584match (&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);
585586// struct _class_t {
587 // struct _class_t* isa;
588 // struct _class_t* const superclass;
589 // void* cache;
590 // IMP* vtable;
591 // struct class_ro_t* ro;
592 // }
593594let class_t = self.type_named_struct("struct._class_t");
595let els = [self.type_ptr(); 5];
596let packed = false;
597self.set_struct_body(class_t, &els, packed);
598599self.objc_class_t.set(Some(class_t));
600class_t601 }
602603// We do our best here to match what Clang does when compiling Objective-C natively. We
604 // deduplicate references within a CGU, but we need a reference definition in each referencing
605 // CGU. All attempts at using external references to a single reference definition result in
606 // linker errors.
607fn get_objc_classref(&self, classname: Symbol) -> &'ll Value {
608let mut classrefs = self.objc_classrefs.borrow_mut();
609if let Some(classref) = classrefs.get(&classname).copied() {
610return classref;
611 }
612613let g = match self.objc_abi_version() {
6141 => {
615// See Clang's `CGObjCMac::EmitClassRefFromId`:
616 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5205
617let llval = self.define_objc_classname(classname.as_str());
618let llty = self.type_ptr();
619let sym = self.generate_local_symbol_name("OBJC_CLASS_REFERENCES_");
620let g = self.define_global(&sym, llty).unwrap_or_else(|| {
621::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
sym));bug!("symbol `{}` is already defined", sym);
622 });
623set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
624 llvm::set_initializer(g, llval);
625 llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
626 llvm::set_section(g, c"__OBJC,__cls_refs,literal_pointers,no_dead_strip");
627self.add_compiler_used_global(g);
628g629 }
6302 => {
631// See Clang's `CGObjCNonFragileABIMac::EmitClassRefFromId`:
632 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7423
633let llval = {
634let extern_sym = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("OBJC_CLASS_$_{0}",
classname.as_str()))
})format!("OBJC_CLASS_$_{}", classname.as_str());
635let extern_llty = self.get_objc_class_t();
636self.declare_global(&extern_sym, extern_llty)
637 };
638let llty = self.type_ptr();
639let sym = self.generate_local_symbol_name("OBJC_CLASSLIST_REFERENCES_$_");
640let g = self.define_global(&sym, llty).unwrap_or_else(|| {
641::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
sym));bug!("symbol `{}` is already defined", sym);
642 });
643set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
644 llvm::set_initializer(g, llval);
645 llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
646 llvm::set_section(g, c"__DATA,__objc_classrefs,regular,no_dead_strip");
647self.add_compiler_used_global(g);
648g649 }
650_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
651 };
652653classrefs.insert(classname, g);
654g655 }
656657// We do our best here to match what Clang does when compiling Objective-C natively. We
658 // deduplicate references within a CGU, but we need a reference definition in each referencing
659 // CGU. All attempts at using external references to a single reference definition result in
660 // linker errors.
661 //
662 // Newer versions of Apple Clang generate calls to `@"objc_msgSend$methname"` selector stub
663 // functions. We don't currently do that. The code we generate is closer to what Apple Clang
664 // generates with the `-fno-objc-msgsend-selector-stubs` option.
665fn get_objc_selref(&self, methname: Symbol) -> &'ll Value {
666let mut selrefs = self.objc_selrefs.borrow_mut();
667if let Some(selref) = selrefs.get(&methname).copied() {
668return selref;
669 }
670671let abi_version = self.objc_abi_version();
672673// See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
674 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
675let methname_llval = self.null_terminate_const_bytes(methname.as_str().as_bytes());
676let methname_llty = self.val_ty(methname_llval);
677let methname_sym = self.generate_local_symbol_name("OBJC_METH_VAR_NAME_");
678let methname_g = self.define_global(&methname_sym, methname_llty).unwrap_or_else(|| {
679::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
methname_sym));bug!("symbol `{}` is already defined", methname_sym);
680 });
681set_global_alignment(self, methname_g, self.tcx.data_layout.i8_align);
682 llvm::set_initializer(methname_g, methname_llval);
683 llvm::set_linkage(methname_g, llvm::Linkage::PrivateLinkage);
684 llvm::set_section(
685methname_g,
686match abi_version {
6871 => c"__TEXT,__cstring,cstring_literals",
6882 => c"__TEXT,__objc_methname,cstring_literals",
689_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
690 },
691 );
692 llvm::LLVMSetGlobalConstant(methname_g, llvm::TRUE);
693 llvm::LLVMSetUnnamedAddress(methname_g, llvm::UnnamedAddr::Global);
694self.add_compiler_used_global(methname_g);
695696// See Clang's `CGObjCMac::EmitSelectorAddr`:
697 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5243
698 // And Clang's `CGObjCNonFragileABIMac::EmitSelectorAddr`:
699 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7586
700let selref_llval = methname_g;
701let selref_llty = self.type_ptr();
702let selref_sym = self.generate_local_symbol_name("OBJC_SELECTOR_REFERENCES_");
703let selref_g = self.define_global(&selref_sym, selref_llty).unwrap_or_else(|| {
704::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
selref_sym));bug!("symbol `{}` is already defined", selref_sym);
705 });
706set_global_alignment(self, selref_g, self.tcx.data_layout.pointer_align().abi);
707 llvm::set_initializer(selref_g, selref_llval);
708 llvm::set_externally_initialized(selref_g, true);
709 llvm::set_linkage(
710selref_g,
711match abi_version {
7121 => llvm::Linkage::PrivateLinkage,
7132 => llvm::Linkage::InternalLinkage,
714_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
715 },
716 );
717 llvm::set_section(
718selref_g,
719match abi_version {
7201 => c"__OBJC,__message_refs,literal_pointers,no_dead_strip",
7212 => c"__DATA,__objc_selrefs,literal_pointers,no_dead_strip",
722_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
723 },
724 );
725self.add_compiler_used_global(selref_g);
726727selrefs.insert(methname, selref_g);
728selref_g729 }
730731// We do our best here to match what Clang does when compiling Objective-C natively.
732 // See Clang's `ObjCTypesHelper`:
733 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5936
734 // And Clang's `CGObjCMac::EmitModuleInfo`:
735 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5151
736pub(crate) fn define_objc_module_info(&mut self) {
737match (&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);
738739// struct _objc_module {
740 // long version; // Hardcoded to 7 in Clang.
741 // long size; // sizeof(struct _objc_module)
742 // char* name; // Hardcoded to classname "" in Clang.
743 // struct _objc_symtab* symtab; // Null without class or category definitions.
744 // }
745746let llty = self.type_named_struct("struct._objc_module");
747let i32_llty = self.type_i32();
748let ptr_llty = self.type_ptr();
749let packed = false;
750self.set_struct_body(llty, &[i32_llty, i32_llty, ptr_llty, ptr_llty], packed);
751752let version = self.const_uint(i32_llty, 7);
753let size = self.const_uint(i32_llty, 16);
754let name = self.define_objc_classname("");
755let symtab = self.const_null(ptr_llty);
756let llval = crate::common::named_struct(llty, &[version, size, name, symtab]);
757758let sym = "OBJC_MODULES";
759let g = self.define_global(&sym, llty).unwrap_or_else(|| {
760::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
sym));bug!("symbol `{}` is already defined", sym);
761 });
762set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
763 llvm::set_initializer(g, llval);
764 llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
765 llvm::set_section(g, c"__OBJC,__module_info,regular,no_dead_strip");
766767self.add_compiler_used_global(g);
768 }
769}
770771impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> {
772/// Get a pointer to a global variable.
773 ///
774 /// The pointer will always be in the default address space. If global variables default to a
775 /// different address space, an addrspacecast is inserted.
776fn static_addr_of(&self, alloc: ConstAllocation<'_>, kind: Option<&str>) -> &'ll Value {
777// FIXME: should we cache `const_alloc_to_llvm` to avoid repeating this for the
778 // same `ConstAllocation`?
779let cv = const_alloc_to_llvm(self, alloc.inner(), /*static*/ false);
780781let gv = self.static_addr_of_impl(cv, alloc.inner().align, kind);
782// static_addr_of_impl returns the bare global variable, which might not be in the default
783 // address space. Cast to the default address space if necessary.
784self.const_pointercast(gv, self.type_ptr())
785 }
786787fn codegen_static(&mut self, def_id: DefId) {
788self.codegen_static_item(def_id)
789 }
790}