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