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