1 #[cfg(feature = "master")]
2 use gccjit::{FnAttribute, VarAttribute, Visibility};
3 use gccjit::{Function, GlobalKind, LValue, RValue, ToRValue};
4 use rustc_codegen_ssa::traits::{BaseTypeMethods, ConstMethods, DerivedTypeMethods, StaticMethods};
5 use rustc_middle::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};
11 use rustc_span::def_id::DefId;
12 use rustc_target::abi::{self, Align, HasDataLayout, Primitive, Size, WrappingRange};
13
14 use crate::base;
15 use crate::context::CodegenCx;
16 use crate::errors::InvalidMinimumAlignment;
17 use crate::type_of::LayoutGccExt;
18
set_global_alignment<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, gv: LValue<'gcc>, mut align: Align)19 fn set_global_alignment<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, gv: LValue<'gcc>, mut align: Align) {
20 // The target may require greater alignment for globals than the type does.
21 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
22 // which can force it to be smaller. Rust doesn't support this yet.
23 if let Some(min) = cx.sess().target.min_global_align {
24 match Align::from_bits(min) {
25 Ok(min) => align = align.max(min),
26 Err(err) => {
27 cx.sess().emit_err(InvalidMinimumAlignment { err: err.to_string() });
28 }
29 }
30 }
31 gv.set_alignment(align.bytes() as i32);
32 }
33
34 impl<'gcc, 'tcx> StaticMethods for CodegenCx<'gcc, 'tcx> {
static_addr_of(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc>35 fn static_addr_of(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc> {
36 // TODO(antoyo): implement a proper rvalue comparison in libgccjit instead of doing the
37 // following:
38 for (value, variable) in &*self.const_globals.borrow() {
39 if format!("{:?}", value) == format!("{:?}", cv) {
40 if let Some(global_variable) = self.global_lvalues.borrow().get(variable) {
41 let alignment = align.bits() as i32;
42 if alignment > global_variable.get_alignment() {
43 global_variable.set_alignment(alignment);
44 }
45 }
46 return *variable;
47 }
48 }
49 let global_value = self.static_addr_of_mut(cv, align, kind);
50 #[cfg(feature = "master")]
51 self.global_lvalues.borrow().get(&global_value)
52 .expect("`static_addr_of_mut` did not add the global to `self.global_lvalues`")
53 .global_set_readonly();
54 self.const_globals.borrow_mut().insert(cv, global_value);
55 global_value
56 }
57
codegen_static(&self, def_id: DefId, is_mutable: bool)58 fn codegen_static(&self, def_id: DefId, is_mutable: bool) {
59 let attrs = self.tcx.codegen_fn_attrs(def_id);
60
61 let value =
62 match codegen_static_initializer(&self, def_id) {
63 Ok((value, _)) => value,
64 // Error has already been reported
65 Err(_) => return,
66 };
67
68 let global = self.get_static(def_id);
69
70 // boolean SSA values are i1, but they have to be stored in i8 slots,
71 // otherwise some LLVM optimization passes don't work as expected
72 let val_llty = self.val_ty(value);
73 let value =
74 if val_llty == self.type_i1() {
75 unimplemented!();
76 }
77 else {
78 value
79 };
80
81 let instance = Instance::mono(self.tcx, def_id);
82 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
83 let gcc_type = self.layout_of(ty).gcc_type(self);
84
85 set_global_alignment(self, global, self.align_of(ty));
86
87 let value = self.bitcast_if_needed(value, gcc_type);
88 global.global_set_initializer_rvalue(value);
89
90 // As an optimization, all shared statics which do not have interior
91 // mutability are placed into read-only memory.
92 if !is_mutable {
93 if self.type_is_freeze(ty) {
94 #[cfg(feature = "master")]
95 global.global_set_readonly();
96 }
97 }
98
99 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
100 // Do not allow LLVM to change the alignment of a TLS on macOS.
101 //
102 // By default a global's alignment can be freely increased.
103 // This allows LLVM to generate more performant instructions
104 // e.g., using load-aligned into a SIMD register.
105 //
106 // However, on macOS 10.10 or below, the dynamic linker does not
107 // respect any alignment given on the TLS (radar 24221680).
108 // This will violate the alignment assumption, and causing segfault at runtime.
109 //
110 // This bug is very easy to trigger. In `println!` and `panic!`,
111 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
112 // which the values would be `mem::replace`d on initialization.
113 // The implementation of `mem::replace` will use SIMD
114 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
115 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
116 // which macOS's dyld disregarded and causing crashes
117 // (see issues #51794, #51758, #50867, #48866 and #44056).
118 //
119 // To workaround the bug, we trick LLVM into not increasing
120 // the global's alignment by explicitly assigning a section to it
121 // (equivalent to automatically generating a `#[link_section]` attribute).
122 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
123 // of `lib/IR/Globals.cpp` for why this works.
124 //
125 // When the alignment is not increased, the optimized `mem::replace`
126 // will use load-unaligned instructions instead, and thus avoiding the crash.
127 //
128 // We could remove this hack whenever we decide to drop macOS 10.10 support.
129 if self.tcx.sess.target.options.is_like_osx {
130 // The `inspect` method is okay here because we checked for provenance, and
131 // because we are doing this access to inspect the final interpreter state
132 // (not as part of the interpreter execution).
133 //
134 // FIXME: This check requires that the (arbitrary) value of undefined bytes
135 // happens to be zero. Instead, we should only check the value of defined bytes
136 // and set all undefined bytes to zero if this allocation is headed for the
137 // BSS.
138 unimplemented!();
139 }
140 }
141
142 // Wasm statics with custom link sections get special treatment as they
143 // go into custom sections of the wasm executable.
144 if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
145 if let Some(_section) = attrs.link_section {
146 unimplemented!();
147 }
148 } else {
149 // TODO(antoyo): set link section.
150 }
151
152 if attrs.flags.contains(CodegenFnAttrFlags::USED) || attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
153 self.add_used_global(global.to_rvalue());
154 }
155 }
156
157 /// Add a global value to a list to be stored in the `llvm.used` variable, an array of i8*.
add_used_global(&self, _global: RValue<'gcc>)158 fn add_used_global(&self, _global: RValue<'gcc>) {
159 // TODO(antoyo)
160 }
161
add_compiler_used_global(&self, global: RValue<'gcc>)162 fn add_compiler_used_global(&self, global: RValue<'gcc>) {
163 // NOTE: seems like GCC does not make the distinction between compiler.used and used.
164 self.add_used_global(global);
165 }
166 }
167
168 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
169 #[cfg_attr(not(feature="master"), allow(unused_variables))]
add_used_function(&self, function: Function<'gcc>)170 pub fn add_used_function(&self, function: Function<'gcc>) {
171 #[cfg(feature = "master")]
172 function.add_attribute(FnAttribute::Used);
173 }
174
static_addr_of_mut(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc>175 pub fn static_addr_of_mut(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc> {
176 let global =
177 match kind {
178 Some(kind) if !self.tcx.sess.fewer_names() => {
179 let name = self.generate_local_symbol_name(kind);
180 // TODO(antoyo): check if it's okay that no link_section is set.
181
182 let typ = self.val_ty(cv).get_aligned(align.bytes());
183 let global = self.declare_private_global(&name[..], typ);
184 global
185 }
186 _ => {
187 let typ = self.val_ty(cv).get_aligned(align.bytes());
188 let global = self.declare_unnamed_global(typ);
189 global
190 },
191 };
192 global.global_set_initializer_rvalue(cv);
193 // TODO(antoyo): set unnamed address.
194 let rvalue = global.get_address(None);
195 self.global_lvalues.borrow_mut().insert(rvalue, global);
196 rvalue
197 }
198
get_static(&self, def_id: DefId) -> LValue<'gcc>199 pub fn get_static(&self, def_id: DefId) -> LValue<'gcc> {
200 let instance = Instance::mono(self.tcx, def_id);
201 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
202 if let Some(&global) = self.instances.borrow().get(&instance) {
203 return global;
204 }
205
206 let defined_in_current_codegen_unit =
207 self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
208 assert!(
209 !defined_in_current_codegen_unit,
210 "consts::get_static() should always hit the cache for \
211 statics defined in the same CGU, but did not for `{:?}`",
212 def_id
213 );
214
215 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
216 let sym = self.tcx.symbol_name(instance).name;
217
218 let global =
219 if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
220 let llty = self.layout_of(ty).gcc_type(self);
221 if let Some(global) = self.get_declared_value(sym) {
222 if self.val_ty(global) != self.type_ptr_to(llty) {
223 span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
224 }
225 }
226
227 let is_tls = fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
228 let global = self.declare_global(
229 &sym,
230 llty,
231 GlobalKind::Exported,
232 is_tls,
233 fn_attrs.link_section,
234 );
235
236 if !self.tcx.is_reachable_non_generic(def_id) {
237 #[cfg(feature = "master")]
238 global.add_attribute(VarAttribute::Visibility(Visibility::Hidden));
239 }
240
241 global
242 } else {
243 check_and_apply_linkage(&self, &fn_attrs, ty, sym)
244 };
245
246 if !def_id.is_local() {
247 let needs_dll_storage_attr = false; // TODO(antoyo)
248
249 // If this assertion triggers, there's something wrong with commandline
250 // argument validation.
251 debug_assert!(
252 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
253 && self.tcx.sess.target.options.is_like_msvc
254 && self.tcx.sess.opts.cg.prefer_dynamic)
255 );
256
257 if needs_dll_storage_attr {
258 // This item is external but not foreign, i.e., it originates from an external Rust
259 // crate. Since we don't know whether this crate will be linked dynamically or
260 // statically in the final application, we always mark such symbols as 'dllimport'.
261 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
262 // to make things work.
263 //
264 // However, in some scenarios we defer emission of statics to downstream
265 // crates, so there are cases where a static with an upstream DefId
266 // is actually present in the current crate. We can find out via the
267 // is_codegened_item query.
268 if !self.tcx.is_codegened_item(def_id) {
269 unimplemented!();
270 }
271 }
272 }
273
274 // TODO(antoyo): set dll storage class.
275
276 self.instances.borrow_mut().insert(instance, global);
277 global
278 }
279 }
280
const_alloc_to_gcc<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, alloc: ConstAllocation<'tcx>) -> RValue<'gcc>281 pub fn const_alloc_to_gcc<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, alloc: ConstAllocation<'tcx>) -> RValue<'gcc> {
282 let alloc = alloc.inner();
283 let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
284 let dl = cx.data_layout();
285 let pointer_size = dl.pointer_size.bytes() as usize;
286
287 let mut next_offset = 0;
288 for &(offset, alloc_id) in alloc.provenance().ptrs().iter() {
289 let offset = offset.bytes();
290 assert_eq!(offset as usize as u64, offset);
291 let offset = offset as usize;
292 if offset > next_offset {
293 // This `inspect` is okay since we have checked that it is not within a pointer with provenance, it
294 // is within the bounds of the allocation, and it doesn't affect interpreter execution
295 // (we inspect the result after interpreter execution). Any undef byte is replaced with
296 // some arbitrary byte value.
297 //
298 // FIXME: relay undef bytes to codegen as undef const bytes
299 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(next_offset..offset);
300 llvals.push(cx.const_bytes(bytes));
301 }
302 let ptr_offset =
303 read_target_uint( dl.endian,
304 // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
305 // affect interpreter execution (we inspect the result after interpreter execution),
306 // and we properly interpret the provenance as a relocation pointer offset.
307 alloc.inspect_with_uninit_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
308 )
309 .expect("const_alloc_to_llvm: could not read relocation pointer")
310 as u64;
311
312 let address_space = cx.tcx.global_alloc(alloc_id).address_space(cx);
313
314 llvals.push(cx.scalar_to_backend(
315 InterpScalar::from_pointer(
316 interpret::Pointer::new(alloc_id, Size::from_bytes(ptr_offset)),
317 &cx.tcx,
318 ),
319 abi::Scalar::Initialized { value: Primitive::Pointer(address_space), valid_range: WrappingRange::full(dl.pointer_size) },
320 cx.type_i8p_ext(address_space),
321 ));
322 next_offset = offset + pointer_size;
323 }
324 if alloc.len() >= next_offset {
325 let range = next_offset..alloc.len();
326 // This `inspect` is okay since we have check that it is after all provenance, it is
327 // within the bounds of the allocation, and it doesn't affect interpreter execution (we
328 // inspect the result after interpreter execution). Any undef byte is replaced with some
329 // arbitrary byte value.
330 //
331 // FIXME: relay undef bytes to codegen as undef const bytes
332 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
333 llvals.push(cx.const_bytes(bytes));
334 }
335
336 cx.const_struct(&llvals, true)
337 }
338
codegen_static_initializer<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, def_id: DefId) -> Result<(RValue<'gcc>, ConstAllocation<'tcx>), ErrorHandled>339 pub fn codegen_static_initializer<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, def_id: DefId) -> Result<(RValue<'gcc>, ConstAllocation<'tcx>), ErrorHandled> {
340 let alloc = cx.tcx.eval_static_initializer(def_id)?;
341 Ok((const_alloc_to_gcc(cx, alloc), alloc))
342 }
343
check_and_apply_linkage<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, attrs: &CodegenFnAttrs, ty: Ty<'tcx>, sym: &str) -> LValue<'gcc>344 fn check_and_apply_linkage<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, attrs: &CodegenFnAttrs, ty: Ty<'tcx>, sym: &str) -> LValue<'gcc> {
345 let is_tls = attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
346 let gcc_type = cx.layout_of(ty).gcc_type(cx);
347 if let Some(linkage) = attrs.import_linkage {
348 // Declare a symbol `foo` with the desired linkage.
349 let global1 = cx.declare_global_with_linkage(&sym, cx.type_i8(), base::global_linkage_to_gcc(linkage));
350
351 // Declare an internal global `extern_with_linkage_foo` which
352 // is initialized with the address of `foo`. If `foo` is
353 // discarded during linking (for example, if `foo` has weak
354 // linkage and there are no definitions), then
355 // `extern_with_linkage_foo` will instead be initialized to
356 // zero.
357 let mut real_name = "_rust_extern_with_linkage_".to_string();
358 real_name.push_str(&sym);
359 let global2 = cx.define_global(&real_name, gcc_type, is_tls, attrs.link_section);
360 // TODO(antoyo): set linkage.
361 let value = cx.const_ptrcast(global1.get_address(None), gcc_type);
362 global2.global_set_initializer_rvalue(value);
363 // TODO(antoyo): use global_set_initializer() when it will work.
364 global2
365 }
366 else {
367 // Generate an external declaration.
368 // FIXME(nagisa): investigate whether it can be changed into define_global
369
370 // Thread-local statics in some other crate need to *always* be linked
371 // against in a thread-local fashion, so we need to be sure to apply the
372 // thread-local attribute locally if it was present remotely. If we
373 // don't do this then linker errors can be generated where the linker
374 // complains that one object files has a thread local version of the
375 // symbol and another one doesn't.
376 cx.declare_global(&sym, gcc_type, GlobalKind::Imported, is_tls, attrs.link_section)
377 }
378 }
379