]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/consts.rs
remove unneeded deps
[rust.git] / src / librustc_codegen_llvm / consts.rs
1 use crate::llvm::{self, SetUnnamedAddr, True};
2 use crate::debuginfo;
3 use crate::common::CodegenCx;
4 use crate::base;
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
8 use libc::c_uint;
9 use rustc::hir::def_id::DefId;
10 use rustc::mir::interpret::{ConstValue, Allocation, read_target_uint,
11     Pointer, ErrorHandled, GlobalId};
12 use rustc::mir::mono::MonoItem;
13 use rustc::hir::Node;
14 use syntax_pos::Span;
15 use rustc_target::abi::HasDataLayout;
16 use syntax::symbol::sym;
17 use syntax_pos::symbol::LocalInternedString;
18 use rustc::ty::{self, Ty, Instance};
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: 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             cx.sess().span_fatal(
119                 span, "must have type `*const T` or `*mut T` due to `#[linkage]` attribute")
120         };
121         unsafe {
122             // Declare a symbol `foo` with the desired linkage.
123             let g1 = cx.declare_global(&sym, llty2);
124             llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
125
126             // Declare an internal global `extern_with_linkage_foo` which
127             // is initialized with the address of `foo`.  If `foo` is
128             // discarded during linking (for example, if `foo` has weak
129             // linkage and there are no definitions), then
130             // `extern_with_linkage_foo` will instead be initialized to
131             // zero.
132             let mut real_name = "_rust_extern_with_linkage_".to_string();
133             real_name.push_str(&sym);
134             let g2 = cx.define_global(&real_name, llty).unwrap_or_else(||{
135                 cx.sess().span_fatal(span, &format!("symbol `{}` is already defined", &sym))
136             });
137             llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
138             llvm::LLVMSetInitializer(g2, g1);
139             g2
140         }
141     } else {
142         // Generate an external declaration.
143         // FIXME(nagisa): investigate whether it can be changed into define_global
144         cx.declare_global(&sym, llty)
145     }
146 }
147
148 pub fn ptrcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
149     unsafe {
150         llvm::LLVMConstPointerCast(val, ty)
151     }
152 }
153
154 impl CodegenCx<'ll, 'tcx> {
155     crate fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
156         unsafe {
157             llvm::LLVMConstBitCast(val, ty)
158         }
159     }
160
161     crate fn static_addr_of_mut(
162         &self,
163         cv: &'ll Value,
164         align: Align,
165         kind: Option<&str>,
166     ) -> &'ll Value {
167         unsafe {
168             let gv = match kind {
169                 Some(kind) if !self.tcx.sess.fewer_names() => {
170                     let name = self.generate_local_symbol_name(kind);
171                     let gv = self.define_global(&name[..],
172                         self.val_ty(cv)).unwrap_or_else(||{
173                             bug!("symbol `{}` is already defined", name);
174                     });
175                     llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
176                     gv
177                 },
178                 _ => self.define_private_global(self.val_ty(cv)),
179             };
180             llvm::LLVMSetInitializer(gv, cv);
181             set_global_alignment(&self, gv, align);
182             SetUnnamedAddr(gv, true);
183             gv
184         }
185     }
186
187     crate fn get_static(&self, def_id: DefId) -> &'ll Value {
188         let instance = Instance::mono(self.tcx, def_id);
189         if let Some(&g) = self.instances.borrow().get(&instance) {
190             return g;
191         }
192
193         let defined_in_current_codegen_unit = self.codegen_unit
194                                                 .items()
195                                                 .contains_key(&MonoItem::Static(def_id));
196         assert!(!defined_in_current_codegen_unit,
197                 "consts::get_static() should always hit the cache for \
198                  statics defined in the same CGU, but did not for `{:?}`",
199                  def_id);
200
201         let ty = instance.ty(self.tcx);
202         let sym = self.tcx.symbol_name(instance).as_str();
203
204         debug!("get_static: sym={} instance={:?}", sym, instance);
205
206         let g = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
207
208             let llty = self.layout_of(ty).llvm_type(self);
209             let (g, attrs) = match self.tcx.hir().get_by_hir_id(id) {
210                 Node::Item(&hir::Item {
211                     ref attrs, span, node: hir::ItemKind::Static(..), ..
212                 }) => {
213                     if self.get_declared_value(&sym[..]).is_some() {
214                         span_bug!(span, "Conflicting symbol names for static?");
215                     }
216
217                     let g = self.define_global(&sym[..], llty).unwrap();
218
219                     if !self.tcx.is_reachable_non_generic(def_id) {
220                         unsafe {
221                             llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
222                         }
223                     }
224
225                     (g, attrs)
226                 }
227
228                 Node::ForeignItem(&hir::ForeignItem {
229                     ref attrs, span, node: hir::ForeignItemKind::Static(..), ..
230                 }) => {
231                     let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
232                     (check_and_apply_linkage(&self, &fn_attrs, ty, sym, span), attrs)
233                 }
234
235                 item => bug!("get_static: expected static, found {:?}", item)
236             };
237
238             debug!("get_static: sym={} attrs={:?}", sym, attrs);
239
240             for attr in attrs {
241                 if attr.check_name(sym::thread_local) {
242                     llvm::set_thread_local_mode(g, self.tls_model);
243                 }
244             }
245
246             g
247         } else {
248             // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
249             debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id));
250
251             let attrs = self.tcx.codegen_fn_attrs(def_id);
252             let span = self.tcx.def_span(def_id);
253             let g = check_and_apply_linkage(&self, &attrs, ty, sym, span);
254
255             // Thread-local statics in some other crate need to *always* be linked
256             // against in a thread-local fashion, so we need to be sure to apply the
257             // thread-local attribute locally if it was present remotely. If we
258             // don't do this then linker errors can be generated where the linker
259             // complains that one object files has a thread local version of the
260             // symbol and another one doesn't.
261             if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
262                 llvm::set_thread_local_mode(g, self.tls_model);
263             }
264
265             let needs_dll_storage_attr =
266                 self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) &&
267                 // ThinLTO can't handle this workaround in all cases, so we don't
268                 // emit the attrs. Instead we make them unnecessary by disallowing
269                 // dynamic linking when linker plugin based LTO is enabled.
270                 !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
271
272             // If this assertion triggers, there's something wrong with commandline
273             // argument validation.
274             debug_assert!(!(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
275                             self.tcx.sess.target.target.options.is_like_msvc &&
276                             self.tcx.sess.opts.cg.prefer_dynamic));
277
278             if needs_dll_storage_attr {
279                 // This item is external but not foreign, i.e., it originates from an external Rust
280                 // crate. Since we don't know whether this crate will be linked dynamically or
281                 // statically in the final application, we always mark such symbols as 'dllimport'.
282                 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
283                 // to make things work.
284                 //
285                 // However, in some scenarios we defer emission of statics to downstream
286                 // crates, so there are cases where a static with an upstream DefId
287                 // is actually present in the current crate. We can find out via the
288                 // is_codegened_item query.
289                 if !self.tcx.is_codegened_item(def_id) {
290                     unsafe {
291                         llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
292                     }
293                 }
294             }
295             g
296         };
297
298         if self.use_dll_storage_attrs && self.tcx.is_dllimport_foreign_item(def_id) {
299             // For foreign (native) libs we know the exact storage type to use.
300             unsafe {
301                 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
302             }
303         }
304
305         self.instances.borrow_mut().insert(instance, g);
306         g
307     }
308 }
309
310 impl StaticMethods for CodegenCx<'ll, 'tcx> {
311     fn static_addr_of(
312         &self,
313         cv: &'ll Value,
314         align: Align,
315         kind: Option<&str>,
316     ) -> &'ll Value {
317         if let Some(&gv) = self.const_globals.borrow().get(&cv) {
318             unsafe {
319                 // Upgrade the alignment in cases where the same constant is used with different
320                 // alignment requirements
321                 let llalign = align.bytes() as u32;
322                 if llalign > llvm::LLVMGetAlignment(gv) {
323                     llvm::LLVMSetAlignment(gv, llalign);
324                 }
325             }
326             return gv;
327         }
328         let gv = self.static_addr_of_mut(cv, align, kind);
329         unsafe {
330             llvm::LLVMSetGlobalConstant(gv, True);
331         }
332         self.const_globals.borrow_mut().insert(cv, gv);
333         gv
334     }
335
336     fn codegen_static(
337         &self,
338         def_id: DefId,
339         is_mutable: bool,
340     ) {
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.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 empty_string = const_cstr!("");
371                 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
372                 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
373                 llvm::LLVMSetValueName(g, empty_string.as_ptr());
374
375                 let linkage = llvm::LLVMRustGetLinkage(g);
376                 let visibility = llvm::LLVMRustGetVisibility(g);
377
378                 let new_g = llvm::LLVMRustGetOrInsertGlobal(
379                     self.llmod, name_string.as_ptr(), val_llty);
380
381                 llvm::LLVMRustSetLinkage(new_g, linkage);
382                 llvm::LLVMRustSetVisibility(new_g, visibility);
383
384                 // To avoid breaking any invariants, we leave around the old
385                 // global for the moment; we'll replace all references to it
386                 // with the new global later. (See base::codegen_backend.)
387                 self.statics_to_rauw.borrow_mut().push((g, new_g));
388                 new_g
389             };
390             set_global_alignment(&self, g, self.align_of(ty));
391             llvm::LLVMSetInitializer(g, v);
392
393             // As an optimization, all shared statics which do not have interior
394             // mutability are placed into read-only memory.
395             if !is_mutable {
396                 if self.type_is_freeze(ty) {
397                     llvm::LLVMSetGlobalConstant(g, llvm::True);
398                 }
399             }
400
401             debuginfo::create_global_var_metadata(&self, def_id, g);
402
403             if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
404                 llvm::set_thread_local_mode(g, self.tls_model);
405
406                 // Do not allow LLVM to change the alignment of a TLS on macOS.
407                 //
408                 // By default a global's alignment can be freely increased.
409                 // This allows LLVM to generate more performant instructions
410                 // e.g., using load-aligned into a SIMD register.
411                 //
412                 // However, on macOS 10.10 or below, the dynamic linker does not
413                 // respect any alignment given on the TLS (radar 24221680).
414                 // This will violate the alignment assumption, and causing segfault at runtime.
415                 //
416                 // This bug is very easy to trigger. In `println!` and `panic!`,
417                 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
418                 // which the values would be `mem::replace`d on initialization.
419                 // The implementation of `mem::replace` will use SIMD
420                 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
421                 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
422                 // which macOS's dyld disregarded and causing crashes
423                 // (see issues #51794, #51758, #50867, #48866 and #44056).
424                 //
425                 // To workaround the bug, we trick LLVM into not increasing
426                 // the global's alignment by explicitly assigning a section to it
427                 // (equivalent to automatically generating a `#[link_section]` attribute).
428                 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
429                 // of `lib/IR/Globals.cpp` for why this works.
430                 //
431                 // When the alignment is not increased, the optimized `mem::replace`
432                 // will use load-unaligned instructions instead, and thus avoiding the crash.
433                 //
434                 // We could remove this hack whenever we decide to drop macOS 10.10 support.
435                 if self.tcx.sess.target.target.options.is_like_osx {
436                     let sect_name = if alloc.bytes.iter().all(|b| *b == 0) {
437                         CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_bss\0")
438                     } else {
439                         CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_data\0")
440                     };
441                     llvm::LLVMSetSection(g, sect_name.as_ptr());
442                 }
443             }
444
445
446             // Wasm statics with custom link sections get special treatment as they
447             // go into custom sections of the wasm executable.
448             if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
449                 if let Some(section) = attrs.link_section {
450                     let section = llvm::LLVMMDStringInContext(
451                         self.llcx,
452                         section.as_str().as_ptr() as *const _,
453                         section.as_str().len() as c_uint,
454                     );
455                     let alloc = llvm::LLVMMDStringInContext(
456                         self.llcx,
457                         alloc.bytes.as_ptr() as *const _,
458                         alloc.bytes.len() as c_uint,
459                     );
460                     let data = [section, alloc];
461                     let meta = llvm::LLVMMDNodeInContext(self.llcx, data.as_ptr(), 2);
462                     llvm::LLVMAddNamedMetadataOperand(
463                         self.llmod,
464                         "wasm.custom_sections\0".as_ptr() as *const _,
465                         meta,
466                     );
467                 }
468             } else {
469                 base::set_link_section(g, &attrs);
470             }
471
472             if attrs.flags.contains(CodegenFnAttrFlags::USED) {
473                 // This static will be stored in the llvm.used variable which is an array of i8*
474                 let cast = llvm::LLVMConstPointerCast(g, self.type_i8p());
475                 self.used_statics.borrow_mut().push(cast);
476             }
477         }
478     }
479 }