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(uv)
133 if fx.tcx.is_static(uv.def.did) =>
135 assert!(uv.substs(fx.tcx).is_empty());
136 assert!(uv.promoted.is_none());
138 return codegen_static_ref(fx, uv.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, _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,
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: &'tcx Allocation,
261 ) -> crate::pointer::Pointer {
262 let alloc_id = fx.tcx.create_memory_alloc(alloc);
264 data_id_for_alloc_id(&mut fx.constants_cx, &mut *fx.module, alloc_id, alloc.mutability);
266 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
267 if fx.clif_comments.enabled() {
268 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
270 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
271 crate::pointer::Pointer::new(global_ptr)
274 pub(crate) fn data_id_for_alloc_id(
276 module: &mut dyn Module,
278 mutability: rustc_hir::Mutability,
280 cx.todo.push(TodoItem::Alloc(alloc_id));
281 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
282 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
286 fn data_id_for_static(
288 module: &mut dyn Module,
292 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
293 let linkage = if definition {
294 crate::linkage::get_static_linkage(tcx, def_id)
295 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
296 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
303 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
304 let symbol_name = tcx.symbol_name(instance).name;
305 let ty = instance.ty(tcx, ParamEnv::reveal_all());
306 let is_mutable = if tcx.is_mutable_static(def_id) {
309 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
311 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
313 let attrs = tcx.codegen_fn_attrs(def_id);
320 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
324 if rlinkage.is_some() {
325 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
326 // Declare an internal global `extern_with_linkage_foo` which
327 // is initialized with the address of `foo`. If `foo` is
328 // discarded during linking (for example, if `foo` has weak
329 // linkage and there are no definitions), then
330 // `extern_with_linkage_foo` will instead be initialized to
333 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
334 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
335 let mut data_ctx = DataContext::new();
336 data_ctx.set_align(align);
337 let data = module.declare_data_in_data(data_id, &mut data_ctx);
338 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
339 data_ctx.write_data_addr(0, data, 0);
340 match module.define_data(ref_data_id, &data_ctx) {
341 // Every time the static is referenced there will be another definition of this global,
342 // so duplicate definitions are expected and allowed.
343 Err(ModuleError::DuplicateDefinition(_)) => {}
352 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
353 while let Some(todo_item) = cx.todo.pop() {
354 let (data_id, alloc, section_name) = match todo_item {
355 TodoItem::Alloc(alloc_id) => {
356 //println!("alloc_id {}", alloc_id);
357 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
358 GlobalAlloc::Memory(alloc) => alloc,
359 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
361 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
363 .declare_anonymous_data(
364 alloc.mutability == rustc_hir::Mutability::Mut,
369 (data_id, alloc, None)
371 TodoItem::Static(def_id) => {
372 //println!("static {:?}", def_id);
374 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
376 let alloc = tcx.eval_static_initializer(def_id).unwrap();
378 let data_id = data_id_for_static(tcx, module, def_id, true);
379 (data_id, alloc, section_name)
383 //("data_id {}", data_id);
384 if cx.done.contains(&data_id) {
388 let mut data_ctx = DataContext::new();
389 data_ctx.set_align(alloc.align.bytes());
391 if let Some(section_name) = section_name {
392 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
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",
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.relocations().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.get_global_alloc(alloc_id).unwrap();
422 let data_id = match reloc_target_alloc {
423 GlobalAlloc::Function(instance) => {
424 assert_eq!(addend, 0);
425 let func_id = crate::abi::import_function(tcx, module, instance);
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.mutability)
433 GlobalAlloc::Static(def_id) => {
434 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
436 tcx.sess.fatal(&format!(
437 "Allocation {:?} contains reference to TLS value {:?}",
442 // Don't push a `TodoItem::Static` here, as it will cause statics used by
443 // multiple crates to be duplicated between them. It isn't necessary anyway,
444 // as it will get pushed by `codegen_static` when necessary.
445 data_id_for_static(tcx, module, def_id, false)
449 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
450 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
453 module.define_data(data_id, &data_ctx).unwrap();
454 cx.done.insert(data_id);
457 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
460 pub(crate) fn mir_operand_get_const_val<'tcx>(
461 fx: &FunctionCx<'_, '_, 'tcx>,
462 operand: &Operand<'tcx>,
463 ) -> Option<ConstValue<'tcx>> {
465 Operand::Constant(const_) => match const_.literal {
466 ConstantKind::Ty(const_) => {
467 fx.monomorphize(const_).eval(fx.tcx, ParamEnv::reveal_all()).val.try_to_value()
469 ConstantKind::Val(val, _) => Some(val),
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() {
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 {
484 Rvalue::Cast(CastKind::Misc, operand, ty) => {
485 if computed_const_val.is_some() {
486 return None; // local assigned twice
488 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
491 let const_val = mir_operand_get_const_val(fx, operand)?;
492 if fx.layout_of(ty).size
493 != const_val.try_to_scalar_int()?.size()
497 computed_const_val = Some(const_val);
499 Rvalue::Use(operand) => {
500 computed_const_val = mir_operand_get_const_val(fx, operand)
505 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
506 if &**stmt_place == place =>
510 StatementKind::LlvmInlineAsm(_) | StatementKind::CopyNonOverlapping(_) => {
512 } // conservative handling
513 StatementKind::Assign(_)
514 | StatementKind::FakeRead(_)
515 | StatementKind::SetDiscriminant { .. }
516 | StatementKind::StorageLive(_)
517 | StatementKind::StorageDead(_)
518 | StatementKind::Retag(_, _)
519 | StatementKind::AscribeUserType(_, _)
520 | StatementKind::Coverage(_)
521 | StatementKind::Nop => {}
524 match &bb_data.terminator().kind {
525 TerminatorKind::Goto { .. }
526 | TerminatorKind::SwitchInt { .. }
527 | TerminatorKind::Resume
528 | TerminatorKind::Abort
529 | TerminatorKind::Return
530 | TerminatorKind::Unreachable
531 | TerminatorKind::Drop { .. }
532 | TerminatorKind::Assert { .. } => {}
533 TerminatorKind::DropAndReplace { .. }
534 | TerminatorKind::Yield { .. }
535 | TerminatorKind::GeneratorDrop
536 | TerminatorKind::FalseEdge { .. }
537 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
538 TerminatorKind::InlineAsm { .. } => return None,
539 TerminatorKind::Call { destination: Some((call_place, _)), .. }
540 if call_place == place =>
544 TerminatorKind::Call { .. } => {}