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