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