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