]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_llvm/src/consts.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / compiler / rustc_codegen_llvm / src / consts.rs
CommitLineData
9fa01778 1use crate::base;
dfeec247
XL
2use crate::common::CodegenCx;
3use crate::debuginfo;
ba9703b0 4use crate::llvm::{self, True};
5e7ed085 5use crate::llvm_util;
9fa01778
XL
6use crate::type_::Type;
7use crate::type_of::LayoutLlvmExt;
8use crate::value::Value;
6a06907d 9use cstr::cstr;
8faf50e0 10use libc::c_uint;
dfeec247 11use rustc_codegen_ssa::traits::*;
dfeec247 12use rustc_hir::def_id::DefId;
ba9703b0
XL
13use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
14use rustc_middle::mir::interpret::{
5e7ed085 15 read_target_uint, Allocation, ConstAllocation, ErrorHandled, GlobalAlloc, InitChunk, Pointer,
94222f64 16 Scalar as InterpScalar,
ba9703b0
XL
17};
18use rustc_middle::mir::mono::MonoItem;
c295e0f8 19use rustc_middle::ty::layout::LayoutOf;
ba9703b0
XL
20use rustc_middle::ty::{self, Instance, Ty};
21use rustc_middle::{bug, span_bug};
94222f64 22use rustc_target::abi::{
c295e0f8 23 AddressSpace, Align, HasDataLayout, Primitive, Scalar, Size, WrappingRange,
94222f64
XL
24};
25use std::ops::Range;
3dfed10e 26use tracing::debug;
e9174d1e 27
5e7ed085
FG
28pub fn const_alloc_to_llvm<'ll>(cx: &CodegenCx<'ll, '_>, alloc: ConstAllocation<'_>) -> &'ll Value {
29 let alloc = alloc.inner();
e1599b0c 30 let mut llvals = Vec::with_capacity(alloc.relocations().len() + 1);
a1dfa0c6
XL
31 let dl = cx.data_layout();
32 let pointer_size = dl.pointer_size.bytes() as usize;
33
94222f64
XL
34 // Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`,
35 // so `range` must be within the bounds of `alloc` and not contain or overlap a relocation.
36 fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
37 llvals: &mut Vec<&'ll Value>,
38 cx: &'a CodegenCx<'ll, 'b>,
39 alloc: &'a Allocation,
40 range: Range<usize>,
41 ) {
5e7ed085 42 let chunks = alloc
94222f64
XL
43 .init_mask()
44 .range_as_init_chunks(Size::from_bytes(range.start), Size::from_bytes(range.end));
45
46 let chunk_to_llval = move |chunk| match chunk {
47 InitChunk::Init(range) => {
48 let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
49 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
50 cx.const_bytes(bytes)
51 }
52 InitChunk::Uninit(range) => {
53 let len = range.end.bytes() - range.start.bytes();
54 cx.const_undef(cx.type_array(cx.type_i8(), len))
55 }
56 };
57
5e7ed085
FG
58 // Generating partially-uninit consts is limited to small numbers of chunks,
59 // to avoid the cost of generating large complex const expressions.
60 // For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element,
61 // and would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
62 let max = if llvm_util::get_version() < (14, 0, 0) {
63 // Generating partially-uninit consts inhibits optimizations in LLVM < 14.
64 // See https://github.com/rust-lang/rust/issues/84565.
65 1
66 } else {
064997fb 67 cx.sess().opts.unstable_opts.uninit_const_chunk_threshold
5e7ed085
FG
68 };
69 let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
94222f64 70
5e7ed085 71 if allow_uninit_chunks {
94222f64
XL
72 llvals.extend(chunks.map(chunk_to_llval));
73 } else {
5e7ed085
FG
74 // If this allocation contains any uninit bytes, codegen as if it was initialized
75 // (using some arbitrary value for uninit bytes).
76 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
77 llvals.push(cx.const_bytes(bytes));
94222f64
XL
78 }
79 }
80
a1dfa0c6 81 let mut next_offset = 0;
136023e0 82 for &(offset, alloc_id) in alloc.relocations().iter() {
a1dfa0c6
XL
83 let offset = offset.bytes();
84 assert_eq!(offset as usize as u64, offset);
85 let offset = offset as usize;
86 if offset > next_offset {
e1599b0c
XL
87 // This `inspect` is okay since we have checked that it is not within a relocation, it
88 // is within the bounds of the allocation, and it doesn't affect interpreter execution
94222f64
XL
89 // (we inspect the result after interpreter execution).
90 append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
a1dfa0c6
XL
91 }
92 let ptr_offset = read_target_uint(
93 dl.endian,
e1599b0c
XL
94 // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
95 // affect interpreter execution (we inspect the result after interpreter execution),
96 // and we properly interpret the relocation as a relocation pointer offset.
3dfed10e 97 alloc.inspect_with_uninit_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
dfeec247
XL
98 )
99 .expect("const_alloc_to_llvm: could not read relocation pointer")
100 as u64;
3dfed10e
XL
101
102 let address_space = match cx.tcx.global_alloc(alloc_id) {
103 GlobalAlloc::Function(..) => cx.data_layout().instruction_address_space,
064997fb
FG
104 GlobalAlloc::Static(..) | GlobalAlloc::Memory(..) | GlobalAlloc::VTable(..) => {
105 AddressSpace::DATA
106 }
3dfed10e
XL
107 };
108
a1dfa0c6 109 llvals.push(cx.scalar_to_backend(
136023e0
XL
110 InterpScalar::from_pointer(
111 Pointer::new(alloc_id, Size::from_bytes(ptr_offset)),
112 &cx.tcx,
113 ),
04454e1e
FG
114 Scalar::Initialized {
115 value: Primitive::Pointer,
116 valid_range: WrappingRange::full(dl.pointer_size),
117 },
3dfed10e 118 cx.type_i8p_ext(address_space),
a1dfa0c6
XL
119 ));
120 next_offset = offset + pointer_size;
1a4d82fc 121 }
e1599b0c
XL
122 if alloc.len() >= next_offset {
123 let range = next_offset..alloc.len();
124 // This `inspect` is okay since we have check that it is after all relocations, it is
125 // within the bounds of the allocation, and it doesn't affect interpreter execution (we
94222f64
XL
126 // inspect the result after interpreter execution).
127 append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
a1dfa0c6
XL
128 }
129
130 cx.const_struct(&llvals, true)
1a4d82fc
JJ
131}
132
a2a8927a 133pub fn codegen_static_initializer<'ll, 'tcx>(
a1dfa0c6
XL
134 cx: &CodegenCx<'ll, 'tcx>,
135 def_id: DefId,
5e7ed085 136) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> {
1b1a35ee 137 let alloc = cx.tcx.eval_static_initializer(def_id)?;
a1dfa0c6 138 Ok((const_alloc_to_llvm(cx, alloc), alloc))
3b2f2976
XL
139}
140
a2a8927a 141fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
ea8adc8c
XL
142 // The target may require greater alignment for globals than the type does.
143 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
144 // which can force it to be smaller. Rust doesn't support this yet.
29967ef6 145 if let Some(min) = cx.sess().target.min_global_align {
a1dfa0c6 146 match Align::from_bits(min) {
ff7c6d11 147 Ok(min) => align = align.max(min),
ea8adc8c 148 Err(err) => {
2c00a5a8 149 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
ea8adc8c
XL
150 }
151 }
152 }
153 unsafe {
a1dfa0c6 154 llvm::LLVMSetAlignment(gv, align.bytes() as u32);
ea8adc8c
XL
155 }
156}
157
a2a8927a 158fn check_and_apply_linkage<'ll, 'tcx>(
b7449926 159 cx: &CodegenCx<'ll, 'tcx>,
8faf50e0
XL
160 attrs: &CodegenFnAttrs,
161 ty: Ty<'tcx>,
3dfed10e 162 sym: &str,
29967ef6 163 span_def_id: DefId,
b7449926 164) -> &'ll Value {
8faf50e0
XL
165 let llty = cx.layout_of(ty).llvm_type(cx);
166 if let Some(linkage) = attrs.linkage {
167 debug!("get_static: sym={} linkage={:?}", sym, linkage);
168
169 // If this is a static with a linkage specified, then we need to handle
170 // it a little specially. The typesystem prevents things like &T and
171 // extern "C" fn() from being non-null, so we can't just declare a
172 // static and call it a day. Some linkages (like weak) will make it such
173 // that the static actually has a null value.
1b1a35ee 174 let llty2 = if let ty::RawPtr(ref mt) = ty.kind() {
0bf4aa26
XL
175 cx.layout_of(mt.ty).llvm_type(cx)
176 } else {
dc9dc135 177 cx.sess().span_fatal(
29967ef6 178 cx.tcx.def_span(span_def_id),
dfeec247
XL
179 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
180 )
8faf50e0
XL
181 };
182 unsafe {
183 // Declare a symbol `foo` with the desired linkage.
c295e0f8 184 let g1 = cx.declare_global(sym, llty2);
8faf50e0
XL
185 llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
186
187 // Declare an internal global `extern_with_linkage_foo` which
188 // is initialized with the address of `foo`. If `foo` is
189 // discarded during linking (for example, if `foo` has weak
190 // linkage and there are no definitions), then
191 // `extern_with_linkage_foo` will instead be initialized to
192 // zero.
193 let mut real_name = "_rust_extern_with_linkage_".to_string();
c295e0f8 194 real_name.push_str(sym);
dfeec247 195 let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
29967ef6
XL
196 cx.sess().span_fatal(
197 cx.tcx.def_span(span_def_id),
198 &format!("symbol `{}` is already defined", &sym),
199 )
8faf50e0
XL
200 });
201 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
202 llvm::LLVMSetInitializer(g2, g1);
203 g2
204 }
205 } else {
206 // Generate an external declaration.
207 // FIXME(nagisa): investigate whether it can be changed into define_global
c295e0f8 208 cx.declare_global(sym, llty)
8faf50e0
XL
209 }
210}
211
a2a8927a 212pub fn ptrcast<'ll>(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
dfeec247 213 unsafe { llvm::LLVMConstPointerCast(val, ty) }
a1dfa0c6 214}
c1a9b12d 215
a2a8927a 216impl<'ll> CodegenCx<'ll, '_> {
923072b8 217 pub(crate) fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
dfeec247 218 unsafe { llvm::LLVMConstBitCast(val, ty) }
a1dfa0c6 219 }
c1a9b12d 220
923072b8 221 pub(crate) fn static_addr_of_mut(
a1dfa0c6
XL
222 &self,
223 cv: &'ll Value,
224 align: Align,
225 kind: Option<&str>,
226 ) -> &'ll Value {
227 unsafe {
228 let gv = match kind {
229 Some(kind) if !self.tcx.sess.fewer_names() => {
230 let name = self.generate_local_symbol_name(kind);
a2a8927a 231 let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| {
dfeec247 232 bug!("symbol `{}` is already defined", name);
a1dfa0c6
XL
233 });
234 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
235 gv
dfeec247 236 }
a1dfa0c6
XL
237 _ => self.define_private_global(self.val_ty(cv)),
238 };
239 llvm::LLVMSetInitializer(gv, cv);
c295e0f8 240 set_global_alignment(self, gv, align);
ba9703b0 241 llvm::SetUnnamedAddress(gv, llvm::UnnamedAddr::Global);
a1dfa0c6
XL
242 gv
243 }
244 }
8faf50e0 245
923072b8 246 pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
a1dfa0c6
XL
247 let instance = Instance::mono(self.tcx, def_id);
248 if let Some(&g) = self.instances.borrow().get(&instance) {
249 return g;
250 }
251
dfeec247
XL
252 let defined_in_current_codegen_unit =
253 self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
254 assert!(
255 !defined_in_current_codegen_unit,
256 "consts::get_static() should always hit the cache for \
a1dfa0c6 257 statics defined in the same CGU, but did not for `{:?}`",
dfeec247
XL
258 def_id
259 );
a1dfa0c6 260
3dfed10e 261 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
e74abb32 262 let sym = self.tcx.symbol_name(instance).name;
5869c6ff 263 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
a1dfa0c6 264
5869c6ff 265 debug!("get_static: sym={} instance={:?} fn_attrs={:?}", sym, instance, fn_attrs);
a1dfa0c6 266
5869c6ff 267 let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
a1dfa0c6 268 let llty = self.layout_of(ty).llvm_type(self);
5869c6ff
XL
269 if let Some(g) = self.get_declared_value(sym) {
270 if self.val_ty(g) != self.type_ptr_to(llty) {
271 span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
a1dfa0c6 272 }
5869c6ff 273 }
a1dfa0c6 274
5869c6ff 275 let g = self.declare_global(sym, llty);
a1dfa0c6 276
5869c6ff
XL
277 if !self.tcx.is_reachable_non_generic(def_id) {
278 unsafe {
279 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
a1dfa0c6
XL
280 }
281 }
c1a9b12d 282
9e0c209e 283 g
c1a9b12d 284 } else {
c295e0f8 285 check_and_apply_linkage(self, fn_attrs, ty, sym, def_id)
5869c6ff 286 };
a1dfa0c6 287
5869c6ff
XL
288 // Thread-local statics in some other crate need to *always* be linked
289 // against in a thread-local fashion, so we need to be sure to apply the
290 // thread-local attribute locally if it was present remotely. If we
291 // don't do this then linker errors can be generated where the linker
292 // complains that one object files has a thread local version of the
293 // symbol and another one doesn't.
294 if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
295 llvm::set_thread_local_mode(g, self.tls_model);
296 }
a1dfa0c6 297
5869c6ff 298 if !def_id.is_local() {
dfeec247 299 let needs_dll_storage_attr = self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) &&
a1dfa0c6
XL
300 // ThinLTO can't handle this workaround in all cases, so we don't
301 // emit the attrs. Instead we make them unnecessary by disallowing
9fa01778
XL
302 // dynamic linking when linker plugin based LTO is enabled.
303 !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
a1dfa0c6
XL
304
305 // If this assertion triggers, there's something wrong with commandline
306 // argument validation.
dfeec247
XL
307 debug_assert!(
308 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
29967ef6 309 && self.tcx.sess.target.is_like_windows
dfeec247
XL
310 && self.tcx.sess.opts.cg.prefer_dynamic)
311 );
a1dfa0c6
XL
312
313 if needs_dll_storage_attr {
0731742a 314 // This item is external but not foreign, i.e., it originates from an external Rust
a1dfa0c6
XL
315 // crate. Since we don't know whether this crate will be linked dynamically or
316 // statically in the final application, we always mark such symbols as 'dllimport'.
317 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
318 // to make things work.
319 //
320 // However, in some scenarios we defer emission of statics to downstream
321 // crates, so there are cases where a static with an upstream DefId
322 // is actually present in the current crate. We can find out via the
323 // is_codegened_item query.
324 if !self.tcx.is_codegened_item(def_id) {
325 unsafe {
326 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
327 }
328 }
329 }
5869c6ff 330 }
a1dfa0c6
XL
331
332 if self.use_dll_storage_attrs && self.tcx.is_dllimport_foreign_item(def_id) {
333 // For foreign (native) libs we know the exact storage type to use.
334 unsafe {
335 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
1a4d82fc
JJ
336 }
337 }
c1a9b12d 338
17df50a5
XL
339 unsafe {
340 if self.should_assume_dso_local(g, true) {
341 llvm::LLVMRustSetDSOLocal(g, true);
342 }
343 }
344
a1dfa0c6
XL
345 self.instances.borrow_mut().insert(instance, g);
346 g
347 }
348}
349
a2a8927a 350impl<'ll> StaticMethods for CodegenCx<'ll, '_> {
dfeec247 351 fn static_addr_of(&self, cv: &'ll Value, align: Align, kind: Option<&str>) -> &'ll Value {
a1dfa0c6
XL
352 if let Some(&gv) = self.const_globals.borrow().get(&cv) {
353 unsafe {
354 // Upgrade the alignment in cases where the same constant is used with different
355 // alignment requirements
356 let llalign = align.bytes() as u32;
357 if llalign > llvm::LLVMGetAlignment(gv) {
358 llvm::LLVMSetAlignment(gv, llalign);
359 }
94b46f34 360 }
a1dfa0c6
XL
361 return gv;
362 }
363 let gv = self.static_addr_of_mut(cv, align, kind);
364 unsafe {
365 llvm::LLVMSetGlobalConstant(gv, True);
c1a9b12d 366 }
a1dfa0c6
XL
367 self.const_globals.borrow_mut().insert(cv, gv);
368 gv
369 }
5bcae85e 370
dfeec247 371 fn codegen_static(&self, def_id: DefId, is_mutable: bool) {
a1dfa0c6
XL
372 unsafe {
373 let attrs = self.tcx.codegen_fn_attrs(def_id);
374
5e7ed085 375 let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
a1dfa0c6 376 // Error has already been reported
5e7ed085 377 return;
a1dfa0c6 378 };
5e7ed085 379 let alloc = alloc.inner();
a1dfa0c6
XL
380
381 let g = self.get_static(def_id);
382
383 // boolean SSA values are i1, but they have to be stored in i8 slots,
384 // otherwise some LLVM optimization passes don't work as expected
385 let mut val_llty = self.val_ty(v);
386 let v = if val_llty == self.type_i1() {
387 val_llty = self.type_i8();
388 llvm::LLVMConstZExt(v, val_llty)
389 } else {
390 v
391 };
392
393 let instance = Instance::mono(self.tcx, def_id);
3dfed10e 394 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
a1dfa0c6
XL
395 let llty = self.layout_of(ty).llvm_type(self);
396 let g = if val_llty == llty {
397 g
398 } else {
399 // If we created the global with the wrong type,
400 // correct the type.
60c5eb7d
XL
401 let name = llvm::get_value_name(g).to_vec();
402 llvm::set_value_name(g, b"");
a1dfa0c6
XL
403
404 let linkage = llvm::LLVMRustGetLinkage(g);
405 let visibility = llvm::LLVMRustGetVisibility(g);
406
407 let new_g = llvm::LLVMRustGetOrInsertGlobal(
dfeec247
XL
408 self.llmod,
409 name.as_ptr().cast(),
410 name.len(),
411 val_llty,
412 );
a1dfa0c6
XL
413
414 llvm::LLVMRustSetLinkage(new_g, linkage);
415 llvm::LLVMRustSetVisibility(new_g, visibility);
416
04454e1e
FG
417 // The old global has had its name removed but is returned by
418 // get_static since it is in the instance cache. Provide an
419 // alternative lookup that points to the new global so that
420 // global_asm! can compute the correct mangled symbol name
421 // for the global.
422 self.renamed_statics.borrow_mut().insert(def_id, new_g);
423
a1dfa0c6
XL
424 // To avoid breaking any invariants, we leave around the old
425 // global for the moment; we'll replace all references to it
426 // with the new global later. (See base::codegen_backend.)
427 self.statics_to_rauw.borrow_mut().push((g, new_g));
428 new_g
429 };
c295e0f8 430 set_global_alignment(self, g, self.align_of(ty));
a1dfa0c6
XL
431 llvm::LLVMSetInitializer(g, v);
432
17df50a5
XL
433 if self.should_assume_dso_local(g, true) {
434 llvm::LLVMRustSetDSOLocal(g, true);
435 }
436
a1dfa0c6
XL
437 // As an optimization, all shared statics which do not have interior
438 // mutability are placed into read-only memory.
29967ef6
XL
439 if !is_mutable && self.type_is_freeze(ty) {
440 llvm::LLVMSetGlobalConstant(g, llvm::True);
a1dfa0c6 441 }
5bcae85e 442
5e7ed085 443 debuginfo::build_global_var_di_node(self, def_id, g);
a1dfa0c6
XL
444
445 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
446 llvm::set_thread_local_mode(g, self.tls_model);
447
448 // Do not allow LLVM to change the alignment of a TLS on macOS.
449 //
450 // By default a global's alignment can be freely increased.
451 // This allows LLVM to generate more performant instructions
0731742a 452 // e.g., using load-aligned into a SIMD register.
a1dfa0c6
XL
453 //
454 // However, on macOS 10.10 or below, the dynamic linker does not
455 // respect any alignment given on the TLS (radar 24221680).
456 // This will violate the alignment assumption, and causing segfault at runtime.
457 //
458 // This bug is very easy to trigger. In `println!` and `panic!`,
459 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
460 // which the values would be `mem::replace`d on initialization.
461 // The implementation of `mem::replace` will use SIMD
462 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
463 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
464 // which macOS's dyld disregarded and causing crashes
465 // (see issues #51794, #51758, #50867, #48866 and #44056).
466 //
467 // To workaround the bug, we trick LLVM into not increasing
468 // the global's alignment by explicitly assigning a section to it
469 // (equivalent to automatically generating a `#[link_section]` attribute).
470 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
471 // of `lib/IR/Globals.cpp` for why this works.
472 //
473 // When the alignment is not increased, the optimized `mem::replace`
474 // will use load-unaligned instructions instead, and thus avoiding the crash.
475 //
476 // We could remove this hack whenever we decide to drop macOS 10.10 support.
29967ef6 477 if self.tcx.sess.target.is_like_osx {
ba9703b0
XL
478 // The `inspect` method is okay here because we checked relocations, and
479 // because we are doing this access to inspect the final interpreter state
480 // (not as part of the interpreter execution).
481 //
482 // FIXME: This check requires that the (arbitrary) value of undefined bytes
483 // happens to be zero. Instead, we should only check the value of defined bytes
484 // and set all undefined bytes to zero if this allocation is headed for the
485 // BSS.
486 let all_bytes_are_zero = alloc.relocations().is_empty()
487 && alloc
3dfed10e 488 .inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len())
e1599b0c 489 .iter()
ba9703b0
XL
490 .all(|&byte| byte == 0);
491
492 let sect_name = if all_bytes_are_zero {
6a06907d 493 cstr!("__DATA,__thread_bss")
a1dfa0c6 494 } else {
6a06907d 495 cstr!("__DATA,__thread_data")
a1dfa0c6
XL
496 };
497 llvm::LLVMSetSection(g, sect_name.as_ptr());
498 }
499 }
500
a1dfa0c6
XL
501 // Wasm statics with custom link sections get special treatment as they
502 // go into custom sections of the wasm executable.
3c0e092e 503 if self.tcx.sess.target.is_like_wasm {
a1dfa0c6
XL
504 if let Some(section) = attrs.link_section {
505 let section = llvm::LLVMMDStringInContext(
506 self.llcx,
e74abb32 507 section.as_str().as_ptr().cast(),
a1dfa0c6
XL
508 section.as_str().len() as c_uint,
509 );
e1599b0c
XL
510 assert!(alloc.relocations().is_empty());
511
512 // The `inspect` method is okay here because we checked relocations, and
513 // because we are doing this access to inspect the final interpreter state (not
514 // as part of the interpreter execution).
dfeec247 515 let bytes =
3dfed10e 516 alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
a1dfa0c6
XL
517 let alloc = llvm::LLVMMDStringInContext(
518 self.llcx,
e74abb32 519 bytes.as_ptr().cast(),
e1599b0c 520 bytes.len() as c_uint,
a1dfa0c6
XL
521 );
522 let data = [section, alloc];
523 let meta = llvm::LLVMMDNodeInContext(self.llcx, data.as_ptr(), 2);
524 llvm::LLVMAddNamedMetadataOperand(
525 self.llmod,
e74abb32 526 "wasm.custom_sections\0".as_ptr().cast(),
a1dfa0c6
XL
527 meta,
528 );
529 }
530 } else {
c295e0f8 531 base::set_link_section(g, attrs);
8faf50e0 532 }
8faf50e0 533
a1dfa0c6 534 if attrs.flags.contains(CodegenFnAttrFlags::USED) {
5099ac24
FG
535 // `USED` and `USED_LINKER` can't be used together.
536 assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER));
537
94222f64
XL
538 // The semantics of #[used] in Rust only require the symbol to make it into the
539 // object file. It is explicitly allowed for the linker to strip the symbol if it
064997fb
FG
540 // is dead, which means we are allowed use `llvm.compiler.used` instead of
541 // `llvm.used` here.
542 //
94222f64
XL
543 // Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
544 // sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
064997fb
FG
545 // in the handling of `.init_array` (the static constructor list) in versions of
546 // the gold linker (prior to the one released with binutils 2.36).
547 //
548 // That said, we only ever emit these when compiling for ELF targets, unless
549 // `#[used(compiler)]` is explicitly requested. This is to avoid similar breakage
550 // on other targets, in particular MachO targets have *their* static constructor
551 // lists broken if `llvm.compiler.used` is emitted rather than llvm.used. However,
552 // that check happens when assigning the `CodegenFnAttrFlags` in `rustc_typeck`,
553 // so we don't need to take care of it here.
94222f64 554 self.add_compiler_used_global(g);
a1dfa0c6 555 }
5099ac24
FG
556 if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
557 // `USED` and `USED_LINKER` can't be used together.
558 assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED));
559
560 self.add_used_global(g);
561 }
cc61c64b 562 }
1a4d82fc 563 }
3dfed10e
XL
564
565 /// Add a global value to a list to be stored in the `llvm.used` variable, an array of i8*.
566 fn add_used_global(&self, global: &'ll Value) {
567 let cast = unsafe { llvm::LLVMConstPointerCast(global, self.type_i8p()) };
568 self.used_statics.borrow_mut().push(cast);
569 }
94222f64
XL
570
571 /// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
572 /// an array of i8*.
573 fn add_compiler_used_global(&self, global: &'ll Value) {
574 let cast = unsafe { llvm::LLVMConstPointerCast(global, self.type_i8p()) };
575 self.compiler_used_statics.borrow_mut().push(cast);
576 }
1a4d82fc 577}