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