]> git.lizzy.rs Git - rust.git/blob - src/constant.rs
5c3477a4ddb8e8d49438b85bc93c7cd2ae9c7cba
[rust.git] / src / constant.rs
1 //! Handling of `static`s, `const`s and promoted allocations
2
3 use rustc_span::DUMMY_SP;
4
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_errors::ErrorReported;
7 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8 use rustc_middle::mir::interpret::{
9     read_target_uint, AllocId, Allocation, ConstValue, ErrorHandled, GlobalAlloc, Pointer, Scalar,
10 };
11 use rustc_middle::ty::{Const, ConstKind};
12
13 use cranelift_codegen::ir::GlobalValueData;
14 use cranelift_module::*;
15
16 use crate::prelude::*;
17
18 #[derive(Default)]
19 pub(crate) struct ConstantCx {
20     todo: Vec<TodoItem>,
21     done: FxHashSet<DataId>,
22 }
23
24 #[derive(Copy, Clone, Debug)]
25 enum TodoItem {
26     Alloc(AllocId),
27     Static(DefId),
28 }
29
30 impl ConstantCx {
31     pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut impl Module) {
32         //println!("todo {:?}", self.todo);
33         define_all_allocs(tcx, module, &mut self);
34         //println!("done {:?}", self.done);
35         self.done.clear();
36     }
37 }
38
39 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, impl Module>) {
40     for constant in &fx.mir.required_consts {
41         let const_ = fx.monomorphize(&constant.literal);
42         match const_.val {
43             ConstKind::Value(_) => {}
44             ConstKind::Unevaluated(def, ref substs, promoted) => {
45                 if let Err(err) =
46                     fx.tcx
47                         .const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
48                 {
49                     match err {
50                         ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
51                             fx.tcx
52                                 .sess
53                                 .span_err(constant.span, "erroneous constant encountered");
54                         }
55                         ErrorHandled::TooGeneric => {
56                             span_bug!(
57                                 constant.span,
58                                 "codgen encountered polymorphic constant: {:?}",
59                                 err
60                             );
61                         }
62                     }
63                 }
64             }
65             ConstKind::Param(_)
66             | ConstKind::Infer(_)
67             | ConstKind::Bound(_, _)
68             | ConstKind::Placeholder(_)
69             | ConstKind::Error(_) => unreachable!("{:?}", const_),
70         }
71     }
72 }
73
74 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
75     constants_cx.todo.push(TodoItem::Static(def_id));
76 }
77
78 pub(crate) fn codegen_tls_ref<'tcx>(
79     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
80     def_id: DefId,
81     layout: TyAndLayout<'tcx>,
82 ) -> CValue<'tcx> {
83     let data_id = data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
84     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
85     #[cfg(debug_assertions)]
86     fx.add_comment(local_data_id, format!("tls {:?}", def_id));
87     let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
88     CValue::by_val(tls_ptr, layout)
89 }
90
91 fn codegen_static_ref<'tcx>(
92     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
93     def_id: DefId,
94     layout: TyAndLayout<'tcx>,
95 ) -> CPlace<'tcx> {
96     let data_id = data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
97     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
98     #[cfg(debug_assertions)]
99     fx.add_comment(local_data_id, format!("{:?}", def_id));
100     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
101     assert!(!layout.is_unsized(), "unsized statics aren't supported");
102     assert!(
103         matches!(fx.bcx.func.global_values[local_data_id], GlobalValueData::Symbol { tls: false, ..}),
104         "tls static referenced without Rvalue::ThreadLocalRef"
105     );
106     CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
107 }
108
109 pub(crate) fn trans_constant<'tcx>(
110     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
111     constant: &Constant<'tcx>,
112 ) -> CValue<'tcx> {
113     let const_ = fx.monomorphize(&constant.literal);
114     let const_val = match const_.val {
115         ConstKind::Value(const_val) => const_val,
116         ConstKind::Unevaluated(def, ref substs, promoted) if fx.tcx.is_static(def.did) => {
117             assert!(substs.is_empty());
118             assert!(promoted.is_none());
119
120             return codegen_static_ref(
121                 fx,
122                 def.did,
123                 fx.layout_of(fx.monomorphize(&constant.literal.ty)),
124             )
125             .to_cvalue(fx);
126         }
127         ConstKind::Unevaluated(def, ref substs, promoted) => {
128             match fx
129                 .tcx
130                 .const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
131             {
132                 Ok(const_val) => const_val,
133                 Err(_) => {
134                     if promoted.is_none() {
135                         fx.tcx
136                             .sess
137                             .span_err(constant.span, "erroneous constant encountered");
138                     }
139                     return crate::trap::trap_unreachable_ret_value(
140                         fx,
141                         fx.layout_of(const_.ty),
142                         "erroneous constant encountered",
143                     );
144                 }
145             }
146         }
147         ConstKind::Param(_)
148         | ConstKind::Infer(_)
149         | ConstKind::Bound(_, _)
150         | ConstKind::Placeholder(_)
151         | ConstKind::Error(_) => unreachable!("{:?}", const_),
152     };
153
154     trans_const_value(fx, const_val, const_.ty)
155 }
156
157 pub(crate) fn trans_const_value<'tcx>(
158     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
159     const_val: ConstValue<'tcx>,
160     ty: Ty<'tcx>,
161 ) -> CValue<'tcx> {
162     let layout = fx.layout_of(ty);
163     assert!(!layout.is_unsized(), "sized const value");
164
165     if layout.is_zst() {
166         return CValue::by_ref(
167             crate::Pointer::dangling(layout.align.pref),
168             layout,
169         );
170     }
171
172     match const_val {
173         ConstValue::Scalar(x) => {
174             if fx.clif_type(layout.ty).is_none() {
175                 let (size, align) = (layout.size, layout.align.pref);
176                 let mut alloc = Allocation::from_bytes(
177                     std::iter::repeat(0)
178                         .take(size.bytes_usize())
179                         .collect::<Vec<u8>>(),
180                     align,
181                 );
182                 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
183                 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
184                 let alloc = fx.tcx.intern_const_alloc(alloc);
185                 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
186             }
187
188             match x {
189                 Scalar::Raw { data, size } => {
190                     assert_eq!(u64::from(size), layout.size.bytes());
191                     CValue::const_val(fx, layout, data)
192                 }
193                 Scalar::Ptr(ptr) => {
194                     let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
195                     let base_addr = match alloc_kind {
196                         Some(GlobalAlloc::Memory(alloc)) => {
197                             fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
198                             let data_id = data_id_for_alloc_id(
199                                 &mut fx.cx.module,
200                                 ptr.alloc_id,
201                                 alloc.mutability,
202                             );
203                             let local_data_id =
204                                 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
205                             #[cfg(debug_assertions)]
206                             fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
207                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
208                         }
209                         Some(GlobalAlloc::Function(instance)) => {
210                             let func_id =
211                                 crate::abi::import_function(fx.tcx, &mut fx.cx.module, instance);
212                             let local_func_id =
213                                 fx.cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
214                             fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
215                         }
216                         Some(GlobalAlloc::Static(def_id)) => {
217                             assert!(fx.tcx.is_static(def_id));
218                             let data_id =
219                                 data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
220                             let local_data_id =
221                                 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
222                             #[cfg(debug_assertions)]
223                             fx.add_comment(local_data_id, format!("{:?}", def_id));
224                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
225                         }
226                         None => bug!("missing allocation {:?}", ptr.alloc_id),
227                     };
228                     let val = if ptr.offset.bytes() != 0 {
229                         fx.bcx
230                             .ins()
231                             .iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
232                     } else {
233                         base_addr
234                     };
235                     CValue::by_val(val, layout)
236                 }
237             }
238         }
239         ConstValue::ByRef { alloc, offset } => CValue::by_ref(
240             pointer_for_allocation(fx, alloc)
241                 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
242             layout,
243         ),
244         ConstValue::Slice { data, start, end } => {
245             let ptr = pointer_for_allocation(fx, data)
246                 .offset_i64(fx, i64::try_from(start).unwrap())
247                 .get_addr(fx);
248             let len = fx.bcx.ins().iconst(
249                 fx.pointer_type,
250                 i64::try_from(end.checked_sub(start).unwrap()).unwrap(),
251             );
252             CValue::by_val_pair(ptr, len, layout)
253         }
254     }
255 }
256
257 fn pointer_for_allocation<'tcx>(
258     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
259     alloc: &'tcx Allocation,
260 ) -> crate::pointer::Pointer {
261     let alloc_id = fx.tcx.create_memory_alloc(alloc);
262     fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
263     let data_id = data_id_for_alloc_id(&mut fx.cx.module, alloc_id, alloc.mutability);
264
265     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
266     #[cfg(debug_assertions)]
267     fx.add_comment(local_data_id, format!("{:?}", alloc_id));
268     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
269     crate::pointer::Pointer::new(global_ptr)
270 }
271
272 fn data_id_for_alloc_id(
273     module: &mut impl Module,
274     alloc_id: AllocId,
275     mutability: rustc_hir::Mutability,
276 ) -> DataId {
277     module
278         .declare_data(
279             &format!("__alloc_{:x}", alloc_id.0),
280             Linkage::Local,
281             mutability == rustc_hir::Mutability::Mut,
282             false,
283         )
284         .unwrap()
285 }
286
287 fn data_id_for_static(
288     tcx: TyCtxt<'_>,
289     module: &mut impl Module,
290     def_id: DefId,
291     definition: bool,
292 ) -> DataId {
293     let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
294     let linkage = if definition {
295         crate::linkage::get_static_linkage(tcx, def_id)
296     } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
297         || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
298     {
299         Linkage::Preemptible
300     } else {
301         Linkage::Import
302     };
303
304     let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
305     let symbol_name = tcx.symbol_name(instance).name;
306     let ty = instance.ty(tcx, ParamEnv::reveal_all());
307     let is_mutable = if tcx.is_mutable_static(def_id) {
308         true
309     } else {
310         !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
311     };
312     let align = tcx
313         .layout_of(ParamEnv::reveal_all().and(ty))
314         .unwrap()
315         .align
316         .pref
317         .bytes();
318
319     let attrs = tcx.codegen_fn_attrs(def_id);
320
321     let data_id = module
322         .declare_data(
323             &*symbol_name,
324             linkage,
325             is_mutable,
326             attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
327         )
328         .unwrap();
329
330     if rlinkage.is_some() {
331         // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
332         // Declare an internal global `extern_with_linkage_foo` which
333         // is initialized with the address of `foo`.  If `foo` is
334         // discarded during linking (for example, if `foo` has weak
335         // linkage and there are no definitions), then
336         // `extern_with_linkage_foo` will instead be initialized to
337         // zero.
338
339         let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
340         let ref_data_id = module
341             .declare_data(&ref_name, Linkage::Local, false, false)
342             .unwrap();
343         let mut data_ctx = DataContext::new();
344         data_ctx.set_align(align);
345         let data = module.declare_data_in_data(data_id, &mut data_ctx);
346         data_ctx.define(
347             std::iter::repeat(0)
348                 .take(pointer_ty(tcx).bytes() as usize)
349                 .collect(),
350         );
351         data_ctx.write_data_addr(0, data, 0);
352         match module.define_data(ref_data_id, &data_ctx) {
353             // Every time the static is referenced there will be another definition of this global,
354             // so duplicate definitions are expected and allowed.
355             Err(ModuleError::DuplicateDefinition(_)) => {}
356             res => res.unwrap(),
357         }
358         ref_data_id
359     } else {
360         data_id
361     }
362 }
363
364 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut impl Module, cx: &mut ConstantCx) {
365     while let Some(todo_item) = cx.todo.pop() {
366         let (data_id, alloc, section_name) = match todo_item {
367             TodoItem::Alloc(alloc_id) => {
368                 //println!("alloc_id {}", alloc_id);
369                 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
370                     GlobalAlloc::Memory(alloc) => alloc,
371                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
372                 };
373                 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
374                 (data_id, alloc, None)
375             }
376             TodoItem::Static(def_id) => {
377                 //println!("static {:?}", def_id);
378
379                 let section_name = tcx
380                     .codegen_fn_attrs(def_id)
381                     .link_section
382                     .map(|s| s.as_str());
383
384                 let alloc = tcx.eval_static_initializer(def_id).unwrap();
385
386                 let data_id = data_id_for_static(tcx, module, def_id, true);
387                 (data_id, alloc, section_name)
388             }
389         };
390
391         //("data_id {}", data_id);
392         if cx.done.contains(&data_id) {
393             continue;
394         }
395
396         let mut data_ctx = DataContext::new();
397         data_ctx.set_align(alloc.align.bytes());
398
399         if let Some(section_name) = section_name {
400             // FIXME set correct segment for Mach-O files
401             data_ctx.set_segment_section("", &*section_name);
402         }
403
404         let bytes = alloc
405             .inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len())
406             .to_vec();
407         data_ctx.define(bytes.into_boxed_slice());
408
409         for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
410             let addend = {
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,
416                 );
417                 read_target_uint(endianness, bytes).unwrap()
418             };
419
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);
427                     continue;
428                 }
429                 GlobalAlloc::Memory(target_alloc) => {
430                     cx.todo.push(TodoItem::Alloc(reloc));
431                     data_id_for_alloc_id(module, reloc, target_alloc.mutability)
432                 }
433                 GlobalAlloc::Static(def_id) => {
434                     if tcx
435                         .codegen_fn_attrs(def_id)
436                         .flags
437                         .contains(CodegenFnAttrFlags::THREAD_LOCAL)
438                     {
439                         tcx.sess.fatal(&format!(
440                             "Allocation {:?} contains reference to TLS value {:?}",
441                             alloc, def_id
442                         ));
443                     }
444
445                     // Don't push a `TodoItem::Static` here, as it will cause statics used by
446                     // multiple crates to be duplicated between them. It isn't necessary anyway,
447                     // as it will get pushed by `codegen_static` when necessary.
448                     data_id_for_static(tcx, module, def_id, false)
449                 }
450             };
451
452             let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
453             data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
454         }
455
456         module.define_data(data_id, &data_ctx).unwrap();
457         cx.done.insert(data_id);
458     }
459
460     assert!(cx.todo.is_empty(), "{:?}", cx.todo);
461 }
462
463 pub(crate) fn mir_operand_get_const_val<'tcx>(
464     fx: &FunctionCx<'_, 'tcx, impl Module>,
465     operand: &Operand<'tcx>,
466 ) -> Option<&'tcx Const<'tcx>> {
467     match operand {
468         Operand::Copy(_) | Operand::Move(_) => None,
469         Operand::Constant(const_) => Some(
470             fx.monomorphize(&const_.literal)
471                 .eval(fx.tcx, ParamEnv::reveal_all()),
472         ),
473     }
474 }