]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/layout_sanity_check.rs
sanity_check_layout: less rightwards drift
[rust.git] / compiler / rustc_ty_utils / src / layout_sanity_check.rs
1 use rustc_middle::ty::{
2     layout::{LayoutCx, TyAndLayout},
3     TyCtxt,
4 };
5 use rustc_target::abi::*;
6
7 use std::cmp;
8
9 /// Enforce some basic invariants on layouts.
10 pub(super) fn sanity_check_layout<'tcx>(
11     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
12     layout: &TyAndLayout<'tcx>,
13 ) {
14     // Type-level uninhabitedness should always imply ABI uninhabitedness.
15     if layout.ty.is_privately_uninhabited(cx.tcx, cx.param_env) {
16         assert!(layout.abi.is_uninhabited());
17     }
18
19     if layout.size.bytes() % layout.align.abi.bytes() != 0 {
20         bug!("size is not a multiple of align, in the following layout:\n{layout:#?}");
21     }
22
23     if !cfg!(debug_assertions) {
24         // Stop here, the rest is kind of expensive.
25         return;
26     }
27
28     /// Yields non-ZST fields of the type
29     fn non_zst_fields<'tcx, 'a>(
30         cx: &'a LayoutCx<'tcx, TyCtxt<'tcx>>,
31         layout: &'a TyAndLayout<'tcx>,
32     ) -> impl Iterator<Item = (Size, TyAndLayout<'tcx>)> + 'a {
33         (0..layout.layout.fields().count()).filter_map(|i| {
34             let field = layout.field(cx, i);
35             // Also checking `align == 1` here leads to test failures in
36             // `layout/zero-sized-array-union.rs`, where a type has a zero-size field with
37             // alignment 4 that still gets ignored during layout computation (which is okay
38             // since other fields already force alignment 4).
39             let zst = field.is_zst();
40             (!zst).then(|| (layout.fields.offset(i), field))
41         })
42     }
43
44     fn skip_newtypes<'tcx>(
45         cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
46         layout: &TyAndLayout<'tcx>,
47     ) -> TyAndLayout<'tcx> {
48         if matches!(layout.layout.variants(), Variants::Multiple { .. }) {
49             // Definitely not a newtype of anything.
50             return *layout;
51         }
52         let mut fields = non_zst_fields(cx, layout);
53         let Some(first) = fields.next() else {
54             // No fields here, so this could be a primitive or enum -- either way it's not a newtype around a thing
55             return *layout
56         };
57         if fields.next().is_none() {
58             let (offset, first) = first;
59             if offset == Size::ZERO && first.layout.size() == layout.size {
60                 // This is a newtype, so keep recursing.
61                 // FIXME(RalfJung): I don't think it would be correct to do any checks for
62                 // alignment here, so we don't. Is that correct?
63                 return skip_newtypes(cx, &first);
64             }
65         }
66         // No more newtypes here.
67         *layout
68     }
69
70     fn check_layout_abi<'tcx>(cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, layout: &TyAndLayout<'tcx>) {
71         match layout.layout.abi() {
72             Abi::Scalar(scalar) => {
73                 // No padding in scalars.
74                 let size = scalar.size(cx);
75                 let align = scalar.align(cx).abi;
76                 assert_eq!(
77                     layout.layout.size(),
78                     size,
79                     "size mismatch between ABI and layout in {layout:#?}"
80                 );
81                 assert_eq!(
82                     layout.layout.align().abi,
83                     align,
84                     "alignment mismatch between ABI and layout in {layout:#?}"
85                 );
86                 // Check that this matches the underlying field.
87                 let inner = skip_newtypes(cx, layout);
88                 assert!(
89                     matches!(inner.layout.abi(), Abi::Scalar(_)),
90                     "`Scalar` type {} is newtype around non-`Scalar` type {}",
91                     layout.ty,
92                     inner.ty
93                 );
94                 match inner.layout.fields() {
95                     FieldsShape::Primitive => {
96                         // Fine.
97                     }
98                     FieldsShape::Union(..) => {
99                         // FIXME: I guess we could also check something here? Like, look at all fields?
100                         return;
101                     }
102                     FieldsShape::Arbitrary { .. } => {
103                         // Should be an enum, the only field is the discriminant.
104                         assert!(
105                             inner.ty.is_enum(),
106                             "`Scalar` layout for non-primitive non-enum type {}",
107                             inner.ty
108                         );
109                         assert_eq!(
110                             inner.layout.fields().count(),
111                             1,
112                             "`Scalar` layout for multiple-field type in {inner:#?}",
113                         );
114                         let offset = inner.layout.fields().offset(0);
115                         let field = inner.field(cx, 0);
116                         // The field should be at the right offset, and match the `scalar` layout.
117                         assert_eq!(
118                             offset,
119                             Size::ZERO,
120                             "`Scalar` field at non-0 offset in {inner:#?}",
121                         );
122                         assert_eq!(field.size, size, "`Scalar` field with bad size in {inner:#?}",);
123                         assert_eq!(
124                             field.align.abi, align,
125                             "`Scalar` field with bad align in {inner:#?}",
126                         );
127                         assert!(
128                             matches!(field.abi, Abi::Scalar(_)),
129                             "`Scalar` field with bad ABI in {inner:#?}",
130                         );
131                     }
132                     _ => {
133                         panic!("`Scalar` layout for non-primitive non-enum type {}", inner.ty);
134                     }
135                 }
136             }
137             Abi::ScalarPair(scalar1, scalar2) => {
138                 // Sanity-check scalar pairs. These are a bit more flexible and support
139                 // padding, but we can at least ensure both fields actually fit into the layout
140                 // and the alignment requirement has not been weakened.
141                 let size1 = scalar1.size(cx);
142                 let align1 = scalar1.align(cx).abi;
143                 let size2 = scalar2.size(cx);
144                 let align2 = scalar2.align(cx).abi;
145                 assert!(
146                     layout.layout.align().abi >= cmp::max(align1, align2),
147                     "alignment mismatch between ABI and layout in {layout:#?}",
148                 );
149                 let field2_offset = size1.align_to(align2);
150                 assert!(
151                     layout.layout.size() >= field2_offset + size2,
152                     "size mismatch between ABI and layout in {layout:#?}"
153                 );
154                 // Check that the underlying pair of fields matches.
155                 let inner = skip_newtypes(cx, layout);
156                 assert!(
157                     matches!(inner.layout.abi(), Abi::ScalarPair(..)),
158                     "`ScalarPair` type {} is newtype around non-`ScalarPair` type {}",
159                     layout.ty,
160                     inner.ty
161                 );
162                 if matches!(inner.layout.variants(), Variants::Multiple { .. }) {
163                     // FIXME: ScalarPair for enums is enormously complicated and it is very hard
164                     // to check anything about them.
165                     return;
166                 }
167                 match inner.layout.fields() {
168                     FieldsShape::Arbitrary { .. } => {
169                         // Checked below.
170                     }
171                     FieldsShape::Union(..) => {
172                         // FIXME: I guess we could also check something here? Like, look at all fields?
173                         return;
174                     }
175                     _ => {
176                         panic!("`ScalarPair` layout with unexpected field shape in {inner:#?}");
177                     }
178                 }
179                 let mut fields = non_zst_fields(cx, &inner);
180                 let (offset1, field1) = fields.next().unwrap_or_else(|| {
181                     panic!(
182                         "`ScalarPair` layout for type with not even one non-ZST field: {inner:#?}"
183                     )
184                 });
185                 let (offset2, field2) = fields.next().unwrap_or_else(|| {
186                     panic!(
187                         "`ScalarPair` layout for type with less than two non-ZST fields: {inner:#?}"
188                     )
189                 });
190                 assert!(
191                     fields.next().is_none(),
192                     "`ScalarPair` layout for type with at least three non-ZST fields: {inner:#?}"
193                 );
194                 // The fields might be in opposite order.
195                 let (offset1, field1, offset2, field2) = if offset1 <= offset2 {
196                     (offset1, field1, offset2, field2)
197                 } else {
198                     (offset2, field2, offset1, field1)
199                 };
200                 // The fields should be at the right offset, and match the `scalar` layout.
201                 assert_eq!(
202                     offset1,
203                     Size::ZERO,
204                     "`ScalarPair` first field at non-0 offset in {inner:#?}",
205                 );
206                 assert_eq!(
207                     field1.size, size1,
208                     "`ScalarPair` first field with bad size in {inner:#?}",
209                 );
210                 assert_eq!(
211                     field1.align.abi, align1,
212                     "`ScalarPair` first field with bad align in {inner:#?}",
213                 );
214                 assert!(
215                     matches!(field1.abi, Abi::Scalar(_)),
216                     "`ScalarPair` first field with bad ABI in {inner:#?}",
217                 );
218                 assert_eq!(
219                     offset2, field2_offset,
220                     "`ScalarPair` second field at bad offset in {inner:#?}",
221                 );
222                 assert_eq!(
223                     field2.size, size2,
224                     "`ScalarPair` second field with bad size in {inner:#?}",
225                 );
226                 assert_eq!(
227                     field2.align.abi, align2,
228                     "`ScalarPair` second field with bad align in {inner:#?}",
229                 );
230                 assert!(
231                     matches!(field2.abi, Abi::Scalar(_)),
232                     "`ScalarPair` second field with bad ABI in {inner:#?}",
233                 );
234             }
235             Abi::Vector { count, element } => {
236                 // No padding in vectors. Alignment can be strengthened, though.
237                 assert!(
238                     layout.layout.align().abi >= element.align(cx).abi,
239                     "alignment mismatch between ABI and layout in {layout:#?}"
240                 );
241                 let size = element.size(cx) * count;
242                 assert_eq!(
243                     layout.layout.size(),
244                     size.align_to(cx.data_layout().vector_align(size).abi),
245                     "size mismatch between ABI and layout in {layout:#?}"
246                 );
247             }
248             Abi::Uninhabited | Abi::Aggregate { .. } => {} // Nothing to check.
249         }
250     }
251
252     check_layout_abi(cx, layout);
253
254     if let Variants::Multiple { variants, .. } = &layout.variants {
255         for variant in variants.iter() {
256             // No nested "multiple".
257             assert!(matches!(variant.variants, Variants::Single { .. }));
258             // Variants should have the same or a smaller size as the full thing,
259             // and same for alignment.
260             if variant.size > layout.size {
261                 bug!(
262                     "Type with size {} bytes has variant with size {} bytes: {layout:#?}",
263                     layout.size.bytes(),
264                     variant.size.bytes(),
265                 )
266             }
267             if variant.align.abi > layout.align.abi {
268                 bug!(
269                     "Type with alignment {} bytes has variant with alignment {} bytes: {layout:#?}",
270                     layout.align.abi.bytes(),
271                     variant.align.abi.bytes(),
272                 )
273             }
274             // Skip empty variants.
275             if variant.size == Size::ZERO
276                 || variant.fields.count() == 0
277                 || variant.abi.is_uninhabited()
278             {
279                 // These are never actually accessed anyway, so we can skip the coherence check
280                 // for them. They also fail that check, since they have
281                 // `Aggregate`/`Uninhbaited` ABI even when the main type is
282                 // `Scalar`/`ScalarPair`. (Note that sometimes, variants with fields have size
283                 // 0, and sometimes, variants without fields have non-0 size.)
284                 continue;
285             }
286             // The top-level ABI and the ABI of the variants should be coherent.
287             let scalar_coherent =
288                 |s1: Scalar, s2: Scalar| s1.size(cx) == s2.size(cx) && s1.align(cx) == s2.align(cx);
289             let abi_coherent = match (layout.abi, variant.abi) {
290                 (Abi::Scalar(s1), Abi::Scalar(s2)) => scalar_coherent(s1, s2),
291                 (Abi::ScalarPair(a1, b1), Abi::ScalarPair(a2, b2)) => {
292                     scalar_coherent(a1, a2) && scalar_coherent(b1, b2)
293                 }
294                 (Abi::Uninhabited, _) => true,
295                 (Abi::Aggregate { .. }, _) => true,
296                 _ => false,
297             };
298             if !abi_coherent {
299                 bug!(
300                     "Variant ABI is incompatible with top-level ABI:\nvariant={:#?}\nTop-level: {layout:#?}",
301                     variant
302                 );
303             }
304         }
305     }
306 }