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