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