canon::generic: a generic pointer an aggregate or a vector holds takes its leaf's group
A generic pointer held in a struct, array or vector value was refused as GenericPointer(Aggregate). Each generic pointer such a value holds is now a leaf, a union-find node of its own: a struct's leaves are its fields' in order, an array's or a vector's its element's, shared by every element. An insertvalue's leaves under its indices take the inserted value's and its others the aggregate operand's; an extractvalue's take its operand's under its indices, as does a generic pointer it extracts; a phi, select, freeze or shufflevector's take their operands'; insertelement and extractelement link a vector's one leaf. A constant brings in each leaf's space; an aggregate a load or a call gives stays refused (Memory, Call), and so does one passed to a call or returned (Call). Each such value's type becomes its type with each leaf its group's pointer, and its constants alike. This is MPS's array_ref and _MPSKernelInOut passed by value under MSL 4.1, which the inliner leaves as insertvalue chains read by extractvalue. The plan moves to generic/plan.rs: its union-find nodes are the instructions, the cells' slots and the leaves, and nullness flows along the links from a value to what takes it. Canon tests: a device pointer through one field, through the first of two fields of different spaces and through a select of two structs keeps its space; a field a null may reach compares with null; an array of a device and a thread pointer is TwoSpaces; a struct loaded from memory is Memory.
This commit is contained in:
1 parent
acc4a77b0b
commit
5aceb23b08
4 files changed
+1257
-346
No files matched your search
@@ -8,38 +8,41 @@
|
||||
//!
|
||||
//! Generic pointers that must share a type share a space: a `getelementptr`, `bitcast`,
|
||||
//! `addrspacecast` or `freeze` of a generic pointer and its operand, a `phi` or `select` and its
|
||||
//! operands, the two sides of an `icmp`, and the generic pointers stored into and loaded from one
|
||||
//! slot of thread memory whose every access the translation sees ([`cells`]). Each such group has
|
||||
//! one space where every pointer entering it does:
|
||||
//! operands, the two sides of an `icmp`, the generic pointers stored into and loaded from one
|
||||
//! slot of thread memory whose every access the translation sees ([`cells`]), and a generic
|
||||
//! pointer an aggregate or a vector value holds (a *leaf*) and what it comes from ([`leaves`]).
|
||||
//! The links are the union-find of [`plan`]. Each such group has one space where every pointer
|
||||
//! entering it does:
|
||||
//!
|
||||
//! - an `addrspacecast` from a pointer of a device, thread or threadgroup space brings in that
|
||||
//! space, and so does a constant expression of such a cast;
|
||||
//! - a null, undefined or poison constant brings in none: it points nowhere;
|
||||
//! - a generic pointer a call, an `inttoptr`, an atomic, an aggregate or a load from other memory
|
||||
//! gives, or a parameter, brings in a space only the run knows.
|
||||
//! - a generic pointer a call, an `inttoptr`, an atomic or a load from other memory gives, or a
|
||||
//! parameter, brings in a space only the run knows, and so does an aggregate a load or a call
|
||||
//! gives for each of its leaves.
|
||||
//!
|
||||
//! A group that pointers of two spaces enter, or one a space only the run knows, is
|
||||
//! `Unsupported{GenericPointer(..)}` at the instruction where it does, naming how
|
||||
//! ([`GenericPointer`]): no Vulkan pointer holds either. So is a generic pointer passed to a call
|
||||
//! other than a query (the callee's type names the generic space) or returned (`Call`), or held
|
||||
//! in an aggregate or a vector value (`Aggregate`).
|
||||
//! other than a query (the callee's type names the generic space) or returned, alone or in an
|
||||
//! aggregate (`Call`).
|
||||
//!
|
||||
//! Each generic pointer then is its group's pointer type, and a group that no space enters a
|
||||
//! thread pointer (it addresses nothing). A cast into the generic space is its operand. A cast
|
||||
//! out of it is its operand where it names the group's space, and poison where it names another
|
||||
//! (an `addrspacecast` of a pointer not of the space it names is poison). Every other instruction
|
||||
//! keeps its operation, its generic constants those of its group's type (a store's, its
|
||||
//! value's group's). A query is false for
|
||||
//! another space; for the group's own space it is true, or, where a null constant may reach the
|
||||
//! pointer (through thread memory too), whether the pointer is not null, as Metal answers no space
|
||||
//! for a null generic
|
||||
//! pointer. That answer is the pointer's structure's where it decides it: a variable's or a
|
||||
//! global's address, a cast of one or an in-bounds step from one is not null, a null constant is,
|
||||
//! and a `select` between two such pointers is not null where its condition picks the one that
|
||||
//! is not. Else it is a comparison with the null pointer of the group's space. A generic pointer
|
||||
//! that only answered queries read goes, with what only it reads. Aggregate types that hold
|
||||
//! generic pointers (an `alloca`'s or a `getelementptr`'s source type) keep them: they lay out
|
||||
//! bytes, and a pointer of every space is 64 bits.
|
||||
//! thread pointer (it addresses nothing); an aggregate or a vector value's type is its type with
|
||||
//! each leaf its group's pointer. A cast into the generic space is its operand. A cast out of it
|
||||
//! is its operand where it names the group's space, and poison where it names another (an
|
||||
//! `addrspacecast` of a pointer not of the space it names is poison). Every other instruction
|
||||
//! keeps its operation, its generic constants those of its group's type (a store's, its value's
|
||||
//! group's; an aggregate constant's, its leaves'). A query is false for another space; for the
|
||||
//! group's own space it is true, or, where a null constant may reach the pointer (through thread
|
||||
//! memory and aggregates too), whether the pointer is not null, as Metal answers no space for a
|
||||
//! null generic pointer. That answer is the pointer's structure's where it decides it: a
|
||||
//! variable's or a global's address, a cast of one or an in-bounds step from one is not null, a
|
||||
//! null constant is, and a `select` between two such pointers is not null where its condition
|
||||
//! picks the one that is not. Else it is a comparison with the null pointer of the group's space.
|
||||
//! A generic pointer that only answered queries read goes, with what only it reads. Aggregate
|
||||
//! types that hold generic pointers in memory (an `alloca`'s or a `getelementptr`'s source type)
|
||||
//! keep them: they lay out bytes, and a pointer of every space is 64 bits.
|
||||
|
||||
use crate::budget::Meter;
|
||||
use crate::error::{DiagName, Error, Feature, GenericPointer, Location, Unsupported};
|
||||
@@ -50,6 +53,10 @@ use crate::ir::{FuncId, Idx, InstId, InstKind, IntPredicate, ModuleParts, Type,
|
||||
use super::rewrite::{apply, filled, invariant, scoped, BodyEdit};
|
||||
|
||||
mod cells;
|
||||
mod leaves;
|
||||
mod plan;
|
||||
|
||||
use plan::{plan, Plan};
|
||||
|
||||
/// The most aggregate levels searched for a generic pointer in a type.
|
||||
const DEPTH: u32 = 32;
|
||||
@@ -281,48 +288,6 @@ enum NotNull {
|
||||
Run,
|
||||
}
|
||||
|
||||
/// The generic operands of `kind` that share the result's group (or, for an `icmp`, each other's).
|
||||
fn linked(kind: &InstKind) -> Vec<Value> {
|
||||
match kind {
|
||||
InstKind::Gep { base, .. } => vec![*base],
|
||||
InstKind::Cast {
|
||||
op: CastOp::Bitcast | CastOp::AddrSpaceCast,
|
||||
v,
|
||||
}
|
||||
| InstKind::Freeze(v) => vec![*v],
|
||||
InstKind::Phi { incoming, .. } => incoming.iter().map(|&(v, _)| v).collect(),
|
||||
InstKind::Select { t, f, .. } => vec![*t, *f],
|
||||
InstKind::ICmp { a, b, .. } => vec![*a, *b],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The group's representative of `i` (path halving).
|
||||
fn find(parent: &mut [u32], i: usize) -> usize {
|
||||
let mut x = i;
|
||||
while let Some(&p) = parent.get(x) {
|
||||
let p = p as usize;
|
||||
if p == x {
|
||||
break;
|
||||
}
|
||||
let grand = parent.get(p).copied().unwrap_or(p as u32);
|
||||
if let Some(slot) = parent.get_mut(x) {
|
||||
*slot = grand;
|
||||
}
|
||||
x = grand as usize;
|
||||
}
|
||||
x
|
||||
}
|
||||
|
||||
fn union(parent: &mut [u32], a: usize, b: usize) {
|
||||
let (ra, rb) = (find(parent, a), find(parent, b));
|
||||
if ra != rb {
|
||||
if let Some(slot) = parent.get_mut(ra) {
|
||||
*slot = rb as u32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `body` with every generic pointer a pointer of its group's space (module docs), and whether a
|
||||
/// query folded (SCCP then folds what it decides). `func` is the entry whose body it is.
|
||||
pub(super) fn resolve(
|
||||
@@ -355,277 +320,6 @@ pub(super) fn resolve(
|
||||
Ok((edited, plan.folds))
|
||||
}
|
||||
|
||||
/// Each generic instruction's group space and nullness; `None` when the body holds no generic
|
||||
/// pointer.
|
||||
struct Plan {
|
||||
/// Per instruction: its group's space (`Unseen` for a non-generic instruction).
|
||||
space: Vec<Space>,
|
||||
/// Per instruction: whether a null constant may reach it.
|
||||
null: Vec<bool>,
|
||||
/// Whether a query is answered.
|
||||
folds: bool,
|
||||
}
|
||||
|
||||
fn plan(cx: &Cx<'_>, m: &mut Meter, held: &mut usize) -> Result<Option<Plan>, Error> {
|
||||
let n = cx.body.insts.len();
|
||||
// Whether anything is generic: an instruction's result or any operand.
|
||||
let mut any = false;
|
||||
for inst in cx.body.insts.values() {
|
||||
m.tick(1)?;
|
||||
any |= cx.generic(inst.ty);
|
||||
inst.kind.for_each_value(|v| any |= cx.is_generic(v));
|
||||
if any {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return Ok(None);
|
||||
}
|
||||
// Union-find nodes: the instructions, then the slots of thread memory generic pointers pass
|
||||
// through.
|
||||
let cells = cells::find(cx, m, held)?;
|
||||
let nodes = n + cells.as_ref().map_or(0, |c| c.slots);
|
||||
let mut parent: Vec<u32> = filled(m, held, nodes, 0)?;
|
||||
for (k, slot) in parent.iter_mut().enumerate() {
|
||||
*slot = u32::try_from(k).map_err(|_| invariant("instruction ids past u32"))?;
|
||||
}
|
||||
let slot = |node: u32| n + node as usize;
|
||||
let mut source: Vec<Space> = filled(m, held, n, Space::Unseen)?;
|
||||
let mut null: Vec<bool> = filled(m, held, n, false)?;
|
||||
let mut folds = false;
|
||||
for (i, inst) in cx.body.insts.iter() {
|
||||
m.tick(1)?;
|
||||
let generic = cx.generic(inst.ty);
|
||||
// Generic values held where no group reaches: an aggregate or a vector.
|
||||
if !generic && cx.holds_generic(inst.ty, 0)? {
|
||||
return Err(cx.refuse(GenericPointer::Aggregate, i));
|
||||
}
|
||||
// A store of a generic pointer is in its value's group, and in its slot's where it
|
||||
// stores into a cell.
|
||||
if let InstKind::Store { val, .. } = inst.kind {
|
||||
if cx.is_generic(val) {
|
||||
let (vs, vz) = cx.operand(val)?;
|
||||
if let Some(x) = source.get_mut(i.index()) {
|
||||
*x = vs;
|
||||
}
|
||||
if let Some(x) = null.get_mut(i.index()) {
|
||||
*x = vz;
|
||||
}
|
||||
if let Value::Inst(j) = val {
|
||||
union(&mut parent, i.index(), j.index());
|
||||
}
|
||||
if let Some(Some(node)) = cells.as_ref().and_then(|c| c.reach(i)) {
|
||||
union(&mut parent, i.index(), slot(node));
|
||||
}
|
||||
}
|
||||
}
|
||||
match &inst.kind {
|
||||
InstKind::Call(call) => {
|
||||
let query = matches!(
|
||||
call.callee,
|
||||
Callee::Air {
|
||||
op: AirIntrinsic::PointerSpace(_),
|
||||
..
|
||||
}
|
||||
);
|
||||
if call.args.iter().any(|&a| cx.is_generic(a)) && !query {
|
||||
return Err(cx.refuse(GenericPointer::Call, i));
|
||||
}
|
||||
folds |= query;
|
||||
// A query's pointer is its own group's.
|
||||
}
|
||||
InstKind::Ret(Some(v)) if cx.is_generic(*v) => {
|
||||
return Err(cx.refuse(GenericPointer::Call, i))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !generic {
|
||||
// An `icmp` of generic pointers joins its sides' groups.
|
||||
if let InstKind::ICmp { a, b, .. } = inst.kind {
|
||||
if let (Value::Inst(x), Value::Inst(y)) = (a, b) {
|
||||
if cx.is_generic(a) && cx.is_generic(b) {
|
||||
union(&mut parent, x.index(), y.index());
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (mut s, mut z) = (Space::Unseen, false);
|
||||
match &inst.kind {
|
||||
InstKind::Cast {
|
||||
op: CastOp::AddrSpaceCast,
|
||||
v,
|
||||
} if !cx.is_generic(*v) => match cx.ty(*v).and_then(|t| cx.parts.types.get(t)) {
|
||||
Some(Type::Ptr { space }) => {
|
||||
s = Space::One(*space);
|
||||
z = matches!(
|
||||
v,
|
||||
Value::Const(c) if matches!(cx.parts.consts.get(*c).map(|k| &k.value), Some(Const::Null))
|
||||
);
|
||||
}
|
||||
_ => s = Space::Many(GenericPointer::Integer, Some(i)),
|
||||
},
|
||||
InstKind::Gep { .. }
|
||||
| InstKind::Cast {
|
||||
op: CastOp::Bitcast | CastOp::AddrSpaceCast,
|
||||
..
|
||||
}
|
||||
| InstKind::Freeze(_)
|
||||
| InstKind::Phi { .. }
|
||||
| InstKind::Select { .. } => {
|
||||
for v in linked(&inst.kind) {
|
||||
let (vs, vz) = cx.operand(v)?;
|
||||
s = s.join(vs, Some(i));
|
||||
z |= vz;
|
||||
if let Value::Inst(j) = v {
|
||||
union(&mut parent, i.index(), j.index());
|
||||
}
|
||||
}
|
||||
}
|
||||
// A load from a cell's slot is in the slot's group.
|
||||
InstKind::Load { .. } => match cells.as_ref().and_then(|c| c.reach(i)) {
|
||||
Some(Some(node)) => union(&mut parent, i.index(), slot(node)),
|
||||
_ => s = Space::Many(GenericPointer::Memory, Some(i)),
|
||||
},
|
||||
InstKind::AtomicRmw { .. } | InstKind::CmpXchg { .. } => {
|
||||
s = Space::Many(GenericPointer::Memory, Some(i));
|
||||
}
|
||||
InstKind::Call(_) => s = Space::Many(GenericPointer::Call, Some(i)),
|
||||
InstKind::ExtractValue { .. }
|
||||
| InstKind::ExtractElement { .. }
|
||||
| InstKind::InsertValue { .. }
|
||||
| InstKind::InsertElement { .. }
|
||||
| InstKind::ShuffleVector { .. } => s = Space::Many(GenericPointer::Aggregate, Some(i)),
|
||||
// An `inttoptr`: no other operation makes a pointer.
|
||||
_ => s = Space::Many(GenericPointer::Integer, Some(i)),
|
||||
}
|
||||
if let Some(slot) = source.get_mut(i.index()) {
|
||||
*slot = s;
|
||||
}
|
||||
if let Some(slot) = null.get_mut(i.index()) {
|
||||
*slot = z;
|
||||
}
|
||||
}
|
||||
// An access at an unknown offset of a cell may be at any of its slots.
|
||||
for &(a, b) in cells.as_ref().map_or(&[][..], |c| &c.links[..]) {
|
||||
union(&mut parent, slot(a), slot(b));
|
||||
}
|
||||
// Each group's space: the join of what enters each of its members.
|
||||
let mut group: Vec<Space> = filled(m, held, nodes, Space::Unseen)?;
|
||||
for (i, _) in cx.body.insts.iter() {
|
||||
m.tick(1)?;
|
||||
let r = find(&mut parent, i.index());
|
||||
let s = source.get(i.index()).copied().unwrap_or(Space::Unseen);
|
||||
if let Some(slot) = group.get_mut(r) {
|
||||
*slot = slot.join(s, Some(i));
|
||||
}
|
||||
}
|
||||
// An `icmp`'s constant sides enter its group too.
|
||||
for inst in cx.body.insts.values() {
|
||||
if let InstKind::ICmp { a, b, .. } = inst.kind {
|
||||
if !(cx.is_generic(a) && cx.is_generic(b)) {
|
||||
continue;
|
||||
}
|
||||
if let (Value::Inst(x), c @ Value::Const(_)) | (c @ Value::Const(_), Value::Inst(x)) =
|
||||
(a, b)
|
||||
{
|
||||
let r = find(&mut parent, x.index());
|
||||
let (s, _) = cx.operand(c)?;
|
||||
if let Some(slot) = group.get_mut(r) {
|
||||
*slot = slot.join(s, Some(x));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut space: Vec<Space> = filled(m, held, n, Space::Unseen)?;
|
||||
for (i, inst) in cx.body.insts.iter() {
|
||||
m.tick(1)?;
|
||||
if !cx.generic(inst.ty) && !shares(cx, &inst.kind) {
|
||||
continue;
|
||||
}
|
||||
let r = match &inst.kind {
|
||||
// A query's or a comparison's group is its pointer's.
|
||||
InstKind::Call(call) if !cx.generic(inst.ty) => match call.args.first() {
|
||||
Some(Value::Inst(p)) => find(&mut parent, p.index()),
|
||||
_ => continue,
|
||||
},
|
||||
InstKind::ICmp { a, b, .. } if !cx.generic(inst.ty) => match (a, b) {
|
||||
(Value::Inst(p), _) | (_, Value::Inst(p)) => find(&mut parent, p.index()),
|
||||
_ => continue,
|
||||
},
|
||||
_ => find(&mut parent, i.index()),
|
||||
};
|
||||
let s = group.get(r).copied().unwrap_or(Space::Unseen);
|
||||
if let Space::Many(how, at) = s {
|
||||
return Err(cx.refuse(how, at.unwrap_or(i)));
|
||||
}
|
||||
if let Some(slot) = space.get_mut(i.index()) {
|
||||
*slot = s;
|
||||
}
|
||||
}
|
||||
// Nullness, forward to a fixed point: a null constant reaches what it enters and what that
|
||||
// reaches, a cell's slot through a store and a load from the slot through it (a slot an
|
||||
// access at an unknown offset reaches, through that access's node). A load of a slot no store
|
||||
// has written reads an undefined pointer, which may be taken as not null.
|
||||
let slots = cells.as_ref().map_or(0, |c| c.slots);
|
||||
let mut slot_null: Vec<bool> = filled(m, held, slots, false)?;
|
||||
let reach = |i: InstId| cells.as_ref().and_then(|c| c.reach(i)).flatten();
|
||||
let mut changed = true;
|
||||
let mut rounds = 0;
|
||||
while changed {
|
||||
changed = false;
|
||||
rounds += 1;
|
||||
if rounds > nodes + 1 {
|
||||
return Err(invariant("nullness does not settle"));
|
||||
}
|
||||
for &(a, b) in cells.as_ref().map_or(&[][..], |c| &c.links[..]) {
|
||||
let (x, y) = (slot_null.get(a as usize), slot_null.get(b as usize));
|
||||
let either = x.copied().unwrap_or(false) || y.copied().unwrap_or(false);
|
||||
for k in [a, b] {
|
||||
if let Some(z) = slot_null.get_mut(k as usize) {
|
||||
changed |= either && !*z;
|
||||
*z |= either;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, inst) in cx.body.insts.iter() {
|
||||
m.tick(1)?;
|
||||
if let (InstKind::Store { val, .. }, Some(node)) = (&inst.kind, reach(i)) {
|
||||
let stored = null.get(i.index()).copied().unwrap_or(false)
|
||||
|| matches!(val, Value::Inst(j) if null.get(j.index()).copied().unwrap_or(false));
|
||||
if let Some(z) = slot_null.get_mut(node as usize) {
|
||||
changed |= stored && !*z;
|
||||
*z |= stored;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !cx.generic(inst.ty) || null.get(i.index()).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let reached = match &inst.kind {
|
||||
InstKind::Cast {
|
||||
op: CastOp::AddrSpaceCast,
|
||||
v,
|
||||
} if !cx.is_generic(*v) => false,
|
||||
InstKind::Load { .. } => reach(i)
|
||||
.and_then(|node| slot_null.get(node as usize).copied())
|
||||
.unwrap_or(false),
|
||||
kind => linked(kind).iter().any(|v| match v {
|
||||
Value::Inst(j) => null.get(j.index()).copied().unwrap_or(false),
|
||||
_ => false,
|
||||
}),
|
||||
};
|
||||
if reached {
|
||||
if let Some(slot) = null.get_mut(i.index()) {
|
||||
*slot = true;
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(Plan { space, null, folds }))
|
||||
}
|
||||
|
||||
/// Whether `kind` is a query or a comparison of generic pointers, whose space is its pointer's,
|
||||
/// or a store of a generic pointer, whose space is its value's.
|
||||
fn shares(cx: &Cx<'_>, kind: &InstKind) -> bool {
|
||||
@@ -769,6 +463,17 @@ fn rewrite(
|
||||
})
|
||||
);
|
||||
let own = plan.space.get(i.index()).copied().unwrap_or(Space::Unseen);
|
||||
// An aggregate or a vector that holds generic pointers: its leaves' spaces.
|
||||
if let Some(leaves) = plan.leaves.as_ref() {
|
||||
if let Some(at) = leaves.of(i, parts, inst.ty) {
|
||||
let mut r = leaves::Retyped {
|
||||
leaves,
|
||||
interned: &mut interned,
|
||||
};
|
||||
leaves::rewrite(parts, &mut r, &plan.leaf_space, (i, inst), at, &mut edit, m)?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// A cast into the generic space, or a no-op cast within it, is its operand.
|
||||
if let InstKind::Cast {
|
||||
op: CastOp::AddrSpaceCast | CastOp::Bitcast,
|
||||
@@ -922,10 +627,18 @@ fn rewrite(
|
||||
}
|
||||
}
|
||||
// Every other instruction: its generic result its group's type, its generic constants
|
||||
// that type's.
|
||||
// that type's, and each aggregate constant holding generic pointers each the space its
|
||||
// leaf brings.
|
||||
let holds = |parts: &ModuleParts, v: Value| match (v, plan.leaves.as_ref()) {
|
||||
(Value::Const(c), Some(l)) => parts
|
||||
.consts
|
||||
.ty(c)
|
||||
.is_some_and(|t| !generic_of(parts, v) && l.counted(parts, t).unwrap_or(0) > 0),
|
||||
_ => false,
|
||||
};
|
||||
let mut constants = false;
|
||||
inst.kind.for_each_value(|v| {
|
||||
constants |= matches!(v, Value::Const(_)) && generic_of(parts, v);
|
||||
constants |= matches!(v, Value::Const(_)) && (generic_of(parts, v) || holds(parts, v));
|
||||
});
|
||||
let shared = result_generic || shares_in(parts, body, (name, params), &inst.kind);
|
||||
if constants {
|
||||
@@ -972,6 +685,35 @@ fn rewrite(
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut aggregates: Vec<ConstId> = Vec::new();
|
||||
kind.for_each_value(|v| {
|
||||
if let (Value::Const(c), true) = (v, holds(parts, v)) {
|
||||
aggregates.push(c);
|
||||
}
|
||||
});
|
||||
for c in aggregates {
|
||||
if mapped.iter().any(|(k, _)| *k == c) {
|
||||
continue;
|
||||
}
|
||||
let (Some(leaves), Some(old)) = (plan.leaves.as_ref(), parts.consts.ty(c)) else {
|
||||
continue;
|
||||
};
|
||||
let cx = Cx {
|
||||
name,
|
||||
body,
|
||||
parts,
|
||||
params,
|
||||
};
|
||||
let Some(spaces) = leaves::own_spaces(&cx, leaves, c)? else {
|
||||
continue;
|
||||
};
|
||||
let mut r = leaves::Retyped {
|
||||
leaves,
|
||||
interned: &mut interned,
|
||||
};
|
||||
let t = r.ty(parts, old, &spaces, m)?;
|
||||
mapped.push((c, r.constant(parts, c, t, &spaces, m)?));
|
||||
}
|
||||
kind.for_each_value_mut(|v| {
|
||||
if let Value::Const(c) = *v {
|
||||
if let Some(&(_, n)) = mapped.iter().find(|(k, _)| *k == c) {
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
//! Aggregate and vector values that hold generic pointers.
|
||||
//!
|
||||
//! Each generic pointer a struct, array or vector value holds is a *leaf*: a struct's leaves are
|
||||
//! its fields' in order, and an array's or a vector's are its element type's, shared by every
|
||||
//! element (an index only the run knows picks any of them). Each leaf of each instruction whose
|
||||
//! value holds one is a union-find node, in the group of what it comes from:
|
||||
//!
|
||||
//! - an `insertvalue`'s leaves under its indices, the inserted value's; its others, its
|
||||
//! aggregate operand's (all of them where an index steps into an array, whose elements share
|
||||
//! leaves);
|
||||
//! - an `extractvalue`'s leaves (or the generic pointer it extracts), its aggregate operand's
|
||||
//! under its indices;
|
||||
//! - a `phi`'s, a `select`'s or a `freeze`'s leaves, its operands';
|
||||
//! - a vector's one leaf through `insertelement`, `extractelement` and `shufflevector`.
|
||||
//!
|
||||
//! A constant operand brings in each leaf's space; an aggregate a load, a call or a parameter
|
||||
//! gives brings in a space only the run knows. Each such value then holds pointers of its leaves'
|
||||
//! spaces: its type is its type with each generic pointer that space's ([`Retyped`]), its
|
||||
//! constants retyped alike.
|
||||
|
||||
use crate::budget::Meter;
|
||||
use crate::error::{Error, GenericPointer};
|
||||
use crate::ir::{AddrSpace, Const, ConstId, Constant, Idx, Inst, InstId, InstKind, ModuleParts};
|
||||
use crate::ir::{Type, TypeId, Value};
|
||||
|
||||
use super::super::rewrite::{filled, invariant, BodyEdit};
|
||||
use super::{refused, retyped, taken, Cx, Interned, Space, DEPTH};
|
||||
|
||||
/// No leaves.
|
||||
const NONE: u32 = u32::MAX;
|
||||
|
||||
/// The leaves of the entry's instructions.
|
||||
pub(super) struct Leaves {
|
||||
/// Per instruction: its first leaf, where its value is an aggregate or a vector that holds
|
||||
/// generic pointers; `NONE` else.
|
||||
first: Vec<u32>,
|
||||
/// Per type, the leaves it holds (`NONE` until counted).
|
||||
counts: Vec<u32>,
|
||||
/// How many leaves there are.
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
impl Leaves {
|
||||
/// The leaves of the entry's instructions, `None` when no instruction's value or constant
|
||||
/// operand holds a generic pointer in an aggregate or a vector. Every type such a value or
|
||||
/// constant has is counted, with the types it holds.
|
||||
pub fn find(cx: &Cx<'_>, m: &mut Meter, held: &mut usize) -> Result<Option<Leaves>, Error> {
|
||||
let n = cx.body.insts.len();
|
||||
let mut leaves = Leaves {
|
||||
first: filled(m, held, n, NONE)?,
|
||||
counts: filled(m, held, cx.parts.types.len(), NONE)?,
|
||||
total: 0,
|
||||
};
|
||||
let mut total = 0u32;
|
||||
let mut any = false;
|
||||
let mut constants = Vec::new();
|
||||
for (i, inst) in cx.body.insts.iter() {
|
||||
m.tick(1)?;
|
||||
constants.clear();
|
||||
inst.kind.for_each_value(|v| {
|
||||
if let Some(t) = cx.ty(v).filter(|&t| {
|
||||
matches!(v, Value::Const(_))
|
||||
&& !cx.generic(t)
|
||||
&& cx.parts.types.holds_pointer(t)
|
||||
}) {
|
||||
constants.push(t);
|
||||
}
|
||||
});
|
||||
for &t in &constants {
|
||||
any |= leaves.count(cx.parts, t, 0)? > 0;
|
||||
}
|
||||
if cx.generic(inst.ty) || !cx.parts.types.holds_pointer(inst.ty) {
|
||||
continue;
|
||||
}
|
||||
let count = leaves.count(cx.parts, inst.ty, 0)?;
|
||||
if count == 0 {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
if let Some(f) = leaves.first.get_mut(i.index()) {
|
||||
*f = total;
|
||||
}
|
||||
total = total
|
||||
.checked_add(count)
|
||||
.ok_or_else(|| invariant("leaves past u32"))?;
|
||||
}
|
||||
leaves.total = total as usize;
|
||||
Ok(any.then_some(leaves))
|
||||
}
|
||||
|
||||
/// The first leaf of instruction `i`'s value and how many it holds, where it holds any.
|
||||
pub fn of(&self, i: InstId, parts: &ModuleParts, ty: TypeId) -> Option<(u32, u32)> {
|
||||
let f = *self.first.get(i.index())?;
|
||||
if f == NONE {
|
||||
return None;
|
||||
}
|
||||
Some((f, self.counted(parts, ty)?))
|
||||
}
|
||||
|
||||
/// The leaves type `ty` holds, counted already.
|
||||
pub fn counted(&self, parts: &ModuleParts, ty: TypeId) -> Option<u32> {
|
||||
match parts.types.get(ty) {
|
||||
Some(Type::Ptr {
|
||||
space: AddrSpace::Generic,
|
||||
}) => Some(1),
|
||||
_ => self.counts.get(ty.index()).copied().filter(|&c| c != NONE),
|
||||
}
|
||||
}
|
||||
|
||||
/// The leaves type `ty` holds: a generic pointer is one.
|
||||
pub fn count(&mut self, parts: &ModuleParts, ty: TypeId, depth: u32) -> Result<u32, Error> {
|
||||
if depth > DEPTH {
|
||||
return Err(refused(GenericPointer::Aggregate));
|
||||
}
|
||||
if let Some(c) = self.counted(parts, ty) {
|
||||
return Ok(c);
|
||||
}
|
||||
let c = match parts.types.get(ty) {
|
||||
Some(Type::Vector { elem, .. } | Type::Array { elem, .. }) => {
|
||||
self.count(parts, *elem, depth + 1)?
|
||||
}
|
||||
Some(Type::Struct { fields, .. }) => {
|
||||
let mut sum = 0u32;
|
||||
for &f in fields.iter() {
|
||||
sum = sum
|
||||
.checked_add(self.count(parts, f, depth + 1)?)
|
||||
.ok_or_else(|| invariant("leaves past u32"))?;
|
||||
}
|
||||
sum
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
if let Some(slot) = self.counts.get_mut(ty.index()) {
|
||||
*slot = c;
|
||||
}
|
||||
Ok(c)
|
||||
}
|
||||
|
||||
/// The leaves of type `ty` (counted) the value at `indices` holds, `lo..hi`, and whether
|
||||
/// every index steps into a struct (so the value is those leaves alone, not one of an
|
||||
/// array's elements that share them).
|
||||
pub fn range(
|
||||
&self,
|
||||
parts: &ModuleParts,
|
||||
ty: TypeId,
|
||||
indices: &[u32],
|
||||
) -> Result<(u32, u32, bool), Error> {
|
||||
let count = |t: TypeId| {
|
||||
self.counted(parts, t)
|
||||
.ok_or_else(|| invariant("a type's leaves not counted"))
|
||||
};
|
||||
let (mut lo, mut ty, mut exact) = (0u32, ty, true);
|
||||
for &k in indices {
|
||||
match parts.types.get(ty) {
|
||||
Some(Type::Struct { fields, .. }) => {
|
||||
let k = k as usize;
|
||||
for &f in fields.iter().take(k) {
|
||||
lo = lo
|
||||
.checked_add(count(f)?)
|
||||
.ok_or_else(|| invariant("leaves past u32"))?;
|
||||
}
|
||||
ty = *fields
|
||||
.get(k)
|
||||
.ok_or_else(|| invariant("an aggregate index out of range"))?;
|
||||
}
|
||||
Some(Type::Array { elem, .. } | Type::Vector { elem, .. }) => {
|
||||
ty = *elem;
|
||||
exact = false;
|
||||
}
|
||||
_ => return Err(invariant("an aggregate index into a scalar")),
|
||||
}
|
||||
}
|
||||
let hi = lo
|
||||
.checked_add(count(ty)?)
|
||||
.ok_or_else(|| invariant("leaves past u32"))?;
|
||||
Ok((lo, hi, exact))
|
||||
}
|
||||
}
|
||||
|
||||
/// The space leaf `k` of constant `c` brings in, and whether it is null. `None` where the
|
||||
/// constant holds fewer leaves.
|
||||
pub(super) fn constant_leaf(
|
||||
cx: &Cx<'_>,
|
||||
leaves: &Leaves,
|
||||
c: ConstId,
|
||||
k: u32,
|
||||
depth: u32,
|
||||
) -> Result<(Space, bool), Error> {
|
||||
if depth > DEPTH {
|
||||
return Err(refused(GenericPointer::Aggregate));
|
||||
}
|
||||
let ty = cx
|
||||
.parts
|
||||
.consts
|
||||
.ty(c)
|
||||
.ok_or_else(|| invariant("a constant out of range"))?;
|
||||
if cx.generic(ty) {
|
||||
return cx.constant(c, 0);
|
||||
}
|
||||
let value = &cx
|
||||
.parts
|
||||
.consts
|
||||
.get(c)
|
||||
.ok_or_else(|| invariant("a constant out of range"))?
|
||||
.value;
|
||||
Ok(match (value, cx.parts.types.get(ty)) {
|
||||
(Const::Null, _) => (Space::Unseen, true),
|
||||
(Const::Undef | Const::Poison, _) => (Space::Unseen, false),
|
||||
(Const::Aggregate(elems), Some(Type::Struct { fields, .. })) => {
|
||||
let mut lo = 0u32;
|
||||
for (&e, &f) in elems.iter().zip(fields.iter()) {
|
||||
let n = leaves.counted(cx.parts, f).unwrap_or(0);
|
||||
if k < lo + n {
|
||||
return constant_leaf(cx, leaves, e, k - lo, depth + 1);
|
||||
}
|
||||
lo += n;
|
||||
}
|
||||
return Err(invariant("a constant leaf out of range"));
|
||||
}
|
||||
// Every element holds the shared leaves.
|
||||
(Const::Aggregate(elems), Some(Type::Array { .. } | Type::Vector { .. })) => {
|
||||
let (mut s, mut z) = (Space::Unseen, false);
|
||||
for &e in elems.iter() {
|
||||
let (es, ez) = constant_leaf(cx, leaves, e, k, depth + 1)?;
|
||||
s = s.join(es, None);
|
||||
z |= ez;
|
||||
}
|
||||
(s, z)
|
||||
}
|
||||
_ => (Space::Many(GenericPointer::Aggregate, None), false),
|
||||
})
|
||||
}
|
||||
|
||||
/// Types and constants with their generic pointers made pointers of their leaves' spaces.
|
||||
pub(super) struct Retyped<'a> {
|
||||
pub leaves: &'a Leaves,
|
||||
pub interned: &'a mut Interned,
|
||||
}
|
||||
|
||||
impl Retyped<'_> {
|
||||
/// Type `ty` with its leaves' generic pointers of `spaces`, one a leaf.
|
||||
pub fn ty(
|
||||
&mut self,
|
||||
parts: &mut ModuleParts,
|
||||
ty: TypeId,
|
||||
spaces: &[AddrSpace],
|
||||
m: &mut Meter,
|
||||
) -> Result<TypeId, Error> {
|
||||
let t = parts
|
||||
.types
|
||||
.get(ty)
|
||||
.cloned()
|
||||
.ok_or_else(|| invariant("a type out of range"))?;
|
||||
let made = match t {
|
||||
Type::Ptr {
|
||||
space: AddrSpace::Generic,
|
||||
} => {
|
||||
let s = *spaces.first().ok_or_else(|| invariant("a leaf's space"))?;
|
||||
return self.interned.ptr(parts, s, m);
|
||||
}
|
||||
Type::Struct {
|
||||
fields,
|
||||
packed,
|
||||
name,
|
||||
} => {
|
||||
let mut lo = 0usize;
|
||||
let mut out = Vec::new();
|
||||
m.reserve(&mut out, fields.len())?;
|
||||
for &f in fields.iter() {
|
||||
let n = self.leaves.counted(parts, f).unwrap_or(0) as usize;
|
||||
let part = spaces
|
||||
.get(lo..lo + n)
|
||||
.ok_or_else(|| invariant("a struct's leaves"))?;
|
||||
out.push(if n == 0 {
|
||||
f
|
||||
} else {
|
||||
self.ty(parts, f, part, m)?
|
||||
});
|
||||
lo += n;
|
||||
}
|
||||
m.release(out.capacity() * std::mem::size_of::<TypeId>());
|
||||
if out.iter().eq(fields.iter()) {
|
||||
return Ok(ty);
|
||||
}
|
||||
Type::Struct {
|
||||
fields: out.into_boxed_slice(),
|
||||
packed,
|
||||
name,
|
||||
}
|
||||
}
|
||||
Type::Array { elem, len } => Type::Array {
|
||||
elem: self.ty(parts, elem, spaces, m)?,
|
||||
len,
|
||||
},
|
||||
Type::Vector { elem, len } => Type::Vector {
|
||||
elem: self.ty(parts, elem, spaces, m)?,
|
||||
len,
|
||||
},
|
||||
_ => return Ok(ty),
|
||||
};
|
||||
parts.types.intern(made, m)
|
||||
}
|
||||
|
||||
/// Constant `c` as a constant of type `ty`, the retyped form of its own, whose leaves are of
|
||||
/// `spaces`.
|
||||
pub fn constant(
|
||||
&mut self,
|
||||
parts: &mut ModuleParts,
|
||||
c: ConstId,
|
||||
ty: TypeId,
|
||||
spaces: &[AddrSpace],
|
||||
m: &mut Meter,
|
||||
) -> Result<ConstId, Error> {
|
||||
let k = parts
|
||||
.consts
|
||||
.get(c)
|
||||
.cloned()
|
||||
.ok_or_else(|| invariant("a constant out of range"))?;
|
||||
if parts.consts.ty(c) == Some(ty) {
|
||||
return Ok(c);
|
||||
}
|
||||
let value = match k.value {
|
||||
v @ (Const::Null | Const::Undef | Const::Poison) => v,
|
||||
Const::Aggregate(elems) => {
|
||||
let fields: Vec<TypeId> = match parts.types.get(ty) {
|
||||
Some(Type::Struct { fields, .. }) => fields.to_vec(),
|
||||
Some(Type::Array { elem, .. } | Type::Vector { elem, .. }) => {
|
||||
vec![*elem; elems.len()]
|
||||
}
|
||||
_ => return Err(invariant("an aggregate constant of a scalar type")),
|
||||
};
|
||||
let olds: Vec<TypeId> = match parts.types.get(k.ty) {
|
||||
Some(Type::Struct { fields, .. }) => fields.to_vec(),
|
||||
Some(Type::Array { elem, .. } | Type::Vector { elem, .. }) => {
|
||||
vec![*elem; elems.len()]
|
||||
}
|
||||
_ => return Err(invariant("an aggregate constant of a scalar type")),
|
||||
};
|
||||
let shared = !matches!(parts.types.get(ty), Some(Type::Struct { .. }));
|
||||
let mut lo = 0usize;
|
||||
let mut out = Vec::with_capacity(elems.len());
|
||||
for ((&e, &f), &old) in elems.iter().zip(fields.iter()).zip(olds.iter()) {
|
||||
let n = self.leaves.counted(parts, old).unwrap_or(0) as usize;
|
||||
let part = if shared {
|
||||
spaces
|
||||
} else {
|
||||
let p = spaces
|
||||
.get(lo..lo + n)
|
||||
.ok_or_else(|| invariant("a constant's leaves"))?;
|
||||
lo += n;
|
||||
p
|
||||
};
|
||||
out.push(if n == 0 {
|
||||
e
|
||||
} else if matches!(
|
||||
parts.types.get(old),
|
||||
Some(Type::Ptr {
|
||||
space: AddrSpace::Generic
|
||||
})
|
||||
) {
|
||||
let s = *part.first().ok_or_else(|| invariant("a leaf's space"))?;
|
||||
retyped(parts, self.interned, e, s, 0, m)?
|
||||
} else {
|
||||
self.constant(parts, e, f, part, m)?
|
||||
});
|
||||
}
|
||||
Const::Aggregate(out.into_boxed_slice())
|
||||
}
|
||||
_ => return Err(refused(GenericPointer::Aggregate)),
|
||||
};
|
||||
parts.consts.intern(Constant { ty, value }, m)
|
||||
}
|
||||
|
||||
/// Constant operand `c` of an instruction whose value is of type `ty` (retyped) and holds
|
||||
/// leaves of `spaces`: that type's constant.
|
||||
fn operand(
|
||||
&mut self,
|
||||
parts: &mut ModuleParts,
|
||||
v: &mut Value,
|
||||
ty: TypeId,
|
||||
spaces: &[AddrSpace],
|
||||
m: &mut Meter,
|
||||
) -> Result<bool, Error> {
|
||||
let Value::Const(c) = *v else {
|
||||
return Ok(false);
|
||||
};
|
||||
*v = Value::Const(self.constant(parts, c, ty, spaces, m)?);
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// The spaces of constant `c`'s leaves, each the space it brings itself (thread where none):
|
||||
/// `None` where it holds none.
|
||||
pub(super) fn own_spaces(
|
||||
cx: &Cx<'_>,
|
||||
leaves: &Leaves,
|
||||
c: ConstId,
|
||||
) -> Result<Option<Vec<AddrSpace>>, Error> {
|
||||
let Some(ty) = cx.parts.consts.ty(c) else {
|
||||
return Err(invariant("a constant out of range"));
|
||||
};
|
||||
if cx.generic(ty) {
|
||||
return Ok(None);
|
||||
}
|
||||
let count = leaves.counted(cx.parts, ty).unwrap_or(0);
|
||||
if count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for k in 0..count {
|
||||
match constant_leaf(cx, leaves, c, k, 0)?.0 {
|
||||
Space::Many(how, _) => return Err(refused(how)),
|
||||
s => out.push(taken(s)),
|
||||
}
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// The rewrite of instruction `i`, whose value holds `count` leaves from `first`: its type with
|
||||
/// each leaf's group's space, and its constant operands retyped alike.
|
||||
pub(super) fn rewrite(
|
||||
parts: &mut ModuleParts,
|
||||
r: &mut Retyped<'_>,
|
||||
leaf_space: &[Space],
|
||||
(i, inst): (InstId, &Inst),
|
||||
(first, count): (u32, u32),
|
||||
edit: &mut BodyEdit,
|
||||
m: &mut Meter,
|
||||
) -> Result<(), Error> {
|
||||
let spaces: Vec<AddrSpace> = leaf_space
|
||||
.get(first as usize..first as usize + count as usize)
|
||||
.ok_or_else(|| invariant("an instruction's leaves out of range"))?
|
||||
.iter()
|
||||
.map(|&s| taken(s))
|
||||
.collect();
|
||||
let ty = r.ty(parts, inst.ty, &spaces, m)?;
|
||||
let mut kind = inst.kind.clone();
|
||||
let mut changed = false;
|
||||
match &mut kind {
|
||||
InstKind::InsertValue { agg, val, indices } => {
|
||||
changed |= r.operand(parts, agg, ty, &spaces, m)?;
|
||||
if let Value::Const(c) = *val {
|
||||
let (lo, hi, _) = r.leaves.range(parts, inst.ty, indices)?;
|
||||
if lo < hi {
|
||||
let part = spaces
|
||||
.get(lo as usize..hi as usize)
|
||||
.ok_or_else(|| invariant("an inserted value's leaves"))?;
|
||||
let old = parts
|
||||
.consts
|
||||
.ty(c)
|
||||
.ok_or_else(|| invariant("a constant out of range"))?;
|
||||
let new = if matches!(
|
||||
parts.types.get(old),
|
||||
Some(Type::Ptr {
|
||||
space: AddrSpace::Generic
|
||||
})
|
||||
) {
|
||||
let s = *part.first().ok_or_else(|| invariant("a leaf's space"))?;
|
||||
retyped(parts, r.interned, c, s, 0, m)?
|
||||
} else {
|
||||
let t = r.ty(parts, old, part, m)?;
|
||||
r.constant(parts, c, t, part, m)?
|
||||
};
|
||||
*val = Value::Const(new);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
InstKind::InsertElement { vec, elt, .. } => {
|
||||
changed |= r.operand(parts, vec, ty, &spaces, m)?;
|
||||
if let Value::Const(c) = *elt {
|
||||
let s = *spaces.first().ok_or_else(|| invariant("a leaf's space"))?;
|
||||
*elt = Value::Const(retyped(parts, r.interned, c, s, 0, m)?);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
InstKind::Phi { incoming, .. } => {
|
||||
for (v, _) in incoming.iter_mut() {
|
||||
changed |= r.operand(parts, v, ty, &spaces, m)?;
|
||||
}
|
||||
}
|
||||
InstKind::Select { t, f, .. } | InstKind::ShuffleVector { a: t, b: f, .. } => {
|
||||
changed |= r.operand(parts, t, ty, &spaces, m)?;
|
||||
changed |= r.operand(parts, f, ty, &spaces, m)?;
|
||||
}
|
||||
InstKind::Freeze(v) => changed |= r.operand(parts, v, ty, &spaces, m)?,
|
||||
_ => {}
|
||||
}
|
||||
if changed {
|
||||
edit.rewrite.insert(i, kind);
|
||||
}
|
||||
if ty != inst.ty {
|
||||
edit.retype.insert(i, ty);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
//! The plan: each generic pointer's group, the space every pointer entering it brings, and
|
||||
//! whether a null pointer may reach it.
|
||||
//!
|
||||
//! The union-find's nodes are the instructions, then the slots of thread memory generic pointers
|
||||
//! pass through ([`cells`]), then the leaves of the aggregate and vector values that hold them
|
||||
//! ([`leaves`]). Nullness flows along the same links, from a value to what takes it: an operand to
|
||||
//! the address it derives, a stored value to its slot and the slot to its loads, an inserted value
|
||||
//! or an aggregate's leaf to the leaf that takes it.
|
||||
|
||||
use crate::budget::Meter;
|
||||
use crate::error::{Error, GenericPointer};
|
||||
use crate::intrinsics::AirIntrinsic;
|
||||
use crate::ir::{Callee, CastOp, Const, Idx, InstId, InstKind, Type, Value};
|
||||
|
||||
use super::super::rewrite::{filled, invariant};
|
||||
use super::cells::{self, Cells};
|
||||
use super::leaves::{constant_leaf, Leaves};
|
||||
use super::{shares, Cx, Space};
|
||||
|
||||
/// Each generic instruction's group space and nullness, and each leaf's space.
|
||||
pub(super) struct Plan {
|
||||
/// Per instruction: its group's space (`Unseen` for a non-generic instruction).
|
||||
pub space: Vec<Space>,
|
||||
/// Per instruction: whether a null constant may reach it.
|
||||
pub null: Vec<bool>,
|
||||
/// Whether a query is answered.
|
||||
pub folds: bool,
|
||||
/// The leaves of the aggregate and vector values that hold generic pointers.
|
||||
pub leaves: Option<Leaves>,
|
||||
/// Per leaf: its group's space.
|
||||
pub leaf_space: Vec<Space>,
|
||||
}
|
||||
|
||||
/// The generic operands of `kind` that share the result's group (or, for an `icmp`, each other's).
|
||||
fn linked(kind: &InstKind) -> Vec<Value> {
|
||||
match kind {
|
||||
InstKind::Gep { base, .. } => vec![*base],
|
||||
InstKind::Cast {
|
||||
op: CastOp::Bitcast | CastOp::AddrSpaceCast,
|
||||
v,
|
||||
}
|
||||
| InstKind::Freeze(v) => vec![*v],
|
||||
InstKind::Phi { incoming, .. } => incoming.iter().map(|&(v, _)| v).collect(),
|
||||
InstKind::Select { t, f, .. } => vec![*t, *f],
|
||||
InstKind::ICmp { a, b, .. } => vec![*a, *b],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The union-find, what enters each node, and the links nullness flows along.
|
||||
struct Groups<'c, 'a> {
|
||||
cx: &'c Cx<'a>,
|
||||
/// Instructions, then slots, then leaves.
|
||||
n: usize,
|
||||
slots: usize,
|
||||
parent: Vec<u32>,
|
||||
source: Vec<Space>,
|
||||
null: Vec<bool>,
|
||||
/// Nullness flows from the first node to the second.
|
||||
flow: Vec<(u32, u32)>,
|
||||
}
|
||||
|
||||
impl Groups<'_, '_> {
|
||||
fn slot(&self, node: u32) -> usize {
|
||||
self.n + node as usize
|
||||
}
|
||||
|
||||
fn leaf(&self, first: u32, k: u32) -> usize {
|
||||
self.n + self.slots + first as usize + k as usize
|
||||
}
|
||||
|
||||
/// The group's representative of `i` (path halving).
|
||||
fn find(&mut self, i: usize) -> usize {
|
||||
let mut x = i;
|
||||
while let Some(&p) = self.parent.get(x) {
|
||||
let p = p as usize;
|
||||
if p == x {
|
||||
break;
|
||||
}
|
||||
let grand = self.parent.get(p).copied().unwrap_or(p as u32);
|
||||
if let Some(slot) = self.parent.get_mut(x) {
|
||||
*slot = grand;
|
||||
}
|
||||
x = grand as usize;
|
||||
}
|
||||
x
|
||||
}
|
||||
|
||||
fn union(&mut self, a: usize, b: usize) {
|
||||
let (ra, rb) = (self.find(a), self.find(b));
|
||||
if ra != rb {
|
||||
if let Some(slot) = self.parent.get_mut(ra) {
|
||||
*slot = rb as u32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Node `to` takes node `from`'s pointers: one group, and `from`'s nullness flows to `to`.
|
||||
fn takes(&mut self, to: usize, from: usize, m: &mut Meter) -> Result<(), Error> {
|
||||
self.union(to, from);
|
||||
let pair = (
|
||||
u32::try_from(from).map_err(|_| invariant("nodes past u32"))?,
|
||||
u32::try_from(to).map_err(|_| invariant("nodes past u32"))?,
|
||||
);
|
||||
m.reserve(&mut self.flow, 1)?;
|
||||
self.flow.push(pair);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Space `s` enters node `at_node`, a null pointer with it where `z`.
|
||||
fn enter(&mut self, node: usize, s: Space, z: bool, at: InstId) {
|
||||
if let Some(x) = self.source.get_mut(node) {
|
||||
*x = x.join(s, Some(at));
|
||||
}
|
||||
if let Some(x) = self.null.get_mut(node) {
|
||||
*x |= z;
|
||||
}
|
||||
}
|
||||
|
||||
/// Node `to` takes leaf `k` of operand `v` (a generic pointer operand is its own leaf 0), at
|
||||
/// instruction `at`.
|
||||
fn operand(
|
||||
&mut self,
|
||||
to: usize,
|
||||
(v, k): (Value, u32),
|
||||
leaves: &mut Option<Leaves>,
|
||||
at: InstId,
|
||||
m: &mut Meter,
|
||||
) -> Result<(), Error> {
|
||||
let cx = self.cx;
|
||||
match v {
|
||||
Value::Inst(j) => {
|
||||
let ty = cx
|
||||
.body
|
||||
.insts
|
||||
.get(j)
|
||||
.map(|x| x.ty)
|
||||
.ok_or_else(|| invariant("an operand out of range"))?;
|
||||
let from = if cx.generic(ty) {
|
||||
j.index()
|
||||
} else {
|
||||
let (first, count) = leaves
|
||||
.as_ref()
|
||||
.and_then(|l| l.of(j, cx.parts, ty))
|
||||
.ok_or_else(|| invariant("an aggregate operand without leaves"))?;
|
||||
if k >= count {
|
||||
return Err(invariant("a leaf out of range"));
|
||||
}
|
||||
self.leaf(first, k)
|
||||
};
|
||||
self.takes(to, from, m)
|
||||
}
|
||||
Value::Const(c) => {
|
||||
let (s, z) = match leaves.as_mut() {
|
||||
Some(l) => constant_leaf(cx, l, c, k, 0)?,
|
||||
None => cx.constant(c, 0)?,
|
||||
};
|
||||
self.enter(to, s, z, at);
|
||||
Ok(())
|
||||
}
|
||||
Value::Arg(_) => {
|
||||
self.enter(to, Space::Many(GenericPointer::Call, Some(at)), false, at);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn plan(cx: &Cx<'_>, m: &mut Meter, held: &mut usize) -> Result<Option<Plan>, Error> {
|
||||
let n = cx.body.insts.len();
|
||||
// Whether anything is generic: an instruction's result or any operand, or a generic pointer
|
||||
// an aggregate or a vector holds.
|
||||
let mut any = false;
|
||||
for inst in cx.body.insts.values() {
|
||||
m.tick(1)?;
|
||||
any |= cx.generic(inst.ty) || holds(cx, Some(inst.ty))?;
|
||||
// A type too deep to search is planned, and refused there.
|
||||
inst.kind.for_each_value(|v| {
|
||||
any |= cx.is_generic(v)
|
||||
|| (matches!(v, Value::Const(_)) && holds(cx, cx.ty(v)).unwrap_or(true));
|
||||
});
|
||||
if any {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return Ok(None);
|
||||
}
|
||||
let cells = cells::find(cx, m, held)?;
|
||||
let mut leaves = Leaves::find(cx, m, held)?;
|
||||
let slots = cells.as_ref().map_or(0, |c| c.slots);
|
||||
let total = leaves.as_ref().map_or(0, |l| l.total);
|
||||
let nodes = n + slots + total;
|
||||
let mut g = Groups {
|
||||
cx,
|
||||
n,
|
||||
slots,
|
||||
parent: filled(m, held, nodes, 0)?,
|
||||
source: filled(m, held, nodes, Space::Unseen)?,
|
||||
null: filled(m, held, nodes, false)?,
|
||||
flow: Vec::new(),
|
||||
};
|
||||
for (k, slot) in g.parent.iter_mut().enumerate() {
|
||||
*slot = u32::try_from(k).map_err(|_| invariant("nodes past u32"))?;
|
||||
}
|
||||
let reach = |c: &Option<Cells>, i: InstId| c.as_ref().and_then(|c| c.reach(i));
|
||||
let mut folds = false;
|
||||
for (i, inst) in cx.body.insts.iter() {
|
||||
m.tick(1)?;
|
||||
let generic = cx.generic(inst.ty);
|
||||
match &inst.kind {
|
||||
InstKind::Call(call) => {
|
||||
let query = matches!(
|
||||
call.callee,
|
||||
Callee::Air {
|
||||
op: AirIntrinsic::PointerSpace(_),
|
||||
..
|
||||
}
|
||||
);
|
||||
let mut crossing = false;
|
||||
for &a in call.args.iter() {
|
||||
crossing |= cx.is_generic(a) || holds(cx, cx.ty(a))?;
|
||||
}
|
||||
if crossing && !query {
|
||||
return Err(cx.refuse(GenericPointer::Call, i));
|
||||
}
|
||||
folds |= query;
|
||||
// A query's pointer is its own group's.
|
||||
}
|
||||
InstKind::Ret(Some(v)) if cx.is_generic(*v) || holds(cx, cx.ty(*v))? => {
|
||||
return Err(cx.refuse(GenericPointer::Call, i))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// An aggregate or a vector that holds generic pointers: its leaves.
|
||||
if let Some((first, count)) = leaves.as_ref().and_then(|l| l.of(i, cx.parts, inst.ty)) {
|
||||
aggregate(
|
||||
&mut g,
|
||||
&mut leaves,
|
||||
(i, &inst.kind, inst.ty),
|
||||
(first, count),
|
||||
m,
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
// A store of a generic pointer is in its value's group, and in its slot's where it
|
||||
// stores into a cell.
|
||||
if let InstKind::Store { val, .. } = inst.kind {
|
||||
if cx.is_generic(val) {
|
||||
g.operand(i.index(), (val, 0), &mut leaves, i, m)?;
|
||||
if let Some(Some(node)) = reach(&cells, i) {
|
||||
let s = g.slot(node);
|
||||
g.takes(s, i.index(), m)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !generic {
|
||||
// An `icmp` of generic pointers joins its sides' groups.
|
||||
if let InstKind::ICmp { a, b, .. } = inst.kind {
|
||||
if let (Value::Inst(x), Value::Inst(y)) = (a, b) {
|
||||
if cx.is_generic(a) && cx.is_generic(b) {
|
||||
g.union(x.index(), y.index());
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match &inst.kind {
|
||||
InstKind::Cast {
|
||||
op: CastOp::AddrSpaceCast,
|
||||
v,
|
||||
} if !cx.is_generic(*v) => match cx.ty(*v).and_then(|t| cx.parts.types.get(t)) {
|
||||
Some(Type::Ptr { space }) => {
|
||||
let z = matches!(
|
||||
v,
|
||||
Value::Const(c) if matches!(cx.parts.consts.get(*c).map(|k| &k.value), Some(Const::Null))
|
||||
);
|
||||
g.enter(i.index(), Space::One(*space), z, i);
|
||||
}
|
||||
_ => g.enter(
|
||||
i.index(),
|
||||
Space::Many(GenericPointer::Integer, Some(i)),
|
||||
false,
|
||||
i,
|
||||
),
|
||||
},
|
||||
InstKind::Gep { .. }
|
||||
| InstKind::Cast {
|
||||
op: CastOp::Bitcast | CastOp::AddrSpaceCast,
|
||||
..
|
||||
}
|
||||
| InstKind::Freeze(_)
|
||||
| InstKind::Phi { .. }
|
||||
| InstKind::Select { .. } => {
|
||||
for v in linked(&inst.kind) {
|
||||
g.operand(i.index(), (v, 0), &mut leaves, i, m)?;
|
||||
}
|
||||
}
|
||||
// A load from a cell's slot is in the slot's group.
|
||||
InstKind::Load { .. } => match reach(&cells, i) {
|
||||
Some(Some(node)) => {
|
||||
let s = g.slot(node);
|
||||
g.takes(i.index(), s, m)?;
|
||||
}
|
||||
_ => g.enter(
|
||||
i.index(),
|
||||
Space::Many(GenericPointer::Memory, Some(i)),
|
||||
false,
|
||||
i,
|
||||
),
|
||||
},
|
||||
// A generic pointer an aggregate or a vector holds is its leaf's.
|
||||
InstKind::ExtractValue { agg, indices } => {
|
||||
if matches!(agg, Value::Const(_)) {
|
||||
return Err(cx.refuse(GenericPointer::Aggregate, i));
|
||||
}
|
||||
let ty = cx.ty(*agg).ok_or_else(|| invariant("an operand's type"))?;
|
||||
let (lo, _, _) = range(&mut leaves, cx, ty, indices)?;
|
||||
g.operand(i.index(), (*agg, lo), &mut leaves, i, m)?;
|
||||
}
|
||||
InstKind::ExtractElement { vec, .. } => {
|
||||
if matches!(vec, Value::Const(_)) {
|
||||
return Err(cx.refuse(GenericPointer::Aggregate, i));
|
||||
}
|
||||
g.operand(i.index(), (*vec, 0), &mut leaves, i, m)?;
|
||||
}
|
||||
InstKind::AtomicRmw { .. } | InstKind::CmpXchg { .. } => g.enter(
|
||||
i.index(),
|
||||
Space::Many(GenericPointer::Memory, Some(i)),
|
||||
false,
|
||||
i,
|
||||
),
|
||||
InstKind::Call(_) => g.enter(
|
||||
i.index(),
|
||||
Space::Many(GenericPointer::Call, Some(i)),
|
||||
false,
|
||||
i,
|
||||
),
|
||||
// An `inttoptr`: no other operation makes a pointer.
|
||||
_ => g.enter(
|
||||
i.index(),
|
||||
Space::Many(GenericPointer::Integer, Some(i)),
|
||||
false,
|
||||
i,
|
||||
),
|
||||
}
|
||||
}
|
||||
// An access at an unknown offset of a cell may be at any of its slots.
|
||||
for &(a, b) in cells.as_ref().map_or(&[][..], |c| &c.links[..]) {
|
||||
let (a, b) = (g.slot(a), g.slot(b));
|
||||
g.takes(a, b, m)?;
|
||||
g.takes(b, a, m)?;
|
||||
}
|
||||
// Each group's space: the join of what enters each of its members.
|
||||
let mut group: Vec<Space> = filled(m, held, nodes, Space::Unseen)?;
|
||||
for node in 0..nodes {
|
||||
m.tick(1)?;
|
||||
let r = g.find(node);
|
||||
let s = g.source.get(node).copied().unwrap_or(Space::Unseen);
|
||||
let at = (node < n)
|
||||
.then(|| u32::try_from(node).ok().map(InstId::new))
|
||||
.flatten();
|
||||
if let Some(slot) = group.get_mut(r) {
|
||||
*slot = slot.join(s, at);
|
||||
}
|
||||
}
|
||||
// An `icmp`'s constant sides enter its group too.
|
||||
for inst in cx.body.insts.values() {
|
||||
if let InstKind::ICmp { a, b, .. } = inst.kind {
|
||||
if !(cx.is_generic(a) && cx.is_generic(b)) {
|
||||
continue;
|
||||
}
|
||||
if let (Value::Inst(x), c @ Value::Const(_)) | (c @ Value::Const(_), Value::Inst(x)) =
|
||||
(a, b)
|
||||
{
|
||||
let r = g.find(x.index());
|
||||
let (s, _) = cx.operand(c)?;
|
||||
if let Some(slot) = group.get_mut(r) {
|
||||
*slot = slot.join(s, Some(x));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut space: Vec<Space> = filled(m, held, n, Space::Unseen)?;
|
||||
let mut leaf_space: Vec<Space> = filled(m, held, total, Space::Unseen)?;
|
||||
for (i, inst) in cx.body.insts.iter() {
|
||||
m.tick(1)?;
|
||||
if let Some((first, count)) = leaves.as_ref().and_then(|l| l.of(i, cx.parts, inst.ty)) {
|
||||
for k in 0..count {
|
||||
let r = g.find(g.leaf(first, k));
|
||||
let s = group.get(r).copied().unwrap_or(Space::Unseen);
|
||||
if let Space::Many(how, at) = s {
|
||||
return Err(cx.refuse(how, at.unwrap_or(i)));
|
||||
}
|
||||
if let Some(slot) = leaf_space.get_mut(first as usize + k as usize) {
|
||||
*slot = s;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !cx.generic(inst.ty) && !shares(cx, &inst.kind) {
|
||||
continue;
|
||||
}
|
||||
let r = match &inst.kind {
|
||||
// A query's or a comparison's group is its pointer's.
|
||||
InstKind::Call(call) if !cx.generic(inst.ty) => match call.args.first() {
|
||||
Some(Value::Inst(p)) => g.find(p.index()),
|
||||
_ => continue,
|
||||
},
|
||||
InstKind::ICmp { a, b, .. } if !cx.generic(inst.ty) => match (a, b) {
|
||||
(Value::Inst(p), _) | (_, Value::Inst(p)) => g.find(p.index()),
|
||||
_ => continue,
|
||||
},
|
||||
_ => g.find(i.index()),
|
||||
};
|
||||
let s = group.get(r).copied().unwrap_or(Space::Unseen);
|
||||
if let Space::Many(how, at) = s {
|
||||
return Err(cx.refuse(how, at.unwrap_or(i)));
|
||||
}
|
||||
if let Some(slot) = space.get_mut(i.index()) {
|
||||
*slot = s;
|
||||
}
|
||||
}
|
||||
// Nullness: a null constant reaches the node it enters and, along the flow, what takes it. A
|
||||
// load of a slot no store has written reads an undefined pointer, which may be taken as not
|
||||
// null.
|
||||
*held = held.saturating_add(g.flow.capacity() * std::mem::size_of::<(u32, u32)>());
|
||||
g.flow.sort_unstable();
|
||||
let mut stack: Vec<u32> = Vec::new();
|
||||
m.reserve(&mut stack, nodes)?;
|
||||
*held = held.saturating_add(nodes * std::mem::size_of::<u32>());
|
||||
for (k, &z) in g.null.iter().enumerate() {
|
||||
if z {
|
||||
stack.push(u32::try_from(k).map_err(|_| invariant("nodes past u32"))?);
|
||||
}
|
||||
}
|
||||
while let Some(from) = stack.pop() {
|
||||
m.tick(1)?;
|
||||
let start = g.flow.partition_point(|&(f, _)| f < from);
|
||||
for &(f, to) in g.flow.get(start..).unwrap_or(&[]) {
|
||||
if f != from {
|
||||
break;
|
||||
}
|
||||
if let Some(z) = g.null.get_mut(to as usize) {
|
||||
if !*z {
|
||||
*z = true;
|
||||
stack.push(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
g.null.truncate(n);
|
||||
Ok(Some(Plan {
|
||||
space,
|
||||
null: g.null,
|
||||
folds,
|
||||
leaves,
|
||||
leaf_space,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether type `ty` is an aggregate or a vector that holds a generic pointer.
|
||||
fn holds(cx: &Cx<'_>, ty: Option<crate::ir::TypeId>) -> Result<bool, Error> {
|
||||
match ty {
|
||||
Some(t) if cx.parts.types.holds_pointer(t) && !cx.generic(t) => cx.holds_generic(t, 0),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Leaves::range`] of type `ty`, counted first.
|
||||
fn range(
|
||||
leaves: &mut Option<Leaves>,
|
||||
cx: &Cx<'_>,
|
||||
ty: crate::ir::TypeId,
|
||||
indices: &[u32],
|
||||
) -> Result<(u32, u32, bool), Error> {
|
||||
let l = leaves
|
||||
.as_mut()
|
||||
.ok_or_else(|| invariant("an aggregate without leaves"))?;
|
||||
l.count(cx.parts, ty, 0)?;
|
||||
l.range(cx.parts, ty, indices)
|
||||
}
|
||||
|
||||
/// The links of instruction `i` (of `kind` and type `ty`), whose value is an aggregate or a
|
||||
/// vector holding `count` leaves from `first`: each leaf takes what it comes from.
|
||||
fn aggregate(
|
||||
g: &mut Groups<'_, '_>,
|
||||
leaves: &mut Option<Leaves>,
|
||||
(i, kind, ty): (InstId, &InstKind, crate::ir::TypeId),
|
||||
(first, count): (u32, u32),
|
||||
m: &mut Meter,
|
||||
) -> Result<(), Error> {
|
||||
let cx = g.cx;
|
||||
match kind {
|
||||
InstKind::InsertValue { agg, val, indices } => {
|
||||
let (lo, hi, exact) = range(leaves, cx, ty, indices)?;
|
||||
for k in 0..count {
|
||||
if !(exact && (lo..hi).contains(&k)) {
|
||||
let to = g.leaf(first, k);
|
||||
g.operand(to, (*agg, k), leaves, i, m)?;
|
||||
}
|
||||
}
|
||||
for k in lo..hi {
|
||||
let to = g.leaf(first, k);
|
||||
g.operand(to, (*val, k - lo), leaves, i, m)?;
|
||||
}
|
||||
}
|
||||
InstKind::ExtractValue { agg, indices } => {
|
||||
if matches!(agg, Value::Const(_)) {
|
||||
return Err(cx.refuse(GenericPointer::Aggregate, i));
|
||||
}
|
||||
let from_ty = cx.ty(*agg).ok_or_else(|| invariant("an operand's type"))?;
|
||||
let (lo, _, _) = range(leaves, cx, from_ty, indices)?;
|
||||
for k in 0..count {
|
||||
let to = g.leaf(first, k);
|
||||
g.operand(to, (*agg, lo + k), leaves, i, m)?;
|
||||
}
|
||||
}
|
||||
InstKind::Phi { .. }
|
||||
| InstKind::Select { .. }
|
||||
| InstKind::Freeze(_)
|
||||
| InstKind::ShuffleVector { .. } => {
|
||||
let operands = match kind {
|
||||
InstKind::ShuffleVector { a, b, .. } => vec![*a, *b],
|
||||
other => linked(other),
|
||||
};
|
||||
for v in operands {
|
||||
for k in 0..count {
|
||||
let to = g.leaf(first, k);
|
||||
g.operand(to, (v, k), leaves, i, m)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
InstKind::InsertElement { vec, elt, .. } => {
|
||||
let to = g.leaf(first, 0);
|
||||
g.operand(to, (*vec, 0), leaves, i, m)?;
|
||||
g.operand(to, (*elt, 0), leaves, i, m)?;
|
||||
}
|
||||
_ => {
|
||||
let how = match kind {
|
||||
InstKind::Load { .. } => GenericPointer::Memory,
|
||||
InstKind::Call(_) => GenericPointer::Call,
|
||||
_ => GenericPointer::Aggregate,
|
||||
};
|
||||
for k in 0..count {
|
||||
let to = g.leaf(first, k);
|
||||
g.enter(to, Space::Many(how, Some(i)), false, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -33,6 +33,18 @@ enum Held {
|
||||
Overwritten,
|
||||
/// As `Loaded`, the array's address written to `out[3]` as an integer.
|
||||
Escaped,
|
||||
/// Field 0 of a `{ptr, i32}` built from `in` and 1.
|
||||
Field,
|
||||
/// Field 0 of a `{ptr, ptr}` of `in` and the thread's array.
|
||||
Fields,
|
||||
/// Field 0 of one of two `{ptr, i32}`s, of `in` and of `in + 2`, as word 0 of `in` decides.
|
||||
FieldSelect,
|
||||
/// As `Field`, of `in` or null as word 0 of `in` decides.
|
||||
FieldNullable,
|
||||
/// Element 0 of a `[2 x ptr]` of `in` and the thread's array.
|
||||
ArrayMixed,
|
||||
/// Field 0 of a `{ptr, i32}` loaded from the thread's array.
|
||||
FieldLoaded,
|
||||
}
|
||||
|
||||
/// `kernel k(device float* out, device float* in)` with a generic pointer `p` that `held` gives:
|
||||
@@ -219,6 +231,80 @@ fn queried(held: Held) -> Result<Entry, Error> {
|
||||
store(&mut f, bits, o);
|
||||
load(&mut f, generic, local)
|
||||
}
|
||||
Held::Field
|
||||
| Held::Fields
|
||||
| Held::FieldSelect
|
||||
| Held::FieldNullable
|
||||
| Held::ArrayMixed
|
||||
| Held::FieldLoaded => {
|
||||
let pair = f.module().struct_ty(&[generic, i32t]);
|
||||
let both = f.module().struct_ty(&[generic, generic]);
|
||||
let array = f.module().array(generic, 2);
|
||||
// `val` inserted at field or element `k` of `agg`, or of the type's poison.
|
||||
let insert = |f: &mut FunctionBuilder<'_>, ty, agg: Option<Value>, val, k: u32| {
|
||||
let agg =
|
||||
agg.unwrap_or_else(|| Value::Const(f.module().constant(ty, Const::Poison)));
|
||||
f.push(
|
||||
ty,
|
||||
InstKind::InsertValue {
|
||||
agg,
|
||||
val,
|
||||
indices: Box::new([k]),
|
||||
},
|
||||
)
|
||||
};
|
||||
let agg = match held {
|
||||
Held::Field => {
|
||||
let s = insert(&mut f, pair, None, input, 0);
|
||||
insert(&mut f, pair, Some(s), one, 1)
|
||||
}
|
||||
Held::Fields => {
|
||||
let mine = cast(&mut f, local);
|
||||
let s = insert(&mut f, both, None, mine, 1);
|
||||
insert(&mut f, both, Some(s), input, 0)
|
||||
}
|
||||
Held::FieldSelect => {
|
||||
let other = at(&mut f, input, two);
|
||||
let a = insert(&mut f, pair, None, input, 0);
|
||||
let b = insert(&mut f, pair, None, other, 0);
|
||||
let word = load(&mut f, i32t, arg(1));
|
||||
let c = f.push(
|
||||
i1,
|
||||
InstKind::ICmp {
|
||||
pred: IntPredicate::Ne,
|
||||
a: word,
|
||||
b: zero,
|
||||
},
|
||||
);
|
||||
f.push(
|
||||
pair,
|
||||
InstKind::Select {
|
||||
c,
|
||||
t: a,
|
||||
f: b,
|
||||
fmf: FastMath::NONE,
|
||||
},
|
||||
)
|
||||
}
|
||||
Held::FieldNullable => {
|
||||
let either = pick(&mut f, input, null);
|
||||
insert(&mut f, pair, None, either, 0)
|
||||
}
|
||||
Held::ArrayMixed => {
|
||||
let mine = cast(&mut f, local);
|
||||
let s = insert(&mut f, array, None, input, 0);
|
||||
insert(&mut f, array, Some(s), mine, 1)
|
||||
}
|
||||
_ => load(&mut f, pair, local),
|
||||
};
|
||||
f.push(
|
||||
generic,
|
||||
InstKind::ExtractValue {
|
||||
agg,
|
||||
indices: Box::new([0]),
|
||||
},
|
||||
)
|
||||
}
|
||||
};
|
||||
let x = match held {
|
||||
Held::LocalOrNull | Held::NullOrLocal => no,
|
||||
@@ -256,18 +342,19 @@ fn queried(held: Held) -> Result<Entry, Error> {
|
||||
}
|
||||
|
||||
/// Whether any instruction of the specialized entry names the generic space in its type or in an
|
||||
/// operand's.
|
||||
/// operand's, at any depth of an aggregate or a vector.
|
||||
fn names_generic(e: &Entry) -> bool {
|
||||
let types = e.module.types();
|
||||
let body = e.module.func(e.func).unwrap().body.as_ref().unwrap();
|
||||
let generic = |t: Option<TypeId>| {
|
||||
matches!(
|
||||
t.and_then(|t| types.get(t)),
|
||||
Some(Type::Ptr {
|
||||
space: AddrSpace::Generic
|
||||
})
|
||||
)
|
||||
};
|
||||
fn holds(types: &crate::ir::TypeTable, t: TypeId) -> bool {
|
||||
match types.get(t) {
|
||||
Some(Type::Ptr { space }) => *space == AddrSpace::Generic,
|
||||
Some(Type::Array { elem, .. } | Type::Vector { elem, .. }) => holds(types, *elem),
|
||||
Some(Type::Struct { fields, .. }) => fields.iter().any(|&f| holds(types, f)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let generic = |t: Option<TypeId>| t.is_some_and(|t| holds(types, t));
|
||||
body.insts.values().any(|inst| {
|
||||
let mut any = generic(Some(inst.ty));
|
||||
inst.kind.for_each_value(|v| {
|
||||
@@ -367,6 +454,40 @@ fn a_generic_pointer_of_two_spaces_or_of_memory_is_refused() {
|
||||
assert!(refused(queried(Held::AnySlot), GenericPointer::TwoSpaces));
|
||||
assert!(refused(queried(Held::Overwritten), GenericPointer::Memory));
|
||||
assert!(refused(queried(Held::Escaped), GenericPointer::Memory));
|
||||
// An array's elements share one space.
|
||||
assert!(refused(
|
||||
queried(Held::ArrayMixed),
|
||||
GenericPointer::TwoSpaces
|
||||
));
|
||||
assert!(refused(queried(Held::FieldLoaded), GenericPointer::Memory));
|
||||
}
|
||||
|
||||
/// A generic pointer an aggregate holds is in the group of what its field takes: a device
|
||||
/// pointer, through one field of two of different spaces and through a `select` of two
|
||||
/// aggregates. Where no null reaches the field, the queries are answered; where one may, the
|
||||
/// device query compares the pointer with the device null.
|
||||
#[test]
|
||||
fn a_generic_pointer_an_aggregate_holds_is_its_field_s_space() {
|
||||
for (held, device) in [
|
||||
(Held::Field, Some(1.0)),
|
||||
(Held::Fields, Some(1.0)),
|
||||
(Held::FieldSelect, Some(1.0)),
|
||||
(Held::FieldNullable, None),
|
||||
] {
|
||||
let e = queried(held).unwrap_or_else(|e| panic!("{held:?}: {e}"));
|
||||
let text = body_text(&e);
|
||||
assert!(!names_generic(&e), "{held:?}: {text}");
|
||||
let compared = text
|
||||
.lines()
|
||||
.any(|l| l.contains("icmp ne") && l.contains("ptr addrspace(1) zeroinitializer"));
|
||||
assert_eq!(compared, device.is_none(), "{held:?}: {text}");
|
||||
let words = stored(&e);
|
||||
assert_eq!(
|
||||
words[words.len().saturating_sub(2)..],
|
||||
[device, Some(0.0)],
|
||||
"{held:?}: {text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A generic pointer loaded from a slot of thread memory whose every access is visible is in the
|
||||
|
||||
Reference in new issue
Block a user