]> git.lizzy.rs Git - rust.git/blob - src/constant.rs
Sync from rust 3e826bb11228508fbe749e594038d6727208aa94
[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>) -> 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, impl Module>,
83     def_id: DefId,
84     layout: TyAndLayout<'tcx>,
85 ) -> CValue<'tcx> {
86     let data_id = data_id_for_static(fx.tcx, &mut 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, impl Module>,
96     def_id: DefId,
97     layout: TyAndLayout<'tcx>,
98 ) -> CPlace<'tcx> {
99     let data_id = data_id_for_static(fx.tcx, &mut 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, impl Module>,
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!(constant.span, "erroneous constant not captured by required_consts");
141                 }
142             }
143         }
144         ConstKind::Param(_)
145         | ConstKind::Infer(_)
146         | ConstKind::Bound(_, _)
147         | ConstKind::Placeholder(_)
148         | ConstKind::Error(_) => unreachable!("{:?}", const_),
149     };
150
151     codegen_const_value(fx, const_val, const_.ty)
152 }
153
154 pub(crate) fn codegen_const_value<'tcx>(
155     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
156     const_val: ConstValue<'tcx>,
157     ty: Ty<'tcx>,
158 ) -> CValue<'tcx> {
159     let layout = fx.layout_of(ty);
160     assert!(!layout.is_unsized(), "sized const value");
161
162     if layout.is_zst() {
163         return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
164     }
165
166     match const_val {
167         ConstValue::Scalar(x) => {
168             if fx.clif_type(layout.ty).is_none() {
169                 let (size, align) = (layout.size, layout.align.pref);
170                 let mut alloc = Allocation::from_bytes(
171                     std::iter::repeat(0)
172                         .take(size.bytes_usize())
173                         .collect::<Vec<u8>>(),
174                     align,
175                 );
176                 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
177                 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
178                 let alloc = fx.tcx.intern_const_alloc(alloc);
179                 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
180             }
181
182             match x {
183                 Scalar::Int(int) => CValue::const_val(fx, layout, int),
184                 Scalar::Ptr(ptr) => {
185                     let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
186                     let base_addr = match alloc_kind {
187                         Some(GlobalAlloc::Memory(alloc)) => {
188                             fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
189                             let data_id = data_id_for_alloc_id(
190                                 &mut fx.cx.module,
191                                 ptr.alloc_id,
192                                 alloc.mutability,
193                             );
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, &mut 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 =
210                                 data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
211                             let local_data_id =
212                                 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
213                             #[cfg(debug_assertions)]
214                             fx.add_comment(local_data_id, format!("{:?}", def_id));
215                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
216                         }
217                         None => bug!("missing allocation {:?}", ptr.alloc_id),
218                     };
219                     let val = if ptr.offset.bytes() != 0 {
220                         fx.bcx
221                             .ins()
222                             .iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
223                     } else {
224                         base_addr
225                     };
226                     CValue::by_val(val, layout)
227                 }
228             }
229         }
230         ConstValue::ByRef { alloc, offset } => CValue::by_ref(
231             pointer_for_allocation(fx, alloc)
232                 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
233             layout,
234         ),
235         ConstValue::Slice { data, start, end } => {
236             let ptr = pointer_for_allocation(fx, data)
237                 .offset_i64(fx, i64::try_from(start).unwrap())
238                 .get_addr(fx);
239             let len = fx.bcx.ins().iconst(
240                 fx.pointer_type,
241                 i64::try_from(end.checked_sub(start).unwrap()).unwrap(),
242             );
243             CValue::by_val_pair(ptr, len, layout)
244         }
245     }
246 }
247
248 fn pointer_for_allocation<'tcx>(
249     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
250     alloc: &'tcx Allocation,
251 ) -> crate::pointer::Pointer {
252     let alloc_id = fx.tcx.create_memory_alloc(alloc);
253     fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
254     let data_id = data_id_for_alloc_id(&mut fx.cx.module, alloc_id, alloc.mutability);
255
256     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
257     #[cfg(debug_assertions)]
258     fx.add_comment(local_data_id, format!("{:?}", alloc_id));
259     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
260     crate::pointer::Pointer::new(global_ptr)
261 }
262
263 fn data_id_for_alloc_id(
264     module: &mut impl Module,
265     alloc_id: AllocId,
266     mutability: rustc_hir::Mutability,
267 ) -> DataId {
268     module
269         .declare_data(
270             &format!(".L__alloc_{:x}", alloc_id.0),
271             Linkage::Local,
272             mutability == rustc_hir::Mutability::Mut,
273             false,
274         )
275         .unwrap()
276 }
277
278 fn data_id_for_static(
279     tcx: TyCtxt<'_>,
280     module: &mut impl Module,
281     def_id: DefId,
282     definition: bool,
283 ) -> DataId {
284     let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
285     let linkage = if definition {
286         crate::linkage::get_static_linkage(tcx, def_id)
287     } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
288         || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
289     {
290         Linkage::Preemptible
291     } else {
292         Linkage::Import
293     };
294
295     let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
296     let symbol_name = tcx.symbol_name(instance).name;
297     let ty = instance.ty(tcx, ParamEnv::reveal_all());
298     let is_mutable = if tcx.is_mutable_static(def_id) {
299         true
300     } else {
301         !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
302     };
303     let align = tcx
304         .layout_of(ParamEnv::reveal_all().and(ty))
305         .unwrap()
306         .align
307         .pref
308         .bytes();
309
310     let attrs = tcx.codegen_fn_attrs(def_id);
311
312     let data_id = module
313         .declare_data(
314             &*symbol_name,
315             linkage,
316             is_mutable,
317             attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
318         )
319         .unwrap();
320
321     if rlinkage.is_some() {
322         // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
323         // Declare an internal global `extern_with_linkage_foo` which
324         // is initialized with the address of `foo`.  If `foo` is
325         // discarded during linking (for example, if `foo` has weak
326         // linkage and there are no definitions), then
327         // `extern_with_linkage_foo` will instead be initialized to
328         // zero.
329
330         let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
331         let ref_data_id = module
332             .declare_data(&ref_name, Linkage::Local, false, false)
333             .unwrap();
334         let mut data_ctx = DataContext::new();
335         data_ctx.set_align(align);
336         let data = module.declare_data_in_data(data_id, &mut data_ctx);
337         data_ctx.define(
338             std::iter::repeat(0)
339                 .take(pointer_ty(tcx).bytes() as usize)
340                 .collect(),
341         );
342         data_ctx.write_data_addr(0, data, 0);
343         match module.define_data(ref_data_id, &data_ctx) {
344             // Every time the static is referenced there will be another definition of this global,
345             // so duplicate definitions are expected and allowed.
346             Err(ModuleError::DuplicateDefinition(_)) => {}
347             res => res.unwrap(),
348         }
349         ref_data_id
350     } else {
351         data_id
352     }
353 }
354
355 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut impl Module, cx: &mut ConstantCx) {
356     while let Some(todo_item) = cx.todo.pop() {
357         let (data_id, alloc, section_name) = match todo_item {
358             TodoItem::Alloc(alloc_id) => {
359                 //println!("alloc_id {}", alloc_id);
360                 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
361                     GlobalAlloc::Memory(alloc) => alloc,
362                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
363                 };
364                 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
365                 (data_id, alloc, None)
366             }
367             TodoItem::Static(def_id) => {
368                 //println!("static {:?}", def_id);
369
370                 let section_name = tcx
371                     .codegen_fn_attrs(def_id)
372                     .link_section
373                     .map(|s| s.as_str());
374
375                 let alloc = tcx.eval_static_initializer(def_id).unwrap();
376
377                 let data_id = data_id_for_static(tcx, module, def_id, true);
378                 (data_id, alloc, section_name)
379             }
380         };
381
382         //("data_id {}", data_id);
383         if cx.done.contains(&data_id) {
384             continue;
385         }
386
387         let mut data_ctx = DataContext::new();
388         data_ctx.set_align(alloc.align.bytes());
389
390         if let Some(section_name) = section_name {
391             // FIXME set correct segment for Mach-O files
392             data_ctx.set_segment_section("", &*section_name);
393         }
394
395         let bytes = alloc
396             .inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len())
397             .to_vec();
398         data_ctx.define(bytes.into_boxed_slice());
399
400         for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
401             let addend = {
402                 let endianness = tcx.data_layout.endian;
403                 let offset = offset.bytes() as usize;
404                 let ptr_size = tcx.data_layout.pointer_size;
405                 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
406                     offset..offset + ptr_size.bytes() as usize,
407                 );
408                 read_target_uint(endianness, bytes).unwrap()
409             };
410
411             let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
412             let data_id = match reloc_target_alloc {
413                 GlobalAlloc::Function(instance) => {
414                     assert_eq!(addend, 0);
415                     let func_id = crate::abi::import_function(tcx, module, instance);
416                     let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
417                     data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
418                     continue;
419                 }
420                 GlobalAlloc::Memory(target_alloc) => {
421                     cx.todo.push(TodoItem::Alloc(reloc));
422                     data_id_for_alloc_id(module, reloc, target_alloc.mutability)
423                 }
424                 GlobalAlloc::Static(def_id) => {
425                     if tcx
426                         .codegen_fn_attrs(def_id)
427                         .flags
428                         .contains(CodegenFnAttrFlags::THREAD_LOCAL)
429                     {
430                         tcx.sess.fatal(&format!(
431                             "Allocation {:?} contains reference to TLS value {:?}",
432                             alloc, def_id
433                         ));
434                     }
435
436                     // Don't push a `TodoItem::Static` here, as it will cause statics used by
437                     // multiple crates to be duplicated between them. It isn't necessary anyway,
438                     // as it will get pushed by `codegen_static` when necessary.
439                     data_id_for_static(tcx, module, def_id, false)
440                 }
441             };
442
443             let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
444             data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
445         }
446
447         // FIXME don't duplicate definitions in lazy jit mode
448         let _ = module.define_data(data_id, &data_ctx);
449         cx.done.insert(data_id);
450     }
451
452     assert!(cx.todo.is_empty(), "{:?}", cx.todo);
453 }
454
455 pub(crate) fn mir_operand_get_const_val<'tcx>(
456     fx: &FunctionCx<'_, 'tcx, impl Module>,
457     operand: &Operand<'tcx>,
458 ) -> Option<&'tcx Const<'tcx>> {
459     match operand {
460         Operand::Copy(_) | Operand::Move(_) => None,
461         Operand::Constant(const_) => Some(
462             fx.monomorphize(const_.literal)
463                 .eval(fx.tcx, ParamEnv::reveal_all()),
464         ),
465     }
466 }