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