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,
8 use rustc_span::DUMMY_SP;
10 use cranelift_codegen::ir::GlobalValueData;
11 use cranelift_module::*;
13 use crate::prelude::*;
15 pub(crate) struct ConstantCx {
17 done: FxHashSet<DataId>,
18 anon_allocs: FxHashMap<AllocId, DataId>,
21 #[derive(Copy, Clone, Debug)]
28 pub(crate) fn new() -> Self {
29 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
32 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
33 //println!("todo {:?}", self.todo);
34 define_all_allocs(tcx, module, &mut self);
35 //println!("done {:?}", self.done);
40 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
41 let mut all_constants_ok = true;
42 for constant in &fx.mir.required_consts {
43 let unevaluated = match fx.monomorphize(constant.literal) {
44 ConstantKind::Ty(_) => unreachable!(),
45 ConstantKind::Unevaluated(uv, _) => uv,
46 ConstantKind::Val(..) => continue,
49 if let Err(err) = fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
50 all_constants_ok = false;
52 ErrorHandled::Reported(_) | ErrorHandled::Linted => {
53 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
55 ErrorHandled::TooGeneric => {
56 span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
64 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
65 let mut constants_cx = ConstantCx::new();
66 constants_cx.todo.push(TodoItem::Static(def_id));
67 constants_cx.finalize(tcx, module);
70 pub(crate) fn codegen_tls_ref<'tcx>(
71 fx: &mut FunctionCx<'_, '_, 'tcx>,
73 layout: TyAndLayout<'tcx>,
75 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
76 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
77 if fx.clif_comments.enabled() {
78 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
80 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
81 CValue::by_val(tls_ptr, layout)
84 fn codegen_static_ref<'tcx>(
85 fx: &mut FunctionCx<'_, '_, 'tcx>,
87 layout: TyAndLayout<'tcx>,
89 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
90 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
91 if fx.clif_comments.enabled() {
92 fx.add_comment(local_data_id, format!("{:?}", def_id));
94 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
95 assert!(!layout.is_unsized(), "unsized statics aren't supported");
98 fx.bcx.func.global_values[local_data_id],
99 GlobalValueData::Symbol { tls: false, .. }
101 "tls static referenced without Rvalue::ThreadLocalRef"
103 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
106 pub(crate) fn codegen_constant<'tcx>(
107 fx: &mut FunctionCx<'_, '_, 'tcx>,
108 constant: &Constant<'tcx>,
110 let (const_val, ty) = match fx.monomorphize(constant.literal) {
111 ConstantKind::Ty(const_) => unreachable!("{:?}", const_),
112 ConstantKind::Unevaluated(mir::UnevaluatedConst { def, substs, promoted }, ty)
113 if fx.tcx.is_static(def.did) =>
115 assert!(substs.is_empty());
116 assert!(promoted.is_none());
118 return codegen_static_ref(fx, def.did, fx.layout_of(ty)).to_cvalue(fx);
120 ConstantKind::Unevaluated(unevaluated, ty) => {
121 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
122 Ok(const_val) => (const_val, ty),
124 span_bug!(constant.span, "erroneous constant not captured by required_consts");
128 ConstantKind::Val(val, ty) => (val, ty),
131 codegen_const_value(fx, const_val, ty)
134 pub(crate) fn codegen_const_value<'tcx>(
135 fx: &mut FunctionCx<'_, '_, 'tcx>,
136 const_val: ConstValue<'tcx>,
139 let layout = fx.layout_of(ty);
140 assert!(!layout.is_unsized(), "sized const value");
143 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
147 ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
148 ConstValue::Scalar(x) => match x {
149 Scalar::Int(int) => {
150 if fx.clif_type(layout.ty).is_some() {
151 return CValue::const_val(fx, layout, int);
153 let raw_val = int.to_bits(int.size()).unwrap();
154 let val = match int.size().bytes() {
155 1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
156 2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
157 4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
158 8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
160 let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
162 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
163 fx.bcx.ins().iconcat(lsb, msb)
168 let place = CPlace::new_stack_slot(fx, layout);
169 place.to_ptr().store(fx, val, MemFlags::trusted());
173 Scalar::Ptr(ptr, _size) => {
174 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
175 let base_addr = match fx.tcx.global_alloc(alloc_id) {
176 GlobalAlloc::Memory(alloc) => {
177 let data_id = data_id_for_alloc_id(
178 &mut fx.constants_cx,
181 alloc.inner().mutability,
184 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
185 if fx.clif_comments.enabled() {
186 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
188 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
190 GlobalAlloc::Function(instance) => {
191 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
193 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
194 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
196 GlobalAlloc::VTable(ty, trait_ref) => {
197 let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
198 let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
199 // FIXME: factor this common code with the `Memory` arm into a function?
200 let data_id = data_id_for_alloc_id(
201 &mut fx.constants_cx,
204 alloc.inner().mutability,
207 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
208 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
210 GlobalAlloc::Static(def_id) => {
211 assert!(fx.tcx.is_static(def_id));
212 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
214 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
215 if fx.clif_comments.enabled() {
216 fx.add_comment(local_data_id, format!("{:?}", def_id));
218 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
221 let val = if offset.bytes() != 0 {
222 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
226 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())
241 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
242 CValue::by_val_pair(ptr, len, layout)
247 pub(crate) fn pointer_for_allocation<'tcx>(
248 fx: &mut FunctionCx<'_, '_, 'tcx>,
249 alloc: ConstAllocation<'tcx>,
250 ) -> crate::pointer::Pointer {
251 let alloc_id = fx.tcx.create_memory_alloc(alloc);
252 let data_id = data_id_for_alloc_id(
253 &mut fx.constants_cx,
256 alloc.inner().mutability,
259 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
260 if fx.clif_comments.enabled() {
261 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
263 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
264 crate::pointer::Pointer::new(global_ptr)
267 pub(crate) fn data_id_for_alloc_id(
269 module: &mut dyn Module,
271 mutability: rustc_hir::Mutability,
273 cx.todo.push(TodoItem::Alloc(alloc_id));
274 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
275 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
279 fn data_id_for_static(
281 module: &mut dyn Module,
285 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
286 let linkage = if definition {
287 crate::linkage::get_static_linkage(tcx, def_id)
288 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
289 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
296 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
297 let symbol_name = tcx.symbol_name(instance).name;
298 let ty = instance.ty(tcx, ParamEnv::reveal_all());
299 let is_mutable = if tcx.is_mutable_static(def_id) {
302 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
304 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
306 let attrs = tcx.codegen_fn_attrs(def_id);
308 let data_id = match module.declare_data(
312 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
314 Ok(data_id) => data_id,
315 Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
316 "attempt to declare `{symbol_name}` as static, but it was already declared as function"
318 Err(err) => Err::<_, _>(err).unwrap(),
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.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
332 let mut data_ctx = DataContext::new();
333 data_ctx.set_align(align);
334 let data = module.declare_data_in_data(data_id, &mut data_ctx);
335 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
336 data_ctx.write_data_addr(0, data, 0);
337 match module.define_data(ref_data_id, &data_ctx) {
338 // Every time the static is referenced there will be another definition of this global,
339 // so duplicate definitions are expected and allowed.
340 Err(ModuleError::DuplicateDefinition(_)) => {}
349 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
350 while let Some(todo_item) = cx.todo.pop() {
351 let (data_id, alloc, section_name) = match todo_item {
352 TodoItem::Alloc(alloc_id) => {
353 let alloc = match tcx.global_alloc(alloc_id) {
354 GlobalAlloc::Memory(alloc) => alloc,
355 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::VTable(..) => {
359 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
361 .declare_anonymous_data(
362 alloc.inner().mutability == rustc_hir::Mutability::Mut,
367 (data_id, alloc, None)
369 TodoItem::Static(def_id) => {
370 //println!("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 //("data_id {}", data_id);
382 if cx.done.contains(&data_id) {
386 let mut data_ctx = DataContext::new();
387 let alloc = alloc.inner();
388 data_ctx.set_align(alloc.align.bytes());
390 if let Some(section_name) = section_name {
391 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
392 let section_name = section_name.as_str();
393 if let Some(names) = section_name.split_once(',') {
396 tcx.sess.fatal(&format!(
397 "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
402 ("", section_name.as_str())
404 data_ctx.set_segment_section(segment_name, section_name);
407 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
408 data_ctx.define(bytes.into_boxed_slice());
410 for &(offset, alloc_id) in alloc.provenance().iter() {
412 let endianness = tcx.data_layout.endian;
413 let offset = offset.bytes() as usize;
414 let ptr_size = tcx.data_layout.pointer_size;
415 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
416 offset..offset + ptr_size.bytes() as usize,
418 read_target_uint(endianness, bytes).unwrap()
421 let reloc_target_alloc = tcx.global_alloc(alloc_id);
422 let data_id = match reloc_target_alloc {
423 GlobalAlloc::Function(instance) => {
424 assert_eq!(addend, 0);
426 crate::abi::import_function(tcx, module, instance.polymorphize(tcx));
427 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
428 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
431 GlobalAlloc::Memory(target_alloc) => {
432 data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
434 GlobalAlloc::VTable(ty, trait_ref) => {
435 let alloc_id = tcx.vtable_allocation((ty, trait_ref));
436 data_id_for_alloc_id(cx, module, alloc_id, Mutability::Not)
438 GlobalAlloc::Static(def_id) => {
439 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
441 tcx.sess.fatal(&format!(
442 "Allocation {:?} contains reference to TLS value {:?}",
447 // Don't push a `TodoItem::Static` here, as it will cause statics used by
448 // multiple crates to be duplicated between them. It isn't necessary anyway,
449 // as it will get pushed by `codegen_static` when necessary.
450 data_id_for_static(tcx, module, def_id, false)
454 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
455 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
458 module.define_data(data_id, &data_ctx).unwrap();
459 cx.done.insert(data_id);
462 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
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_) => match const_.literal {
471 ConstantKind::Ty(const_) => fx
472 .monomorphize(const_)
473 .eval_for_mir(fx.tcx, ParamEnv::reveal_all())
474 .try_to_value(fx.tcx),
475 ConstantKind::Val(val, _) => Some(val),
476 ConstantKind::Unevaluated(uv, _) => {
477 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), uv, None).ok()
480 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
481 // inside a temporary before being passed to the intrinsic requiring the const argument.
482 // This code tries to find a single constant defining definition of the referenced local.
483 Operand::Copy(place) | Operand::Move(place) => {
484 if !place.projection.is_empty() {
487 let mut computed_const_val = None;
488 for bb_data in fx.mir.basic_blocks.iter() {
489 for stmt in &bb_data.statements {
491 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
492 match &local_and_rvalue.1 {
493 Rvalue::Cast(CastKind::Misc, operand, ty) => {
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 { .. } => {}