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