]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/consts.rs
49f30d6757494677c6f3a44d01c2fbc47352bbfa
[rust.git] / src / librustc_codegen_llvm / consts.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use libc::c_uint;
12 use llvm::{self, SetUnnamedAddr, True};
13 use rustc::hir::def_id::DefId;
14 use rustc::hir::Node;
15 use debuginfo;
16 use base;
17 use monomorphize::MonoItem;
18 use common::CodegenCx;
19 use declare;
20 use monomorphize::Instance;
21 use syntax_pos::Span;
22 use syntax_pos::symbol::LocalInternedString;
23 use type_::Type;
24 use type_of::LayoutLlvmExt;
25 use value::Value;
26 use rustc::ty::{self, Ty};
27 use interfaces::{CommonWriteMethods, TypeMethods};
28
29 use rustc::ty::layout::{Align, LayoutOf};
30
31 use rustc::hir::{self, CodegenFnAttrs, CodegenFnAttrFlags};
32
33 use std::ffi::{CStr, CString};
34
35 pub fn ptrcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
36     unsafe {
37         llvm::LLVMConstPointerCast(val, ty)
38     }
39 }
40
41 pub fn bitcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
42     unsafe {
43         llvm::LLVMConstBitCast(val, ty)
44     }
45 }
46
47 fn set_global_alignment(cx: &CodegenCx<'ll, '_>,
48                         gv: &'ll Value,
49                         mut align: Align) {
50     // The target may require greater alignment for globals than the type does.
51     // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
52     // which can force it to be smaller.  Rust doesn't support this yet.
53     if let Some(min) = cx.sess().target.target.options.min_global_align {
54         match ty::layout::Align::from_bits(min, min) {
55             Ok(min) => align = align.max(min),
56             Err(err) => {
57                 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
58             }
59         }
60     }
61     unsafe {
62         llvm::LLVMSetAlignment(gv, align.abi() as u32);
63     }
64 }
65
66 pub fn addr_of_mut(
67     cx: &CodegenCx<'ll, '_>,
68     cv: &'ll Value,
69     align: Align,
70     kind: Option<&str>,
71 ) -> &'ll Value {
72     unsafe {
73         let gv = match kind {
74             Some(kind) if !cx.tcx.sess.fewer_names() => {
75                 let name = cx.generate_local_symbol_name(kind);
76                 let gv = declare::define_global(cx, &name[..],
77                     cx.val_ty(cv)).unwrap_or_else(||{
78                         bug!("symbol `{}` is already defined", name);
79                 });
80                 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
81                 gv
82             },
83             _ => declare::define_private_global(cx, cx.val_ty(cv)),
84         };
85         llvm::LLVMSetInitializer(gv, cv);
86         set_global_alignment(cx, gv, align);
87         SetUnnamedAddr(gv, true);
88         gv
89     }
90 }
91
92 pub fn addr_of(
93     cx: &CodegenCx<'ll, '_>,
94     cv: &'ll Value,
95     align: Align,
96     kind: Option<&str>,
97 ) -> &'ll Value {
98     if let Some(&gv) = cx.const_globals.borrow().get(&cv) {
99         unsafe {
100             // Upgrade the alignment in cases where the same constant is used with different
101             // alignment requirements
102             let llalign = align.abi() as u32;
103             if llalign > llvm::LLVMGetAlignment(gv) {
104                 llvm::LLVMSetAlignment(gv, llalign);
105             }
106         }
107         return gv;
108     }
109     let gv = addr_of_mut(cx, cv, align, kind);
110     unsafe {
111         llvm::LLVMSetGlobalConstant(gv, True);
112     }
113     cx.const_globals.borrow_mut().insert(cv, gv);
114     gv
115 }
116
117 pub fn get_static(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll Value {
118     let instance = Instance::mono(cx.tcx, def_id);
119     if let Some(&g) = cx.instances.borrow().get(&instance) {
120         return g;
121     }
122
123     let defined_in_current_codegen_unit = cx.codegen_unit
124                                             .items()
125                                             .contains_key(&MonoItem::Static(def_id));
126     assert!(!defined_in_current_codegen_unit,
127             "consts::get_static() should always hit the cache for \
128              statics defined in the same CGU, but did not for `{:?}`",
129             def_id);
130
131     let ty = instance.ty(cx.tcx);
132     let sym = cx.tcx.symbol_name(instance).as_str();
133
134     debug!("get_static: sym={} instance={:?}", sym, instance);
135
136     let g = if let Some(id) = cx.tcx.hir.as_local_node_id(def_id) {
137
138         let llty = cx.layout_of(ty).llvm_type(cx);
139         let (g, attrs) = match cx.tcx.hir.get(id) {
140             Node::Item(&hir::Item {
141                 ref attrs, span, node: hir::ItemKind::Static(..), ..
142             }) => {
143                 if declare::get_declared_value(cx, &sym[..]).is_some() {
144                     span_bug!(span, "Conflicting symbol names for static?");
145                 }
146
147                 let g = declare::define_global(cx, &sym[..], llty).unwrap();
148
149                 if !cx.tcx.is_reachable_non_generic(def_id) {
150                     unsafe {
151                         llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
152                     }
153                 }
154
155                 (g, attrs)
156             }
157
158             Node::ForeignItem(&hir::ForeignItem {
159                 ref attrs, span, node: hir::ForeignItemKind::Static(..), ..
160             }) => {
161                 let fn_attrs = cx.tcx.codegen_fn_attrs(def_id);
162                 (check_and_apply_linkage(cx, &fn_attrs, ty, sym, Some(span)), attrs)
163             }
164
165             item => bug!("get_static: expected static, found {:?}", item)
166         };
167
168         debug!("get_static: sym={} attrs={:?}", sym, attrs);
169
170         for attr in attrs {
171             if attr.check_name("thread_local") {
172                 llvm::set_thread_local_mode(g, cx.tls_model);
173             }
174         }
175
176         g
177     } else {
178         // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
179         debug!("get_static: sym={} item_attr={:?}", sym, cx.tcx.item_attrs(def_id));
180
181         let attrs = cx.tcx.codegen_fn_attrs(def_id);
182         let g = check_and_apply_linkage(cx, &attrs, ty, sym, None);
183
184         // Thread-local statics in some other crate need to *always* be linked
185         // against in a thread-local fashion, so we need to be sure to apply the
186         // thread-local attribute locally if it was present remotely. If we
187         // don't do this then linker errors can be generated where the linker
188         // complains that one object files has a thread local version of the
189         // symbol and another one doesn't.
190         if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
191             llvm::set_thread_local_mode(g, cx.tls_model);
192         }
193
194         let needs_dll_storage_attr =
195             cx.use_dll_storage_attrs && !cx.tcx.is_foreign_item(def_id) &&
196             // ThinLTO can't handle this workaround in all cases, so we don't
197             // emit the attrs. Instead we make them unnecessary by disallowing
198             // dynamic linking when cross-language LTO is enabled.
199             !cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled();
200
201         // If this assertion triggers, there's something wrong with commandline
202         // argument validation.
203         debug_assert!(!(cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
204                         cx.tcx.sess.target.target.options.is_like_msvc &&
205                         cx.tcx.sess.opts.cg.prefer_dynamic));
206
207         if needs_dll_storage_attr {
208             // This item is external but not foreign, i.e. it originates from an external Rust
209             // crate. Since we don't know whether this crate will be linked dynamically or
210             // statically in the final application, we always mark such symbols as 'dllimport'.
211             // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs to
212             // make things work.
213             //
214             // However, in some scenarios we defer emission of statics to downstream
215             // crates, so there are cases where a static with an upstream DefId
216             // is actually present in the current crate. We can find out via the
217             // is_codegened_item query.
218             if !cx.tcx.is_codegened_item(def_id) {
219                 unsafe {
220                     llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
221                 }
222             }
223         }
224         g
225     };
226
227     if cx.use_dll_storage_attrs && cx.tcx.is_dllimport_foreign_item(def_id) {
228         // For foreign (native) libs we know the exact storage type to use.
229         unsafe {
230             llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
231         }
232     }
233
234     cx.instances.borrow_mut().insert(instance, g);
235     g
236 }
237
238 fn check_and_apply_linkage(
239     cx: &CodegenCx<'ll, 'tcx>,
240     attrs: &CodegenFnAttrs,
241     ty: Ty<'tcx>,
242     sym: LocalInternedString,
243     span: Option<Span>
244 ) -> &'ll Value {
245     let llty = cx.layout_of(ty).llvm_type(cx);
246     if let Some(linkage) = attrs.linkage {
247         debug!("get_static: sym={} linkage={:?}", sym, linkage);
248
249         // If this is a static with a linkage specified, then we need to handle
250         // it a little specially. The typesystem prevents things like &T and
251         // extern "C" fn() from being non-null, so we can't just declare a
252         // static and call it a day. Some linkages (like weak) will make it such
253         // that the static actually has a null value.
254         let llty2 = if let ty::RawPtr(ref mt) = ty.sty {
255             cx.layout_of(mt.ty).llvm_type(cx)
256         } else {
257             if let Some(span) = span {
258                 cx.sess().span_fatal(span, "must have type `*const T` or `*mut T`")
259             } else {
260                 bug!("must have type `*const T` or `*mut T`")
261             }
262         };
263         unsafe {
264             // Declare a symbol `foo` with the desired linkage.
265             let g1 = declare::declare_global(cx, &sym, llty2);
266             llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
267
268             // Declare an internal global `extern_with_linkage_foo` which
269             // is initialized with the address of `foo`.  If `foo` is
270             // discarded during linking (for example, if `foo` has weak
271             // linkage and there are no definitions), then
272             // `extern_with_linkage_foo` will instead be initialized to
273             // zero.
274             let mut real_name = "_rust_extern_with_linkage_".to_string();
275             real_name.push_str(&sym);
276             let g2 = declare::define_global(cx, &real_name, llty).unwrap_or_else(||{
277                 if let Some(span) = span {
278                     cx.sess().span_fatal(
279                         span,
280                         &format!("symbol `{}` is already defined", &sym)
281                     )
282                 } else {
283                     bug!("symbol `{}` is already defined", &sym)
284                 }
285             });
286             llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
287             llvm::LLVMSetInitializer(g2, g1);
288             g2
289         }
290     } else {
291         // Generate an external declaration.
292         // FIXME(nagisa): investigate whether it can be changed into define_global
293         declare::declare_global(cx, &sym, llty)
294     }
295 }
296
297 pub fn codegen_static<'a, 'tcx>(
298     cx: &CodegenCx<'a, 'tcx>,
299     def_id: DefId,
300     is_mutable: bool,
301 ) {
302     unsafe {
303         let attrs = cx.tcx.codegen_fn_attrs(def_id);
304
305         let (v, alloc) = match ::mir::codegen_static_initializer(cx, def_id) {
306             Ok(v) => v,
307             // Error has already been reported
308             Err(_) => return,
309         };
310
311         let g = get_static(cx, def_id);
312
313         // boolean SSA values are i1, but they have to be stored in i8 slots,
314         // otherwise some LLVM optimization passes don't work as expected
315         let mut val_llty = cx.val_ty(v);
316         let v = if val_llty == cx.i1() {
317             val_llty = cx.i8();
318             llvm::LLVMConstZExt(v, val_llty)
319         } else {
320             v
321         };
322
323         let instance = Instance::mono(cx.tcx, def_id);
324         let ty = instance.ty(cx.tcx);
325         let llty = cx.layout_of(ty).llvm_type(cx);
326         let g = if val_llty == llty {
327             g
328         } else {
329             // If we created the global with the wrong type,
330             // correct the type.
331             let empty_string = const_cstr!("");
332             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
333             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
334             llvm::LLVMSetValueName(g, empty_string.as_ptr());
335
336             let linkage = llvm::LLVMRustGetLinkage(g);
337             let visibility = llvm::LLVMRustGetVisibility(g);
338
339             let new_g = llvm::LLVMRustGetOrInsertGlobal(
340                 cx.llmod, name_string.as_ptr(), val_llty);
341
342             llvm::LLVMRustSetLinkage(new_g, linkage);
343             llvm::LLVMRustSetVisibility(new_g, visibility);
344
345             // To avoid breaking any invariants, we leave around the old
346             // global for the moment; we'll replace all references to it
347             // with the new global later. (See base::codegen_backend.)
348             cx.statics_to_rauw.borrow_mut().push((g, new_g));
349             new_g
350         };
351         set_global_alignment(cx, g, cx.align_of(ty));
352         llvm::LLVMSetInitializer(g, v);
353
354         // As an optimization, all shared statics which do not have interior
355         // mutability are placed into read-only memory.
356         if !is_mutable {
357             if cx.type_is_freeze(ty) {
358                 llvm::LLVMSetGlobalConstant(g, llvm::True);
359             }
360         }
361
362         debuginfo::create_global_var_metadata(cx, def_id, g);
363
364         if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
365             llvm::set_thread_local_mode(g, cx.tls_model);
366
367             // Do not allow LLVM to change the alignment of a TLS on macOS.
368             //
369             // By default a global's alignment can be freely increased.
370             // This allows LLVM to generate more performant instructions
371             // e.g. using load-aligned into a SIMD register.
372             //
373             // However, on macOS 10.10 or below, the dynamic linker does not
374             // respect any alignment given on the TLS (radar 24221680).
375             // This will violate the alignment assumption, and causing segfault at runtime.
376             //
377             // This bug is very easy to trigger. In `println!` and `panic!`,
378             // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
379             // which the values would be `mem::replace`d on initialization.
380             // The implementation of `mem::replace` will use SIMD
381             // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
382             // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
383             // which macOS's dyld disregarded and causing crashes
384             // (see issues #51794, #51758, #50867, #48866 and #44056).
385             //
386             // To workaround the bug, we trick LLVM into not increasing
387             // the global's alignment by explicitly assigning a section to it
388             // (equivalent to automatically generating a `#[link_section]` attribute).
389             // See the comment in the `GlobalValue::canIncreaseAlignment()` function
390             // of `lib/IR/Globals.cpp` for why this works.
391             //
392             // When the alignment is not increased, the optimized `mem::replace`
393             // will use load-unaligned instructions instead, and thus avoiding the crash.
394             //
395             // We could remove this hack whenever we decide to drop macOS 10.10 support.
396             if cx.tcx.sess.target.target.options.is_like_osx {
397                 let sect_name = if alloc.bytes.iter().all(|b| *b == 0) {
398                     CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_bss\0")
399                 } else {
400                     CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_data\0")
401                 };
402                 llvm::LLVMSetSection(g, sect_name.as_ptr());
403             }
404         }
405
406
407         // Wasm statics with custom link sections get special treatment as they
408         // go into custom sections of the wasm executable.
409         if cx.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
410             if let Some(section) = attrs.link_section {
411                 let section = llvm::LLVMMDStringInContext(
412                     cx.llcx,
413                     section.as_str().as_ptr() as *const _,
414                     section.as_str().len() as c_uint,
415                 );
416                 let alloc = llvm::LLVMMDStringInContext(
417                     cx.llcx,
418                     alloc.bytes.as_ptr() as *const _,
419                     alloc.bytes.len() as c_uint,
420                 );
421                 let data = [section, alloc];
422                 let meta = llvm::LLVMMDNodeInContext(cx.llcx, data.as_ptr(), 2);
423                 llvm::LLVMAddNamedMetadataOperand(
424                     cx.llmod,
425                     "wasm.custom_sections\0".as_ptr() as *const _,
426                     meta,
427                 );
428             }
429         } else {
430             base::set_link_section(g, &attrs);
431         }
432
433         if attrs.flags.contains(CodegenFnAttrFlags::USED) {
434             // This static will be stored in the llvm.used variable which is an array of i8*
435             let cast = llvm::LLVMConstPointerCast(g, cx.i8p());
436             cx.used_statics.borrow_mut().push(cast);
437         }
438     }
439 }