1 //! Handling of `static`s, `const`s and promoted allocations
3 use rustc_span::DUMMY_SP;
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,
11 use rustc_middle::ty::{Const, ConstKind};
13 use cranelift_codegen::ir::GlobalValueData;
14 use cranelift_module::*;
16 use crate::prelude::*;
19 pub(crate) struct ConstantCx {
21 done: FxHashSet<DataId>,
24 #[derive(Copy, Clone, Debug)]
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);
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_ = fx.monomorphize(constant.literal);
44 ConstKind::Value(_) => {}
45 ConstKind::Unevaluated(def, ref substs, promoted) => {
48 .const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
50 all_constants_ok = false;
52 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
55 .span_err(constant.span, "erroneous constant encountered");
57 ErrorHandled::TooGeneric => {
60 "codgen encountered polymorphic constant: {:?}",
69 | ConstKind::Bound(_, _)
70 | ConstKind::Placeholder(_)
71 | ConstKind::Error(_) => unreachable!("{:?}", const_),
77 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
78 constants_cx.todo.push(TodoItem::Static(def_id));
81 pub(crate) fn codegen_tls_ref<'tcx>(
82 fx: &mut FunctionCx<'_, '_, 'tcx>,
84 layout: TyAndLayout<'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)
94 fn codegen_static_ref<'tcx>(
95 fx: &mut FunctionCx<'_, '_, 'tcx>,
97 layout: TyAndLayout<'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");
107 fx.bcx.func.global_values[local_data_id],
108 GlobalValueData::Symbol { tls: false, .. }
110 "tls static referenced without Rvalue::ThreadLocalRef"
112 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
115 pub(crate) fn codegen_constant<'tcx>(
116 fx: &mut FunctionCx<'_, '_, 'tcx>,
117 constant: &Constant<'tcx>,
119 let const_ = fx.monomorphize(constant.literal);
120 let const_val = match const_.val {
121 ConstKind::Value(const_val) => const_val,
122 ConstKind::Unevaluated(def, ref substs, promoted) if fx.tcx.is_static(def.did) => {
123 assert!(substs.is_empty());
124 assert!(promoted.is_none());
126 return codegen_static_ref(
129 fx.layout_of(fx.monomorphize(&constant.literal.ty)),
133 ConstKind::Unevaluated(def, ref substs, promoted) => {
136 .const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
138 Ok(const_val) => const_val,
142 "erroneous constant not captured by required_consts"
148 | ConstKind::Infer(_)
149 | ConstKind::Bound(_, _)
150 | ConstKind::Placeholder(_)
151 | ConstKind::Error(_) => unreachable!("{:?}", const_),
154 codegen_const_value(fx, const_val, const_.ty)
157 pub(crate) fn codegen_const_value<'tcx>(
158 fx: &mut FunctionCx<'_, '_, 'tcx>,
159 const_val: ConstValue<'tcx>,
162 let layout = fx.layout_of(ty);
163 assert!(!layout.is_unsized(), "sized const value");
166 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
170 ConstValue::Scalar(x) => {
171 if fx.clif_type(layout.ty).is_none() {
172 let (size, align) = (layout.size, layout.align.pref);
173 let mut alloc = Allocation::from_bytes(
175 .take(size.bytes_usize())
176 .collect::<Vec<u8>>(),
179 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
180 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
181 let alloc = fx.tcx.intern_const_alloc(alloc);
182 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
186 Scalar::Int(int) => CValue::const_val(fx, layout, int),
187 Scalar::Ptr(ptr) => {
188 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
189 let base_addr = match alloc_kind {
190 Some(GlobalAlloc::Memory(alloc)) => {
191 fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
193 data_id_for_alloc_id(fx.cx.module, ptr.alloc_id, alloc.mutability);
195 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
196 #[cfg(debug_assertions)]
197 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
198 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
200 Some(GlobalAlloc::Function(instance)) => {
202 crate::abi::import_function(fx.tcx, fx.cx.module, instance);
204 fx.cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
205 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
207 Some(GlobalAlloc::Static(def_id)) => {
208 assert!(fx.tcx.is_static(def_id));
209 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
211 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
212 #[cfg(debug_assertions)]
213 fx.add_comment(local_data_id, format!("{:?}", def_id));
214 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
216 None => bug!("missing allocation {:?}", ptr.alloc_id),
218 let val = if ptr.offset.bytes() != 0 {
221 .iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
225 CValue::by_val(val, layout)
229 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
230 pointer_for_allocation(fx, alloc)
231 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
234 ConstValue::Slice { data, start, end } => {
235 let ptr = pointer_for_allocation(fx, data)
236 .offset_i64(fx, i64::try_from(start).unwrap())
238 let len = fx.bcx.ins().iconst(
240 i64::try_from(end.checked_sub(start).unwrap()).unwrap(),
242 CValue::by_val_pair(ptr, len, layout)
247 fn pointer_for_allocation<'tcx>(
248 fx: &mut FunctionCx<'_, '_, 'tcx>,
249 alloc: &'tcx Allocation,
250 ) -> crate::pointer::Pointer {
251 let alloc_id = fx.tcx.create_memory_alloc(alloc);
252 fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
253 let data_id = data_id_for_alloc_id(fx.cx.module, alloc_id, alloc.mutability);
255 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
256 #[cfg(debug_assertions)]
257 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
258 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
259 crate::pointer::Pointer::new(global_ptr)
262 fn data_id_for_alloc_id(
263 module: &mut dyn Module,
265 mutability: rustc_hir::Mutability,
269 &format!(".L__alloc_{:x}", alloc_id.0),
271 mutability == rustc_hir::Mutability::Mut,
277 fn data_id_for_static(
279 module: &mut dyn Module,
283 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
284 let linkage = if definition {
285 crate::linkage::get_static_linkage(tcx, def_id)
286 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
287 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
294 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
295 let symbol_name = tcx.symbol_name(instance).name;
296 let ty = instance.ty(tcx, ParamEnv::reveal_all());
297 let is_mutable = if tcx.is_mutable_static(def_id) {
300 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
303 .layout_of(ParamEnv::reveal_all().and(ty))
309 let attrs = tcx.codegen_fn_attrs(def_id);
316 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
320 if rlinkage.is_some() {
321 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
322 // Declare an internal global `extern_with_linkage_foo` which
323 // is initialized with the address of `foo`. If `foo` is
324 // discarded during linking (for example, if `foo` has weak
325 // linkage and there are no definitions), then
326 // `extern_with_linkage_foo` will instead be initialized to
329 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
330 let ref_data_id = module
331 .declare_data(&ref_name, Linkage::Local, false, false)
333 let mut data_ctx = DataContext::new();
334 data_ctx.set_align(align);
335 let data = module.declare_data_in_data(data_id, &mut data_ctx);
338 .take(pointer_ty(tcx).bytes() as usize)
341 data_ctx.write_data_addr(0, data, 0);
342 match module.define_data(ref_data_id, &data_ctx) {
343 // Every time the static is referenced there will be another definition of this global,
344 // so duplicate definitions are expected and allowed.
345 Err(ModuleError::DuplicateDefinition(_)) => {}
354 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
355 while let Some(todo_item) = cx.todo.pop() {
356 let (data_id, alloc, section_name) = match todo_item {
357 TodoItem::Alloc(alloc_id) => {
358 //println!("alloc_id {}", alloc_id);
359 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
360 GlobalAlloc::Memory(alloc) => alloc,
361 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
363 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
364 (data_id, alloc, None)
366 TodoItem::Static(def_id) => {
367 //println!("static {:?}", def_id);
369 let section_name = tcx
370 .codegen_fn_attrs(def_id)
372 .map(|s| s.as_str());
374 let alloc = tcx.eval_static_initializer(def_id).unwrap();
376 let data_id = data_id_for_static(tcx, module, def_id, true);
377 (data_id, alloc, section_name)
381 //("data_id {}", data_id);
382 if cx.done.contains(&data_id) {
386 let mut data_ctx = DataContext::new();
387 data_ctx.set_align(alloc.align.bytes());
389 if let Some(section_name) = section_name {
390 // FIXME set correct segment for Mach-O files
391 data_ctx.set_segment_section("", &*section_name);
395 .inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len())
397 data_ctx.define(bytes.into_boxed_slice());
399 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
401 let endianness = tcx.data_layout.endian;
402 let offset = offset.bytes() as usize;
403 let ptr_size = tcx.data_layout.pointer_size;
404 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
405 offset..offset + ptr_size.bytes() as usize,
407 read_target_uint(endianness, bytes).unwrap()
410 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
411 let data_id = match reloc_target_alloc {
412 GlobalAlloc::Function(instance) => {
413 assert_eq!(addend, 0);
414 let func_id = crate::abi::import_function(tcx, module, instance);
415 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
416 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
419 GlobalAlloc::Memory(target_alloc) => {
420 cx.todo.push(TodoItem::Alloc(reloc));
421 data_id_for_alloc_id(module, reloc, target_alloc.mutability)
423 GlobalAlloc::Static(def_id) => {
425 .codegen_fn_attrs(def_id)
427 .contains(CodegenFnAttrFlags::THREAD_LOCAL)
429 tcx.sess.fatal(&format!(
430 "Allocation {:?} contains reference to TLS value {:?}",
435 // Don't push a `TodoItem::Static` here, as it will cause statics used by
436 // multiple crates to be duplicated between them. It isn't necessary anyway,
437 // as it will get pushed by `codegen_static` when necessary.
438 data_id_for_static(tcx, module, def_id, false)
442 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
443 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
446 // FIXME don't duplicate definitions in lazy jit mode
447 let _ = module.define_data(data_id, &data_ctx);
448 cx.done.insert(data_id);
451 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
454 pub(crate) fn mir_operand_get_const_val<'tcx>(
455 fx: &FunctionCx<'_, '_, 'tcx>,
456 operand: &Operand<'tcx>,
457 ) -> Option<&'tcx Const<'tcx>> {
459 Operand::Copy(_) | Operand::Move(_) => None,
460 Operand::Constant(const_) => Some(
461 fx.monomorphize(const_.literal)
462 .eval(fx.tcx, ParamEnv::reveal_all()),