1 //! Handling of `static`s, `const`s and promoted allocations
3 use rustc_span::DUMMY_SP;
5 use rustc_ast::Mutability;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::ErrorReported;
8 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
9 use rustc_middle::mir::interpret::{
10 alloc_range, read_target_uint, AllocId, Allocation, ConstValue, ErrorHandled, GlobalAlloc,
13 use rustc_middle::ty::ConstKind;
15 use cranelift_codegen::ir::GlobalValueData;
16 use cranelift_module::*;
18 use crate::prelude::*;
20 pub(crate) struct ConstantCx {
22 done: FxHashSet<DataId>,
23 anon_allocs: FxHashMap<AllocId, DataId>,
26 #[derive(Copy, Clone, Debug)]
33 pub(crate) fn new() -> Self {
34 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
37 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
38 //println!("todo {:?}", self.todo);
39 define_all_allocs(tcx, module, &mut self);
40 //println!("done {:?}", self.done);
45 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
46 let mut all_constants_ok = true;
47 for constant in &fx.mir.required_consts {
48 let const_ = match fx.monomorphize(constant.literal) {
49 ConstantKind::Ty(ct) => ct,
50 ConstantKind::Val(..) => continue,
53 ConstKind::Value(_) => {}
54 ConstKind::Unevaluated(unevaluated) => {
56 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None)
58 all_constants_ok = false;
60 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
61 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
63 ErrorHandled::TooGeneric => {
66 "codgen encountered polymorphic constant: {:?}",
75 | ConstKind::Bound(_, _)
76 | ConstKind::Placeholder(_)
77 | ConstKind::Error(_) => unreachable!("{:?}", const_),
83 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
84 let mut constants_cx = ConstantCx::new();
85 constants_cx.todo.push(TodoItem::Static(def_id));
86 constants_cx.finalize(tcx, module);
89 pub(crate) fn codegen_tls_ref<'tcx>(
90 fx: &mut FunctionCx<'_, '_, 'tcx>,
92 layout: TyAndLayout<'tcx>,
94 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
95 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
96 if fx.clif_comments.enabled() {
97 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
99 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
100 CValue::by_val(tls_ptr, layout)
103 fn codegen_static_ref<'tcx>(
104 fx: &mut FunctionCx<'_, '_, 'tcx>,
106 layout: TyAndLayout<'tcx>,
108 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
109 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
110 if fx.clif_comments.enabled() {
111 fx.add_comment(local_data_id, format!("{:?}", def_id));
113 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
114 assert!(!layout.is_unsized(), "unsized statics aren't supported");
117 fx.bcx.func.global_values[local_data_id],
118 GlobalValueData::Symbol { tls: false, .. }
120 "tls static referenced without Rvalue::ThreadLocalRef"
122 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
125 pub(crate) fn codegen_constant<'tcx>(
126 fx: &mut FunctionCx<'_, '_, 'tcx>,
127 constant: &Constant<'tcx>,
129 let const_ = match fx.monomorphize(constant.literal) {
130 ConstantKind::Ty(ct) => ct,
131 ConstantKind::Val(val, ty) => return codegen_const_value(fx, val, ty),
133 let const_val = match const_.val {
134 ConstKind::Value(const_val) => const_val,
135 ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted })
136 if fx.tcx.is_static(def.did) =>
138 assert!(substs.is_empty());
139 assert!(promoted.is_none());
141 return codegen_static_ref(fx, def.did, fx.layout_of(const_.ty)).to_cvalue(fx);
143 ConstKind::Unevaluated(unevaluated) => {
144 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
145 Ok(const_val) => const_val,
147 span_bug!(constant.span, "erroneous constant not captured by required_consts");
152 | ConstKind::Infer(_)
153 | ConstKind::Bound(_, _)
154 | ConstKind::Placeholder(_)
155 | ConstKind::Error(_) => unreachable!("{:?}", const_),
158 codegen_const_value(fx, const_val, const_.ty)
161 pub(crate) fn codegen_const_value<'tcx>(
162 fx: &mut FunctionCx<'_, '_, 'tcx>,
163 const_val: ConstValue<'tcx>,
166 let layout = fx.layout_of(ty);
167 assert!(!layout.is_unsized(), "sized const value");
170 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
174 ConstValue::Scalar(x) => {
175 if fx.clif_type(layout.ty).is_none() {
176 let (size, align) = (layout.size, layout.align.pref);
177 let mut alloc = Allocation::from_bytes(
178 std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
182 alloc.write_scalar(fx, alloc_range(Size::ZERO, size), x.into()).unwrap();
183 let alloc = fx.tcx.intern_const_alloc(alloc);
184 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
188 Scalar::Int(int) => CValue::const_val(fx, layout, int),
189 Scalar::Ptr(ptr) => {
190 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
191 let base_addr = match alloc_kind {
192 Some(GlobalAlloc::Memory(alloc)) => {
193 let data_id = data_id_for_alloc_id(
194 &mut fx.constants_cx,
200 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
201 if fx.clif_comments.enabled() {
202 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
204 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
206 Some(GlobalAlloc::Function(instance)) => {
207 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
209 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
210 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
212 Some(GlobalAlloc::Static(def_id)) => {
213 assert!(fx.tcx.is_static(def_id));
214 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
216 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
217 if fx.clif_comments.enabled() {
218 fx.add_comment(local_data_id, format!("{:?}", def_id));
220 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
222 None => bug!("missing allocation {:?}", ptr.alloc_id),
224 let val = if ptr.offset.bytes() != 0 {
225 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
229 CValue::by_val(val, layout)
233 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
234 pointer_for_allocation(fx, alloc)
235 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
238 ConstValue::Slice { data, start, end } => {
239 let ptr = pointer_for_allocation(fx, data)
240 .offset_i64(fx, i64::try_from(start).unwrap())
245 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
246 CValue::by_val_pair(ptr, len, layout)
251 fn pointer_for_allocation<'tcx>(
252 fx: &mut FunctionCx<'_, '_, 'tcx>,
253 alloc: &'tcx Allocation,
254 ) -> crate::pointer::Pointer {
255 let alloc_id = fx.tcx.create_memory_alloc(alloc);
257 data_id_for_alloc_id(&mut fx.constants_cx, &mut *fx.module, alloc_id, alloc.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);
313 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
317 if rlinkage.is_some() {
318 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
319 // Declare an internal global `extern_with_linkage_foo` which
320 // is initialized with the address of `foo`. If `foo` is
321 // discarded during linking (for example, if `foo` has weak
322 // linkage and there are no definitions), then
323 // `extern_with_linkage_foo` will instead be initialized to
326 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
327 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
328 let mut data_ctx = DataContext::new();
329 data_ctx.set_align(align);
330 let data = module.declare_data_in_data(data_id, &mut data_ctx);
331 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
332 data_ctx.write_data_addr(0, data, 0);
333 match module.define_data(ref_data_id, &data_ctx) {
334 // Every time the static is referenced there will be another definition of this global,
335 // so duplicate definitions are expected and allowed.
336 Err(ModuleError::DuplicateDefinition(_)) => {}
345 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
346 while let Some(todo_item) = cx.todo.pop() {
347 let (data_id, alloc, section_name) = match todo_item {
348 TodoItem::Alloc(alloc_id) => {
349 //println!("alloc_id {}", alloc_id);
350 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
351 GlobalAlloc::Memory(alloc) => alloc,
352 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
354 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
356 .declare_anonymous_data(
357 alloc.mutability == rustc_hir::Mutability::Mut,
362 (data_id, alloc, None)
364 TodoItem::Static(def_id) => {
365 //println!("static {:?}", def_id);
367 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
369 let alloc = tcx.eval_static_initializer(def_id).unwrap();
371 let data_id = data_id_for_static(tcx, module, def_id, true);
372 (data_id, alloc, section_name)
376 //("data_id {}", data_id);
377 if cx.done.contains(&data_id) {
381 let mut data_ctx = DataContext::new();
382 data_ctx.set_align(alloc.align.bytes());
384 if let Some(section_name) = section_name {
385 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
386 if let Some(names) = section_name.split_once(',') {
389 tcx.sess.fatal(&format!(
390 "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
397 data_ctx.set_segment_section(segment_name, section_name);
400 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
401 data_ctx.define(bytes.into_boxed_slice());
403 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
405 let endianness = tcx.data_layout.endian;
406 let offset = offset.bytes() as usize;
407 let ptr_size = tcx.data_layout.pointer_size;
408 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
409 offset..offset + ptr_size.bytes() as usize,
411 read_target_uint(endianness, bytes).unwrap()
414 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
415 let data_id = match reloc_target_alloc {
416 GlobalAlloc::Function(instance) => {
417 assert_eq!(addend, 0);
418 let func_id = crate::abi::import_function(tcx, module, instance);
419 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
420 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
423 GlobalAlloc::Memory(target_alloc) => {
424 data_id_for_alloc_id(cx, module, reloc, target_alloc.mutability)
426 GlobalAlloc::Static(def_id) => {
427 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
429 tcx.sess.fatal(&format!(
430 "Allocation {:?} contains reference to TLS value {:?}",
435 // Don't push a `TodoItem::Static` here, as it will cause statics used by
436 // multiple crates to be duplicated between them. It isn't necessary anyway,
437 // as it will get pushed by `codegen_static` when necessary.
438 data_id_for_static(tcx, module, def_id, false)
442 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
443 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
446 module.define_data(data_id, &data_ctx).unwrap();
447 cx.done.insert(data_id);
450 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
453 pub(crate) fn mir_operand_get_const_val<'tcx>(
454 fx: &FunctionCx<'_, '_, 'tcx>,
455 operand: &Operand<'tcx>,
456 ) -> Option<ConstValue<'tcx>> {
458 Operand::Constant(const_) => match const_.literal {
459 ConstantKind::Ty(const_) => {
460 fx.monomorphize(const_).eval(fx.tcx, ParamEnv::reveal_all()).val.try_to_value()
462 ConstantKind::Val(val, _) => Some(val),
464 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
465 // inside a temporary before being passed to the intrinsic requiring the const argument.
466 // This code tries to find a single constant defining definition of the referenced local.
467 Operand::Copy(place) | Operand::Move(place) => {
468 if !place.projection.is_empty() {
471 let mut computed_const_val = None;
472 for bb_data in fx.mir.basic_blocks() {
473 for stmt in &bb_data.statements {
475 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
476 match &local_and_rvalue.1 {
477 Rvalue::Cast(CastKind::Misc, operand, ty) => {
478 if computed_const_val.is_some() {
479 return None; // local assigned twice
481 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
484 let const_val = mir_operand_get_const_val(fx, operand)?;
485 if fx.layout_of(ty).size
486 != const_val.try_to_scalar_int()?.size()
490 computed_const_val = Some(const_val);
492 Rvalue::Use(operand) => {
493 computed_const_val = mir_operand_get_const_val(fx, operand)
498 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
499 if &**stmt_place == place =>
503 StatementKind::LlvmInlineAsm(_) | StatementKind::CopyNonOverlapping(_) => {
505 } // conservative handling
506 StatementKind::Assign(_)
507 | StatementKind::FakeRead(_)
508 | StatementKind::SetDiscriminant { .. }
509 | StatementKind::StorageLive(_)
510 | StatementKind::StorageDead(_)
511 | StatementKind::Retag(_, _)
512 | StatementKind::AscribeUserType(_, _)
513 | StatementKind::Coverage(_)
514 | StatementKind::Nop => {}
517 match &bb_data.terminator().kind {
518 TerminatorKind::Goto { .. }
519 | TerminatorKind::SwitchInt { .. }
520 | TerminatorKind::Resume
521 | TerminatorKind::Abort
522 | TerminatorKind::Return
523 | TerminatorKind::Unreachable
524 | TerminatorKind::Drop { .. }
525 | TerminatorKind::Assert { .. } => {}
526 TerminatorKind::DropAndReplace { .. }
527 | TerminatorKind::Yield { .. }
528 | TerminatorKind::GeneratorDrop
529 | TerminatorKind::FalseEdge { .. }
530 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
531 TerminatorKind::InlineAsm { .. } => return None,
532 TerminatorKind::Call { destination: Some((call_place, _)), .. }
533 if call_place == place =>
537 TerminatorKind::Call { .. } => {}