1 //! Handling of `static`s, `const`s and promoted allocations
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_errors::ErrorReported;
5 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
6 use rustc_middle::mir::interpret::{
7 read_target_uint, AllocId, Allocation, ConstValue, ErrorHandled, GlobalAlloc, Scalar,
9 use rustc_middle::ty::ConstKind;
10 use rustc_span::DUMMY_SP;
12 use cranelift_codegen::ir::GlobalValueData;
13 use cranelift_module::*;
15 use crate::prelude::*;
17 pub(crate) struct ConstantCx {
19 done: FxHashSet<DataId>,
20 anon_allocs: FxHashMap<AllocId, DataId>,
23 #[derive(Copy, Clone, Debug)]
30 pub(crate) fn new() -> Self {
31 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
34 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
35 //println!("todo {:?}", self.todo);
36 define_all_allocs(tcx, module, &mut self);
37 //println!("done {:?}", self.done);
42 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
43 let mut all_constants_ok = true;
44 for constant in &fx.mir.required_consts {
45 let const_ = match fx.monomorphize(constant.literal) {
46 ConstantKind::Ty(ct) => ct,
47 ConstantKind::Val(..) => continue,
50 ConstKind::Value(_) => {}
51 ConstKind::Unevaluated(unevaluated) => {
53 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None)
55 all_constants_ok = false;
57 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
58 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
60 ErrorHandled::TooGeneric => {
63 "codgen encountered polymorphic constant: {:?}",
72 | ConstKind::Bound(_, _)
73 | ConstKind::Placeholder(_)
74 | ConstKind::Error(_) => unreachable!("{:?}", const_),
80 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
81 let mut constants_cx = ConstantCx::new();
82 constants_cx.todo.push(TodoItem::Static(def_id));
83 constants_cx.finalize(tcx, module);
86 pub(crate) fn codegen_tls_ref<'tcx>(
87 fx: &mut FunctionCx<'_, '_, 'tcx>,
89 layout: TyAndLayout<'tcx>,
91 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
92 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
93 if fx.clif_comments.enabled() {
94 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
96 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
97 CValue::by_val(tls_ptr, layout)
100 fn codegen_static_ref<'tcx>(
101 fx: &mut FunctionCx<'_, '_, 'tcx>,
103 layout: TyAndLayout<'tcx>,
105 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
106 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
107 if fx.clif_comments.enabled() {
108 fx.add_comment(local_data_id, format!("{:?}", def_id));
110 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
111 assert!(!layout.is_unsized(), "unsized statics aren't supported");
114 fx.bcx.func.global_values[local_data_id],
115 GlobalValueData::Symbol { tls: false, .. }
117 "tls static referenced without Rvalue::ThreadLocalRef"
119 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
122 pub(crate) fn codegen_constant<'tcx>(
123 fx: &mut FunctionCx<'_, '_, 'tcx>,
124 constant: &Constant<'tcx>,
126 let const_ = match fx.monomorphize(constant.literal) {
127 ConstantKind::Ty(ct) => ct,
128 ConstantKind::Val(val, ty) => return codegen_const_value(fx, val, ty),
130 let const_val = match const_.val {
131 ConstKind::Value(const_val) => const_val,
132 ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted })
133 if fx.tcx.is_static(def.did) =>
135 assert!(substs.is_empty());
136 assert!(promoted.is_none());
138 return codegen_static_ref(fx, def.did, fx.layout_of(const_.ty)).to_cvalue(fx);
140 ConstKind::Unevaluated(unevaluated) => {
141 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
142 Ok(const_val) => const_val,
144 span_bug!(constant.span, "erroneous constant not captured by required_consts");
149 | ConstKind::Infer(_)
150 | ConstKind::Bound(_, _)
151 | ConstKind::Placeholder(_)
152 | ConstKind::Error(_) => unreachable!("{:?}", const_),
155 codegen_const_value(fx, const_val, const_.ty)
158 pub(crate) fn codegen_const_value<'tcx>(
159 fx: &mut FunctionCx<'_, '_, 'tcx>,
160 const_val: ConstValue<'tcx>,
163 let layout = fx.layout_of(ty);
164 assert!(!layout.is_unsized(), "sized const value");
167 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
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) => {
197 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
198 let base_addr = match alloc_kind {
199 Some(GlobalAlloc::Memory(alloc)) => {
200 let data_id = data_id_for_alloc_id(
201 &mut fx.constants_cx,
207 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
208 if fx.clif_comments.enabled() {
209 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
211 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
213 Some(GlobalAlloc::Function(instance)) => {
214 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
216 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
217 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
219 Some(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)
229 None => bug!("missing allocation {:?}", ptr.alloc_id),
231 let val = if ptr.offset.bytes() != 0 {
232 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
236 CValue::by_val(val, layout)
239 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
240 pointer_for_allocation(fx, alloc)
241 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
244 ConstValue::Slice { data, start, end } => {
245 let ptr = pointer_for_allocation(fx, data)
246 .offset_i64(fx, i64::try_from(start).unwrap())
251 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
252 CValue::by_val_pair(ptr, len, layout)
257 pub(crate) fn pointer_for_allocation<'tcx>(
258 fx: &mut FunctionCx<'_, '_, 'tcx>,
259 alloc: &'tcx Allocation,
260 ) -> crate::pointer::Pointer {
261 let alloc_id = fx.tcx.create_memory_alloc(alloc);
263 data_id_for_alloc_id(&mut fx.constants_cx, &mut *fx.module, alloc_id, alloc.mutability);
265 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
266 if fx.clif_comments.enabled() {
267 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
269 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
270 crate::pointer::Pointer::new(global_ptr)
273 pub(crate) fn data_id_for_alloc_id(
275 module: &mut dyn Module,
277 mutability: rustc_hir::Mutability,
279 cx.todo.push(TodoItem::Alloc(alloc_id));
280 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
281 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
285 fn data_id_for_static(
287 module: &mut dyn Module,
291 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
292 let linkage = if definition {
293 crate::linkage::get_static_linkage(tcx, def_id)
294 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
295 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
302 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
303 let symbol_name = tcx.symbol_name(instance).name;
304 let ty = instance.ty(tcx, ParamEnv::reveal_all());
305 let is_mutable = if tcx.is_mutable_static(def_id) {
308 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
310 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
312 let attrs = tcx.codegen_fn_attrs(def_id);
319 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
323 if rlinkage.is_some() {
324 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
325 // Declare an internal global `extern_with_linkage_foo` which
326 // is initialized with the address of `foo`. If `foo` is
327 // discarded during linking (for example, if `foo` has weak
328 // linkage and there are no definitions), then
329 // `extern_with_linkage_foo` will instead be initialized to
332 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
333 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
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);
337 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
338 data_ctx.write_data_addr(0, data, 0);
339 match module.define_data(ref_data_id, &data_ctx) {
340 // Every time the static is referenced there will be another definition of this global,
341 // so duplicate definitions are expected and allowed.
342 Err(ModuleError::DuplicateDefinition(_)) => {}
351 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
352 while let Some(todo_item) = cx.todo.pop() {
353 let (data_id, alloc, section_name) = match todo_item {
354 TodoItem::Alloc(alloc_id) => {
355 //println!("alloc_id {}", alloc_id);
356 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
357 GlobalAlloc::Memory(alloc) => alloc,
358 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
360 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
362 .declare_anonymous_data(
363 alloc.mutability == rustc_hir::Mutability::Mut,
368 (data_id, alloc, None)
370 TodoItem::Static(def_id) => {
371 //println!("static {:?}", def_id);
373 let section_name = tcx.codegen_fn_attrs(def_id).link_section.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 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
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",
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, (_tag, reloc)) in alloc.relocations().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.get_global_alloc(reloc).unwrap();
421 let data_id = match reloc_target_alloc {
422 GlobalAlloc::Function(instance) => {
423 assert_eq!(addend, 0);
424 let func_id = crate::abi::import_function(tcx, module, instance);
425 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
426 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
429 GlobalAlloc::Memory(target_alloc) => {
430 data_id_for_alloc_id(cx, module, reloc, target_alloc.mutability)
432 GlobalAlloc::Static(def_id) => {
433 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
435 tcx.sess.fatal(&format!(
436 "Allocation {:?} contains reference to TLS value {:?}",
441 // Don't push a `TodoItem::Static` here, as it will cause statics used by
442 // multiple crates to be duplicated between them. It isn't necessary anyway,
443 // as it will get pushed by `codegen_static` when necessary.
444 data_id_for_static(tcx, module, def_id, false)
448 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
449 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
452 module.define_data(data_id, &data_ctx).unwrap();
453 cx.done.insert(data_id);
456 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
459 pub(crate) fn mir_operand_get_const_val<'tcx>(
460 fx: &FunctionCx<'_, '_, 'tcx>,
461 operand: &Operand<'tcx>,
462 ) -> Option<ConstValue<'tcx>> {
464 Operand::Constant(const_) => match const_.literal {
465 ConstantKind::Ty(const_) => {
466 fx.monomorphize(const_).eval(fx.tcx, ParamEnv::reveal_all()).val.try_to_value()
468 ConstantKind::Val(val, _) => Some(val),
470 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
471 // inside a temporary before being passed to the intrinsic requiring the const argument.
472 // This code tries to find a single constant defining definition of the referenced local.
473 Operand::Copy(place) | Operand::Move(place) => {
474 if !place.projection.is_empty() {
477 let mut computed_const_val = None;
478 for bb_data in fx.mir.basic_blocks() {
479 for stmt in &bb_data.statements {
481 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
482 match &local_and_rvalue.1 {
483 Rvalue::Cast(CastKind::Misc, operand, ty) => {
484 if computed_const_val.is_some() {
485 return None; // local assigned twice
487 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
490 let const_val = mir_operand_get_const_val(fx, operand)?;
491 if fx.layout_of(ty).size
492 != const_val.try_to_scalar_int()?.size()
496 computed_const_val = Some(const_val);
498 Rvalue::Use(operand) => {
499 computed_const_val = mir_operand_get_const_val(fx, operand)
504 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
505 if &**stmt_place == place =>
509 StatementKind::LlvmInlineAsm(_) | StatementKind::CopyNonOverlapping(_) => {
511 } // conservative handling
512 StatementKind::Assign(_)
513 | StatementKind::FakeRead(_)
514 | StatementKind::SetDiscriminant { .. }
515 | StatementKind::StorageLive(_)
516 | StatementKind::StorageDead(_)
517 | StatementKind::Retag(_, _)
518 | StatementKind::AscribeUserType(_, _)
519 | StatementKind::Coverage(_)
520 | StatementKind::Nop => {}
523 match &bb_data.terminator().kind {
524 TerminatorKind::Goto { .. }
525 | TerminatorKind::SwitchInt { .. }
526 | TerminatorKind::Resume
527 | TerminatorKind::Abort
528 | TerminatorKind::Return
529 | TerminatorKind::Unreachable
530 | TerminatorKind::Drop { .. }
531 | TerminatorKind::Assert { .. } => {}
532 TerminatorKind::DropAndReplace { .. }
533 | TerminatorKind::Yield { .. }
534 | TerminatorKind::GeneratorDrop
535 | TerminatorKind::FalseEdge { .. }
536 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
537 TerminatorKind::InlineAsm { .. } => return None,
538 TerminatorKind::Call { destination: Some((call_place, _)), .. }
539 if call_place == place =>
543 TerminatorKind::Call { .. } => {}