]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_codegen_cranelift/src/constant.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / compiler / rustc_codegen_cranelift / src / constant.rs
1 //! Handling of `static`s, `const`s and promoted allocations
2
3 use rustc_span::DUMMY_SP;
4
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_errors::ErrorReported;
7 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8 use rustc_middle::mir::interpret::{
9 read_target_uint, AllocId, Allocation, ConstValue, ErrorHandled, GlobalAlloc, Pointer, Scalar,
10 };
11 use rustc_middle::ty::ConstKind;
12
13 use cranelift_codegen::ir::GlobalValueData;
14 use cranelift_module::*;
15
16 use crate::prelude::*;
17
18 #[derive(Default)]
19 pub(crate) struct ConstantCx {
20 todo: Vec<TodoItem>,
21 done: FxHashSet<DataId>,
22 }
23
24 #[derive(Copy, Clone, Debug)]
25 enum TodoItem {
26 Alloc(AllocId),
27 Static(DefId),
28 }
29
30 impl ConstantCx {
31 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
32 //println!("todo {:?}", self.todo);
33 define_all_allocs(tcx, module, &mut self);
34 //println!("done {:?}", self.done);
35 self.done.clear();
36 }
37 }
38
39 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
40 let mut all_constants_ok = true;
41 for constant in &fx.mir.required_consts {
42 let const_ = match fx.monomorphize(constant.literal) {
43 ConstantKind::Ty(ct) => ct,
44 ConstantKind::Val(..) => continue,
45 };
46 match const_.val {
47 ConstKind::Value(_) => {}
48 ConstKind::Unevaluated(def, ref substs, promoted) => {
49 if let Err(err) =
50 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
51 {
52 all_constants_ok = false;
53 match err {
54 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
55 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
56 }
57 ErrorHandled::TooGeneric => {
58 span_bug!(
59 constant.span,
60 "codgen encountered polymorphic constant: {:?}",
61 err
62 );
63 }
64 }
65 }
66 }
67 ConstKind::Param(_)
68 | ConstKind::Infer(_)
69 | ConstKind::Bound(_, _)
70 | ConstKind::Placeholder(_)
71 | ConstKind::Error(_) => unreachable!("{:?}", const_),
72 }
73 }
74 all_constants_ok
75 }
76
77 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
78 constants_cx.todo.push(TodoItem::Static(def_id));
79 }
80
81 pub(crate) fn codegen_tls_ref<'tcx>(
82 fx: &mut FunctionCx<'_, '_, 'tcx>,
83 def_id: DefId,
84 layout: TyAndLayout<'tcx>,
85 ) -> CValue<'tcx> {
86 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
87 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
88 #[cfg(debug_assertions)]
89 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
90 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
91 CValue::by_val(tls_ptr, layout)
92 }
93
94 fn codegen_static_ref<'tcx>(
95 fx: &mut FunctionCx<'_, '_, 'tcx>,
96 def_id: DefId,
97 layout: TyAndLayout<'tcx>,
98 ) -> CPlace<'tcx> {
99 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
100 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
101 #[cfg(debug_assertions)]
102 fx.add_comment(local_data_id, format!("{:?}", def_id));
103 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
104 assert!(!layout.is_unsized(), "unsized statics aren't supported");
105 assert!(
106 matches!(
107 fx.bcx.func.global_values[local_data_id],
108 GlobalValueData::Symbol { tls: false, .. }
109 ),
110 "tls static referenced without Rvalue::ThreadLocalRef"
111 );
112 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
113 }
114
115 pub(crate) fn codegen_constant<'tcx>(
116 fx: &mut FunctionCx<'_, '_, 'tcx>,
117 constant: &Constant<'tcx>,
118 ) -> CValue<'tcx> {
119 let const_ = match fx.monomorphize(constant.literal) {
120 ConstantKind::Ty(ct) => ct,
121 ConstantKind::Val(val, ty) => return codegen_const_value(fx, val, ty),
122 };
123 let const_val = match const_.val {
124 ConstKind::Value(const_val) => const_val,
125 ConstKind::Unevaluated(def, ref substs, promoted) if fx.tcx.is_static(def.did) => {
126 assert!(substs.is_empty());
127 assert!(promoted.is_none());
128
129 return codegen_static_ref(fx, def.did, fx.layout_of(const_.ty)).to_cvalue(fx);
130 }
131 ConstKind::Unevaluated(def, ref substs, promoted) => {
132 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None) {
133 Ok(const_val) => const_val,
134 Err(_) => {
135 span_bug!(constant.span, "erroneous constant not captured by required_consts");
136 }
137 }
138 }
139 ConstKind::Param(_)
140 | ConstKind::Infer(_)
141 | ConstKind::Bound(_, _)
142 | ConstKind::Placeholder(_)
143 | ConstKind::Error(_) => unreachable!("{:?}", const_),
144 };
145
146 codegen_const_value(fx, const_val, const_.ty)
147 }
148
149 pub(crate) fn codegen_const_value<'tcx>(
150 fx: &mut FunctionCx<'_, '_, 'tcx>,
151 const_val: ConstValue<'tcx>,
152 ty: Ty<'tcx>,
153 ) -> CValue<'tcx> {
154 let layout = fx.layout_of(ty);
155 assert!(!layout.is_unsized(), "sized const value");
156
157 if layout.is_zst() {
158 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
159 }
160
161 match const_val {
162 ConstValue::Scalar(x) => {
163 if fx.clif_type(layout.ty).is_none() {
164 let (size, align) = (layout.size, layout.align.pref);
165 let mut alloc = Allocation::from_bytes(
166 std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
167 align,
168 );
169 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
170 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
171 let alloc = fx.tcx.intern_const_alloc(alloc);
172 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
173 }
174
175 match x {
176 Scalar::Int(int) => CValue::const_val(fx, layout, int),
177 Scalar::Ptr(ptr) => {
178 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
179 let base_addr = match alloc_kind {
180 Some(GlobalAlloc::Memory(alloc)) => {
181 fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
182 let data_id =
183 data_id_for_alloc_id(fx.cx.module, ptr.alloc_id, alloc.mutability);
184 let local_data_id =
185 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
186 #[cfg(debug_assertions)]
187 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
188 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
189 }
190 Some(GlobalAlloc::Function(instance)) => {
191 let func_id =
192 crate::abi::import_function(fx.tcx, fx.cx.module, instance);
193 let local_func_id =
194 fx.cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
195 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
196 }
197 Some(GlobalAlloc::Static(def_id)) => {
198 assert!(fx.tcx.is_static(def_id));
199 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
200 let local_data_id =
201 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
202 #[cfg(debug_assertions)]
203 fx.add_comment(local_data_id, format!("{:?}", def_id));
204 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
205 }
206 None => bug!("missing allocation {:?}", ptr.alloc_id),
207 };
208 let val = if ptr.offset.bytes() != 0 {
209 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
210 } else {
211 base_addr
212 };
213 CValue::by_val(val, layout)
214 }
215 }
216 }
217 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
218 pointer_for_allocation(fx, alloc)
219 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
220 layout,
221 ),
222 ConstValue::Slice { data, start, end } => {
223 let ptr = pointer_for_allocation(fx, data)
224 .offset_i64(fx, i64::try_from(start).unwrap())
225 .get_addr(fx);
226 let len = fx
227 .bcx
228 .ins()
229 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
230 CValue::by_val_pair(ptr, len, layout)
231 }
232 }
233 }
234
235 fn pointer_for_allocation<'tcx>(
236 fx: &mut FunctionCx<'_, '_, 'tcx>,
237 alloc: &'tcx Allocation,
238 ) -> crate::pointer::Pointer {
239 let alloc_id = fx.tcx.create_memory_alloc(alloc);
240 fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
241 let data_id = data_id_for_alloc_id(fx.cx.module, alloc_id, alloc.mutability);
242
243 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
244 #[cfg(debug_assertions)]
245 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
246 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
247 crate::pointer::Pointer::new(global_ptr)
248 }
249
250 fn data_id_for_alloc_id(
251 module: &mut dyn Module,
252 alloc_id: AllocId,
253 mutability: rustc_hir::Mutability,
254 ) -> DataId {
255 module
256 .declare_data(
257 &format!(".L__alloc_{:x}", alloc_id.0),
258 Linkage::Local,
259 mutability == rustc_hir::Mutability::Mut,
260 false,
261 )
262 .unwrap()
263 }
264
265 fn data_id_for_static(
266 tcx: TyCtxt<'_>,
267 module: &mut dyn Module,
268 def_id: DefId,
269 definition: bool,
270 ) -> DataId {
271 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
272 let linkage = if definition {
273 crate::linkage::get_static_linkage(tcx, def_id)
274 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
275 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
276 {
277 Linkage::Preemptible
278 } else {
279 Linkage::Import
280 };
281
282 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
283 let symbol_name = tcx.symbol_name(instance).name;
284 let ty = instance.ty(tcx, ParamEnv::reveal_all());
285 let is_mutable = if tcx.is_mutable_static(def_id) {
286 true
287 } else {
288 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
289 };
290 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
291
292 let attrs = tcx.codegen_fn_attrs(def_id);
293
294 let data_id = module
295 .declare_data(
296 &*symbol_name,
297 linkage,
298 is_mutable,
299 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
300 )
301 .unwrap();
302
303 if rlinkage.is_some() {
304 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
305 // Declare an internal global `extern_with_linkage_foo` which
306 // is initialized with the address of `foo`. If `foo` is
307 // discarded during linking (for example, if `foo` has weak
308 // linkage and there are no definitions), then
309 // `extern_with_linkage_foo` will instead be initialized to
310 // zero.
311
312 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
313 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
314 let mut data_ctx = DataContext::new();
315 data_ctx.set_align(align);
316 let data = module.declare_data_in_data(data_id, &mut data_ctx);
317 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
318 data_ctx.write_data_addr(0, data, 0);
319 match module.define_data(ref_data_id, &data_ctx) {
320 // Every time the static is referenced there will be another definition of this global,
321 // so duplicate definitions are expected and allowed.
322 Err(ModuleError::DuplicateDefinition(_)) => {}
323 res => res.unwrap(),
324 }
325 ref_data_id
326 } else {
327 data_id
328 }
329 }
330
331 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
332 while let Some(todo_item) = cx.todo.pop() {
333 let (data_id, alloc, section_name) = match todo_item {
334 TodoItem::Alloc(alloc_id) => {
335 //println!("alloc_id {}", alloc_id);
336 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
337 GlobalAlloc::Memory(alloc) => alloc,
338 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
339 };
340 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
341 (data_id, alloc, None)
342 }
343 TodoItem::Static(def_id) => {
344 //println!("static {:?}", def_id);
345
346 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
347
348 let alloc = tcx.eval_static_initializer(def_id).unwrap();
349
350 let data_id = data_id_for_static(tcx, module, def_id, true);
351 (data_id, alloc, section_name)
352 }
353 };
354
355 //("data_id {}", data_id);
356 if cx.done.contains(&data_id) {
357 continue;
358 }
359
360 let mut data_ctx = DataContext::new();
361 data_ctx.set_align(alloc.align.bytes());
362
363 if let Some(section_name) = section_name {
364 // FIXME set correct segment for Mach-O files
365 data_ctx.set_segment_section("", &*section_name);
366 }
367
368 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
369 data_ctx.define(bytes.into_boxed_slice());
370
371 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
372 let addend = {
373 let endianness = tcx.data_layout.endian;
374 let offset = offset.bytes() as usize;
375 let ptr_size = tcx.data_layout.pointer_size;
376 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
377 offset..offset + ptr_size.bytes() as usize,
378 );
379 read_target_uint(endianness, bytes).unwrap()
380 };
381
382 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
383 let data_id = match reloc_target_alloc {
384 GlobalAlloc::Function(instance) => {
385 assert_eq!(addend, 0);
386 let func_id = crate::abi::import_function(tcx, module, instance);
387 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
388 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
389 continue;
390 }
391 GlobalAlloc::Memory(target_alloc) => {
392 cx.todo.push(TodoItem::Alloc(reloc));
393 data_id_for_alloc_id(module, reloc, target_alloc.mutability)
394 }
395 GlobalAlloc::Static(def_id) => {
396 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
397 {
398 tcx.sess.fatal(&format!(
399 "Allocation {:?} contains reference to TLS value {:?}",
400 alloc, def_id
401 ));
402 }
403
404 // Don't push a `TodoItem::Static` here, as it will cause statics used by
405 // multiple crates to be duplicated between them. It isn't necessary anyway,
406 // as it will get pushed by `codegen_static` when necessary.
407 data_id_for_static(tcx, module, def_id, false)
408 }
409 };
410
411 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
412 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
413 }
414
415 // FIXME don't duplicate definitions in lazy jit mode
416 let _ = module.define_data(data_id, &data_ctx);
417 cx.done.insert(data_id);
418 }
419
420 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
421 }
422
423 pub(crate) fn mir_operand_get_const_val<'tcx>(
424 fx: &FunctionCx<'_, '_, 'tcx>,
425 operand: &Operand<'tcx>,
426 ) -> Option<ConstValue<'tcx>> {
427 match operand {
428 Operand::Copy(_) | Operand::Move(_) => None,
429 Operand::Constant(const_) => match const_.literal {
430 ConstantKind::Ty(const_) => {
431 fx.monomorphize(const_).eval(fx.tcx, ParamEnv::reveal_all()).val.try_to_value()
432 }
433 ConstantKind::Val(val, _) => Some(val),
434 },
435 }
436 }