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