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