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;
19 use trans_item::{TransItem, TransItemExt};
20 use common::{self, CrateContext, val_ty};
22 use monomorphize::Instance;
24 use type_of::LayoutLlvmExt;
26 use rustc::ty::layout::{Align, LayoutOf};
30 use std::ffi::{CStr, CString};
34 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
36 llvm::LLVMConstPointerCast(val, ty.to_ref())
40 pub fn bitcast(val: ValueRef, ty: Type) -> ValueRef {
42 llvm::LLVMConstBitCast(val, ty.to_ref())
46 fn set_global_alignment(ccx: &CrateContext,
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),
56 ccx.sess().err(&format!("invalid minimum global alignment: {}", err));
61 llvm::LLVMSetAlignment(gv, align.abi() as u32);
65 pub fn addr_of_mut(ccx: &CrateContext,
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);
75 llvm::LLVMSetInitializer(gv, cv);
76 set_global_alignment(ccx, gv, align);
77 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
78 SetUnnamedAddr(gv, true);
83 pub fn addr_of(ccx: &CrateContext,
88 if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
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);
99 let gv = addr_of_mut(ccx, cv, align, kind);
101 llvm::LLVMSetGlobalConstant(gv, True);
103 ccx.const_globals().borrow_mut().insert(cv, gv);
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) {
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) {
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(..), ..
121 let sym = TransItem::Static(id).symbol_name(ccx.tcx());
123 let defined_in_current_codegen_unit = ccx.codegen_unit()
125 .contains_key(&TransItem::Static(id));
126 assert!(!defined_in_current_codegen_unit);
128 if declare::get_declared_value(ccx, &sym[..]).is_some() {
129 span_bug!(span, "trans: Conflicting symbol names for static?");
132 let g = declare::define_global(ccx, &sym[..], llty).unwrap();
134 if !ccx.tcx().is_exported_symbol(def_id) {
136 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
143 hir_map::NodeForeignItem(&hir::ForeignItem {
144 ref attrs, span, node: hir::ForeignItemStatic(..), ..
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,
157 ccx.sess().span_fatal(span, "invalid linkage specified");
160 let llty2 = match ty.sty {
161 ty::TyRawPtr(ref mt) => ccx.layout_of(mt.ty).llvm_type(ccx),
163 ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
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));
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
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))
183 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
184 llvm::LLVMSetInitializer(g2, g1);
188 // Generate an external declaration.
189 declare::declare_global(ccx, &sym, llty)
195 item => bug!("get_static: expected static, found {:?}", item)
199 if attr.check_name("thread_local") {
200 llvm::set_thread_local_mode(g, ccx.tls_model());
206 let sym = ccx.tcx().symbol_name(instance);
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());
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
229 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
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.
238 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
242 ccx.instances().borrow_mut().insert(instance, g);
243 ccx.statics().borrow_mut().insert(g, def_id);
247 pub fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
250 attrs: &[ast::Attribute])
251 -> Result<ValueRef, ConstEvalErr<'tcx>> {
253 let def_id = ccx.tcx().hir.local_def_id(id);
254 let g = get_static(ccx, def_id);
256 let v = ::mir::trans_static_initializer(ccx, def_id)?;
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())
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 {
274 // If we created the global with the wrong 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());
281 let linkage = llvm::LLVMRustGetLinkage(g);
282 let visibility = llvm::LLVMRustGetVisibility(g);
284 let new_g = llvm::LLVMRustGetOrInsertGlobal(
285 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
287 llvm::LLVMRustSetLinkage(new_g, linkage);
288 llvm::LLVMRustSetVisibility(new_g, visibility);
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));
296 set_global_alignment(ccx, g, ccx.align_of(ty));
297 llvm::LLVMSetInitializer(g, v);
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);
307 debuginfo::create_global_var_metadata(ccx, id, g);
309 if attr::contains_name(attrs, "thread_local") {
310 llvm::set_thread_local_mode(g, ccx.tls_model());
313 base::set_link_section(ccx, g, attrs);
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);