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_middle::ty::ConstKind;
9 use rustc_span::DUMMY_SP;
11 use cranelift_codegen::ir::GlobalValueData;
12 use cranelift_module::*;
14 use crate::prelude::*;
16 pub(crate) struct ConstantCx {
18 done: FxHashSet<DataId>,
19 anon_allocs: FxHashMap<AllocId, DataId>,
22 #[derive(Copy, Clone, Debug)]
29 pub(crate) fn new() -> Self {
30 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
33 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
34 //println!("todo {:?}", self.todo);
35 define_all_allocs(tcx, module, &mut self);
36 //println!("done {:?}", self.done);
41 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
42 let mut all_constants_ok = true;
43 for constant in &fx.mir.required_consts {
44 let unevaluated = match fx.monomorphize(constant.literal) {
45 ConstantKind::Ty(ct) => match ct.kind() {
46 ConstKind::Unevaluated(uv) => uv.expand(),
47 ConstKind::Value(_) => continue,
50 | ConstKind::Bound(_, _)
51 | ConstKind::Placeholder(_)
52 | ConstKind::Error(_) => unreachable!("{:?}", ct),
54 ConstantKind::Unevaluated(uv, _) => uv,
55 ConstantKind::Val(..) => continue,
58 if let Err(err) = fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
59 all_constants_ok = false;
61 ErrorHandled::Reported(_) | ErrorHandled::Linted => {
62 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
64 ErrorHandled::TooGeneric => {
65 span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
73 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
74 let mut constants_cx = ConstantCx::new();
75 constants_cx.todo.push(TodoItem::Static(def_id));
76 constants_cx.finalize(tcx, module);
79 pub(crate) fn codegen_tls_ref<'tcx>(
80 fx: &mut FunctionCx<'_, '_, 'tcx>,
82 layout: TyAndLayout<'tcx>,
84 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
85 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
86 if fx.clif_comments.enabled() {
87 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
89 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
90 CValue::by_val(tls_ptr, layout)
93 fn codegen_static_ref<'tcx>(
94 fx: &mut FunctionCx<'_, '_, 'tcx>,
96 layout: TyAndLayout<'tcx>,
98 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
99 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
100 if fx.clif_comments.enabled() {
101 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_val, ty) = match fx.monomorphize(constant.literal) {
120 ConstantKind::Ty(const_) => unreachable!("{:?}", const_),
121 ConstantKind::Unevaluated(ty::Unevaluated { def, substs, promoted }, ty)
122 if fx.tcx.is_static(def.did) =>
124 assert!(substs.is_empty());
125 assert!(promoted.is_none());
127 return codegen_static_ref(fx, def.did, fx.layout_of(ty)).to_cvalue(fx);
129 ConstantKind::Unevaluated(unevaluated, ty) => {
130 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
131 Ok(const_val) => (const_val, ty),
133 span_bug!(constant.span, "erroneous constant not captured by required_consts");
137 ConstantKind::Val(val, ty) => (val, ty),
140 codegen_const_value(fx, const_val, ty)
143 pub(crate) fn codegen_const_value<'tcx>(
144 fx: &mut FunctionCx<'_, '_, 'tcx>,
145 const_val: ConstValue<'tcx>,
148 let layout = fx.layout_of(ty);
149 assert!(!layout.is_unsized(), "sized const value");
152 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
156 ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
157 ConstValue::Scalar(x) => match x {
158 Scalar::Int(int) => {
159 if fx.clif_type(layout.ty).is_some() {
160 return CValue::const_val(fx, layout, int);
162 let raw_val = int.to_bits(int.size()).unwrap();
163 let val = match int.size().bytes() {
164 1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
165 2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
166 4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
167 8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
169 let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
171 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
172 fx.bcx.ins().iconcat(lsb, msb)
177 let place = CPlace::new_stack_slot(fx, layout);
178 place.to_ptr().store(fx, val, MemFlags::trusted());
182 Scalar::Ptr(ptr, _size) => {
183 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
184 let base_addr = match fx.tcx.global_alloc(alloc_id) {
185 GlobalAlloc::Memory(alloc) => {
186 let data_id = data_id_for_alloc_id(
187 &mut fx.constants_cx,
190 alloc.inner().mutability,
193 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
194 if fx.clif_comments.enabled() {
195 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
197 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
199 GlobalAlloc::Function(instance) => {
200 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
202 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
203 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
205 GlobalAlloc::VTable(ty, trait_ref) => {
206 let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
207 let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
208 // FIXME: factor this common code with the `Memory` arm into a function?
209 let data_id = data_id_for_alloc_id(
210 &mut fx.constants_cx,
213 alloc.inner().mutability,
216 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
217 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
219 GlobalAlloc::Static(def_id) => {
220 assert!(fx.tcx.is_static(def_id));
221 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
223 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
224 if fx.clif_comments.enabled() {
225 fx.add_comment(local_data_id, format!("{:?}", def_id));
227 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
230 let val = if offset.bytes() != 0 {
231 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
235 CValue::by_val(val, layout)
238 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
239 pointer_for_allocation(fx, alloc)
240 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
243 ConstValue::Slice { data, start, end } => {
244 let ptr = pointer_for_allocation(fx, data)
245 .offset_i64(fx, i64::try_from(start).unwrap())
250 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
251 CValue::by_val_pair(ptr, len, layout)
256 pub(crate) fn pointer_for_allocation<'tcx>(
257 fx: &mut FunctionCx<'_, '_, 'tcx>,
258 alloc: ConstAllocation<'tcx>,
259 ) -> crate::pointer::Pointer {
260 let alloc_id = fx.tcx.create_memory_alloc(alloc);
261 let data_id = data_id_for_alloc_id(
262 &mut fx.constants_cx,
265 alloc.inner().mutability,
268 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
269 if fx.clif_comments.enabled() {
270 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
272 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
273 crate::pointer::Pointer::new(global_ptr)
276 pub(crate) fn data_id_for_alloc_id(
278 module: &mut dyn Module,
280 mutability: rustc_hir::Mutability,
282 cx.todo.push(TodoItem::Alloc(alloc_id));
283 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
284 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
288 fn data_id_for_static(
290 module: &mut dyn Module,
294 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
295 let linkage = if definition {
296 crate::linkage::get_static_linkage(tcx, def_id)
297 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
298 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
305 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
306 let symbol_name = tcx.symbol_name(instance).name;
307 let ty = instance.ty(tcx, ParamEnv::reveal_all());
308 let is_mutable = if tcx.is_mutable_static(def_id) {
311 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
313 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
315 let attrs = tcx.codegen_fn_attrs(def_id);
317 let data_id = match module.declare_data(
321 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
323 Ok(data_id) => data_id,
324 Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
325 "attempt to declare `{symbol_name}` as static, but it was already declared as function"
327 Err(err) => Err::<_, _>(err).unwrap(),
330 if rlinkage.is_some() {
331 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
332 // Declare an internal global `extern_with_linkage_foo` which
333 // is initialized with the address of `foo`. If `foo` is
334 // discarded during linking (for example, if `foo` has weak
335 // linkage and there are no definitions), then
336 // `extern_with_linkage_foo` will instead be initialized to
339 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
340 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
341 let mut data_ctx = DataContext::new();
342 data_ctx.set_align(align);
343 let data = module.declare_data_in_data(data_id, &mut data_ctx);
344 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
345 data_ctx.write_data_addr(0, data, 0);
346 match module.define_data(ref_data_id, &data_ctx) {
347 // Every time the static is referenced there will be another definition of this global,
348 // so duplicate definitions are expected and allowed.
349 Err(ModuleError::DuplicateDefinition(_)) => {}
358 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
359 while let Some(todo_item) = cx.todo.pop() {
360 let (data_id, alloc, section_name) = match todo_item {
361 TodoItem::Alloc(alloc_id) => {
362 let alloc = match tcx.global_alloc(alloc_id) {
363 GlobalAlloc::Memory(alloc) => alloc,
364 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::VTable(..) => {
368 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
370 .declare_anonymous_data(
371 alloc.inner().mutability == rustc_hir::Mutability::Mut,
376 (data_id, alloc, None)
378 TodoItem::Static(def_id) => {
379 //println!("static {:?}", def_id);
381 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
383 let alloc = tcx.eval_static_initializer(def_id).unwrap();
385 let data_id = data_id_for_static(tcx, module, def_id, true);
386 (data_id, alloc, section_name)
390 //("data_id {}", data_id);
391 if cx.done.contains(&data_id) {
395 let mut data_ctx = DataContext::new();
396 let alloc = alloc.inner();
397 data_ctx.set_align(alloc.align.bytes());
399 if let Some(section_name) = section_name {
400 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
401 let section_name = section_name.as_str();
402 if let Some(names) = section_name.split_once(',') {
405 tcx.sess.fatal(&format!(
406 "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
411 ("", section_name.as_str())
413 data_ctx.set_segment_section(segment_name, section_name);
416 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
417 data_ctx.define(bytes.into_boxed_slice());
419 for &(offset, alloc_id) in alloc.provenance().iter() {
421 let endianness = tcx.data_layout.endian;
422 let offset = offset.bytes() as usize;
423 let ptr_size = tcx.data_layout.pointer_size;
424 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
425 offset..offset + ptr_size.bytes() as usize,
427 read_target_uint(endianness, bytes).unwrap()
430 let reloc_target_alloc = tcx.global_alloc(alloc_id);
431 let data_id = match reloc_target_alloc {
432 GlobalAlloc::Function(instance) => {
433 assert_eq!(addend, 0);
435 crate::abi::import_function(tcx, module, instance.polymorphize(tcx));
436 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
437 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
440 GlobalAlloc::Memory(target_alloc) => {
441 data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
443 GlobalAlloc::VTable(ty, trait_ref) => {
444 let alloc_id = tcx.vtable_allocation((ty, trait_ref));
445 data_id_for_alloc_id(cx, module, alloc_id, Mutability::Not)
447 GlobalAlloc::Static(def_id) => {
448 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
450 tcx.sess.fatal(&format!(
451 "Allocation {:?} contains reference to TLS value {:?}",
456 // Don't push a `TodoItem::Static` here, as it will cause statics used by
457 // multiple crates to be duplicated between them. It isn't necessary anyway,
458 // as it will get pushed by `codegen_static` when necessary.
459 data_id_for_static(tcx, module, def_id, false)
463 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
464 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
467 module.define_data(data_id, &data_ctx).unwrap();
468 cx.done.insert(data_id);
471 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
474 pub(crate) fn mir_operand_get_const_val<'tcx>(
475 fx: &FunctionCx<'_, '_, 'tcx>,
476 operand: &Operand<'tcx>,
477 ) -> Option<ConstValue<'tcx>> {
479 Operand::Constant(const_) => match const_.literal {
480 ConstantKind::Ty(const_) => fx
481 .monomorphize(const_)
482 .eval_for_mir(fx.tcx, ParamEnv::reveal_all())
483 .try_to_value(fx.tcx),
484 ConstantKind::Val(val, _) => Some(val),
485 ConstantKind::Unevaluated(uv, _) => {
486 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), uv, None).ok()
489 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
490 // inside a temporary before being passed to the intrinsic requiring the const argument.
491 // This code tries to find a single constant defining definition of the referenced local.
492 Operand::Copy(place) | Operand::Move(place) => {
493 if !place.projection.is_empty() {
496 let mut computed_const_val = None;
497 for bb_data in fx.mir.basic_blocks.iter() {
498 for stmt in &bb_data.statements {
500 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
501 match &local_and_rvalue.1 {
502 Rvalue::Cast(CastKind::Misc, operand, ty) => {
503 if computed_const_val.is_some() {
504 return None; // local assigned twice
506 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
509 let const_val = mir_operand_get_const_val(fx, operand)?;
510 if fx.layout_of(*ty).size
511 != const_val.try_to_scalar_int()?.size()
515 computed_const_val = Some(const_val);
517 Rvalue::Use(operand) => {
518 computed_const_val = mir_operand_get_const_val(fx, operand)
523 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
524 if &**stmt_place == place =>
528 StatementKind::Intrinsic(ref intrinsic) => match **intrinsic {
529 NonDivergingIntrinsic::CopyNonOverlapping(..) => return None,
530 NonDivergingIntrinsic::Assume(..) => {}
532 // conservative handling
533 StatementKind::Assign(_)
534 | StatementKind::FakeRead(_)
535 | StatementKind::SetDiscriminant { .. }
536 | StatementKind::Deinit(_)
537 | StatementKind::StorageLive(_)
538 | StatementKind::StorageDead(_)
539 | StatementKind::Retag(_, _)
540 | StatementKind::AscribeUserType(_, _)
541 | StatementKind::Coverage(_)
542 | StatementKind::Nop => {}
545 match &bb_data.terminator().kind {
546 TerminatorKind::Goto { .. }
547 | TerminatorKind::SwitchInt { .. }
548 | TerminatorKind::Resume
549 | TerminatorKind::Abort
550 | TerminatorKind::Return
551 | TerminatorKind::Unreachable
552 | TerminatorKind::Drop { .. }
553 | TerminatorKind::Assert { .. } => {}
554 TerminatorKind::DropAndReplace { .. }
555 | TerminatorKind::Yield { .. }
556 | TerminatorKind::GeneratorDrop
557 | TerminatorKind::FalseEdge { .. }
558 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
559 TerminatorKind::InlineAsm { .. } => return None,
560 TerminatorKind::Call { destination, target: Some(_), .. }
561 if destination == place =>
565 TerminatorKind::Call { .. } => {}