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