1 use gccjit::{GlobalKind, LValue, RValue, ToRValue, Type};
2 use rustc_codegen_ssa::traits::{BaseTypeMethods, ConstMethods, DerivedTypeMethods, StaticMethods};
5 use rustc_middle::{bug, span_bug};
6 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
7 use rustc_middle::mir::mono::MonoItem;
8 use rustc_middle::ty::{self, Instance, Ty};
9 use rustc_middle::ty::layout::LayoutOf;
10 use rustc_middle::mir::interpret::{self, ConstAllocation, ErrorHandled, Scalar as InterpScalar, read_target_uint};
12 use rustc_span::def_id::DefId;
13 use rustc_target::abi::{self, Align, HasDataLayout, Primitive, Size, WrappingRange};
16 use crate::context::CodegenCx;
17 use crate::errors::LinkageConstOrMutType;
18 use crate::type_of::LayoutGccExt;
20 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
21 pub fn const_bitcast(&self, value: RValue<'gcc>, typ: Type<'gcc>) -> RValue<'gcc> {
22 if value.get_type() == self.bool_type.make_pointer() {
23 if let Some(pointee) = typ.get_pointee() {
24 if pointee.dyncast_vector().is_some() {
29 // NOTE: since bitcast makes a value non-constant, don't bitcast if not necessary as some
30 // SIMD builtins require a constant value.
31 self.bitcast_if_needed(value, typ)
35 impl<'gcc, 'tcx> StaticMethods for CodegenCx<'gcc, 'tcx> {
36 fn static_addr_of(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc> {
37 // TODO(antoyo): implement a proper rvalue comparison in libgccjit instead of doing the
39 for (value, variable) in &*self.const_globals.borrow() {
40 if format!("{:?}", value) == format!("{:?}", cv) {
41 if let Some(global_variable) = self.global_lvalues.borrow().get(variable) {
42 let alignment = align.bits() as i32;
43 if alignment > global_variable.get_alignment() {
44 global_variable.set_alignment(alignment);
50 let global_value = self.static_addr_of_mut(cv, align, kind);
51 #[cfg(feature = "master")]
52 self.global_lvalues.borrow().get(&global_value)
53 .expect("`static_addr_of_mut` did not add the global to `self.global_lvalues`")
54 .global_set_readonly();
55 self.const_globals.borrow_mut().insert(cv, global_value);
59 fn codegen_static(&self, def_id: DefId, is_mutable: bool) {
60 let attrs = self.tcx.codegen_fn_attrs(def_id);
63 match codegen_static_initializer(&self, def_id) {
64 Ok((value, _)) => value,
65 // Error has already been reported
69 let global = self.get_static(def_id);
71 // boolean SSA values are i1, but they have to be stored in i8 slots,
72 // otherwise some LLVM optimization passes don't work as expected
73 let val_llty = self.val_ty(value);
75 if val_llty == self.type_i1() {
82 let instance = Instance::mono(self.tcx, def_id);
83 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
84 let gcc_type = self.layout_of(ty).gcc_type(self, true);
86 // TODO(antoyo): set alignment.
88 let value = self.bitcast_if_needed(value, gcc_type);
89 global.global_set_initializer_rvalue(value);
91 // As an optimization, all shared statics which do not have interior
92 // mutability are placed into read-only memory.
94 if self.type_is_freeze(ty) {
95 #[cfg(feature = "master")]
96 global.global_set_readonly();
100 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
101 // Do not allow LLVM to change the alignment of a TLS on macOS.
103 // By default a global's alignment can be freely increased.
104 // This allows LLVM to generate more performant instructions
105 // e.g., using load-aligned into a SIMD register.
107 // However, on macOS 10.10 or below, the dynamic linker does not
108 // respect any alignment given on the TLS (radar 24221680).
109 // This will violate the alignment assumption, and causing segfault at runtime.
111 // This bug is very easy to trigger. In `println!` and `panic!`,
112 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
113 // which the values would be `mem::replace`d on initialization.
114 // The implementation of `mem::replace` will use SIMD
115 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
116 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
117 // which macOS's dyld disregarded and causing crashes
118 // (see issues #51794, #51758, #50867, #48866 and #44056).
120 // To workaround the bug, we trick LLVM into not increasing
121 // the global's alignment by explicitly assigning a section to it
122 // (equivalent to automatically generating a `#[link_section]` attribute).
123 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
124 // of `lib/IR/Globals.cpp` for why this works.
126 // When the alignment is not increased, the optimized `mem::replace`
127 // will use load-unaligned instructions instead, and thus avoiding the crash.
129 // We could remove this hack whenever we decide to drop macOS 10.10 support.
130 if self.tcx.sess.target.options.is_like_osx {
131 // The `inspect` method is okay here because we checked for provenance, and
132 // because we are doing this access to inspect the final interpreter state
133 // (not as part of the interpreter execution).
135 // FIXME: This check requires that the (arbitrary) value of undefined bytes
136 // happens to be zero. Instead, we should only check the value of defined bytes
137 // and set all undefined bytes to zero if this allocation is headed for the
143 // Wasm statics with custom link sections get special treatment as they
144 // go into custom sections of the wasm executable.
145 if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
146 if let Some(_section) = attrs.link_section {
150 // TODO(antoyo): set link section.
153 if attrs.flags.contains(CodegenFnAttrFlags::USED) || attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
154 self.add_used_global(global.to_rvalue());
158 /// Add a global value to a list to be stored in the `llvm.used` variable, an array of i8*.
159 fn add_used_global(&self, _global: RValue<'gcc>) {
163 fn add_compiler_used_global(&self, _global: RValue<'gcc>) {
168 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
169 pub fn static_addr_of_mut(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc> {
172 Some(kind) if !self.tcx.sess.fewer_names() => {
173 let name = self.generate_local_symbol_name(kind);
174 // TODO(antoyo): check if it's okay that no link_section is set.
176 let typ = self.val_ty(cv).get_aligned(align.bytes());
177 let global = self.declare_private_global(&name[..], typ);
181 let typ = self.val_ty(cv).get_aligned(align.bytes());
182 let global = self.declare_unnamed_global(typ);
186 global.global_set_initializer_rvalue(cv);
187 // TODO(antoyo): set unnamed address.
188 let rvalue = global.get_address(None);
189 self.global_lvalues.borrow_mut().insert(rvalue, global);
193 pub fn get_static(&self, def_id: DefId) -> LValue<'gcc> {
194 let instance = Instance::mono(self.tcx, def_id);
195 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
196 if let Some(&global) = self.instances.borrow().get(&instance) {
200 let defined_in_current_codegen_unit =
201 self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
203 !defined_in_current_codegen_unit,
204 "consts::get_static() should always hit the cache for \
205 statics defined in the same CGU, but did not for `{:?}`",
209 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
210 let sym = self.tcx.symbol_name(instance).name;
213 if let Some(def_id) = def_id.as_local() {
214 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
215 let llty = self.layout_of(ty).gcc_type(self, true);
216 // FIXME: refactor this to work without accessing the HIR
217 let global = match self.tcx.hir().get(id) {
218 Node::Item(&hir::Item { span, kind: hir::ItemKind::Static(..), .. }) => {
219 if let Some(global) = self.get_declared_value(&sym) {
220 if self.val_ty(global) != self.type_ptr_to(llty) {
221 span_bug!(span, "Conflicting types for static");
225 let is_tls = fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
226 let global = self.declare_global(
229 GlobalKind::Exported,
231 fn_attrs.link_section,
234 if !self.tcx.is_reachable_non_generic(def_id) {
235 // TODO(antoyo): set visibility.
241 Node::ForeignItem(&hir::ForeignItem {
243 kind: hir::ForeignItemKind::Static(..),
246 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
247 check_and_apply_linkage(&self, &fn_attrs, ty, sym, span)
250 item => bug!("get_static: expected static, found {:?}", item),
256 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
257 //debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id));
259 let attrs = self.tcx.codegen_fn_attrs(def_id);
260 let span = self.tcx.def_span(def_id);
261 let global = check_and_apply_linkage(&self, &attrs, ty, sym, span);
263 let needs_dll_storage_attr = false; // TODO(antoyo)
265 // If this assertion triggers, there's something wrong with commandline
266 // argument validation.
268 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
269 && self.tcx.sess.target.options.is_like_msvc
270 && self.tcx.sess.opts.cg.prefer_dynamic)
273 if needs_dll_storage_attr {
274 // This item is external but not foreign, i.e., it originates from an external Rust
275 // crate. Since we don't know whether this crate will be linked dynamically or
276 // statically in the final application, we always mark such symbols as 'dllimport'.
277 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
278 // to make things work.
280 // However, in some scenarios we defer emission of statics to downstream
281 // crates, so there are cases where a static with an upstream DefId
282 // is actually present in the current crate. We can find out via the
283 // is_codegened_item query.
284 if !self.tcx.is_codegened_item(def_id) {
291 // TODO(antoyo): set dll storage class.
293 self.instances.borrow_mut().insert(instance, global);
298 pub fn const_alloc_to_gcc<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, alloc: ConstAllocation<'tcx>) -> RValue<'gcc> {
299 let alloc = alloc.inner();
300 let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
301 let dl = cx.data_layout();
302 let pointer_size = dl.pointer_size.bytes() as usize;
304 let mut next_offset = 0;
305 for &(offset, alloc_id) in alloc.provenance().ptrs().iter() {
306 let offset = offset.bytes();
307 assert_eq!(offset as usize as u64, offset);
308 let offset = offset as usize;
309 if offset > next_offset {
310 // This `inspect` is okay since we have checked that it is not within a pointer with provenance, it
311 // is within the bounds of the allocation, and it doesn't affect interpreter execution
312 // (we inspect the result after interpreter execution). Any undef byte is replaced with
313 // some arbitrary byte value.
315 // FIXME: relay undef bytes to codegen as undef const bytes
316 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(next_offset..offset);
317 llvals.push(cx.const_bytes(bytes));
320 read_target_uint( dl.endian,
321 // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
322 // affect interpreter execution (we inspect the result after interpreter execution),
323 // and we properly interpret the provenance as a relocation pointer offset.
324 alloc.inspect_with_uninit_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
326 .expect("const_alloc_to_llvm: could not read relocation pointer")
328 llvals.push(cx.scalar_to_backend(
329 InterpScalar::from_pointer(
330 interpret::Pointer::new(alloc_id, Size::from_bytes(ptr_offset)),
333 abi::Scalar::Initialized { value: Primitive::Pointer, valid_range: WrappingRange::full(dl.pointer_size) },
336 next_offset = offset + pointer_size;
338 if alloc.len() >= next_offset {
339 let range = next_offset..alloc.len();
340 // This `inspect` is okay since we have check that it is after all provenance, it is
341 // within the bounds of the allocation, and it doesn't affect interpreter execution (we
342 // inspect the result after interpreter execution). Any undef byte is replaced with some
343 // arbitrary byte value.
345 // FIXME: relay undef bytes to codegen as undef const bytes
346 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
347 llvals.push(cx.const_bytes(bytes));
350 cx.const_struct(&llvals, true)
353 pub fn codegen_static_initializer<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, def_id: DefId) -> Result<(RValue<'gcc>, ConstAllocation<'tcx>), ErrorHandled> {
354 let alloc = cx.tcx.eval_static_initializer(def_id)?;
355 Ok((const_alloc_to_gcc(cx, alloc), alloc))
358 fn check_and_apply_linkage<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, attrs: &CodegenFnAttrs, ty: Ty<'tcx>, sym: &str, span: Span) -> LValue<'gcc> {
359 let is_tls = attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
360 let llty = cx.layout_of(ty).gcc_type(cx, true);
361 if let Some(linkage) = attrs.linkage {
362 // If this is a static with a linkage specified, then we need to handle
363 // it a little specially. The typesystem prevents things like &T and
364 // extern "C" fn() from being non-null, so we can't just declare a
365 // static and call it a day. Some linkages (like weak) will make it such
366 // that the static actually has a null value.
368 if let ty::RawPtr(ref mt) = ty.kind() {
369 cx.layout_of(mt.ty).gcc_type(cx, true)
372 cx.sess().emit_fatal(LinkageConstOrMutType { span: span })
374 // Declare a symbol `foo` with the desired linkage.
375 let global1 = cx.declare_global_with_linkage(&sym, llty2, base::global_linkage_to_gcc(linkage));
377 // Declare an internal global `extern_with_linkage_foo` which
378 // is initialized with the address of `foo`. If `foo` is
379 // discarded during linking (for example, if `foo` has weak
380 // linkage and there are no definitions), then
381 // `extern_with_linkage_foo` will instead be initialized to
383 let mut real_name = "_rust_extern_with_linkage_".to_string();
384 real_name.push_str(&sym);
385 let global2 = cx.define_global(&real_name, llty, is_tls, attrs.link_section);
386 // TODO(antoyo): set linkage.
387 global2.global_set_initializer_rvalue(global1.get_address(None));
388 // TODO(antoyo): use global_set_initializer() when it will work.
392 // Generate an external declaration.
393 // FIXME(nagisa): investigate whether it can be changed into define_global
395 // Thread-local statics in some other crate need to *always* be linked
396 // against in a thread-local fashion, so we need to be sure to apply the
397 // thread-local attribute locally if it was present remotely. If we
398 // don't do this then linker errors can be generated where the linker
399 // complains that one object files has a thread local version of the
400 // symbol and another one doesn't.
401 cx.declare_global(&sym, llty, GlobalKind::Imported, is_tls, attrs.link_section)