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