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