]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/consts.rs
Fixes doc important trait display on mobile
[rust.git] / src / librustc_trans / 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 llvm;
12 use llvm::{SetUnnamedAddr};
13 use llvm::{ValueRef, True};
14 use rustc::hir::def_id::DefId;
15 use rustc::hir::map as hir_map;
16 use rustc::middle::const_val::ConstEvalErr;
17 use debuginfo;
18 use base;
19 use trans_item::{TransItem, TransItemExt};
20 use common::{self, CrateContext, 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;
29
30 use std::ffi::{CStr, CString};
31 use syntax::ast;
32 use syntax::attr;
33
34 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
35     unsafe {
36         llvm::LLVMConstPointerCast(val, ty.to_ref())
37     }
38 }
39
40 pub fn bitcast(val: ValueRef, ty: Type) -> ValueRef {
41     unsafe {
42         llvm::LLVMConstBitCast(val, ty.to_ref())
43     }
44 }
45
46 fn set_global_alignment(ccx: &CrateContext,
47                         gv: ValueRef,
48                         mut align: Align) {
49     // The target may require greater alignment for globals than the type does.
50     // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
51     // which can force it to be smaller.  Rust doesn't support this yet.
52     if let Some(min) = ccx.sess().target.target.options.min_global_align {
53         match ty::layout::Align::from_bits(min, min) {
54             Ok(min) => align = align.max(min),
55             Err(err) => {
56                 ccx.sess().err(&format!("invalid minimum global alignment: {}", err));
57             }
58         }
59     }
60     unsafe {
61         llvm::LLVMSetAlignment(gv, align.abi() as u32);
62     }
63 }
64
65 pub fn addr_of_mut(ccx: &CrateContext,
66                    cv: ValueRef,
67                    align: Align,
68                    kind: &str)
69                     -> ValueRef {
70     unsafe {
71         let name = ccx.generate_local_symbol_name(kind);
72         let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
73             bug!("symbol `{}` is already defined", name);
74         });
75         llvm::LLVMSetInitializer(gv, cv);
76         set_global_alignment(ccx, gv, align);
77         llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
78         SetUnnamedAddr(gv, true);
79         gv
80     }
81 }
82
83 pub fn addr_of(ccx: &CrateContext,
84                cv: ValueRef,
85                align: Align,
86                kind: &str)
87                -> ValueRef {
88     if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
89         unsafe {
90             // Upgrade the alignment in cases where the same constant is used with different
91             // alignment requirements
92             let llalign = align.abi() as u32;
93             if llalign > llvm::LLVMGetAlignment(gv) {
94                 llvm::LLVMSetAlignment(gv, llalign);
95             }
96         }
97         return gv;
98     }
99     let gv = addr_of_mut(ccx, cv, align, kind);
100     unsafe {
101         llvm::LLVMSetGlobalConstant(gv, True);
102     }
103     ccx.const_globals().borrow_mut().insert(cv, gv);
104     gv
105 }
106
107 pub fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef {
108     let instance = Instance::mono(ccx.tcx(), def_id);
109     if let Some(&g) = ccx.instances().borrow().get(&instance) {
110         return g;
111     }
112
113     let ty = common::instance_ty(ccx.tcx(), &instance);
114     let g = if let Some(id) = ccx.tcx().hir.as_local_node_id(def_id) {
115
116         let llty = ccx.layout_of(ty).llvm_type(ccx);
117         let (g, attrs) = match ccx.tcx().hir.get(id) {
118             hir_map::NodeItem(&hir::Item {
119                 ref attrs, span, node: hir::ItemStatic(..), ..
120             }) => {
121                 let sym = TransItem::Static(id).symbol_name(ccx.tcx());
122
123                 let defined_in_current_codegen_unit = ccx.codegen_unit()
124                                                          .items()
125                                                          .contains_key(&TransItem::Static(id));
126                 assert!(!defined_in_current_codegen_unit);
127
128                 if declare::get_declared_value(ccx, &sym[..]).is_some() {
129                     span_bug!(span, "trans: Conflicting symbol names for static?");
130                 }
131
132                 let g = declare::define_global(ccx, &sym[..], llty).unwrap();
133
134                 if !ccx.tcx().is_exported_symbol(def_id) {
135                     unsafe {
136                         llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
137                     }
138                 }
139
140                 (g, attrs)
141             }
142
143             hir_map::NodeForeignItem(&hir::ForeignItem {
144                 ref attrs, span, node: hir::ForeignItemStatic(..), ..
145             }) => {
146                 let sym = ccx.tcx().symbol_name(instance);
147                 let g = if let Some(name) =
148                         attr::first_attr_value_str_by_name(&attrs, "linkage") {
149                     // If this is a static with a linkage specified, then we need to handle
150                     // it a little specially. The typesystem prevents things like &T and
151                     // extern "C" fn() from being non-null, so we can't just declare a
152                     // static and call it a day. Some linkages (like weak) will make it such
153                     // that the static actually has a null value.
154                     let linkage = match base::linkage_by_name(&name.as_str()) {
155                         Some(linkage) => linkage,
156                         None => {
157                             ccx.sess().span_fatal(span, "invalid linkage specified");
158                         }
159                     };
160                     let llty2 = match ty.sty {
161                         ty::TyRawPtr(ref mt) => ccx.layout_of(mt.ty).llvm_type(ccx),
162                         _ => {
163                             ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
164                         }
165                     };
166                     unsafe {
167                         // Declare a symbol `foo` with the desired linkage.
168                         let g1 = declare::declare_global(ccx, &sym, llty2);
169                         llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
170
171                         // Declare an internal global `extern_with_linkage_foo` which
172                         // is initialized with the address of `foo`.  If `foo` is
173                         // discarded during linking (for example, if `foo` has weak
174                         // linkage and there are no definitions), then
175                         // `extern_with_linkage_foo` will instead be initialized to
176                         // zero.
177                         let mut real_name = "_rust_extern_with_linkage_".to_string();
178                         real_name.push_str(&sym);
179                         let g2 = declare::define_global(ccx, &real_name, llty).unwrap_or_else(||{
180                             ccx.sess().span_fatal(span,
181                                 &format!("symbol `{}` is already defined", &sym))
182                         });
183                         llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
184                         llvm::LLVMSetInitializer(g2, g1);
185                         g2
186                     }
187                 } else {
188                     // Generate an external declaration.
189                     declare::declare_global(ccx, &sym, llty)
190                 };
191
192                 (g, attrs)
193             }
194
195             item => bug!("get_static: expected static, found {:?}", item)
196         };
197
198         for attr in attrs {
199             if attr.check_name("thread_local") {
200                 llvm::set_thread_local_mode(g, ccx.tls_model());
201             }
202         }
203
204         g
205     } else {
206         let sym = ccx.tcx().symbol_name(instance);
207
208         // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
209         // FIXME(nagisa): investigate whether it can be changed into define_global
210         let g = declare::declare_global(ccx, &sym, ccx.layout_of(ty).llvm_type(ccx));
211         // Thread-local statics in some other crate need to *always* be linked
212         // against in a thread-local fashion, so we need to be sure to apply the
213         // thread-local attribute locally if it was present remotely. If we
214         // don't do this then linker errors can be generated where the linker
215         // complains that one object files has a thread local version of the
216         // symbol and another one doesn't.
217         for attr in ccx.tcx().get_attrs(def_id).iter() {
218             if attr.check_name("thread_local") {
219                 llvm::set_thread_local_mode(g, ccx.tls_model());
220             }
221         }
222         if ccx.use_dll_storage_attrs() && !ccx.tcx().is_foreign_item(def_id) {
223             // This item is external but not foreign, i.e. it originates from an external Rust
224             // crate. Since we don't know whether this crate will be linked dynamically or
225             // statically in the final application, we always mark such symbols as 'dllimport'.
226             // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs to
227             // make things work.
228             unsafe {
229                 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
230             }
231         }
232         g
233     };
234
235     if ccx.use_dll_storage_attrs() && ccx.tcx().is_dllimport_foreign_item(def_id) {
236         // For foreign (native) libs we know the exact storage type to use.
237         unsafe {
238             llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
239         }
240     }
241
242     ccx.instances().borrow_mut().insert(instance, g);
243     ccx.statics().borrow_mut().insert(g, def_id);
244     g
245 }
246
247 pub fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
248                               m: hir::Mutability,
249                               id: ast::NodeId,
250                               attrs: &[ast::Attribute])
251                               -> Result<ValueRef, ConstEvalErr<'tcx>> {
252     unsafe {
253         let def_id = ccx.tcx().hir.local_def_id(id);
254         let g = get_static(ccx, def_id);
255
256         let v = ::mir::trans_static_initializer(ccx, def_id)?;
257
258         // boolean SSA values are i1, but they have to be stored in i8 slots,
259         // otherwise some LLVM optimization passes don't work as expected
260         let mut val_llty = val_ty(v);
261         let v = if val_llty == Type::i1(ccx) {
262             val_llty = Type::i8(ccx);
263             llvm::LLVMConstZExt(v, val_llty.to_ref())
264         } else {
265             v
266         };
267
268         let instance = Instance::mono(ccx.tcx(), def_id);
269         let ty = common::instance_ty(ccx.tcx(), &instance);
270         let llty = ccx.layout_of(ty).llvm_type(ccx);
271         let g = if val_llty == llty {
272             g
273         } else {
274             // If we created the global with the wrong type,
275             // correct the type.
276             let empty_string = CString::new("").unwrap();
277             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
278             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
279             llvm::LLVMSetValueName(g, empty_string.as_ptr());
280
281             let linkage = llvm::LLVMRustGetLinkage(g);
282             let visibility = llvm::LLVMRustGetVisibility(g);
283
284             let new_g = llvm::LLVMRustGetOrInsertGlobal(
285                 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
286
287             llvm::LLVMRustSetLinkage(new_g, linkage);
288             llvm::LLVMRustSetVisibility(new_g, visibility);
289
290             // To avoid breaking any invariants, we leave around the old
291             // global for the moment; we'll replace all references to it
292             // with the new global later. (See base::trans_crate.)
293             ccx.statics_to_rauw().borrow_mut().push((g, new_g));
294             new_g
295         };
296         set_global_alignment(ccx, g, ccx.align_of(ty));
297         llvm::LLVMSetInitializer(g, v);
298
299         // As an optimization, all shared statics which do not have interior
300         // mutability are placed into read-only memory.
301         if m != hir::MutMutable {
302             if ccx.shared().type_is_freeze(ty) {
303                 llvm::LLVMSetGlobalConstant(g, llvm::True);
304             }
305         }
306
307         debuginfo::create_global_var_metadata(ccx, id, g);
308
309         if attr::contains_name(attrs, "thread_local") {
310             llvm::set_thread_local_mode(g, ccx.tls_model());
311         }
312
313         base::set_link_section(ccx, g, attrs);
314
315         if attr::contains_name(attrs, "used") {
316             // This static will be stored in the llvm.used variable which is an array of i8*
317             let cast = llvm::LLVMConstPointerCast(g, Type::i8p(ccx).to_ref());
318             ccx.used_statics().borrow_mut().push(cast);
319         }
320
321         Ok(g)
322     }
323 }