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 const_ = match fx.monomorphize(constant.literal) {
45 ConstantKind::Ty(ct) => ct,
46 ConstantKind::Val(..) => continue,
49 ConstKind::Value(_) => {}
50 ConstKind::Unevaluated(unevaluated) => {
52 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None)
54 all_constants_ok = false;
56 ErrorHandled::Reported(_) | ErrorHandled::Linted => {
57 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
59 ErrorHandled::TooGeneric => {
62 "codgen encountered polymorphic constant: {:?}",
71 | ConstKind::Bound(_, _)
72 | ConstKind::Placeholder(_)
73 | ConstKind::Error(_) => unreachable!("{:?}", const_),
79 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
80 let mut constants_cx = ConstantCx::new();
81 constants_cx.todo.push(TodoItem::Static(def_id));
82 constants_cx.finalize(tcx, module);
85 pub(crate) fn codegen_tls_ref<'tcx>(
86 fx: &mut FunctionCx<'_, '_, 'tcx>,
88 layout: TyAndLayout<'tcx>,
90 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
91 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
92 if fx.clif_comments.enabled() {
93 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
95 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
96 CValue::by_val(tls_ptr, layout)
99 fn codegen_static_ref<'tcx>(
100 fx: &mut FunctionCx<'_, '_, 'tcx>,
102 layout: TyAndLayout<'tcx>,
104 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
105 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
106 if fx.clif_comments.enabled() {
107 fx.add_comment(local_data_id, format!("{:?}", def_id));
109 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
110 assert!(!layout.is_unsized(), "unsized statics aren't supported");
113 fx.bcx.func.global_values[local_data_id],
114 GlobalValueData::Symbol { tls: false, .. }
116 "tls static referenced without Rvalue::ThreadLocalRef"
118 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
121 pub(crate) fn codegen_constant<'tcx>(
122 fx: &mut FunctionCx<'_, '_, 'tcx>,
123 constant: &Constant<'tcx>,
125 let const_ = match fx.monomorphize(constant.literal) {
126 ConstantKind::Ty(ct) => ct,
127 ConstantKind::Val(val, ty) => return codegen_const_value(fx, val, ty),
129 let const_val = match const_.kind() {
130 ConstKind::Value(valtree) => fx.tcx.valtree_to_const_val((const_.ty(), valtree)),
131 ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted })
132 if fx.tcx.is_static(def.did) =>
134 assert!(substs.is_empty());
135 assert!(promoted.is_none());
137 return codegen_static_ref(fx, def.did, fx.layout_of(const_.ty())).to_cvalue(fx);
139 ConstKind::Unevaluated(unevaluated) => {
140 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
141 Ok(const_val) => const_val,
143 span_bug!(constant.span, "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::ZeroSized => unreachable!(), // we already handles ZST above
171 ConstValue::Scalar(x) => match x {
172 Scalar::Int(int) => {
173 if fx.clif_type(layout.ty).is_some() {
174 return CValue::const_val(fx, layout, int);
176 let raw_val = int.to_bits(int.size()).unwrap();
177 let val = match int.size().bytes() {
178 1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
179 2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
180 4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
181 8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
183 let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
185 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
186 fx.bcx.ins().iconcat(lsb, msb)
191 let place = CPlace::new_stack_slot(fx, layout);
192 place.to_ptr().store(fx, val, MemFlags::trusted());
196 Scalar::Ptr(ptr, _size) => {
197 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
198 let alloc_kind = fx.tcx.get_global_alloc(alloc_id);
199 let base_addr = match alloc_kind {
200 Some(GlobalAlloc::Memory(alloc)) => {
201 let data_id = data_id_for_alloc_id(
202 &mut fx.constants_cx,
205 alloc.inner().mutability,
208 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
209 if fx.clif_comments.enabled() {
210 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
212 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
214 Some(GlobalAlloc::Function(instance)) => {
215 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
217 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
218 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
220 Some(GlobalAlloc::Static(def_id)) => {
221 assert!(fx.tcx.is_static(def_id));
222 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
224 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
225 if fx.clif_comments.enabled() {
226 fx.add_comment(local_data_id, format!("{:?}", def_id));
228 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
230 None => bug!("missing allocation {:?}", alloc_id),
232 let val = if offset.bytes() != 0 {
233 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
237 CValue::by_val(val, layout)
240 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
241 pointer_for_allocation(fx, alloc)
242 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
245 ConstValue::Slice { data, start, end } => {
246 let ptr = pointer_for_allocation(fx, data)
247 .offset_i64(fx, i64::try_from(start).unwrap())
252 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
253 CValue::by_val_pair(ptr, len, layout)
258 pub(crate) fn pointer_for_allocation<'tcx>(
259 fx: &mut FunctionCx<'_, '_, 'tcx>,
260 alloc: ConstAllocation<'tcx>,
261 ) -> crate::pointer::Pointer {
262 let alloc_id = fx.tcx.create_memory_alloc(alloc);
263 let data_id = data_id_for_alloc_id(
264 &mut fx.constants_cx,
267 alloc.inner().mutability,
270 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
271 if fx.clif_comments.enabled() {
272 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
274 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
275 crate::pointer::Pointer::new(global_ptr)
278 pub(crate) fn data_id_for_alloc_id(
280 module: &mut dyn Module,
282 mutability: rustc_hir::Mutability,
284 cx.todo.push(TodoItem::Alloc(alloc_id));
285 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
286 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
290 fn data_id_for_static(
292 module: &mut dyn Module,
296 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
297 let linkage = if definition {
298 crate::linkage::get_static_linkage(tcx, def_id)
299 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
300 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
307 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
308 let symbol_name = tcx.symbol_name(instance).name;
309 let ty = instance.ty(tcx, ParamEnv::reveal_all());
310 let is_mutable = if tcx.is_mutable_static(def_id) {
313 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
315 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
317 let attrs = tcx.codegen_fn_attrs(def_id);
324 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
328 if rlinkage.is_some() {
329 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
330 // Declare an internal global `extern_with_linkage_foo` which
331 // is initialized with the address of `foo`. If `foo` is
332 // discarded during linking (for example, if `foo` has weak
333 // linkage and there are no definitions), then
334 // `extern_with_linkage_foo` will instead be initialized to
337 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
338 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
339 let mut data_ctx = DataContext::new();
340 data_ctx.set_align(align);
341 let data = module.declare_data_in_data(data_id, &mut data_ctx);
342 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
343 data_ctx.write_data_addr(0, data, 0);
344 match module.define_data(ref_data_id, &data_ctx) {
345 // Every time the static is referenced there will be another definition of this global,
346 // so duplicate definitions are expected and allowed.
347 Err(ModuleError::DuplicateDefinition(_)) => {}
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 //println!("alloc_id {}", alloc_id);
361 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
362 GlobalAlloc::Memory(alloc) => alloc,
363 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
365 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
367 .declare_anonymous_data(
368 alloc.inner().mutability == rustc_hir::Mutability::Mut,
373 (data_id, alloc, None)
375 TodoItem::Static(def_id) => {
376 //println!("static {:?}", def_id);
378 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
380 let alloc = tcx.eval_static_initializer(def_id).unwrap();
382 let data_id = data_id_for_static(tcx, module, def_id, true);
383 (data_id, alloc, section_name)
387 //("data_id {}", data_id);
388 if cx.done.contains(&data_id) {
392 let mut data_ctx = DataContext::new();
393 let alloc = alloc.inner();
394 data_ctx.set_align(alloc.align.bytes());
396 if let Some(section_name) = section_name {
397 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
398 let section_name = section_name.as_str();
399 if let Some(names) = section_name.split_once(',') {
402 tcx.sess.fatal(&format!(
403 "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
408 ("", section_name.as_str())
410 data_ctx.set_segment_section(segment_name, section_name);
413 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
414 data_ctx.define(bytes.into_boxed_slice());
416 for &(offset, alloc_id) in alloc.relocations().iter() {
418 let endianness = tcx.data_layout.endian;
419 let offset = offset.bytes() as usize;
420 let ptr_size = tcx.data_layout.pointer_size;
421 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
422 offset..offset + ptr_size.bytes() as usize,
424 read_target_uint(endianness, bytes).unwrap()
427 let reloc_target_alloc = tcx.get_global_alloc(alloc_id).unwrap();
428 let data_id = match reloc_target_alloc {
429 GlobalAlloc::Function(instance) => {
430 assert_eq!(addend, 0);
431 let func_id = crate::abi::import_function(tcx, module, instance);
432 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
433 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
436 GlobalAlloc::Memory(target_alloc) => {
437 data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
439 GlobalAlloc::Static(def_id) => {
440 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
442 tcx.sess.fatal(&format!(
443 "Allocation {:?} contains reference to TLS value {:?}",
448 // Don't push a `TodoItem::Static` here, as it will cause statics used by
449 // multiple crates to be duplicated between them. It isn't necessary anyway,
450 // as it will get pushed by `codegen_static` when necessary.
451 data_id_for_static(tcx, module, def_id, false)
455 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
456 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
459 module.define_data(data_id, &data_ctx).unwrap();
460 cx.done.insert(data_id);
463 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
466 pub(crate) fn mir_operand_get_const_val<'tcx>(
467 fx: &FunctionCx<'_, '_, 'tcx>,
468 operand: &Operand<'tcx>,
469 ) -> Option<ConstValue<'tcx>> {
471 Operand::Constant(const_) => match const_.literal {
472 ConstantKind::Ty(const_) => fx
473 .monomorphize(const_)
474 .eval_for_mir(fx.tcx, ParamEnv::reveal_all())
475 .try_to_value(fx.tcx),
476 ConstantKind::Val(val, _) => Some(val),
478 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
479 // inside a temporary before being passed to the intrinsic requiring the const argument.
480 // This code tries to find a single constant defining definition of the referenced local.
481 Operand::Copy(place) | Operand::Move(place) => {
482 if !place.projection.is_empty() {
485 let mut computed_const_val = None;
486 for bb_data in fx.mir.basic_blocks() {
487 for stmt in &bb_data.statements {
489 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
490 match &local_and_rvalue.1 {
491 Rvalue::Cast(CastKind::Misc, operand, ty) => {
492 if computed_const_val.is_some() {
493 return None; // local assigned twice
495 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
498 let const_val = mir_operand_get_const_val(fx, operand)?;
499 if fx.layout_of(*ty).size
500 != const_val.try_to_scalar_int()?.size()
504 computed_const_val = Some(const_val);
506 Rvalue::Use(operand) => {
507 computed_const_val = mir_operand_get_const_val(fx, operand)
512 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
513 if &**stmt_place == place =>
517 StatementKind::CopyNonOverlapping(_) => {
519 } // conservative handling
520 StatementKind::Assign(_)
521 | StatementKind::FakeRead(_)
522 | StatementKind::SetDiscriminant { .. }
523 | StatementKind::Deinit(_)
524 | StatementKind::StorageLive(_)
525 | StatementKind::StorageDead(_)
526 | StatementKind::Retag(_, _)
527 | StatementKind::AscribeUserType(_, _)
528 | StatementKind::Coverage(_)
529 | StatementKind::Nop => {}
532 match &bb_data.terminator().kind {
533 TerminatorKind::Goto { .. }
534 | TerminatorKind::SwitchInt { .. }
535 | TerminatorKind::Resume
536 | TerminatorKind::Abort
537 | TerminatorKind::Return
538 | TerminatorKind::Unreachable
539 | TerminatorKind::Drop { .. }
540 | TerminatorKind::Assert { .. } => {}
541 TerminatorKind::DropAndReplace { .. }
542 | TerminatorKind::Yield { .. }
543 | TerminatorKind::GeneratorDrop
544 | TerminatorKind::FalseEdge { .. }
545 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
546 TerminatorKind::InlineAsm { .. } => return None,
547 TerminatorKind::Call { destination, target: Some(_), .. }
548 if destination == place =>
552 TerminatorKind::Call { .. } => {}