]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/constant.rs
Rollup merge of #94101 - notriddle:notriddle/strip-test-cases, r=GuillaumeGomez
[rust.git] / compiler / rustc_codegen_cranelift / src / constant.rs
1 //! Handling of `static`s, `const`s and promoted allocations
2
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_errors::ErrorGuaranteed;
5 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
6 use rustc_middle::mir::interpret::{
7     read_target_uint, AllocId, Allocation, ConstValue, ErrorHandled, GlobalAlloc, Scalar,
8 };
9 use rustc_middle::ty::ConstKind;
10 use rustc_span::DUMMY_SP;
11
12 use cranelift_codegen::ir::GlobalValueData;
13 use cranelift_module::*;
14
15 use crate::prelude::*;
16
17 pub(crate) struct ConstantCx {
18     todo: Vec<TodoItem>,
19     done: FxHashSet<DataId>,
20     anon_allocs: FxHashMap<AllocId, DataId>,
21 }
22
23 #[derive(Copy, Clone, Debug)]
24 enum TodoItem {
25     Alloc(AllocId),
26     Static(DefId),
27 }
28
29 impl ConstantCx {
30     pub(crate) fn new() -> Self {
31         ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
32     }
33
34     pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
35         //println!("todo {:?}", self.todo);
36         define_all_allocs(tcx, module, &mut self);
37         //println!("done {:?}", self.done);
38         self.done.clear();
39     }
40 }
41
42 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
43     let mut all_constants_ok = true;
44     for constant in &fx.mir.required_consts {
45         let const_ = match fx.monomorphize(constant.literal) {
46             ConstantKind::Ty(ct) => ct,
47             ConstantKind::Val(..) => continue,
48         };
49         match const_.val() {
50             ConstKind::Value(_) => {}
51             ConstKind::Unevaluated(unevaluated) => {
52                 if let Err(err) =
53                     fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None)
54                 {
55                     all_constants_ok = false;
56                     match err {
57                         ErrorHandled::Reported(ErrorGuaranteed) | ErrorHandled::Linted => {
58                             fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
59                         }
60                         ErrorHandled::TooGeneric => {
61                             span_bug!(
62                                 constant.span,
63                                 "codgen encountered polymorphic constant: {:?}",
64                                 err
65                             );
66                         }
67                     }
68                 }
69             }
70             ConstKind::Param(_)
71             | ConstKind::Infer(_)
72             | ConstKind::Bound(_, _)
73             | ConstKind::Placeholder(_)
74             | ConstKind::Error(_) => unreachable!("{:?}", const_),
75         }
76     }
77     all_constants_ok
78 }
79
80 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
81     let mut constants_cx = ConstantCx::new();
82     constants_cx.todo.push(TodoItem::Static(def_id));
83     constants_cx.finalize(tcx, module);
84 }
85
86 pub(crate) fn codegen_tls_ref<'tcx>(
87     fx: &mut FunctionCx<'_, '_, 'tcx>,
88     def_id: DefId,
89     layout: TyAndLayout<'tcx>,
90 ) -> CValue<'tcx> {
91     let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
92     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
93     if fx.clif_comments.enabled() {
94         fx.add_comment(local_data_id, format!("tls {:?}", def_id));
95     }
96     let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
97     CValue::by_val(tls_ptr, layout)
98 }
99
100 fn codegen_static_ref<'tcx>(
101     fx: &mut FunctionCx<'_, '_, 'tcx>,
102     def_id: DefId,
103     layout: TyAndLayout<'tcx>,
104 ) -> CPlace<'tcx> {
105     let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
106     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
107     if fx.clif_comments.enabled() {
108         fx.add_comment(local_data_id, format!("{:?}", def_id));
109     }
110     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
111     assert!(!layout.is_unsized(), "unsized statics aren't supported");
112     assert!(
113         matches!(
114             fx.bcx.func.global_values[local_data_id],
115             GlobalValueData::Symbol { tls: false, .. }
116         ),
117         "tls static referenced without Rvalue::ThreadLocalRef"
118     );
119     CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
120 }
121
122 pub(crate) fn codegen_constant<'tcx>(
123     fx: &mut FunctionCx<'_, '_, 'tcx>,
124     constant: &Constant<'tcx>,
125 ) -> CValue<'tcx> {
126     let const_ = match fx.monomorphize(constant.literal) {
127         ConstantKind::Ty(ct) => ct,
128         ConstantKind::Val(val, ty) => return codegen_const_value(fx, val, ty),
129     };
130     let const_val = match const_.val() {
131         ConstKind::Value(const_val) => const_val,
132         ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted })
133             if fx.tcx.is_static(def.did) =>
134         {
135             assert!(substs.is_empty());
136             assert!(promoted.is_none());
137
138             return codegen_static_ref(fx, def.did, fx.layout_of(const_.ty())).to_cvalue(fx);
139         }
140         ConstKind::Unevaluated(unevaluated) => {
141             match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
142                 Ok(const_val) => const_val,
143                 Err(_) => {
144                     span_bug!(constant.span, "erroneous constant not captured by required_consts");
145                 }
146             }
147         }
148         ConstKind::Param(_)
149         | ConstKind::Infer(_)
150         | ConstKind::Bound(_, _)
151         | ConstKind::Placeholder(_)
152         | ConstKind::Error(_) => unreachable!("{:?}", const_),
153     };
154
155     codegen_const_value(fx, const_val, const_.ty())
156 }
157
158 pub(crate) fn codegen_const_value<'tcx>(
159     fx: &mut FunctionCx<'_, '_, 'tcx>,
160     const_val: ConstValue<'tcx>,
161     ty: Ty<'tcx>,
162 ) -> CValue<'tcx> {
163     let layout = fx.layout_of(ty);
164     assert!(!layout.is_unsized(), "sized const value");
165
166     if layout.is_zst() {
167         return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
168     }
169
170     match const_val {
171         ConstValue::Scalar(x) => match x {
172             Scalar::Int(int) => {
173                 if fx.clif_type(layout.ty).is_some() {
174                     return CValue::const_val(fx, layout, int);
175                 } else {
176                     let raw_val = int.to_bits(int.size()).unwrap();
177                     let val = match int.size().bytes() {
178                         1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
179                         2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
180                         4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
181                         8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
182                         16 => {
183                             let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
184                             let msb =
185                                 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
186                             fx.bcx.ins().iconcat(lsb, msb)
187                         }
188                         _ => unreachable!(),
189                     };
190
191                     let place = CPlace::new_stack_slot(fx, layout);
192                     place.to_ptr().store(fx, val, MemFlags::trusted());
193                     place.to_cvalue(fx)
194                 }
195             }
196             Scalar::Ptr(ptr, _size) => {
197                 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
198                 let alloc_kind = fx.tcx.get_global_alloc(alloc_id);
199                 let base_addr = match alloc_kind {
200                     Some(GlobalAlloc::Memory(alloc)) => {
201                         let data_id = data_id_for_alloc_id(
202                             &mut fx.constants_cx,
203                             fx.module,
204                             alloc_id,
205                             alloc.mutability,
206                         );
207                         let local_data_id =
208                             fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
209                         if fx.clif_comments.enabled() {
210                             fx.add_comment(local_data_id, format!("{:?}", alloc_id));
211                         }
212                         fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
213                     }
214                     Some(GlobalAlloc::Function(instance)) => {
215                         let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
216                         let local_func_id =
217                             fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
218                         fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
219                     }
220                     Some(GlobalAlloc::Static(def_id)) => {
221                         assert!(fx.tcx.is_static(def_id));
222                         let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
223                         let local_data_id =
224                             fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
225                         if fx.clif_comments.enabled() {
226                             fx.add_comment(local_data_id, format!("{:?}", def_id));
227                         }
228                         fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
229                     }
230                     None => bug!("missing allocation {:?}", alloc_id),
231                 };
232                 let val = if offset.bytes() != 0 {
233                     fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
234                 } else {
235                     base_addr
236                 };
237                 CValue::by_val(val, layout)
238             }
239         },
240         ConstValue::ByRef { alloc, offset } => CValue::by_ref(
241             pointer_for_allocation(fx, alloc)
242                 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
243             layout,
244         ),
245         ConstValue::Slice { data, start, end } => {
246             let ptr = pointer_for_allocation(fx, data)
247                 .offset_i64(fx, i64::try_from(start).unwrap())
248                 .get_addr(fx);
249             let len = fx
250                 .bcx
251                 .ins()
252                 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
253             CValue::by_val_pair(ptr, len, layout)
254         }
255     }
256 }
257
258 pub(crate) fn pointer_for_allocation<'tcx>(
259     fx: &mut FunctionCx<'_, '_, 'tcx>,
260     alloc: &'tcx Allocation,
261 ) -> crate::pointer::Pointer {
262     let alloc_id = fx.tcx.create_memory_alloc(alloc);
263     let data_id =
264         data_id_for_alloc_id(&mut fx.constants_cx, &mut *fx.module, alloc_id, alloc.mutability);
265
266     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
267     if fx.clif_comments.enabled() {
268         fx.add_comment(local_data_id, format!("{:?}", alloc_id));
269     }
270     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
271     crate::pointer::Pointer::new(global_ptr)
272 }
273
274 pub(crate) fn data_id_for_alloc_id(
275     cx: &mut ConstantCx,
276     module: &mut dyn Module,
277     alloc_id: AllocId,
278     mutability: rustc_hir::Mutability,
279 ) -> DataId {
280     cx.todo.push(TodoItem::Alloc(alloc_id));
281     *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
282         module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
283     })
284 }
285
286 fn data_id_for_static(
287     tcx: TyCtxt<'_>,
288     module: &mut dyn Module,
289     def_id: DefId,
290     definition: bool,
291 ) -> DataId {
292     let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
293     let linkage = if definition {
294         crate::linkage::get_static_linkage(tcx, def_id)
295     } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
296         || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
297     {
298         Linkage::Preemptible
299     } else {
300         Linkage::Import
301     };
302
303     let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
304     let symbol_name = tcx.symbol_name(instance).name;
305     let ty = instance.ty(tcx, ParamEnv::reveal_all());
306     let is_mutable = if tcx.is_mutable_static(def_id) {
307         true
308     } else {
309         !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
310     };
311     let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
312
313     let attrs = tcx.codegen_fn_attrs(def_id);
314
315     let data_id = module
316         .declare_data(
317             &*symbol_name,
318             linkage,
319             is_mutable,
320             attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
321         )
322         .unwrap();
323
324     if rlinkage.is_some() {
325         // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
326         // Declare an internal global `extern_with_linkage_foo` which
327         // is initialized with the address of `foo`.  If `foo` is
328         // discarded during linking (for example, if `foo` has weak
329         // linkage and there are no definitions), then
330         // `extern_with_linkage_foo` will instead be initialized to
331         // zero.
332
333         let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
334         let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
335         let mut data_ctx = DataContext::new();
336         data_ctx.set_align(align);
337         let data = module.declare_data_in_data(data_id, &mut data_ctx);
338         data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
339         data_ctx.write_data_addr(0, data, 0);
340         match module.define_data(ref_data_id, &data_ctx) {
341             // Every time the static is referenced there will be another definition of this global,
342             // so duplicate definitions are expected and allowed.
343             Err(ModuleError::DuplicateDefinition(_)) => {}
344             res => res.unwrap(),
345         }
346         ref_data_id
347     } else {
348         data_id
349     }
350 }
351
352 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
353     while let Some(todo_item) = cx.todo.pop() {
354         let (data_id, alloc, section_name) = match todo_item {
355             TodoItem::Alloc(alloc_id) => {
356                 //println!("alloc_id {}", alloc_id);
357                 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
358                     GlobalAlloc::Memory(alloc) => alloc,
359                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
360                 };
361                 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
362                     module
363                         .declare_anonymous_data(
364                             alloc.mutability == rustc_hir::Mutability::Mut,
365                             false,
366                         )
367                         .unwrap()
368                 });
369                 (data_id, alloc, None)
370             }
371             TodoItem::Static(def_id) => {
372                 //println!("static {:?}", def_id);
373
374                 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
375
376                 let alloc = tcx.eval_static_initializer(def_id).unwrap();
377
378                 let data_id = data_id_for_static(tcx, module, def_id, true);
379                 (data_id, alloc, section_name)
380             }
381         };
382
383         //("data_id {}", data_id);
384         if cx.done.contains(&data_id) {
385             continue;
386         }
387
388         let mut data_ctx = DataContext::new();
389         data_ctx.set_align(alloc.align.bytes());
390
391         if let Some(section_name) = section_name {
392             let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
393                 let section_name = section_name.as_str();
394                 if let Some(names) = section_name.split_once(',') {
395                     names
396                 } else {
397                     tcx.sess.fatal(&format!(
398                         "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
399                         section_name
400                     ));
401                 }
402             } else {
403                 ("", section_name.as_str())
404             };
405             data_ctx.set_segment_section(segment_name, section_name);
406         }
407
408         let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
409         data_ctx.define(bytes.into_boxed_slice());
410
411         for &(offset, alloc_id) in alloc.relocations().iter() {
412             let addend = {
413                 let endianness = tcx.data_layout.endian;
414                 let offset = offset.bytes() as usize;
415                 let ptr_size = tcx.data_layout.pointer_size;
416                 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
417                     offset..offset + ptr_size.bytes() as usize,
418                 );
419                 read_target_uint(endianness, bytes).unwrap()
420             };
421
422             let reloc_target_alloc = tcx.get_global_alloc(alloc_id).unwrap();
423             let data_id = match reloc_target_alloc {
424                 GlobalAlloc::Function(instance) => {
425                     assert_eq!(addend, 0);
426                     let func_id = crate::abi::import_function(tcx, module, instance);
427                     let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
428                     data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
429                     continue;
430                 }
431                 GlobalAlloc::Memory(target_alloc) => {
432                     data_id_for_alloc_id(cx, module, alloc_id, target_alloc.mutability)
433                 }
434                 GlobalAlloc::Static(def_id) => {
435                     if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
436                     {
437                         tcx.sess.fatal(&format!(
438                             "Allocation {:?} contains reference to TLS value {:?}",
439                             alloc, def_id
440                         ));
441                     }
442
443                     // Don't push a `TodoItem::Static` here, as it will cause statics used by
444                     // multiple crates to be duplicated between them. It isn't necessary anyway,
445                     // as it will get pushed by `codegen_static` when necessary.
446                     data_id_for_static(tcx, module, def_id, false)
447                 }
448             };
449
450             let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
451             data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
452         }
453
454         module.define_data(data_id, &data_ctx).unwrap();
455         cx.done.insert(data_id);
456     }
457
458     assert!(cx.todo.is_empty(), "{:?}", cx.todo);
459 }
460
461 pub(crate) fn mir_operand_get_const_val<'tcx>(
462     fx: &FunctionCx<'_, '_, 'tcx>,
463     operand: &Operand<'tcx>,
464 ) -> Option<ConstValue<'tcx>> {
465     match operand {
466         Operand::Constant(const_) => match const_.literal {
467             ConstantKind::Ty(const_) => {
468                 fx.monomorphize(const_).eval(fx.tcx, ParamEnv::reveal_all()).val().try_to_value()
469             }
470             ConstantKind::Val(val, _) => Some(val),
471         },
472         // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
473         // inside a temporary before being passed to the intrinsic requiring the const argument.
474         // This code tries to find a single constant defining definition of the referenced local.
475         Operand::Copy(place) | Operand::Move(place) => {
476             if !place.projection.is_empty() {
477                 return None;
478             }
479             let mut computed_const_val = None;
480             for bb_data in fx.mir.basic_blocks() {
481                 for stmt in &bb_data.statements {
482                     match &stmt.kind {
483                         StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
484                             match &local_and_rvalue.1 {
485                                 Rvalue::Cast(CastKind::Misc, operand, ty) => {
486                                     if computed_const_val.is_some() {
487                                         return None; // local assigned twice
488                                     }
489                                     if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
490                                         return None;
491                                     }
492                                     let const_val = mir_operand_get_const_val(fx, operand)?;
493                                     if fx.layout_of(*ty).size
494                                         != const_val.try_to_scalar_int()?.size()
495                                     {
496                                         return None;
497                                     }
498                                     computed_const_val = Some(const_val);
499                                 }
500                                 Rvalue::Use(operand) => {
501                                     computed_const_val = mir_operand_get_const_val(fx, operand)
502                                 }
503                                 _ => return None,
504                             }
505                         }
506                         StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
507                             if &**stmt_place == place =>
508                         {
509                             return None;
510                         }
511                         StatementKind::CopyNonOverlapping(_) => {
512                             return None;
513                         } // conservative handling
514                         StatementKind::Assign(_)
515                         | StatementKind::FakeRead(_)
516                         | StatementKind::SetDiscriminant { .. }
517                         | StatementKind::StorageLive(_)
518                         | StatementKind::StorageDead(_)
519                         | StatementKind::Retag(_, _)
520                         | StatementKind::AscribeUserType(_, _)
521                         | StatementKind::Coverage(_)
522                         | StatementKind::Nop => {}
523                     }
524                 }
525                 match &bb_data.terminator().kind {
526                     TerminatorKind::Goto { .. }
527                     | TerminatorKind::SwitchInt { .. }
528                     | TerminatorKind::Resume
529                     | TerminatorKind::Abort
530                     | TerminatorKind::Return
531                     | TerminatorKind::Unreachable
532                     | TerminatorKind::Drop { .. }
533                     | TerminatorKind::Assert { .. } => {}
534                     TerminatorKind::DropAndReplace { .. }
535                     | TerminatorKind::Yield { .. }
536                     | TerminatorKind::GeneratorDrop
537                     | TerminatorKind::FalseEdge { .. }
538                     | TerminatorKind::FalseUnwind { .. } => unreachable!(),
539                     TerminatorKind::InlineAsm { .. } => return None,
540                     TerminatorKind::Call { destination: Some((call_place, _)), .. }
541                         if call_place == place =>
542                     {
543                         return None;
544                     }
545                     TerminatorKind::Call { .. } => {}
546                 }
547             }
548             computed_const_val
549         }
550     }
551 }