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 addr_of_mut(ccx: &CrateContext,
41 align: machine::llalign,
45 let name = ccx.generate_local_symbol_name(kind);
46 let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
47 bug!("symbol `{}` is already defined", name);
49 llvm::LLVMSetInitializer(gv, cv);
50 llvm::LLVMSetAlignment(gv, align);
51 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
52 SetUnnamedAddr(gv, true);
57 pub fn addr_of(ccx: &CrateContext,
59 align: machine::llalign,
62 if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
64 // Upgrade the alignment in cases where the same constant is used with different
65 // alignment requirements
66 if align > llvm::LLVMGetAlignment(gv) {
67 llvm::LLVMSetAlignment(gv, align);
72 let gv = addr_of_mut(ccx, cv, align, kind);
74 llvm::LLVMSetGlobalConstant(gv, True);
76 ccx.const_globals().borrow_mut().insert(cv, gv);
80 pub fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef {
81 let instance = Instance::mono(ccx.tcx(), def_id);
82 if let Some(&g) = ccx.instances().borrow().get(&instance) {
86 let ty = common::instance_ty(ccx.shared(), &instance);
87 let g = if let Some(id) = ccx.tcx().hir.as_local_node_id(def_id) {
89 let llty = type_of::type_of(ccx, ty);
90 let (g, attrs) = match ccx.tcx().hir.get(id) {
91 hir_map::NodeItem(&hir::Item {
92 ref attrs, span, node: hir::ItemStatic(..), ..
94 let sym = TransItem::Static(id).symbol_name(ccx.tcx());
96 let defined_in_current_codegen_unit = ccx.codegen_unit()
98 .contains_key(&TransItem::Static(id));
99 assert!(!defined_in_current_codegen_unit);
101 if declare::get_declared_value(ccx, &sym[..]).is_some() {
102 span_bug!(span, "trans: Conflicting symbol names for static?");
105 let g = declare::define_global(ccx, &sym[..], llty).unwrap();
110 hir_map::NodeForeignItem(&hir::ForeignItem {
111 ref attrs, span, node: hir::ForeignItemStatic(..), ..
113 let sym = ccx.tcx().symbol_name(instance);
114 let g = if let Some(name) =
115 attr::first_attr_value_str_by_name(&attrs, "linkage") {
116 // If this is a static with a linkage specified, then we need to handle
117 // it a little specially. The typesystem prevents things like &T and
118 // extern "C" fn() from being non-null, so we can't just declare a
119 // static and call it a day. Some linkages (like weak) will make it such
120 // that the static actually has a null value.
121 let linkage = match base::llvm_linkage_by_name(&name.as_str()) {
122 Some(linkage) => linkage,
124 ccx.sess().span_fatal(span, "invalid linkage specified");
127 let llty2 = match ty.sty {
128 ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
130 ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
134 // Declare a symbol `foo` with the desired linkage.
135 let g1 = declare::declare_global(ccx, &sym, llty2);
136 llvm::LLVMRustSetLinkage(g1, linkage);
138 // Declare an internal global `extern_with_linkage_foo` which
139 // is initialized with the address of `foo`. If `foo` is
140 // discarded during linking (for example, if `foo` has weak
141 // linkage and there are no definitions), then
142 // `extern_with_linkage_foo` will instead be initialized to
144 let mut real_name = "_rust_extern_with_linkage_".to_string();
145 real_name.push_str(&sym);
146 let g2 = declare::define_global(ccx, &real_name, llty).unwrap_or_else(||{
147 ccx.sess().span_fatal(span,
148 &format!("symbol `{}` is already defined", &sym))
150 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
151 llvm::LLVMSetInitializer(g2, g1);
155 // Generate an external declaration.
156 declare::declare_global(ccx, &sym, llty)
162 item => bug!("get_static: expected static, found {:?}", item)
166 if attr.check_name("thread_local") {
167 llvm::set_thread_local(g, true);
173 let sym = ccx.tcx().symbol_name(instance);
175 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
176 // FIXME(nagisa): investigate whether it can be changed into define_global
177 let g = declare::declare_global(ccx, &sym, type_of::type_of(ccx, ty));
178 // Thread-local statics in some other crate need to *always* be linked
179 // against in a thread-local fashion, so we need to be sure to apply the
180 // thread-local attribute locally if it was present remotely. If we
181 // don't do this then linker errors can be generated where the linker
182 // complains that one object files has a thread local version of the
183 // symbol and another one doesn't.
184 for attr in ccx.tcx().get_attrs(def_id).iter() {
185 if attr.check_name("thread_local") {
186 llvm::set_thread_local(g, true);
189 if ccx.use_dll_storage_attrs() && !ccx.tcx().is_foreign_item(def_id) {
190 // This item is external but not foreign, i.e. it originates from an external Rust
191 // crate. Since we don't know whether this crate will be linked dynamically or
192 // statically in the final application, we always mark such symbols as 'dllimport'.
193 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs to
196 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
202 if ccx.use_dll_storage_attrs() && ccx.sess().cstore.is_dllimport_foreign_item(def_id) {
203 // For foreign (native) libs we know the exact storage type to use.
205 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
208 ccx.instances().borrow_mut().insert(instance, g);
209 ccx.statics().borrow_mut().insert(g, def_id);
213 pub fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
216 attrs: &[ast::Attribute])
217 -> Result<ValueRef, ConstEvalErr<'tcx>> {
219 let def_id = ccx.tcx().hir.local_def_id(id);
220 let g = get_static(ccx, def_id);
222 let v = ::mir::trans_static_initializer(ccx, def_id)?;
224 // boolean SSA values are i1, but they have to be stored in i8 slots,
225 // otherwise some LLVM optimization passes don't work as expected
226 let mut val_llty = val_ty(v);
227 let v = if val_llty == Type::i1(ccx) {
228 val_llty = Type::i8(ccx);
229 llvm::LLVMConstZExt(v, val_llty.to_ref())
234 let instance = Instance::mono(ccx.tcx(), def_id);
235 let ty = common::instance_ty(ccx.shared(), &instance);
236 let llty = type_of::type_of(ccx, ty);
237 let g = if val_llty == llty {
240 // If we created the global with the wrong type,
242 let empty_string = CString::new("").unwrap();
243 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
244 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
245 llvm::LLVMSetValueName(g, empty_string.as_ptr());
246 let new_g = llvm::LLVMRustGetOrInsertGlobal(
247 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
248 // To avoid breaking any invariants, we leave around the old
249 // global for the moment; we'll replace all references to it
250 // with the new global later. (See base::trans_crate.)
251 ccx.statics_to_rauw().borrow_mut().push((g, new_g));
254 llvm::LLVMSetAlignment(g, ccx.align_of(ty));
255 llvm::LLVMSetInitializer(g, v);
257 // As an optimization, all shared statics which do not have interior
258 // mutability are placed into read-only memory.
259 if m != hir::MutMutable {
260 if ccx.shared().type_is_freeze(ty) {
261 llvm::LLVMSetGlobalConstant(g, llvm::True);
265 debuginfo::create_global_var_metadata(ccx, id, g);
267 if attr::contains_name(attrs,
269 llvm::set_thread_local(g, true);
272 base::set_link_section(ccx, g, attrs);
274 if attr::contains_name(attrs, "used") {
275 // This static will be stored in the llvm.used variable which is an array of i8*
276 let cast = llvm::LLVMConstPointerCast(g, Type::i8p(ccx).to_ref());
277 ccx.used_statics().borrow_mut().push(cast);