]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/consts.rs
15f7132e52d2f66b8e8dd18f39268dcfca58152d
[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
12 use llvm;
13 use llvm::{SetUnnamedAddr};
14 use llvm::{ValueRef, True};
15 use rustc_const_eval::ConstEvalErr;
16 use rustc::hir::def_id::DefId;
17 use rustc::hir::map as hir_map;
18 use {debuginfo, machine};
19 use base::{self, push_ctxt};
20 use trans_item::TransItem;
21 use common::{CrateContext, val_ty};
22 use declare;
23 use monomorphize::{Instance};
24 use type_::Type;
25 use type_of;
26 use rustc::ty;
27
28 use rustc::hir;
29
30 use std::ffi::{CStr, CString};
31 use syntax::ast;
32 use syntax::attr;
33 use syntax::parse::token;
34
35 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
36     unsafe {
37         llvm::LLVMConstPointerCast(val, ty.to_ref())
38     }
39 }
40
41 pub fn addr_of_mut(ccx: &CrateContext,
42                    cv: ValueRef,
43                    align: machine::llalign,
44                    kind: &str)
45                     -> ValueRef {
46     unsafe {
47         // FIXME: this totally needs a better name generation scheme, perhaps a simple global
48         // counter? Also most other uses of gensym in trans.
49         let gsym = token::gensym("_");
50         let name = format!("{}{}", kind, gsym.0);
51         let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
52             bug!("symbol `{}` is already defined", name);
53         });
54         llvm::LLVMSetInitializer(gv, cv);
55         llvm::LLVMSetAlignment(gv, align);
56         llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
57         SetUnnamedAddr(gv, true);
58         gv
59     }
60 }
61
62 pub fn addr_of(ccx: &CrateContext,
63                cv: ValueRef,
64                align: machine::llalign,
65                kind: &str)
66                -> ValueRef {
67     if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
68         unsafe {
69             // Upgrade the alignment in cases where the same constant is used with different
70             // alignment requirements
71             if align > llvm::LLVMGetAlignment(gv) {
72                 llvm::LLVMSetAlignment(gv, align);
73             }
74         }
75         return gv;
76     }
77     let gv = addr_of_mut(ccx, cv, align, kind);
78     unsafe {
79         llvm::LLVMSetGlobalConstant(gv, True);
80     }
81     ccx.const_globals().borrow_mut().insert(cv, gv);
82     gv
83 }
84
85 pub fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef {
86     let instance = Instance::mono(ccx.shared(), def_id);
87     if let Some(&g) = ccx.instances().borrow().get(&instance) {
88         return g;
89     }
90
91     let ty = ccx.tcx().lookup_item_type(def_id).ty;
92     let g = if let Some(id) = ccx.tcx().map.as_local_node_id(def_id) {
93
94         let llty = type_of::type_of(ccx, ty);
95         let (g, attrs) = match ccx.tcx().map.get(id) {
96             hir_map::NodeItem(&hir::Item {
97                 ref attrs, span, node: hir::ItemStatic(..), ..
98             }) => {
99                 let sym = ccx.symbol_map()
100                              .get(TransItem::Static(id))
101                              .expect("Local statics should always be in the SymbolMap");
102                 // Make sure that this is never executed for something inlined.
103                 assert!(!ccx.tcx().map.is_inlined_node_id(id));
104
105                 let defined_in_current_codegen_unit = ccx.codegen_unit()
106                                                          .items()
107                                                          .contains_key(&TransItem::Static(id));
108                 assert!(!defined_in_current_codegen_unit);
109
110                 if declare::get_declared_value(ccx, sym).is_some() {
111                     span_bug!(span, "trans: Conflicting symbol names for static?");
112                 }
113
114                 let g = declare::define_global(ccx, sym, llty).unwrap();
115
116                 (g, attrs)
117             }
118
119             hir_map::NodeForeignItem(&hir::ForeignItem {
120                 ref attrs, span, node: hir::ForeignItemStatic(..), ..
121             }) => {
122                 let sym = instance.symbol_name(ccx.shared());
123                 let g = if let Some(name) =
124                         attr::first_attr_value_str_by_name(&attrs, "linkage") {
125                     // If this is a static with a linkage specified, then we need to handle
126                     // it a little specially. The typesystem prevents things like &T and
127                     // extern "C" fn() from being non-null, so we can't just declare a
128                     // static and call it a day. Some linkages (like weak) will make it such
129                     // that the static actually has a null value.
130                     let linkage = match base::llvm_linkage_by_name(&name) {
131                         Some(linkage) => linkage,
132                         None => {
133                             ccx.sess().span_fatal(span, "invalid linkage specified");
134                         }
135                     };
136                     let llty2 = match ty.sty {
137                         ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
138                         _ => {
139                             ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
140                         }
141                     };
142                     unsafe {
143                         // Declare a symbol `foo` with the desired linkage.
144                         let g1 = declare::declare_global(ccx, &sym, llty2);
145                         llvm::LLVMRustSetLinkage(g1, linkage);
146
147                         // Declare an internal global `extern_with_linkage_foo` which
148                         // is initialized with the address of `foo`.  If `foo` is
149                         // discarded during linking (for example, if `foo` has weak
150                         // linkage and there are no definitions), then
151                         // `extern_with_linkage_foo` will instead be initialized to
152                         // zero.
153                         let mut real_name = "_rust_extern_with_linkage_".to_string();
154                         real_name.push_str(&sym);
155                         let g2 = declare::define_global(ccx, &real_name, llty).unwrap_or_else(||{
156                             ccx.sess().span_fatal(span,
157                                 &format!("symbol `{}` is already defined", &sym))
158                         });
159                         llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
160                         llvm::LLVMSetInitializer(g2, g1);
161                         g2
162                     }
163                 } else {
164                     // Generate an external declaration.
165                     declare::declare_global(ccx, &sym, llty)
166                 };
167
168                 (g, attrs)
169             }
170
171             item => bug!("get_static: expected static, found {:?}", item)
172         };
173
174         for attr in attrs {
175             if attr.check_name("thread_local") {
176                 llvm::set_thread_local(g, true);
177             }
178         }
179
180         g
181     } else {
182         let sym = instance.symbol_name(ccx.shared());
183
184         // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
185         // FIXME(nagisa): investigate whether it can be changed into define_global
186         let g = declare::declare_global(ccx, &sym, type_of::type_of(ccx, ty));
187         // Thread-local statics in some other crate need to *always* be linked
188         // against in a thread-local fashion, so we need to be sure to apply the
189         // thread-local attribute locally if it was present remotely. If we
190         // don't do this then linker errors can be generated where the linker
191         // complains that one object files has a thread local version of the
192         // symbol and another one doesn't.
193         for attr in ccx.tcx().get_attrs(def_id).iter() {
194             if attr.check_name("thread_local") {
195                 llvm::set_thread_local(g, true);
196             }
197         }
198         if ccx.use_dll_storage_attrs() {
199             unsafe {
200                 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
201             }
202         }
203         g
204     };
205
206     ccx.instances().borrow_mut().insert(instance, g);
207     ccx.statics().borrow_mut().insert(g, def_id);
208     g
209 }
210
211 pub fn trans_static(ccx: &CrateContext,
212                     m: hir::Mutability,
213                     id: ast::NodeId,
214                     attrs: &[ast::Attribute])
215                     -> Result<ValueRef, ConstEvalErr> {
216     unsafe {
217         let _icx = push_ctxt("trans_static");
218         let def_id = ccx.tcx().map.local_def_id(id);
219         let g = get_static(ccx, def_id);
220
221         let v = ::mir::trans_static_initializer(ccx, def_id)?;
222
223         // boolean SSA values are i1, but they have to be stored in i8 slots,
224         // otherwise some LLVM optimization passes don't work as expected
225         let mut val_llty = val_ty(v);
226         let v = if val_llty == Type::i1(ccx) {
227             val_llty = Type::i8(ccx);
228             llvm::LLVMConstZExt(v, val_llty.to_ref())
229         } else {
230             v
231         };
232
233         let ty = ccx.tcx().lookup_item_type(def_id).ty;
234         let llty = type_of::type_of(ccx, ty);
235         let g = if val_llty == llty {
236             g
237         } else {
238             // If we created the global with the wrong type,
239             // correct the type.
240             let empty_string = CString::new("").unwrap();
241             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
242             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
243             llvm::LLVMSetValueName(g, empty_string.as_ptr());
244             let new_g = llvm::LLVMRustGetOrInsertGlobal(
245                 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
246             // To avoid breaking any invariants, we leave around the old
247             // global for the moment; we'll replace all references to it
248             // with the new global later. (See base::trans_crate.)
249             ccx.statics_to_rauw().borrow_mut().push((g, new_g));
250             new_g
251         };
252         llvm::LLVMSetAlignment(g, type_of::align_of(ccx, ty));
253         llvm::LLVMSetInitializer(g, v);
254
255         // As an optimization, all shared statics which do not have interior
256         // mutability are placed into read-only memory.
257         if m != hir::MutMutable {
258             let tcontents = ty.type_contents(ccx.tcx());
259             if !tcontents.interior_unsafe() {
260                 llvm::LLVMSetGlobalConstant(g, llvm::True);
261             }
262         }
263
264         debuginfo::create_global_var_metadata(ccx, id, g);
265
266         if attr::contains_name(attrs,
267                                "thread_local") {
268             llvm::set_thread_local(g, true);
269         }
270
271         base::set_link_section(ccx, g, attrs);
272
273         Ok(g)
274     }
275 }