1 //! Handling of `static`s, `const`s and promoted allocations
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
5 use rustc_middle::mir::interpret::{
6 read_target_uint, AllocId, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, Scalar,
9 use cranelift_module::*;
11 use crate::prelude::*;
13 pub(crate) struct ConstantCx {
15 done: FxHashSet<DataId>,
16 anon_allocs: FxHashMap<AllocId, DataId>,
19 #[derive(Copy, Clone, Debug)]
26 pub(crate) fn new() -> Self {
27 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
30 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
31 define_all_allocs(tcx, module, &mut self);
36 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
37 let mut all_constants_ok = true;
38 for constant in &fx.mir.required_consts {
39 if eval_mir_constant(fx, constant).is_none() {
40 all_constants_ok = false;
46 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
47 let mut constants_cx = ConstantCx::new();
48 constants_cx.todo.push(TodoItem::Static(def_id));
49 constants_cx.finalize(tcx, module);
52 pub(crate) fn codegen_tls_ref<'tcx>(
53 fx: &mut FunctionCx<'_, '_, 'tcx>,
55 layout: TyAndLayout<'tcx>,
57 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
58 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
59 if fx.clif_comments.enabled() {
60 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
62 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
63 CValue::by_val(tls_ptr, layout)
66 pub(crate) fn eval_mir_constant<'tcx>(
67 fx: &FunctionCx<'_, '_, 'tcx>,
68 constant: &Constant<'tcx>,
69 ) -> Option<(ConstValue<'tcx>, Ty<'tcx>)> {
70 let constant_kind = fx.monomorphize(constant.literal);
71 let uv = match constant_kind {
72 ConstantKind::Ty(const_) => match const_.kind() {
73 ty::ConstKind::Unevaluated(uv) => uv.expand(),
74 ty::ConstKind::Value(val) => {
75 return Some((fx.tcx.valtree_to_const_val((const_.ty(), val)), const_.ty()));
79 "encountered bad ConstKind after monomorphizing: {:?}",
83 ConstantKind::Unevaluated(mir::UnevaluatedConst { def, .. }, _)
84 if fx.tcx.is_static(def.did) =>
86 span_bug!(constant.span, "MIR constant refers to static");
88 ConstantKind::Unevaluated(uv, _) => uv,
89 ConstantKind::Val(val, _) => return Some((val, constant_kind.ty())),
94 .const_eval_resolve(ty::ParamEnv::reveal_all(), uv, None)
95 .map_err(|err| match err {
96 ErrorHandled::Reported(_) => {
97 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
99 ErrorHandled::TooGeneric => {
100 span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
104 val.map(|val| (val, constant_kind.ty()))
107 pub(crate) fn codegen_constant_operand<'tcx>(
108 fx: &mut FunctionCx<'_, '_, 'tcx>,
109 constant: &Constant<'tcx>,
111 let (const_val, ty) = eval_mir_constant(fx, constant).unwrap_or_else(|| {
112 span_bug!(constant.span, "erroneous constant not captured by required_consts")
115 codegen_const_value(fx, const_val, ty)
118 pub(crate) fn codegen_const_value<'tcx>(
119 fx: &mut FunctionCx<'_, '_, 'tcx>,
120 const_val: ConstValue<'tcx>,
123 let layout = fx.layout_of(ty);
124 assert!(layout.is_sized(), "unsized const value");
127 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
131 ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
132 ConstValue::Scalar(x) => match x {
133 Scalar::Int(int) => {
134 if fx.clif_type(layout.ty).is_some() {
135 return CValue::const_val(fx, layout, int);
137 let raw_val = int.to_bits(int.size()).unwrap();
138 let val = match int.size().bytes() {
139 1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
140 2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
141 4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
142 8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
144 let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
146 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
147 fx.bcx.ins().iconcat(lsb, msb)
152 let place = CPlace::new_stack_slot(fx, layout);
153 place.to_ptr().store(fx, val, MemFlags::trusted());
157 Scalar::Ptr(ptr, _size) => {
158 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
159 let base_addr = match fx.tcx.global_alloc(alloc_id) {
160 GlobalAlloc::Memory(alloc) => {
161 let data_id = data_id_for_alloc_id(
162 &mut fx.constants_cx,
165 alloc.inner().mutability,
168 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
169 if fx.clif_comments.enabled() {
170 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
172 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
174 GlobalAlloc::Function(instance) => {
175 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
177 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
178 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
180 GlobalAlloc::VTable(ty, trait_ref) => {
181 let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
182 let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
183 // FIXME: factor this common code with the `Memory` arm into a function?
184 let data_id = data_id_for_alloc_id(
185 &mut fx.constants_cx,
188 alloc.inner().mutability,
191 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
192 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
194 GlobalAlloc::Static(def_id) => {
195 assert!(fx.tcx.is_static(def_id));
196 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
198 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
199 if fx.clif_comments.enabled() {
200 fx.add_comment(local_data_id, format!("{:?}", def_id));
202 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
205 let val = if offset.bytes() != 0 {
206 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
210 CValue::by_val(val, layout)
213 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
214 pointer_for_allocation(fx, alloc)
215 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
218 ConstValue::Slice { data, start, end } => {
219 let ptr = pointer_for_allocation(fx, data)
220 .offset_i64(fx, i64::try_from(start).unwrap())
225 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
226 CValue::by_val_pair(ptr, len, layout)
231 fn pointer_for_allocation<'tcx>(
232 fx: &mut FunctionCx<'_, '_, 'tcx>,
233 alloc: ConstAllocation<'tcx>,
234 ) -> crate::pointer::Pointer {
235 let alloc_id = fx.tcx.create_memory_alloc(alloc);
236 let data_id = data_id_for_alloc_id(
237 &mut fx.constants_cx,
240 alloc.inner().mutability,
243 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
244 if fx.clif_comments.enabled() {
245 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
247 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
248 crate::pointer::Pointer::new(global_ptr)
251 pub(crate) fn data_id_for_alloc_id(
253 module: &mut dyn Module,
255 mutability: rustc_hir::Mutability,
257 cx.todo.push(TodoItem::Alloc(alloc_id));
260 .or_insert_with(|| module.declare_anonymous_data(mutability.is_mut(), false).unwrap())
263 fn data_id_for_static(
265 module: &mut dyn Module,
269 let attrs = tcx.codegen_fn_attrs(def_id);
271 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
272 let symbol_name = tcx.symbol_name(instance).name;
273 let ty = instance.ty(tcx, ParamEnv::reveal_all());
274 let is_mutable = if tcx.is_mutable_static(def_id) {
277 !ty.is_freeze(tcx, ParamEnv::reveal_all())
279 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
281 if let Some(import_linkage) = attrs.import_linkage {
282 assert!(!definition);
284 let linkage = if import_linkage == rustc_middle::mir::mono::Linkage::ExternalWeak
285 || import_linkage == rustc_middle::mir::mono::Linkage::WeakAny
292 let data_id = match module.declare_data(
296 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
298 Ok(data_id) => data_id,
299 Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
300 "attempt to declare `{symbol_name}` as static, but it was already declared as function"
302 Err(err) => Err::<_, _>(err).unwrap(),
305 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
306 // Declare an internal global `extern_with_linkage_foo` which
307 // is initialized with the address of `foo`. If `foo` is
308 // discarded during linking (for example, if `foo` has weak
309 // linkage and there are no definitions), then
310 // `extern_with_linkage_foo` will instead be initialized to
313 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
314 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
315 let mut data_ctx = DataContext::new();
316 data_ctx.set_align(align);
317 let data = module.declare_data_in_data(data_id, &mut data_ctx);
318 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
319 data_ctx.write_data_addr(0, data, 0);
320 match module.define_data(ref_data_id, &data_ctx) {
321 // Every time the static is referenced there will be another definition of this global,
322 // so duplicate definitions are expected and allowed.
323 Err(ModuleError::DuplicateDefinition(_)) => {}
330 let linkage = if definition {
331 crate::linkage::get_static_linkage(tcx, def_id)
332 } else if attrs.linkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
333 || attrs.linkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
340 let data_id = match module.declare_data(
344 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
346 Ok(data_id) => data_id,
347 Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
348 "attempt to declare `{symbol_name}` as static, but it was already declared as function"
350 Err(err) => Err::<_, _>(err).unwrap(),
356 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
357 while let Some(todo_item) = cx.todo.pop() {
358 let (data_id, alloc, section_name) = match todo_item {
359 TodoItem::Alloc(alloc_id) => {
360 let alloc = match tcx.global_alloc(alloc_id) {
361 GlobalAlloc::Memory(alloc) => alloc,
362 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::VTable(..) => {
366 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
367 module.declare_anonymous_data(alloc.inner().mutability.is_mut(), false).unwrap()
369 (data_id, alloc, None)
371 TodoItem::Static(def_id) => {
372 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
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 if cx.done.contains(&data_id) {
385 let mut data_ctx = DataContext::new();
386 let alloc = alloc.inner();
387 data_ctx.set_align(alloc.align.bytes());
389 if let Some(section_name) = section_name {
390 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
391 let section_name = section_name.as_str();
392 if let Some(names) = section_name.split_once(',') {
395 tcx.sess.fatal(&format!(
396 "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
401 ("", section_name.as_str())
403 data_ctx.set_segment_section(segment_name, section_name);
406 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
407 data_ctx.define(bytes.into_boxed_slice());
409 for &(offset, alloc_id) in alloc.provenance().ptrs().iter() {
411 let endianness = tcx.data_layout.endian;
412 let offset = offset.bytes() as usize;
413 let ptr_size = tcx.data_layout.pointer_size;
414 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
415 offset..offset + ptr_size.bytes() as usize,
417 read_target_uint(endianness, bytes).unwrap()
420 let reloc_target_alloc = tcx.global_alloc(alloc_id);
421 let data_id = match reloc_target_alloc {
422 GlobalAlloc::Function(instance) => {
423 assert_eq!(addend, 0);
425 crate::abi::import_function(tcx, module, instance.polymorphize(tcx));
426 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
427 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
430 GlobalAlloc::Memory(target_alloc) => {
431 data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
433 GlobalAlloc::VTable(ty, trait_ref) => {
434 let alloc_id = tcx.vtable_allocation((ty, trait_ref));
435 data_id_for_alloc_id(cx, module, alloc_id, Mutability::Not)
437 GlobalAlloc::Static(def_id) => {
438 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
440 tcx.sess.fatal(&format!(
441 "Allocation {:?} contains reference to TLS value {:?}",
446 // Don't push a `TodoItem::Static` here, as it will cause statics used by
447 // multiple crates to be duplicated between them. It isn't necessary anyway,
448 // as it will get pushed by `codegen_static` when necessary.
449 data_id_for_static(tcx, module, def_id, false)
453 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
454 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
457 module.define_data(data_id, &data_ctx).unwrap();
458 cx.done.insert(data_id);
461 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
464 /// Used only for intrinsic implementations that need a compile-time constant
465 pub(crate) fn mir_operand_get_const_val<'tcx>(
466 fx: &FunctionCx<'_, '_, 'tcx>,
467 operand: &Operand<'tcx>,
468 ) -> Option<ConstValue<'tcx>> {
470 Operand::Constant(const_) => Some(eval_mir_constant(fx, const_).unwrap().0),
471 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
472 // inside a temporary before being passed to the intrinsic requiring the const argument.
473 // This code tries to find a single constant defining definition of the referenced local.
474 Operand::Copy(place) | Operand::Move(place) => {
475 if !place.projection.is_empty() {
478 let mut computed_const_val = None;
479 for bb_data in fx.mir.basic_blocks.iter() {
480 for stmt in &bb_data.statements {
482 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
483 match &local_and_rvalue.1 {
486 | CastKind::FloatToFloat
487 | CastKind::FloatToInt
488 | CastKind::IntToFloat
489 | CastKind::FnPtrToPtr
490 | CastKind::PtrToPtr,
494 if computed_const_val.is_some() {
495 return None; // local assigned twice
497 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
500 let const_val = mir_operand_get_const_val(fx, operand)?;
501 if fx.layout_of(*ty).size
502 != const_val.try_to_scalar_int()?.size()
506 computed_const_val = Some(const_val);
508 Rvalue::Use(operand) => {
509 computed_const_val = mir_operand_get_const_val(fx, operand)
514 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
515 if &**stmt_place == place =>
519 StatementKind::Intrinsic(ref intrinsic) => match **intrinsic {
520 NonDivergingIntrinsic::CopyNonOverlapping(..) => return None,
521 NonDivergingIntrinsic::Assume(..) => {}
523 // conservative handling
524 StatementKind::Assign(_)
525 | StatementKind::FakeRead(_)
526 | StatementKind::SetDiscriminant { .. }
527 | StatementKind::Deinit(_)
528 | StatementKind::StorageLive(_)
529 | StatementKind::StorageDead(_)
530 | StatementKind::Retag(_, _)
531 | StatementKind::AscribeUserType(_, _)
532 | StatementKind::Coverage(_)
533 | StatementKind::Nop => {}
536 match &bb_data.terminator().kind {
537 TerminatorKind::Goto { .. }
538 | TerminatorKind::SwitchInt { .. }
539 | TerminatorKind::Resume
540 | TerminatorKind::Abort
541 | TerminatorKind::Return
542 | TerminatorKind::Unreachable
543 | TerminatorKind::Drop { .. }
544 | TerminatorKind::Assert { .. } => {}
545 TerminatorKind::DropAndReplace { .. }
546 | TerminatorKind::Yield { .. }
547 | TerminatorKind::GeneratorDrop
548 | TerminatorKind::FalseEdge { .. }
549 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
550 TerminatorKind::InlineAsm { .. } => return None,
551 TerminatorKind::Call { destination, target: Some(_), .. }
552 if destination == place =>
556 TerminatorKind::Call { .. } => {}