1 use rustc_span::DUMMY_SP;
3 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
4 use rustc_middle::mir::interpret::{
5 read_target_uint, AllocId, Allocation, ConstValue, GlobalAlloc, Pointer, Scalar,
7 use rustc_middle::ty::{Const, ConstKind};
8 use rustc_target::abi::Align;
9 use rustc_data_structures::fx::FxHashSet;
11 use cranelift_codegen::ir::GlobalValueData;
12 use cranelift_module::*;
14 use crate::prelude::*;
17 pub(crate) struct ConstantCx {
19 done: FxHashSet<DataId>,
22 #[derive(Copy, Clone, Debug)]
29 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut Module<impl Backend>) {
30 //println!("todo {:?}", self.todo);
31 define_all_allocs(tcx, module, &mut self);
32 //println!("done {:?}", self.done);
37 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
38 constants_cx.todo.push(TodoItem::Static(def_id));
41 pub(crate) fn codegen_tls_ref<'tcx>(
42 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
44 layout: TyAndLayout<'tcx>,
46 let linkage = crate::linkage::get_static_ref_linkage(fx.tcx, def_id);
47 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, linkage);
48 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
49 #[cfg(debug_assertions)]
50 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
51 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
52 CValue::by_val(tls_ptr, layout)
55 fn codegen_static_ref<'tcx>(
56 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
58 layout: TyAndLayout<'tcx>,
60 let linkage = crate::linkage::get_static_ref_linkage(fx.tcx, def_id);
61 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, linkage);
62 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
63 #[cfg(debug_assertions)]
64 fx.add_comment(local_data_id, format!("{:?}", def_id));
65 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
66 assert!(!layout.is_unsized(), "unsized statics aren't supported");
67 assert!(matches!(fx.bcx.func.global_values[local_data_id], GlobalValueData::Symbol { tls: false, ..}), "tls static referenced without Rvalue::ThreadLocalRef");
68 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
71 pub(crate) fn trans_constant<'tcx>(
72 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
73 constant: &Constant<'tcx>,
75 let const_ = fx.monomorphize(&constant.literal);
76 let const_val = match const_.val {
77 ConstKind::Value(const_val) => const_val,
78 ConstKind::Unevaluated(def_id, ref substs, promoted) if fx.tcx.is_static(def_id) => {
79 assert!(substs.is_empty());
80 assert!(promoted.is_none());
82 return codegen_static_ref(
85 fx.layout_of(fx.monomorphize(&constant.literal.ty)),
88 ConstKind::Unevaluated(def_id, ref substs, promoted) => {
89 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), def_id, substs, promoted, None) {
90 Ok(const_val) => const_val,
92 if promoted.is_none() {
93 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
95 return crate::trap::trap_unreachable_ret_value(
97 fx.layout_of(const_.ty),
98 "erroneous constant encountered",
103 ConstKind::Param(_) | ConstKind::Infer(_) | ConstKind::Bound(_, _)
104 | ConstKind::Placeholder(_) | ConstKind::Error(_) => unreachable!("{:?}", const_),
107 trans_const_value(fx, const_val, const_.ty)
110 pub(crate) fn trans_const_value<'tcx>(
111 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
112 const_val: ConstValue<'tcx>,
115 let layout = fx.layout_of(ty);
116 assert!(!layout.is_unsized(), "sized const value");
119 return CValue::by_ref(
120 crate::Pointer::const_addr(fx, i64::try_from(layout.align.pref.bytes()).unwrap()),
126 ConstValue::Scalar(x) => {
127 if fx.clif_type(layout.ty).is_none() {
128 let (size, align) = (layout.size, layout.align.pref);
129 let mut alloc = Allocation::from_bytes(
130 std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
133 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
134 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
135 let alloc = fx.tcx.intern_const_alloc(alloc);
136 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
140 Scalar::Raw { data, size } => {
141 assert_eq!(u64::from(size), layout.size.bytes());
142 return CValue::const_val(fx, layout, data);
144 Scalar::Ptr(ptr) => {
145 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
146 let base_addr = match alloc_kind {
147 Some(GlobalAlloc::Memory(alloc)) => {
148 fx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
149 let data_id = data_id_for_alloc_id(fx.module, ptr.alloc_id, alloc.align, alloc.mutability);
150 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
151 #[cfg(debug_assertions)]
152 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
153 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
155 Some(GlobalAlloc::Function(instance)) => {
156 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
157 let local_func_id = fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
158 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
160 Some(GlobalAlloc::Static(def_id)) => {
161 assert!(fx.tcx.is_static(def_id));
162 let linkage = crate::linkage::get_static_ref_linkage(fx.tcx, def_id);
163 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, linkage);
164 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
165 #[cfg(debug_assertions)]
166 fx.add_comment(local_data_id, format!("{:?}", def_id));
167 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
169 None => bug!("missing allocation {:?}", ptr.alloc_id),
171 let val = fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap());
172 return CValue::by_val(val, layout);
176 ConstValue::ByRef { alloc, offset } => {
178 pointer_for_allocation(fx, alloc)
179 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
183 ConstValue::Slice { data, start, end } => {
184 let ptr = pointer_for_allocation(fx, data)
185 .offset_i64(fx, i64::try_from(start).unwrap())
187 let len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
188 CValue::by_val_pair(ptr, len, layout)
193 fn pointer_for_allocation<'tcx>(
194 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
195 alloc: &'tcx Allocation,
196 ) -> crate::pointer::Pointer {
197 let alloc_id = fx.tcx.create_memory_alloc(alloc);
198 fx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
199 let data_id = data_id_for_alloc_id(fx.module, alloc_id, alloc.align, alloc.mutability);
201 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
202 #[cfg(debug_assertions)]
203 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
204 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
205 crate::pointer::Pointer::new(global_ptr)
208 fn data_id_for_alloc_id<B: Backend>(
209 module: &mut Module<B>,
212 mutability: rustc_hir::Mutability,
216 &format!("__alloc_{}", alloc_id.0),
218 mutability == rustc_hir::Mutability::Mut,
220 Some(align.bytes() as u8),
225 fn data_id_for_static(
227 module: &mut Module<impl Backend>,
231 let instance = Instance::mono(tcx, def_id);
232 let symbol_name = tcx.symbol_name(instance).name.as_str();
233 let ty = instance.monomorphic_ty(tcx);
234 let is_mutable = if tcx.is_mutable_static(def_id) {
237 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
240 .layout_of(ParamEnv::reveal_all().and(ty))
246 let attrs = tcx.codegen_fn_attrs(def_id);
253 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
254 Some(align.try_into().unwrap()),
258 if linkage == Linkage::Preemptible {
259 if let ty::RawPtr(_) = ty.kind {
262 tcx.def_span(def_id),
263 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
267 let mut data_ctx = DataContext::new();
268 data_ctx.define_zeroinit(pointer_ty(tcx).bytes() as usize);
269 match module.define_data(data_id, &data_ctx) {
270 // Everytime a weak static is referenced, there will be a zero pointer definition,
271 // so duplicate definitions are expected and allowed.
272 Err(ModuleError::DuplicateDefinition(_)) => {}
280 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mut ConstantCx) {
281 while let Some(todo_item) = cx.todo.pop() {
282 let (data_id, alloc, section_name) = match todo_item {
283 TodoItem::Alloc(alloc_id) => {
284 //println!("alloc_id {}", alloc_id);
285 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
286 GlobalAlloc::Memory(alloc) => alloc,
287 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
289 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.align, alloc.mutability);
290 (data_id, alloc, None)
292 TodoItem::Static(def_id) => {
293 //println!("static {:?}", def_id);
295 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
297 let const_ = tcx.const_eval_poly(def_id).unwrap();
299 let alloc = match const_ {
300 ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => alloc,
301 _ => bug!("static const eval returned {:#?}", const_),
304 let data_id = data_id_for_static(
308 if tcx.is_reachable_non_generic(def_id) {
311 Linkage::Export // FIXME Set hidden visibility
314 (data_id, alloc, section_name)
318 //("data_id {}", data_id);
319 if cx.done.contains(&data_id) {
323 let mut data_ctx = DataContext::new();
325 if let Some(section_name) = section_name {
326 // FIXME set correct segment for Mach-O files
327 data_ctx.set_segment_section("", &*section_name);
330 let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
331 data_ctx.define(bytes.into_boxed_slice());
333 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
335 let endianness = tcx.data_layout.endian;
336 let offset = offset.bytes() as usize;
337 let ptr_size = tcx.data_layout.pointer_size;
338 let bytes = &alloc.inspect_with_undef_and_ptr_outside_interpreter(offset..offset + ptr_size.bytes() as usize);
339 read_target_uint(endianness, bytes).unwrap()
342 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
343 let data_id = match reloc_target_alloc {
344 GlobalAlloc::Function(instance) => {
345 assert_eq!(addend, 0);
346 let func_id = crate::abi::import_function(tcx, module, instance);
347 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
348 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
351 GlobalAlloc::Memory(target_alloc) => {
352 cx.todo.push(TodoItem::Alloc(reloc));
353 data_id_for_alloc_id(module, reloc, target_alloc.align, target_alloc.mutability)
355 GlobalAlloc::Static(def_id) => {
356 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
357 tcx.sess.fatal(&format!("Allocation {:?} contains reference to TLS value {:?}", alloc, def_id));
360 // Don't push a `TodoItem::Static` here, as it will cause statics used by
361 // multiple crates to be duplicated between them. It isn't necessary anyway,
362 // as it will get pushed by `codegen_static` when necessary.
367 crate::linkage::get_static_ref_linkage(tcx, def_id),
372 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
373 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
376 module.define_data(data_id, &data_ctx).unwrap();
377 cx.done.insert(data_id);
380 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
383 pub(crate) fn mir_operand_get_const_val<'tcx>(
384 fx: &FunctionCx<'_, 'tcx, impl Backend>,
385 operand: &Operand<'tcx>,
386 ) -> Option<&'tcx Const<'tcx>> {
388 Operand::Copy(_) | Operand::Move(_) => None,
389 Operand::Constant(const_) => {
390 Some(fx.monomorphize(&const_.literal).eval(fx.tcx, ParamEnv::reveal_all()))