1 use crate::llvm::{self, SetUnnamedAddr, True};
3 use crate::monomorphize::MonoItem;
4 use crate::common::CodegenCx;
5 use crate::monomorphize::Instance;
7 use crate::type_::Type;
8 use crate::type_of::LayoutLlvmExt;
9 use crate::value::Value;
11 use rustc::hir::def_id::DefId;
12 use rustc::mir::interpret::{ConstValue, Allocation, read_target_uint,
13 Pointer, ErrorHandled, GlobalId};
16 use rustc_target::abi::HasDataLayout;
17 use syntax::symbol::sym;
18 use syntax_pos::symbol::LocalInternedString;
19 use rustc::ty::{self, Ty};
20 use rustc_codegen_ssa::traits::*;
22 use rustc::ty::layout::{self, Size, Align, LayoutOf};
24 use rustc::hir::{self, CodegenFnAttrs, CodegenFnAttrFlags};
26 use std::ffi::{CStr, CString};
28 pub fn const_alloc_to_llvm(cx: &CodegenCx<'ll, '_>, alloc: &Allocation) -> &'ll Value {
29 let mut llvals = Vec::with_capacity(alloc.relocations.len() + 1);
30 let dl = cx.data_layout();
31 let pointer_size = dl.pointer_size.bytes() as usize;
33 let mut next_offset = 0;
34 for &(offset, ((), alloc_id)) in alloc.relocations.iter() {
35 let offset = offset.bytes();
36 assert_eq!(offset as usize as u64, offset);
37 let offset = offset as usize;
38 if offset > next_offset {
39 llvals.push(cx.const_bytes(&alloc.bytes[next_offset..offset]));
41 let ptr_offset = read_target_uint(
43 &alloc.bytes[offset..(offset + pointer_size)],
44 ).expect("const_alloc_to_llvm: could not read relocation pointer") as u64;
45 llvals.push(cx.scalar_to_backend(
46 Pointer::new(alloc_id, Size::from_bytes(ptr_offset)).into(),
48 value: layout::Primitive::Pointer,
53 next_offset = offset + pointer_size;
55 if alloc.bytes.len() >= next_offset {
56 llvals.push(cx.const_bytes(&alloc.bytes[next_offset ..]));
59 cx.const_struct(&llvals, true)
62 pub fn codegen_static_initializer(
63 cx: &CodegenCx<'ll, 'tcx>,
65 ) -> Result<(&'ll Value, &'tcx Allocation), ErrorHandled> {
66 let instance = ty::Instance::mono(cx.tcx, def_id);
71 let param_env = ty::ParamEnv::reveal_all();
72 let static_ = cx.tcx.const_eval(param_env.and(cid))?;
74 let alloc = match static_.val {
75 ConstValue::ByRef(ptr, alloc) if ptr.offset.bytes() == 0 => alloc,
76 _ => bug!("static const eval returned {:#?}", static_),
78 Ok((const_alloc_to_llvm(cx, alloc), alloc))
81 fn set_global_alignment(cx: &CodegenCx<'ll, '_>,
84 // The target may require greater alignment for globals than the type does.
85 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
86 // which can force it to be smaller. Rust doesn't support this yet.
87 if let Some(min) = cx.sess().target.target.options.min_global_align {
88 match Align::from_bits(min) {
89 Ok(min) => align = align.max(min),
91 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
96 llvm::LLVMSetAlignment(gv, align.bytes() as u32);
100 fn check_and_apply_linkage(
101 cx: &CodegenCx<'ll, 'tcx>,
102 attrs: &CodegenFnAttrs,
104 sym: LocalInternedString,
107 let llty = cx.layout_of(ty).llvm_type(cx);
108 if let Some(linkage) = attrs.linkage {
109 debug!("get_static: sym={} linkage={:?}", sym, linkage);
111 // If this is a static with a linkage specified, then we need to handle
112 // it a little specially. The typesystem prevents things like &T and
113 // extern "C" fn() from being non-null, so we can't just declare a
114 // static and call it a day. Some linkages (like weak) will make it such
115 // that the static actually has a null value.
116 let llty2 = if let ty::RawPtr(ref mt) = ty.sty {
117 cx.layout_of(mt.ty).llvm_type(cx)
119 cx.sess().span_fatal(
120 span, "must have type `*const T` or `*mut T` due to `#[linkage]` attribute")
123 // Declare a symbol `foo` with the desired linkage.
124 let g1 = cx.declare_global(&sym, llty2);
125 llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
127 // Declare an internal global `extern_with_linkage_foo` which
128 // is initialized with the address of `foo`. If `foo` is
129 // discarded during linking (for example, if `foo` has weak
130 // linkage and there are no definitions), then
131 // `extern_with_linkage_foo` will instead be initialized to
133 let mut real_name = "_rust_extern_with_linkage_".to_string();
134 real_name.push_str(&sym);
135 let g2 = cx.define_global(&real_name, llty).unwrap_or_else(||{
136 cx.sess().span_fatal(span, &format!("symbol `{}` is already defined", &sym))
138 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
139 llvm::LLVMSetInitializer(g2, g1);
143 // Generate an external declaration.
144 // FIXME(nagisa): investigate whether it can be changed into define_global
145 cx.declare_global(&sym, llty)
149 pub fn ptrcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
151 llvm::LLVMConstPointerCast(val, ty)
155 impl CodegenCx<'ll, 'tcx> {
156 crate fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
158 llvm::LLVMConstBitCast(val, ty)
162 crate fn static_addr_of_mut(
169 let gv = match kind {
170 Some(kind) if !self.tcx.sess.fewer_names() => {
171 let name = self.generate_local_symbol_name(kind);
172 let gv = self.define_global(&name[..],
173 self.val_ty(cv)).unwrap_or_else(||{
174 bug!("symbol `{}` is already defined", name);
176 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
179 _ => self.define_private_global(self.val_ty(cv)),
181 llvm::LLVMSetInitializer(gv, cv);
182 set_global_alignment(&self, gv, align);
183 SetUnnamedAddr(gv, true);
188 crate fn get_static(&self, def_id: DefId) -> &'ll Value {
189 let instance = Instance::mono(self.tcx, def_id);
190 if let Some(&g) = self.instances.borrow().get(&instance) {
194 let defined_in_current_codegen_unit = self.codegen_unit
196 .contains_key(&MonoItem::Static(def_id));
197 assert!(!defined_in_current_codegen_unit,
198 "consts::get_static() should always hit the cache for \
199 statics defined in the same CGU, but did not for `{:?}`",
202 let ty = instance.ty(self.tcx);
203 let sym = self.tcx.symbol_name(instance).as_str();
205 debug!("get_static: sym={} instance={:?}", sym, instance);
207 let g = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
209 let llty = self.layout_of(ty).llvm_type(self);
210 let (g, attrs) = match self.tcx.hir().get_by_hir_id(id) {
211 Node::Item(&hir::Item {
212 ref attrs, span, node: hir::ItemKind::Static(..), ..
214 if self.get_declared_value(&sym[..]).is_some() {
215 span_bug!(span, "Conflicting symbol names for static?");
218 let g = self.define_global(&sym[..], llty).unwrap();
220 if !self.tcx.is_reachable_non_generic(def_id) {
222 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
229 Node::ForeignItem(&hir::ForeignItem {
230 ref attrs, span, node: hir::ForeignItemKind::Static(..), ..
232 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
233 (check_and_apply_linkage(&self, &fn_attrs, ty, sym, span), attrs)
236 item => bug!("get_static: expected static, found {:?}", item)
239 debug!("get_static: sym={} attrs={:?}", sym, attrs);
242 if attr.check_name(sym::thread_local) {
243 llvm::set_thread_local_mode(g, self.tls_model);
249 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
250 debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id));
252 let attrs = self.tcx.codegen_fn_attrs(def_id);
253 let span = self.tcx.def_span(def_id);
254 let g = check_and_apply_linkage(&self, &attrs, ty, sym, span);
256 // Thread-local statics in some other crate need to *always* be linked
257 // against in a thread-local fashion, so we need to be sure to apply the
258 // thread-local attribute locally if it was present remotely. If we
259 // don't do this then linker errors can be generated where the linker
260 // complains that one object files has a thread local version of the
261 // symbol and another one doesn't.
262 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
263 llvm::set_thread_local_mode(g, self.tls_model);
266 let needs_dll_storage_attr =
267 self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) &&
268 // ThinLTO can't handle this workaround in all cases, so we don't
269 // emit the attrs. Instead we make them unnecessary by disallowing
270 // dynamic linking when linker plugin based LTO is enabled.
271 !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
273 // If this assertion triggers, there's something wrong with commandline
274 // argument validation.
275 debug_assert!(!(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
276 self.tcx.sess.target.target.options.is_like_msvc &&
277 self.tcx.sess.opts.cg.prefer_dynamic));
279 if needs_dll_storage_attr {
280 // This item is external but not foreign, i.e., it originates from an external Rust
281 // crate. Since we don't know whether this crate will be linked dynamically or
282 // statically in the final application, we always mark such symbols as 'dllimport'.
283 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
284 // to make things work.
286 // However, in some scenarios we defer emission of statics to downstream
287 // crates, so there are cases where a static with an upstream DefId
288 // is actually present in the current crate. We can find out via the
289 // is_codegened_item query.
290 if !self.tcx.is_codegened_item(def_id) {
292 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
299 if self.use_dll_storage_attrs && self.tcx.is_dllimport_foreign_item(def_id) {
300 // For foreign (native) libs we know the exact storage type to use.
302 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
306 self.instances.borrow_mut().insert(instance, g);
311 impl StaticMethods for CodegenCx<'ll, 'tcx> {
318 if let Some(&gv) = self.const_globals.borrow().get(&cv) {
320 // Upgrade the alignment in cases where the same constant is used with different
321 // alignment requirements
322 let llalign = align.bytes() as u32;
323 if llalign > llvm::LLVMGetAlignment(gv) {
324 llvm::LLVMSetAlignment(gv, llalign);
329 let gv = self.static_addr_of_mut(cv, align, kind);
331 llvm::LLVMSetGlobalConstant(gv, True);
333 self.const_globals.borrow_mut().insert(cv, gv);
343 let attrs = self.tcx.codegen_fn_attrs(def_id);
345 let (v, alloc) = match codegen_static_initializer(&self, def_id) {
347 // Error has already been reported
351 let g = self.get_static(def_id);
353 // boolean SSA values are i1, but they have to be stored in i8 slots,
354 // otherwise some LLVM optimization passes don't work as expected
355 let mut val_llty = self.val_ty(v);
356 let v = if val_llty == self.type_i1() {
357 val_llty = self.type_i8();
358 llvm::LLVMConstZExt(v, val_llty)
363 let instance = Instance::mono(self.tcx, def_id);
364 let ty = instance.ty(self.tcx);
365 let llty = self.layout_of(ty).llvm_type(self);
366 let g = if val_llty == llty {
369 // If we created the global with the wrong type,
371 let empty_string = const_cstr!("");
372 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
373 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
374 llvm::LLVMSetValueName(g, empty_string.as_ptr());
376 let linkage = llvm::LLVMRustGetLinkage(g);
377 let visibility = llvm::LLVMRustGetVisibility(g);
379 let new_g = llvm::LLVMRustGetOrInsertGlobal(
380 self.llmod, name_string.as_ptr(), val_llty);
382 llvm::LLVMRustSetLinkage(new_g, linkage);
383 llvm::LLVMRustSetVisibility(new_g, visibility);
385 // To avoid breaking any invariants, we leave around the old
386 // global for the moment; we'll replace all references to it
387 // with the new global later. (See base::codegen_backend.)
388 self.statics_to_rauw.borrow_mut().push((g, new_g));
391 set_global_alignment(&self, g, self.align_of(ty));
392 llvm::LLVMSetInitializer(g, v);
394 // As an optimization, all shared statics which do not have interior
395 // mutability are placed into read-only memory.
397 if self.type_is_freeze(ty) {
398 llvm::LLVMSetGlobalConstant(g, llvm::True);
402 debuginfo::create_global_var_metadata(&self, def_id, g);
404 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
405 llvm::set_thread_local_mode(g, self.tls_model);
407 // Do not allow LLVM to change the alignment of a TLS on macOS.
409 // By default a global's alignment can be freely increased.
410 // This allows LLVM to generate more performant instructions
411 // e.g., using load-aligned into a SIMD register.
413 // However, on macOS 10.10 or below, the dynamic linker does not
414 // respect any alignment given on the TLS (radar 24221680).
415 // This will violate the alignment assumption, and causing segfault at runtime.
417 // This bug is very easy to trigger. In `println!` and `panic!`,
418 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
419 // which the values would be `mem::replace`d on initialization.
420 // The implementation of `mem::replace` will use SIMD
421 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
422 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
423 // which macOS's dyld disregarded and causing crashes
424 // (see issues #51794, #51758, #50867, #48866 and #44056).
426 // To workaround the bug, we trick LLVM into not increasing
427 // the global's alignment by explicitly assigning a section to it
428 // (equivalent to automatically generating a `#[link_section]` attribute).
429 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
430 // of `lib/IR/Globals.cpp` for why this works.
432 // When the alignment is not increased, the optimized `mem::replace`
433 // will use load-unaligned instructions instead, and thus avoiding the crash.
435 // We could remove this hack whenever we decide to drop macOS 10.10 support.
436 if self.tcx.sess.target.target.options.is_like_osx {
437 let sect_name = if alloc.bytes.iter().all(|b| *b == 0) {
438 CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_bss\0")
440 CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_data\0")
442 llvm::LLVMSetSection(g, sect_name.as_ptr());
447 // Wasm statics with custom link sections get special treatment as they
448 // go into custom sections of the wasm executable.
449 if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
450 if let Some(section) = attrs.link_section {
451 let section = llvm::LLVMMDStringInContext(
453 section.as_str().as_ptr() as *const _,
454 section.as_str().len() as c_uint,
456 let alloc = llvm::LLVMMDStringInContext(
458 alloc.bytes.as_ptr() as *const _,
459 alloc.bytes.len() as c_uint,
461 let data = [section, alloc];
462 let meta = llvm::LLVMMDNodeInContext(self.llcx, data.as_ptr(), 2);
463 llvm::LLVMAddNamedMetadataOperand(
465 "wasm.custom_sections\0".as_ptr() as *const _,
470 base::set_link_section(g, &attrs);
473 if attrs.flags.contains(CodegenFnAttrFlags::USED) {
474 // This static will be stored in the llvm.used variable which is an array of i8*
475 let cast = llvm::LLVMConstPointerCast(g, self.type_i8p());
476 self.used_statics.borrow_mut().push(cast);