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 impl 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<'_, '_, impl Module>) -> 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, impl Module>,
84 layout: TyAndLayout<'tcx>,
86 let data_id = data_id_for_static(fx.tcx, &mut 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, impl Module>,
97 layout: TyAndLayout<'tcx>,
99 let data_id = data_id_for_static(fx.tcx, &mut 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, impl Module>,
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,
140 span_bug!(constant.span, "erroneous constant not captured by required_consts");
145 | ConstKind::Infer(_)
146 | ConstKind::Bound(_, _)
147 | ConstKind::Placeholder(_)
148 | ConstKind::Error(_) => unreachable!("{:?}", const_),
151 codegen_const_value(fx, const_val, const_.ty)
154 pub(crate) fn codegen_const_value<'tcx>(
155 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
156 const_val: ConstValue<'tcx>,
159 let layout = fx.layout_of(ty);
160 assert!(!layout.is_unsized(), "sized const value");
163 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
167 ConstValue::Scalar(x) => {
168 if fx.clif_type(layout.ty).is_none() {
169 let (size, align) = (layout.size, layout.align.pref);
170 let mut alloc = Allocation::from_bytes(
172 .take(size.bytes_usize())
173 .collect::<Vec<u8>>(),
176 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
177 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
178 let alloc = fx.tcx.intern_const_alloc(alloc);
179 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
183 Scalar::Int(int) => CValue::const_val(fx, layout, int),
184 Scalar::Ptr(ptr) => {
185 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
186 let base_addr = match alloc_kind {
187 Some(GlobalAlloc::Memory(alloc)) => {
188 fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
189 let data_id = data_id_for_alloc_id(
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, &mut 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));
210 data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
212 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
213 #[cfg(debug_assertions)]
214 fx.add_comment(local_data_id, format!("{:?}", def_id));
215 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
217 None => bug!("missing allocation {:?}", ptr.alloc_id),
219 let val = if ptr.offset.bytes() != 0 {
222 .iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
226 CValue::by_val(val, layout)
230 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
231 pointer_for_allocation(fx, alloc)
232 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
235 ConstValue::Slice { data, start, end } => {
236 let ptr = pointer_for_allocation(fx, data)
237 .offset_i64(fx, i64::try_from(start).unwrap())
239 let len = fx.bcx.ins().iconst(
241 i64::try_from(end.checked_sub(start).unwrap()).unwrap(),
243 CValue::by_val_pair(ptr, len, layout)
248 fn pointer_for_allocation<'tcx>(
249 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
250 alloc: &'tcx Allocation,
251 ) -> crate::pointer::Pointer {
252 let alloc_id = fx.tcx.create_memory_alloc(alloc);
253 fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
254 let data_id = data_id_for_alloc_id(&mut fx.cx.module, alloc_id, alloc.mutability);
256 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
257 #[cfg(debug_assertions)]
258 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
259 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
260 crate::pointer::Pointer::new(global_ptr)
263 fn data_id_for_alloc_id(
264 module: &mut impl Module,
266 mutability: rustc_hir::Mutability,
270 &format!(".L__alloc_{:x}", alloc_id.0),
272 mutability == rustc_hir::Mutability::Mut,
278 fn data_id_for_static(
280 module: &mut impl Module,
284 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
285 let linkage = if definition {
286 crate::linkage::get_static_linkage(tcx, def_id)
287 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
288 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
295 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
296 let symbol_name = tcx.symbol_name(instance).name;
297 let ty = instance.ty(tcx, ParamEnv::reveal_all());
298 let is_mutable = if tcx.is_mutable_static(def_id) {
301 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
304 .layout_of(ParamEnv::reveal_all().and(ty))
310 let attrs = tcx.codegen_fn_attrs(def_id);
317 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
321 if rlinkage.is_some() {
322 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
323 // Declare an internal global `extern_with_linkage_foo` which
324 // is initialized with the address of `foo`. If `foo` is
325 // discarded during linking (for example, if `foo` has weak
326 // linkage and there are no definitions), then
327 // `extern_with_linkage_foo` will instead be initialized to
330 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
331 let ref_data_id = module
332 .declare_data(&ref_name, Linkage::Local, false, false)
334 let mut data_ctx = DataContext::new();
335 data_ctx.set_align(align);
336 let data = module.declare_data_in_data(data_id, &mut data_ctx);
339 .take(pointer_ty(tcx).bytes() as usize)
342 data_ctx.write_data_addr(0, data, 0);
343 match module.define_data(ref_data_id, &data_ctx) {
344 // Every time the static is referenced there will be another definition of this global,
345 // so duplicate definitions are expected and allowed.
346 Err(ModuleError::DuplicateDefinition(_)) => {}
355 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut impl Module, cx: &mut ConstantCx) {
356 while let Some(todo_item) = cx.todo.pop() {
357 let (data_id, alloc, section_name) = match todo_item {
358 TodoItem::Alloc(alloc_id) => {
359 //println!("alloc_id {}", alloc_id);
360 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
361 GlobalAlloc::Memory(alloc) => alloc,
362 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
364 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
365 (data_id, alloc, None)
367 TodoItem::Static(def_id) => {
368 //println!("static {:?}", def_id);
370 let section_name = tcx
371 .codegen_fn_attrs(def_id)
373 .map(|s| s.as_str());
375 let alloc = tcx.eval_static_initializer(def_id).unwrap();
377 let data_id = data_id_for_static(tcx, module, def_id, true);
378 (data_id, alloc, section_name)
382 //("data_id {}", data_id);
383 if cx.done.contains(&data_id) {
387 let mut data_ctx = DataContext::new();
388 data_ctx.set_align(alloc.align.bytes());
390 if let Some(section_name) = section_name {
391 // FIXME set correct segment for Mach-O files
392 data_ctx.set_segment_section("", &*section_name);
396 .inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len())
398 data_ctx.define(bytes.into_boxed_slice());
400 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
402 let endianness = tcx.data_layout.endian;
403 let offset = offset.bytes() as usize;
404 let ptr_size = tcx.data_layout.pointer_size;
405 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
406 offset..offset + ptr_size.bytes() as usize,
408 read_target_uint(endianness, bytes).unwrap()
411 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
412 let data_id = match reloc_target_alloc {
413 GlobalAlloc::Function(instance) => {
414 assert_eq!(addend, 0);
415 let func_id = crate::abi::import_function(tcx, module, instance);
416 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
417 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
420 GlobalAlloc::Memory(target_alloc) => {
421 cx.todo.push(TodoItem::Alloc(reloc));
422 data_id_for_alloc_id(module, reloc, target_alloc.mutability)
424 GlobalAlloc::Static(def_id) => {
426 .codegen_fn_attrs(def_id)
428 .contains(CodegenFnAttrFlags::THREAD_LOCAL)
430 tcx.sess.fatal(&format!(
431 "Allocation {:?} contains reference to TLS value {:?}",
436 // Don't push a `TodoItem::Static` here, as it will cause statics used by
437 // multiple crates to be duplicated between them. It isn't necessary anyway,
438 // as it will get pushed by `codegen_static` when necessary.
439 data_id_for_static(tcx, module, def_id, false)
443 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
444 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
447 // FIXME don't duplicate definitions in lazy jit mode
448 let _ = module.define_data(data_id, &data_ctx);
449 cx.done.insert(data_id);
452 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
455 pub(crate) fn mir_operand_get_const_val<'tcx>(
456 fx: &FunctionCx<'_, 'tcx, impl Module>,
457 operand: &Operand<'tcx>,
458 ) -> Option<&'tcx Const<'tcx>> {
460 Operand::Copy(_) | Operand::Move(_) => None,
461 Operand::Constant(const_) => Some(
462 fx.monomorphize(const_.literal)
463 .eval(fx.tcx, ParamEnv::reveal_all()),