]> git.lizzy.rs Git - rust.git/blob - src/constant.rs
Mark allocations as mutable when necessary
[rust.git] / src / constant.rs
1 use rustc_span::DUMMY_SP;
2
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,
6 };
7 use rustc_middle::ty::{Const, ConstKind};
8 use rustc_target::abi::Align;
9 use rustc_data_structures::fx::FxHashSet;
10
11 use cranelift_codegen::ir::GlobalValueData;
12 use cranelift_module::*;
13
14 use crate::prelude::*;
15
16 #[derive(Default)]
17 pub(crate) struct ConstantCx {
18     todo: Vec<TodoItem>,
19     done: FxHashSet<DataId>,
20 }
21
22 #[derive(Copy, Clone, Debug)]
23 enum TodoItem {
24     Alloc(AllocId),
25     Static(DefId),
26 }
27
28 impl ConstantCx {
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);
33         self.done.clear();
34     }
35 }
36
37 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
38     constants_cx.todo.push(TodoItem::Static(def_id));
39 }
40
41 pub(crate) fn codegen_tls_ref<'tcx>(
42     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
43     def_id: DefId,
44     layout: TyAndLayout<'tcx>,
45 ) -> CValue<'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)
53 }
54
55 fn codegen_static_ref<'tcx>(
56     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
57     def_id: DefId,
58     layout: TyAndLayout<'tcx>,
59 ) -> CPlace<'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)
69 }
70
71 pub(crate) fn trans_constant<'tcx>(
72     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
73     constant: &Constant<'tcx>,
74 ) -> CValue<'tcx> {
75     let const_ = match constant.literal.val {
76         ConstKind::Unevaluated(def_id, ref substs, promoted) if fx.tcx.is_static(def_id) => {
77             assert!(substs.is_empty());
78             assert!(promoted.is_none());
79
80             return codegen_static_ref(
81                 fx,
82                 def_id,
83                 fx.layout_of(fx.monomorphize(&constant.literal.ty)),
84             ).to_cvalue(fx);
85         }
86         _ => fx.monomorphize(&constant.literal).eval(fx.tcx, ParamEnv::reveal_all()),
87     };
88
89     trans_const_value(fx, const_)
90 }
91
92 pub(crate) fn trans_const_value<'tcx>(
93     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
94     const_: &'tcx Const<'tcx>,
95 ) -> CValue<'tcx> {
96     let ty = fx.monomorphize(&const_.ty);
97     let layout = fx.layout_of(ty);
98     assert!(!layout.is_unsized(), "sized const value");
99
100     if layout.is_zst() {
101         return CValue::by_ref(
102             crate::Pointer::const_addr(fx, i64::try_from(layout.align.pref.bytes()).unwrap()),
103             layout,
104         );
105     }
106     let const_val = match const_.val {
107         ConstKind::Value(const_val) => const_val,
108         _ => unreachable!("Const {:?} should have been evaluated", const_),
109     };
110
111     match const_val {
112         ConstValue::Scalar(x) => {
113             if fx.clif_type(layout.ty).is_none() {
114                 let (size, align) = (layout.size, layout.align.pref);
115                 let mut alloc = Allocation::from_bytes(
116                     std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
117                     align,
118                 );
119                 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
120                 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
121                 let alloc = fx.tcx.intern_const_alloc(alloc);
122                 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
123             }
124
125             match x {
126                 Scalar::Raw { data, size } => {
127                     assert_eq!(u64::from(size), layout.size.bytes());
128                     return CValue::const_val(fx, layout, data);
129                 }
130                 Scalar::Ptr(ptr) => {
131                     let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
132                     let base_addr = match alloc_kind {
133                         Some(GlobalAlloc::Memory(alloc)) => {
134                             fx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
135                             let data_id = data_id_for_alloc_id(fx.module, ptr.alloc_id, alloc.align, alloc.mutability);
136                             let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
137                             #[cfg(debug_assertions)]
138                             fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
139                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
140                         }
141                         Some(GlobalAlloc::Function(instance)) => {
142                             let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
143                             let local_func_id = fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
144                             fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
145                         }
146                         Some(GlobalAlloc::Static(def_id)) => {
147                             assert!(fx.tcx.is_static(def_id));
148                             let linkage = crate::linkage::get_static_ref_linkage(fx.tcx, def_id);
149                             let data_id = data_id_for_static(fx.tcx, fx.module, def_id, linkage);
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!("{:?}", def_id));
153                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
154                         }
155                         None => bug!("missing allocation {:?}", ptr.alloc_id),
156                     };
157                     let val = fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap());
158                     return CValue::by_val(val, layout);
159                 }
160             }
161         }
162         ConstValue::ByRef { alloc, offset } => {
163             CValue::by_ref(
164                 pointer_for_allocation(fx, alloc)
165                     .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
166                 layout,
167             )
168         }
169         ConstValue::Slice { data, start, end } => {
170             let ptr = pointer_for_allocation(fx, data)
171                 .offset_i64(fx, i64::try_from(start).unwrap())
172                 .get_addr(fx);
173             let len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
174             CValue::by_val_pair(ptr, len, layout)
175         }
176     }
177 }
178
179 fn pointer_for_allocation<'tcx>(
180     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
181     alloc: &'tcx Allocation,
182 ) -> crate::pointer::Pointer {
183     let alloc_id = fx.tcx.create_memory_alloc(alloc);
184     fx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
185     let data_id = data_id_for_alloc_id(fx.module, alloc_id, alloc.align, alloc.mutability);
186
187     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
188     #[cfg(debug_assertions)]
189     fx.add_comment(local_data_id, format!("{:?}", alloc_id));
190     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
191     crate::pointer::Pointer::new(global_ptr)
192 }
193
194 fn data_id_for_alloc_id<B: Backend>(
195     module: &mut Module<B>,
196     alloc_id: AllocId,
197     align: Align,
198     mutability: rustc_hir::Mutability,
199 ) -> DataId {
200     module
201         .declare_data(
202             &format!("__alloc_{}", alloc_id.0),
203             Linkage::Local,
204             mutability == rustc_hir::Mutability::Mut,
205             false,
206             Some(align.bytes() as u8),
207         )
208         .unwrap()
209 }
210
211 fn data_id_for_static(
212     tcx: TyCtxt<'_>,
213     module: &mut Module<impl Backend>,
214     def_id: DefId,
215     linkage: Linkage,
216 ) -> DataId {
217     let instance = Instance::mono(tcx, def_id);
218     let symbol_name = tcx.symbol_name(instance).name.as_str();
219     let ty = instance.monomorphic_ty(tcx);
220     let is_mutable = if tcx.is_mutable_static(def_id) {
221         true
222     } else {
223         !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
224     };
225     let align = tcx
226         .layout_of(ParamEnv::reveal_all().and(ty))
227         .unwrap()
228         .align
229         .pref
230         .bytes();
231
232     let attrs = tcx.codegen_fn_attrs(def_id);
233
234     let data_id = module
235         .declare_data(
236             &*symbol_name,
237             linkage,
238             is_mutable,
239             attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
240             Some(align.try_into().unwrap()),
241         )
242         .unwrap();
243
244     if linkage == Linkage::Preemptible {
245         if let ty::RawPtr(_) = ty.kind {
246         } else {
247             tcx.sess.span_fatal(
248                 tcx.def_span(def_id),
249                 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
250             )
251         }
252
253         let mut data_ctx = DataContext::new();
254         data_ctx.define_zeroinit(pointer_ty(tcx).bytes() as usize);
255         match module.define_data(data_id, &data_ctx) {
256             // Everytime a weak static is referenced, there will be a zero pointer definition,
257             // so duplicate definitions are expected and allowed.
258             Err(ModuleError::DuplicateDefinition(_)) => {}
259             res => res.unwrap(),
260         }
261     }
262
263     data_id
264 }
265
266 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mut ConstantCx) {
267     while let Some(todo_item) = cx.todo.pop() {
268         let (data_id, alloc, section_name) = match todo_item {
269             TodoItem::Alloc(alloc_id) => {
270                 //println!("alloc_id {}", alloc_id);
271                 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
272                     GlobalAlloc::Memory(alloc) => alloc,
273                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
274                 };
275                 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.align, alloc.mutability);
276                 (data_id, alloc, None)
277             }
278             TodoItem::Static(def_id) => {
279                 //println!("static {:?}", def_id);
280
281                 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
282
283                 let const_ = tcx.const_eval_poly(def_id).unwrap();
284
285                 let alloc = match const_ {
286                     ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => alloc,
287                     _ => bug!("static const eval returned {:#?}", const_),
288                 };
289
290                 let data_id = data_id_for_static(
291                     tcx,
292                     module,
293                     def_id,
294                     if tcx.is_reachable_non_generic(def_id) {
295                         Linkage::Export
296                     } else {
297                         Linkage::Export // FIXME Set hidden visibility
298                     },
299                 );
300                 (data_id, alloc, section_name)
301             }
302         };
303
304         //("data_id {}", data_id);
305         if cx.done.contains(&data_id) {
306             continue;
307         }
308
309         let mut data_ctx = DataContext::new();
310
311         if let Some(section_name) = section_name {
312             // FIXME set correct segment for Mach-O files
313             data_ctx.set_segment_section("", &*section_name);
314         }
315
316         let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
317         data_ctx.define(bytes.into_boxed_slice());
318
319         for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
320             let addend = {
321                 let endianness = tcx.data_layout.endian;
322                 let offset = offset.bytes() as usize;
323                 let ptr_size = tcx.data_layout.pointer_size;
324                 let bytes = &alloc.inspect_with_undef_and_ptr_outside_interpreter(offset..offset + ptr_size.bytes() as usize);
325                 read_target_uint(endianness, bytes).unwrap()
326             };
327
328             let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
329             let data_id = match reloc_target_alloc {
330                 GlobalAlloc::Function(instance) => {
331                     assert_eq!(addend, 0);
332                     let func_id = crate::abi::import_function(tcx, module, instance);
333                     let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
334                     data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
335                     continue;
336                 }
337                 GlobalAlloc::Memory(target_alloc) => {
338                     cx.todo.push(TodoItem::Alloc(reloc));
339                     data_id_for_alloc_id(module, reloc, target_alloc.align, target_alloc.mutability)
340                 }
341                 GlobalAlloc::Static(def_id) => {
342                     if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
343                         tcx.sess.fatal(&format!("Allocation {:?} contains reference to TLS value {:?}", alloc, def_id));
344                     }
345
346                     // Don't push a `TodoItem::Static` here, as it will cause statics used by
347                     // multiple crates to be duplicated between them. It isn't necessary anyway,
348                     // as it will get pushed by `codegen_static` when necessary.
349                     data_id_for_static(
350                         tcx,
351                         module,
352                         def_id,
353                         crate::linkage::get_static_ref_linkage(tcx, def_id),
354                     )
355                 }
356             };
357
358             let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
359             data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
360         }
361
362         module.define_data(data_id, &data_ctx).unwrap();
363         cx.done.insert(data_id);
364     }
365
366     assert!(cx.todo.is_empty(), "{:?}", cx.todo);
367 }
368
369 pub(crate) fn mir_operand_get_const_val<'tcx>(
370     fx: &FunctionCx<'_, 'tcx, impl Backend>,
371     operand: &Operand<'tcx>,
372 ) -> Option<&'tcx Const<'tcx>> {
373     match operand {
374         Operand::Copy(_) | Operand::Move(_) => None,
375         Operand::Constant(const_) => {
376             Some(fx.monomorphize(&const_.literal).eval(fx.tcx, ParamEnv::reveal_all()))
377         }
378     }
379 }