Skip to content

Commit af06dce

Browse files
committed
Auto merge of #106281 - JulianKnodt:transmute_const_generics, r=b-naber
Add ability to transmute (somewhat) with generic consts in arrays Previously if the expression contained generic consts and did not have a directly equivalent type, transmuting the type in this way was forbidden, despite the two sizes being identical. Instead, we should be able to lazily tell if the two consts are identical, and if so allow them to be transmuted. This is done by normalizing the forms of expressions into sorted order of multiplied terms, which is not generic over all expressions, but should handle most cases. This allows for some _basic_ transmutations between types that are equivalent in size without requiring additional stack space at runtime. I only see one other location at which `SizeSkeleton` is being used, and it checks for equality so this shouldn't affect anywhere else that I can tell. See [this Stackoverflow post](https://stackoverflow.com/questions/73085012/transmute-nested-const-generic-array-rust) for what was previously necessary to convert between types. This PR makes converting nested `T -> [T; 1]` transmutes possible, and `[uB*2; N] -> [uB; N * 2]` possible as well. I'm not sure whether this is something that would be wanted, and if it is it definitely should not be insta-stable, so I'd add a feature gate.
2 parents dd2b195 + b76dd8c commit af06dce

File tree

9 files changed

+450
-0
lines changed

9 files changed

+450
-0
lines changed

compiler/rustc_feature/src/active.rs

+2
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,8 @@ declare_features! (
518518
/// Allows dyn upcasting trait objects via supertraits.
519519
/// Dyn upcasting is casting, e.g., `dyn Foo -> dyn Bar` where `Foo: Bar`.
520520
(active, trait_upcasting, "1.56.0", Some(65991), None),
521+
/// Allows for transmuting between arrays with sizes that contain generic consts.
522+
(active, transmute_generic_consts, "CURRENT_RUSTC_VERSION", Some(109929), None),
521523
/// Allows #[repr(transparent)] on unions (RFC 2645).
522524
(active, transparent_unions, "1.37.0", Some(60405), None),
523525
/// Allows inconsistent bounds in where clauses.

compiler/rustc_hir_typeck/src/intrinsicck.rs

+7
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
8484
let skeleton_string = |ty: Ty<'tcx>, sk| match sk {
8585
Ok(SizeSkeleton::Known(size)) => format!("{} bits", size.bits()),
8686
Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"),
87+
Ok(SizeSkeleton::Generic(size)) => {
88+
if let Some(size) = size.try_eval_target_usize(tcx, self.param_env) {
89+
format!("{size} bytes")
90+
} else {
91+
format!("generic size {size}")
92+
}
93+
}
8794
Err(LayoutError::Unknown(bad)) => {
8895
if bad == ty {
8996
"this type does not have a fixed size".to_owned()

compiler/rustc_middle/src/ty/layout.rs

+95
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,12 @@ pub enum SizeSkeleton<'tcx> {
281281
/// Any statically computable Layout.
282282
Known(Size),
283283

284+
/// This is a generic const expression (i.e. N * 2), which may contain some parameters.
285+
/// It must be of type usize, and represents the size of a type in bytes.
286+
/// It is not required to be evaluatable to a concrete value, but can be used to check
287+
/// that another SizeSkeleton is of equal size.
288+
Generic(ty::Const<'tcx>),
289+
284290
/// A potentially-fat pointer.
285291
Pointer {
286292
/// If true, this pointer is never null.
@@ -326,6 +332,37 @@ impl<'tcx> SizeSkeleton<'tcx> {
326332
),
327333
}
328334
}
335+
ty::Array(inner, len)
336+
if len.ty() == tcx.types.usize && tcx.features().transmute_generic_consts =>
337+
{
338+
match SizeSkeleton::compute(inner, tcx, param_env)? {
339+
// This may succeed because the multiplication of two types may overflow
340+
// but a single size of a nested array will not.
341+
SizeSkeleton::Known(s) => {
342+
if let Some(c) = len.try_eval_target_usize(tcx, param_env) {
343+
let size = s
344+
.bytes()
345+
.checked_mul(c)
346+
.ok_or_else(|| LayoutError::SizeOverflow(ty))?;
347+
return Ok(SizeSkeleton::Known(Size::from_bytes(size)));
348+
}
349+
let len = tcx.expand_abstract_consts(len);
350+
let prev = ty::Const::from_target_usize(tcx, s.bytes());
351+
let Some(gen_size) = mul_sorted_consts(tcx, param_env, len, prev) else {
352+
return Err(LayoutError::SizeOverflow(ty));
353+
};
354+
Ok(SizeSkeleton::Generic(gen_size))
355+
}
356+
SizeSkeleton::Pointer { .. } => Err(err),
357+
SizeSkeleton::Generic(g) => {
358+
let len = tcx.expand_abstract_consts(len);
359+
let Some(gen_size) = mul_sorted_consts(tcx, param_env, len, g) else {
360+
return Err(LayoutError::SizeOverflow(ty));
361+
};
362+
Ok(SizeSkeleton::Generic(gen_size))
363+
}
364+
}
365+
}
329366

330367
ty::Adt(def, substs) => {
331368
// Only newtypes and enums w/ nullable pointer optimization.
@@ -355,6 +392,9 @@ impl<'tcx> SizeSkeleton<'tcx> {
355392
}
356393
ptr = Some(field);
357394
}
395+
SizeSkeleton::Generic(_) => {
396+
return Err(err);
397+
}
358398
}
359399
}
360400
Ok(ptr)
@@ -410,11 +450,66 @@ impl<'tcx> SizeSkeleton<'tcx> {
410450
(SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
411451
a == b
412452
}
453+
// constants are always pre-normalized into a canonical form so this
454+
// only needs to check if their pointers are identical.
455+
(SizeSkeleton::Generic(a), SizeSkeleton::Generic(b)) => a == b,
413456
_ => false,
414457
}
415458
}
416459
}
417460

461+
/// When creating the layout for types with abstract conts in their size (i.e. [usize; 4 * N]),
462+
/// to ensure that they have a canonical order and can be compared directly we combine all
463+
/// constants, and sort the other terms. This allows comparison of expressions of sizes,
464+
/// allowing for things like transmutating between types that depend on generic consts.
465+
/// This returns `None` if multiplication of constants overflows.
466+
fn mul_sorted_consts<'tcx>(
467+
tcx: TyCtxt<'tcx>,
468+
param_env: ty::ParamEnv<'tcx>,
469+
a: ty::Const<'tcx>,
470+
b: ty::Const<'tcx>,
471+
) -> Option<ty::Const<'tcx>> {
472+
use crate::mir::BinOp::Mul;
473+
use ty::ConstKind::Expr;
474+
use ty::Expr::Binop;
475+
476+
let mut work = vec![a, b];
477+
let mut done = vec![];
478+
while let Some(n) = work.pop() {
479+
if let Expr(Binop(Mul, l, r)) = n.kind() {
480+
work.push(l);
481+
work.push(r)
482+
} else {
483+
done.push(n);
484+
}
485+
}
486+
let mut k = 1;
487+
let mut overflow = false;
488+
done.retain(|c| {
489+
let Some(c) = c.try_eval_target_usize(tcx, param_env) else {
490+
return true;
491+
};
492+
let Some(next) = c.checked_mul(k) else {
493+
overflow = true;
494+
return false;
495+
};
496+
k = next;
497+
false
498+
});
499+
if overflow {
500+
return None;
501+
}
502+
if k != 1 {
503+
done.push(ty::Const::from_target_usize(tcx, k));
504+
} else if k == 0 {
505+
return Some(ty::Const::from_target_usize(tcx, 0));
506+
}
507+
done.sort_unstable();
508+
509+
// create a single tree from the buffer
510+
done.into_iter().reduce(|acc, n| tcx.mk_const(Expr(Binop(Mul, n, acc)), n.ty()))
511+
}
512+
418513
pub trait HasTyCtxt<'tcx>: HasDataLayout {
419514
fn tcx(&self) -> TyCtxt<'tcx>;
420515
}

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1496,6 +1496,7 @@ symbols! {
14961496
trait_alias,
14971497
trait_upcasting,
14981498
transmute,
1499+
transmute_generic_consts,
14991500
transmute_opts,
15001501
transmute_trait,
15011502
transparent,
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#![feature(transmute_generic_consts)]
2+
#![feature(generic_const_exprs)]
3+
#![allow(incomplete_features)]
4+
5+
fn foo<const W: usize, const H: usize>(v: [[u32;H+1]; W]) -> [[u32; W+1]; H] {
6+
unsafe {
7+
std::mem::transmute(v)
8+
//~^ ERROR cannot transmute
9+
}
10+
}
11+
12+
fn bar<const W: bool, const H: usize>(v: [[u32; H]; W]) -> [[u32; W]; H] {
13+
//~^ ERROR mismatched types
14+
//~| ERROR mismatched types
15+
unsafe {
16+
std::mem::transmute(v)
17+
//~^ ERROR cannot transmute between types
18+
}
19+
}
20+
21+
fn baz<const W: usize, const H: usize>(v: [[u32; H]; W]) -> [u32; W * H * H] {
22+
unsafe {
23+
std::mem::transmute(v)
24+
//~^ ERROR cannot transmute
25+
}
26+
}
27+
28+
fn overflow(v: [[[u32; 8888888]; 9999999]; 777777777]) -> [[[u32; 9999999]; 777777777]; 8888888] {
29+
unsafe {
30+
std::mem::transmute(v)
31+
//~^ ERROR cannot transmute
32+
}
33+
}
34+
35+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
2+
--> $DIR/transmute-fail.rs:7:5
3+
|
4+
LL | std::mem::transmute(v)
5+
| ^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: source type: `[[u32; H+1]; W]` (generic size [const expr])
8+
= note: target type: `[[u32; W+1]; H]` (generic size [const expr])
9+
10+
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
11+
--> $DIR/transmute-fail.rs:16:5
12+
|
13+
LL | std::mem::transmute(v)
14+
| ^^^^^^^^^^^^^^^^^^^
15+
|
16+
= note: source type: `[[u32; H]; W]` (this type does not have a fixed size)
17+
= note: target type: `[[u32; W]; H]` (size can vary because of [u32; W])
18+
19+
error[E0308]: mismatched types
20+
--> $DIR/transmute-fail.rs:12:53
21+
|
22+
LL | fn bar<const W: bool, const H: usize>(v: [[u32; H]; W]) -> [[u32; W]; H] {
23+
| ^ expected `usize`, found `bool`
24+
25+
error[E0308]: mismatched types
26+
--> $DIR/transmute-fail.rs:12:67
27+
|
28+
LL | fn bar<const W: bool, const H: usize>(v: [[u32; H]; W]) -> [[u32; W]; H] {
29+
| ^ expected `usize`, found `bool`
30+
31+
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
32+
--> $DIR/transmute-fail.rs:23:5
33+
|
34+
LL | std::mem::transmute(v)
35+
| ^^^^^^^^^^^^^^^^^^^
36+
|
37+
= note: source type: `[[u32; H]; W]` (generic size [const expr])
38+
= note: target type: `[u32; W * H * H]` (generic size [const expr])
39+
40+
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
41+
--> $DIR/transmute-fail.rs:30:5
42+
|
43+
LL | std::mem::transmute(v)
44+
| ^^^^^^^^^^^^^^^^^^^
45+
|
46+
= note: source type: `[[[u32; 8888888]; 9999999]; 777777777]` (values of the type `[[[u32; 8888888]; 9999999]; 777777777]` are too big for the current architecture)
47+
= note: target type: `[[[u32; 9999999]; 777777777]; 8888888]` (values of the type `[[[u32; 9999999]; 777777777]; 8888888]` are too big for the current architecture)
48+
49+
error: aborting due to 6 previous errors
50+
51+
Some errors have detailed explanations: E0308, E0512.
52+
For more information about an error, try `rustc --explain E0308`.

tests/ui/const-generics/transmute.rs

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// run-pass
2+
#![feature(generic_const_exprs)]
3+
#![feature(transmute_generic_consts)]
4+
#![allow(incomplete_features)]
5+
6+
fn transpose<const W: usize, const H: usize>(v: [[u32;H]; W]) -> [[u32; W]; H] {
7+
unsafe {
8+
std::mem::transmute(v)
9+
}
10+
}
11+
12+
fn ident<const W: usize, const H: usize>(v: [[u32; H]; W]) -> [[u32; H]; W] {
13+
unsafe {
14+
std::mem::transmute(v)
15+
}
16+
}
17+
18+
fn flatten<const W: usize, const H: usize>(v: [[u32; H]; W]) -> [u32; W * H] {
19+
unsafe {
20+
std::mem::transmute(v)
21+
}
22+
}
23+
24+
fn coagulate<const W: usize, const H: usize>(v: [u32; H*W]) -> [[u32; W];H] {
25+
unsafe {
26+
std::mem::transmute(v)
27+
}
28+
}
29+
30+
fn flatten_3d<const W: usize, const H: usize, const D: usize>(
31+
v: [[[u32; D]; H]; W]
32+
) -> [u32; D * W * H] {
33+
unsafe {
34+
std::mem::transmute(v)
35+
}
36+
}
37+
38+
fn flatten_somewhat<const W: usize, const H: usize, const D: usize>(
39+
v: [[[u32; D]; H]; W]
40+
) -> [[u32; D * W]; H] {
41+
unsafe {
42+
std::mem::transmute(v)
43+
}
44+
}
45+
46+
fn known_size<const L: usize>(v: [u16; L]) -> [u8; L * 2] {
47+
unsafe {
48+
std::mem::transmute(v)
49+
}
50+
}
51+
52+
fn condense_bytes<const L: usize>(v: [u8; L * 2]) -> [u16; L] {
53+
unsafe {
54+
std::mem::transmute(v)
55+
}
56+
}
57+
58+
fn singleton_each<const L: usize>(v: [u8; L]) -> [[u8;1]; L] {
59+
unsafe {
60+
std::mem::transmute(v)
61+
}
62+
}
63+
64+
fn transpose_with_const<const W: usize, const H: usize>(
65+
v: [[u32; 2 * H]; W + W]
66+
) -> [[u32; W + W]; 2 * H] {
67+
unsafe {
68+
std::mem::transmute(v)
69+
}
70+
}
71+
72+
fn main() {
73+
let _ = transpose([[0; 8]; 16]);
74+
let _ = transpose_with_const::<8,4>([[0; 8]; 16]);
75+
let _ = ident([[0; 8]; 16]);
76+
let _ = flatten([[0; 13]; 5]);
77+
let _: [[_; 5]; 13] = coagulate([0; 65]);
78+
let _ = flatten_3d([[[0; 3]; 13]; 5]);
79+
let _ = flatten_somewhat([[[0; 3]; 13]; 5]);
80+
let _ = known_size([16; 13]);
81+
let _: [u16; 5] = condense_bytes([16u8; 10]);
82+
let _ = singleton_each([16; 10]);
83+
}

0 commit comments

Comments
 (0)