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.
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.
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};
19 use trans_item::TransItem;
20 use common::{self, CrateContext, val_ty};
22 use monomorphize::Instance;
29 use std::ffi::{CStr, CString};
33 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
35 llvm::LLVMConstPointerCast(val, ty.to_ref())
39 pub fn bitcast(val: ValueRef, ty: Type) -> ValueRef {
41 llvm::LLVMConstBitCast(val, ty.to_ref())
45 pub fn addr_of_mut(ccx: &CrateContext,
47 align: machine::llalign,
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);
55 llvm::LLVMSetInitializer(gv, cv);
56 llvm::LLVMSetAlignment(gv, align);
57 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
58 SetUnnamedAddr(gv, true);
63 pub fn addr_of(ccx: &CrateContext,
65 align: machine::llalign,
68 if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
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);
78 let gv = addr_of_mut(ccx, cv, align, kind);
80 llvm::LLVMSetGlobalConstant(gv, True);
82 ccx.const_globals().borrow_mut().insert(cv, gv);
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) {
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) {
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(..), ..
100 let sym = TransItem::Static(id).symbol_name(ccx.tcx());
102 let defined_in_current_codegen_unit = ccx.codegen_unit()
104 .contains_key(&TransItem::Static(id));
105 assert!(!defined_in_current_codegen_unit);
107 if declare::get_declared_value(ccx, &sym[..]).is_some() {
108 span_bug!(span, "trans: Conflicting symbol names for static?");
111 let g = declare::define_global(ccx, &sym[..], llty).unwrap();
113 if !ccx.exported_symbols().local_exports().contains(&id) {
115 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
122 hir_map::NodeForeignItem(&hir::ForeignItem {
123 ref attrs, span, node: hir::ForeignItemStatic(..), ..
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,
136 ccx.sess().span_fatal(span, "invalid linkage specified");
139 let llty2 = match ty.sty {
140 ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
142 ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
146 // Declare a symbol `foo` with the desired linkage.
147 let g1 = declare::declare_global(ccx, &sym, llty2);
148 llvm::LLVMRustSetLinkage(g1, linkage);
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
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))
162 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
163 llvm::LLVMSetInitializer(g2, g1);
167 // Generate an external declaration.
168 declare::declare_global(ccx, &sym, llty)
174 item => bug!("get_static: expected static, found {:?}", item)
178 if attr.check_name("thread_local") {
179 llvm::set_thread_local(g, true);
185 let sym = ccx.tcx().symbol_name(instance);
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);
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
208 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
214 if ccx.use_dll_storage_attrs() && ccx.tcx().is_dllimport_foreign_item(def_id) {
215 // For foreign (native) libs we know the exact storage type to use.
217 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
220 ccx.instances().borrow_mut().insert(instance, g);
221 ccx.statics().borrow_mut().insert(g, def_id);
225 pub fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
228 attrs: &[ast::Attribute])
229 -> Result<ValueRef, ConstEvalErr<'tcx>> {
231 let def_id = ccx.tcx().hir.local_def_id(id);
232 let g = get_static(ccx, def_id);
234 let v = ::mir::trans_static_initializer(ccx, def_id)?;
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())
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 {
252 // If we created the global with the wrong 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());
259 let linkage = llvm::LLVMRustGetLinkage(g);
260 let visibility = llvm::LLVMRustGetVisibility(g);
262 let new_g = llvm::LLVMRustGetOrInsertGlobal(
263 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
265 llvm::LLVMRustSetLinkage(new_g, linkage);
266 llvm::LLVMRustSetVisibility(new_g, visibility);
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));
274 llvm::LLVMSetAlignment(g, ccx.align_of(ty));
275 llvm::LLVMSetInitializer(g, v);
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);
285 debuginfo::create_global_var_metadata(ccx, id, g);
287 if attr::contains_name(attrs,
289 llvm::set_thread_local(g, true);
292 base::set_link_section(ccx, g, attrs);
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);