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