Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8734b6f6b7 | ||
|
|
29ad3a6846 |
No files matched your search
@@ -42,6 +42,11 @@ required-features = ["cli"]
|
||||
name = "api_preview"
|
||||
path = "examples/api_preview.rs"
|
||||
|
||||
[[example]]
|
||||
name = "libprobe"
|
||||
path = "examples/libprobe.rs"
|
||||
required-features = ["cli"]
|
||||
|
||||
[lib]
|
||||
name = "metal2vulkan"
|
||||
path = "src/lib.rs"
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Probe (never landed): list a metallib's kernels and write, for each, its bitcode and a device
|
||||
//! file per profile under the runtime's identity policy.
|
||||
//!
|
||||
//! usage: libprobe LIB.metallib OUTDIR PROFILE.json...
|
||||
//! writes OUTDIR/kernels.tsv (index, name hash, name), OUTDIR/kNNN.bc, OUTDIR/<stem>.device.json
|
||||
|
||||
use metal2vulkan::device::{DeviceDescription, DevicePolicy, HandleDomain, PointerDomain};
|
||||
use metal2vulkan::repro::ReproDevice;
|
||||
use metal2vulkan_air::container::{self, FunctionStage, Library};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let lib = std::fs::read(&args[1]).expect("read library");
|
||||
let out = std::path::Path::new(&args[2]);
|
||||
std::fs::create_dir_all(out).expect("outdir");
|
||||
let Library::Metallib(m) = container::parse(&lib).expect("parse") else {
|
||||
panic!("not a metallib");
|
||||
};
|
||||
let mut tsv = String::new();
|
||||
let mut index = 0;
|
||||
for f in &m.functions {
|
||||
if !matches!(f.stage, FunctionStage::Kernel) {
|
||||
continue;
|
||||
}
|
||||
let hash = container::sha256(f.name.as_bytes());
|
||||
let short: String = hash[..4].iter().map(|b| format!("{b:02x}")).collect();
|
||||
writeln!(tsv, "{index}\t{short}\t{}", f.name).unwrap();
|
||||
std::fs::write(out.join(format!("k{index:03}.bc")), f.bitcode).expect("write bc");
|
||||
index += 1;
|
||||
}
|
||||
std::fs::write(out.join("kernels.tsv"), tsv).expect("write tsv");
|
||||
eprintln!("kernels: {index} of {} functions", m.functions.len());
|
||||
for p in &args[3..] {
|
||||
let json = std::fs::read_to_string(p).expect("read profile");
|
||||
let description = DeviceDescription::from_khronos_json(&json, None).expect("profile");
|
||||
let mut policy = DevicePolicy::default();
|
||||
policy.pointer_domain = PointerDomain::Identity;
|
||||
policy.handle_domain = HandleDomain::Identity;
|
||||
let device = ReproDevice::new(description, policy);
|
||||
let stem = std::path::Path::new(p).file_stem().unwrap().to_string_lossy().into_owned();
|
||||
std::fs::write(out.join(format!("{stem}.device.json")), device.to_json().unwrap())
|
||||
.expect("write device");
|
||||
}
|
||||
}
|
||||
@@ -453,6 +453,8 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
PushField::ZeroAddress | PushField::BicubicTexels(_) => {
|
||||
return Err(not_implemented(Feature::IdentityDomains))
|
||||
}
|
||||
// A private arena past the floor is the runtime's own memory, one slot an invocation.
|
||||
PushField::PrivateArenaAddress => return Err(not_implemented(Feature::PrivateMemory)),
|
||||
PushField::SlotBindOffset(SlotRef {
|
||||
class: SlotClass::Texture,
|
||||
..
|
||||
|
||||
+2
@@ -908,6 +908,7 @@ codec_enum! {
|
||||
ArgumentTableAddress,
|
||||
ConstexprSampler(f0),
|
||||
TessellationFactorAddress,
|
||||
PrivateArenaAddress,
|
||||
SlotBounds(f0),
|
||||
ZeroAddress,
|
||||
FetchedColor { color, texels },
|
||||
@@ -1309,6 +1310,7 @@ codec_enum! {
|
||||
TexelBufferParts { slot },
|
||||
AddressAlignment { slot, align },
|
||||
GridTiles,
|
||||
PrivateArena { slot_bytes },
|
||||
}
|
||||
UniformViewChoice { Viewed, Spare, Kept }
|
||||
Mechanism {
|
||||
|
||||
Vendored
+3
-3
@@ -61,7 +61,7 @@ mod tests;
|
||||
/// unchanged version, and its bless records the version. Independent of the crate's version and of
|
||||
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
|
||||
/// history.
|
||||
pub const SEMANTICS_VERSION: u32 = 2235;
|
||||
pub const SEMANTICS_VERSION: u32 = 2236;
|
||||
|
||||
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
|
||||
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
|
||||
@@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2235;
|
||||
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
|
||||
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
|
||||
/// bumps it says what changed; this comment keeps no history.
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 574;
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 575;
|
||||
|
||||
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
|
||||
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
|
||||
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 574;
|
||||
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
|
||||
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
|
||||
/// keeps no history.
|
||||
pub const RUNTIME_VERSION: u32 = 2549;
|
||||
pub const RUNTIME_VERSION: u32 = 2550;
|
||||
|
||||
/// Writes a digest as lowercase hex.
|
||||
pub(crate) fn write_hex(f: &mut fmt::Formatter<'_>, name: &str, hash: &Hash256) -> fmt::Result {
|
||||
|
||||
@@ -13,10 +13,13 @@
|
||||
//! runs up to [`METAL`], 192 KiB a thread, the most a Metal device was measured to hold, and
|
||||
//! records `PrecisionNote::FunctionStorageAssumed`: past the floor it rests on no measurement, and
|
||||
//! a driver that holds less can answer wrongly or hang the GPU, as the RTX 5080 at 48 KiB and the
|
||||
//! RTX 3090 at 192 KiB hung when probed. A kernel, an object or a mesh function past the floor is
|
||||
//! refused, as is a vertex or fragment function past [`METAL`]: typed (`Unsupported{PrivateMemory}`,
|
||||
//! or `Unsupported{Recursion}` for a stage with a call stack, needing
|
||||
//! `VkLimit::FunctionStorageBytesPerThread`).
|
||||
//! RTX 3090 at 192 KiB hung when probed. A kernel without a call stack past the floor keeps the
|
||||
//! private memory a run-time index reaches in device memory the runtime owns, one slot a thread
|
||||
//! (`memory::plan::ArenaLayout::device`, `RuntimeFact::PrivateArena`), and what is left is held
|
||||
//! to the floor. An object or a mesh function past the floor is refused, as are a kernel with a
|
||||
//! call stack past it, a tile function past it, and a vertex or fragment function past [`METAL`]:
|
||||
//! typed (`Unsupported{PrivateMemory}`, or `Unsupported{Recursion}` for a stage with a call stack,
|
||||
//! needing `VkLimit::FunctionStorageBytesPerThread`).
|
||||
//!
|
||||
//! [`ProfileFields::function_storage`]: crate::device::profile::ProfileFields::function_storage
|
||||
|
||||
|
||||
@@ -179,6 +179,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
RuntimeFact::PartialThreadgroups => Mechanism::Variant,
|
||||
// The binder's regions carry the tile as the nominal size, under `MultiRegion` 1.
|
||||
RuntimeFact::GridTiles => Mechanism::RegionSelected,
|
||||
// The runtime pushes its arena's address, and sizes and orders the arena's slots by the
|
||||
// slot's bytes.
|
||||
RuntimeFact::PrivateArena { .. } => Mechanism::PushConstant,
|
||||
// Keyed by the slots bound to a texture whose planes are read in place, on a profile that
|
||||
// reads them so (`ProfileFields::ycbcr_in_place`).
|
||||
RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant,
|
||||
|
||||
@@ -452,6 +452,9 @@ pub struct LocalPlan {
|
||||
pub tg: Option<TgShape>,
|
||||
/// The private arena's byte size, when a pointer into it is used.
|
||||
pub private: Option<u64>,
|
||||
/// The private arena lives in device memory, an invocation's slot of the runtime's memory
|
||||
/// (`memory::plan::ArenaLayout::device`).
|
||||
pub private_device: bool,
|
||||
/// The payload's byte size (its parameter's `air.arg_type_size`), when a pointer into it is
|
||||
/// used.
|
||||
pub payload: Option<u64>,
|
||||
@@ -649,10 +652,31 @@ fn zero_threadgroup(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The private arena of `size` bytes in device memory (`ArenaLayout::device`): a slot of
|
||||
/// `size` rounded up to 16 bytes for each invocation of a dispatch, at the address the runtime
|
||||
/// pushes (`PushField::PrivateArenaAddress`), which the pipeline names with the slot's bytes
|
||||
/// (`RuntimeFact::PrivateArena`). A tile function, whose invocations a render pass's tiles
|
||||
/// place, keeps the refusal of private memory past the floor.
|
||||
fn device_arena(cx: &mut SelectCx<'_>, size: u64) -> Result<(), Error> {
|
||||
let slot = size.next_multiple_of(16);
|
||||
if super::tile::is_tile(cx) {
|
||||
let limit = Capability::Limit {
|
||||
limit: crate::device::VkLimit::FunctionStorageBytesPerThread,
|
||||
required: slot.saturating_add(cx.memory.private_bytes),
|
||||
available: crate::device::function_storage::FLOOR,
|
||||
};
|
||||
return Err(Unsupported::needs(Feature::PrivateMemory, limit).into());
|
||||
}
|
||||
let slot_bytes = u32::try_from(slot).map_err(|_| Error::LimitExceeded(Limit::PrivateArenaBytes))?;
|
||||
cx.push.insert(crate::pipeline::sym::PushField::PrivateArenaAddress);
|
||||
cx.facts.insert(RuntimeFact::PrivateArena { slot_bytes });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record that the function uses `arena`. The threadgroup arena's shape is fixed and checked
|
||||
/// against `maxComputeSharedMemorySize` once, and every region's length becomes a runtime fact of
|
||||
/// the function. A private arena past `budget::PRIVATE_ARENA_BYTES` is
|
||||
/// `LimitExceeded(PrivateArenaBytes)`.
|
||||
/// `LimitExceeded(PrivateArenaBytes)`; one in device memory is the runtime's ([`device_arena`]).
|
||||
pub(super) fn use_arena(cx: &mut SelectCx<'_>, arena: Arena) -> Result<(), Error> {
|
||||
match arena {
|
||||
Arena::Threadgroup => {
|
||||
@@ -726,6 +750,10 @@ pub(super) fn use_arena(cx: &mut SelectCx<'_>, arena: Arena) -> Result<(), Error
|
||||
if size > PRIVATE_ARENA_BYTES {
|
||||
return Err(Error::LimitExceeded(Limit::PrivateArenaBytes));
|
||||
}
|
||||
if cx.memory.priv_arena.device {
|
||||
device_arena(cx, size)?;
|
||||
cx.families.access.local.private_device = true;
|
||||
}
|
||||
cx.families.access.local.private = Some(size);
|
||||
}
|
||||
}
|
||||
@@ -1113,7 +1141,7 @@ pub fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult<LocalDecl> {
|
||||
None => None,
|
||||
},
|
||||
private: match p.private {
|
||||
Some(size) => Some(arena::declare_private(mb, size)?),
|
||||
Some(size) => Some(arena::declare_private(mb, size, p.private_device)?),
|
||||
None => None,
|
||||
},
|
||||
payload: match p.payload {
|
||||
@@ -1944,6 +1972,9 @@ pub(super) fn decl_of(
|
||||
if let Some(tile) = fragment {
|
||||
decl.tile_base = Some(cx.tile_base(fb, tile)?);
|
||||
}
|
||||
if arena == Arena::Private && cx.plan.families.access.local.private_device {
|
||||
decl.slot = Some(cx.arena_slot(fb)?);
|
||||
}
|
||||
Ok(decl)
|
||||
}
|
||||
|
||||
@@ -2061,7 +2092,10 @@ fn float_words(
|
||||
}
|
||||
let two = k32(fb, 2)?;
|
||||
let first = fb.binary(BinOp::ShiftRightLogical, off, two)?;
|
||||
let base = fb.module().global_value(decl.global)?;
|
||||
let Some(global) = decl.global else {
|
||||
return Err(cx.fail("an arena of float words without its array"));
|
||||
};
|
||||
let base = fb.module().global_value(global)?;
|
||||
let access = ops.access(fb, MemAccess::default(), stored.is_some())?;
|
||||
let mut loaded = Vec::with_capacity(lanes as usize);
|
||||
for j in 0..lanes {
|
||||
|
||||
@@ -536,6 +536,9 @@ pub struct DispatchPlan {
|
||||
/// A kernel of the [`LocalSizeForm::Spec`] form without compute derivatives (whose quads are two-dimensional): it declares
|
||||
/// `SpecKey::DeepThreadgroup`, under which its threadgroup runs as one row (the module docs).
|
||||
pub deep: bool,
|
||||
/// A kernel whose private arena lives in device memory (`memory::plan::ArenaLayout::device`):
|
||||
/// each invocation reaches its slot by its index in its dispatch ([`arena_slot`]).
|
||||
pub private_arena: bool,
|
||||
}
|
||||
|
||||
/// The words a flat grid adds: its thread's index, position, and early return, derived once for the
|
||||
@@ -744,6 +747,7 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result<DispatchPlan, Er
|
||||
identity: crate::lower::access::identity(cx.profile),
|
||||
pinned_subgroup_size,
|
||||
deep,
|
||||
private_arena: cx.memory.priv_arena.device,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -770,6 +774,10 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<
|
||||
let Some(plan) = cx.plan.dispatch.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
// The private arena's slot, in the first block, which every access of the arena reads.
|
||||
if plan.private_arena {
|
||||
cx.arena_slot(fb)?;
|
||||
}
|
||||
// A flat grid's invocation past the grid's last thread returns before the body. Its position
|
||||
// is derived here once, with the test, and is the `thread_position_in_grid` every parameter
|
||||
// reads: a second derivation would repeat the divisions in a construct of its own, which the
|
||||
@@ -979,6 +987,8 @@ pub struct KernelDecl {
|
||||
uvec3: TypeId,
|
||||
/// `sx, sy, sz`.
|
||||
size: [ConstId; 3],
|
||||
/// The `WorkgroupSize` composite.
|
||||
workgroup: ConstId,
|
||||
/// `SpecKey::DeepThreadgroup`, where the plan declares it ([`DispatchPlan::deep`]).
|
||||
deep: Option<ConstId>,
|
||||
/// How the kernel tells a region, when it reads a grid builtin.
|
||||
@@ -1080,14 +1090,20 @@ impl Needs {
|
||||
.any(has)
|
||||
|| (local_pos && (dp.local_size == LocalSizeForm::Flat || dp.tile))
|
||||
|| partial;
|
||||
// A private arena in device memory counts its slot from the workgroup's position.
|
||||
let arena = dp.private_arena;
|
||||
Needs {
|
||||
lin,
|
||||
local_pos,
|
||||
workgroup_id: folded
|
||||
|| partial
|
||||
|| arena
|
||||
|| has(K::ThreadPositionInGrid)
|
||||
|| has(K::ThreadgroupPositionInGrid),
|
||||
num_workgroups: folded || has(K::ThreadsPerGrid) || has(K::ThreadgroupsPerGrid),
|
||||
num_workgroups: folded
|
||||
|| arena
|
||||
|| has(K::ThreadsPerGrid)
|
||||
|| has(K::ThreadgroupsPerGrid),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1240,7 +1256,7 @@ impl KernelDecl {
|
||||
.map(|(k, d)| mb.spec(k, u32_, ConstBits(u64::from(d))));
|
||||
let size = [sx?, sy?, sz?];
|
||||
let mut deep = None;
|
||||
match dp.local_size {
|
||||
let workgroup = match dp.local_size {
|
||||
LocalSizeForm::Spec if dp.deep => {
|
||||
let b = mb.ty(Type::Bool)?;
|
||||
let one_row = mb.spec(SpecKey::DeepThreadgroup, b, ConstBits(0))?;
|
||||
@@ -1252,12 +1268,10 @@ impl KernelDecl {
|
||||
})?;
|
||||
let [x, y, z] = [(sn, size[0]), (one, size[1]), (one, size[2])]
|
||||
.map(|(deep, own)| mb.spec_op(SpecOp::Select, u32_, &[one_row, deep, own]));
|
||||
mb.workgroup_size(x?, y?, z?)?;
|
||||
deep = Some(one_row);
|
||||
mb.workgroup_size(x?, y?, z?)?
|
||||
}
|
||||
LocalSizeForm::Spec => {
|
||||
mb.workgroup_size(size[0], size[1], size[2])?;
|
||||
}
|
||||
LocalSizeForm::Spec => mb.workgroup_size(size[0], size[1], size[2])?,
|
||||
LocalSizeForm::Flat => {
|
||||
let n = u64::from(dx) * u64::from(dy) * u64::from(dz);
|
||||
let sn = mb.spec(keys.flat, u32_, ConstBits(n))?;
|
||||
@@ -1265,9 +1279,9 @@ impl KernelDecl {
|
||||
ty: u32_,
|
||||
bits: ConstBits(1),
|
||||
})?;
|
||||
mb.workgroup_size(sn, one, one)?;
|
||||
mb.workgroup_size(sn, one, one)?
|
||||
}
|
||||
}
|
||||
};
|
||||
let multi_region = match (dp.multi_region, dp.identity) {
|
||||
(false, _) => None,
|
||||
(true, identity) => {
|
||||
@@ -1291,7 +1305,8 @@ impl KernelDecl {
|
||||
// A grid tile counts by `LocalInvocationIndex` in either form too, and a deep
|
||||
// threadgroup's position is unflattened from it.
|
||||
let index = (needs.lin && (!flat || by_index || dp.grid_edge))
|
||||
|| (needs.local_pos && deep.is_some());
|
||||
|| (needs.local_pos && deep.is_some())
|
||||
|| dp.private_arena;
|
||||
let subgroups = needs.lin && flat && !by_index && !dp.grid_edge;
|
||||
use crate::spv::BuiltIn as B;
|
||||
let mut var = |on: bool, b: crate::spv::BuiltIn, ty: TypeId| -> BResult<Option<GlobalId>> {
|
||||
@@ -1315,6 +1330,7 @@ impl KernelDecl {
|
||||
draw_index: var(dp.draw_pieces, B::DrawIndex, u32_)?,
|
||||
uvec3,
|
||||
size,
|
||||
workgroup,
|
||||
deep,
|
||||
multi_region,
|
||||
local_id: var(
|
||||
@@ -1339,6 +1355,44 @@ impl KernelDecl {
|
||||
})
|
||||
}
|
||||
|
||||
/// The device address (a `u64`) of the invocation's slot of `slot_bytes` in the private
|
||||
/// arena at `arena` (`PushField::PrivateArenaAddress`): `arena + i · slot_bytes` for its index
|
||||
/// in its dispatch `i = ((wz · ny + wy) · nx + wx) · n + LocalInvocationIndex`, `n` the
|
||||
/// workgroup's invocations. The runtime keeps a dispatch's invocations under 2^32, so `i` is
|
||||
/// counted in 32 bits.
|
||||
pub(crate) fn arena_slot(
|
||||
&self,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
arena: SValue,
|
||||
slot_bytes: u32,
|
||||
) -> BResult<SValue> {
|
||||
let wg = self.load(fb, self.workgroup_id)?;
|
||||
let groups = self.load(fb, self.num_workgroups)?;
|
||||
let index = self.load(fb, self.local_index)?;
|
||||
let size = fb.module().const_value(self.workgroup)?;
|
||||
let n = Self::volume(fb, size)?;
|
||||
let [wx, wy, wz] = [0, 1, 2].map(|i| fb.composite_extract(wg, &[i]));
|
||||
let [nx, ny] = [0, 1].map(|i| fb.composite_extract(groups, &[i]));
|
||||
let group = fb.binary(BinOp::IMul, wz?, ny?)?;
|
||||
let group = fb.binary(BinOp::IAdd, group, wy?)?;
|
||||
let group = fb.binary(BinOp::IMul, group, nx?)?;
|
||||
let group = fb.binary(BinOp::IAdd, group, wx?)?;
|
||||
let first = fb.binary(BinOp::IMul, group, n)?;
|
||||
let at = fb.binary(BinOp::IAdd, first, index)?;
|
||||
let u64_ = fb.module().ty(Type::Int {
|
||||
width: 64,
|
||||
signed: false,
|
||||
})?;
|
||||
let at = fb.convert(ConvOp::UConvert, at, u64_)?;
|
||||
let bytes = fb.module().constant(Constant::Scalar {
|
||||
ty: u64_,
|
||||
bits: ConstBits(u64::from(slot_bytes)),
|
||||
})?;
|
||||
let bytes = fb.module().const_value(bytes)?;
|
||||
let offset = fb.binary(BinOp::IMul, at, bytes)?;
|
||||
fb.binary(BinOp::IAdd, arena, offset)
|
||||
}
|
||||
|
||||
fn load(&self, fb: &mut FunctionBuilder<'_>, g: Option<GlobalId>) -> BResult<SValue> {
|
||||
let Some(g) = g else {
|
||||
return Err(dangling_value());
|
||||
|
||||
@@ -41,6 +41,7 @@ fn plan(form: LocalSizeForm, multi_region: bool) -> DispatchPlan {
|
||||
identity: false,
|
||||
pinned_subgroup_size: None,
|
||||
deep: false,
|
||||
private_arena: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ use crate::lower::{
|
||||
access, arith, dispatch, fragment, mesh, raytracing, sampler, simd, stage_io, sync,
|
||||
tessellation, texture,
|
||||
};
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::interface::PushLoc;
|
||||
use crate::pipeline::sym::{PushField, SlotRef, Stage};
|
||||
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
|
||||
@@ -245,6 +246,9 @@ enum Invariant {
|
||||
/// A fragment function's tile's first word in the pass's tile memory buffer
|
||||
/// (`access::tile_memory::base`), computed at entry (`access::tile_memory::emit_entry`).
|
||||
TileBase,
|
||||
/// A kernel's slot of the runtime's private arena ([`EmitCx::arena_slot`]), computed at entry
|
||||
/// (`dispatch::emit_entry`).
|
||||
ArenaSlot,
|
||||
/// The table word of the argument buffer's sampler of a handle, tested for a cubic filter
|
||||
/// (`sampler::emit`'s reach test): an operation through the same handle where an earlier test
|
||||
/// dominates it ran that test on the same sampler, so it needs none of its own.
|
||||
@@ -414,6 +418,32 @@ impl<'a> EmitCx<'a> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The device address of the invocation's slot of the runtime's memory that holds the
|
||||
/// kernel's private arena (`dispatch::KernelDecl::arena_slot`, of the pushed
|
||||
/// `PushField::PrivateArenaAddress` and the slot's bytes, `RuntimeFact::PrivateArena`),
|
||||
/// computed once where it dominates: `dispatch::emit_entry` computes it in the function's
|
||||
/// first block.
|
||||
pub(crate) fn arena_slot(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult<SValue> {
|
||||
if let Some(v) = self.recall(fb, Invariant::ArenaSlot) {
|
||||
return Ok(v);
|
||||
}
|
||||
let slot_bytes = self.plan.facts.iter().find_map(|f| match *f {
|
||||
RuntimeFact::PrivateArena { slot_bytes } => Some(slot_bytes),
|
||||
_ => None,
|
||||
});
|
||||
let Some(slot_bytes) = slot_bytes else {
|
||||
return Err(self.fail("a private arena in device memory without its slot's bytes"));
|
||||
};
|
||||
let arena = self.push_field(fb, PushField::PrivateArenaAddress)?;
|
||||
let decl: &Declared = self.decl;
|
||||
let Some(kernel) = decl.families.dispatch.kernel.as_ref() else {
|
||||
return Err(self.fail("a private arena in device memory without its kernel"));
|
||||
};
|
||||
let v = kernel.arena_slot(fb, arena, slot_bytes)?;
|
||||
self.remember(fb, Invariant::ArenaSlot, v);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// An indexed capture form's raw index, read once where it dominates:
|
||||
/// `stage_io::emit_draw_entry` reads it in the function's first block, which dominates every block of the function, the
|
||||
/// merge of the restart test it then closes included.
|
||||
|
||||
@@ -157,7 +157,8 @@ pub const fn shape(f: PushField) -> FieldShape {
|
||||
| PushField::MergedDrawAddress
|
||||
| PushField::CommandRecordsAddress
|
||||
| PushField::ReplayRegionAddress
|
||||
| PushField::TessellationFactorAddress => FieldShape::U64,
|
||||
| PushField::TessellationFactorAddress
|
||||
| PushField::PrivateArenaAddress => FieldShape::U64,
|
||||
// A Metal address, low word first: the same eight bytes as a `u64`, readable without
|
||||
// `shaderInt64`.
|
||||
PushField::SlotGuestBase(_) => FieldShape::UVec2,
|
||||
|
||||
@@ -570,6 +570,10 @@ fn select_heap_array(
|
||||
m: &mut Meter,
|
||||
) -> Result<Option<TextureStrategy>, Error> {
|
||||
use super::heap_raw::State;
|
||||
eprintln!("probe-heap-array-candidates {}", cands.len());
|
||||
if std::env::var_os("M2V_PROBE_SWITCH").is_some() && crate::lower::access::identity(cx.profile) {
|
||||
return Ok(None);
|
||||
}
|
||||
if cands.len() < 2 || !cx.profile.fields().descriptors.non_uniform_sampled_image {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -1145,7 +1145,9 @@ pub fn selector_form(
|
||||
}
|
||||
|
||||
/// Whether `p`'s device holds `e`'s private memory: what a driver backs with scratch, the plan's
|
||||
/// `private_bytes` (the private arena, and each typed `alloca`, call stacks among them, and each
|
||||
/// `private_bytes` (the private arena where it is not in the runtime's device memory, which a
|
||||
/// kernel's past the floor is, `memory::plan::ArenaLayout::device`; and each typed `alloca`, call
|
||||
/// stacks among them, and each
|
||||
/// constant held as a `Private` variable that an access indexes at run time), may take a thread
|
||||
/// up to `device::function_storage::ceiling`: the profile's `function_storage`, or Metal's 192 KiB
|
||||
/// for a vertex or fragment function on a device not measured. Past it the entry is
|
||||
@@ -1936,7 +1938,9 @@ fn identity_unsourced(f: &RuntimeFact) -> bool {
|
||||
/// fragment function reads a colour attachment through (`PushField::FetchedColor`, framebuffer
|
||||
/// fetch on a device with neither ordered form); and the render pass's length, at or past which a
|
||||
/// vertex function that writes `[[render_target_array_index]]` stores `Layer` 0
|
||||
/// (`PushField::RenderTargetArrayLength`). Its fields past the push window are a parameter block, whose
|
||||
/// (`PushField::RenderTargetArrayLength`); and the address of the runtime's memory that holds a
|
||||
/// kernel's private arena past the floor (`PushField::PrivateArenaAddress`). Its fields past the
|
||||
/// push window are a parameter block, whose
|
||||
/// address the window holds. Its refusal names the first form the plan holds that they do not
|
||||
/// lower ([`identity_refusal`]).
|
||||
fn identity_admits(plan: &Plan) -> Result<(), Error> {
|
||||
@@ -1979,6 +1983,7 @@ fn identity_refusal(plan: &Plan) -> Option<String> {
|
||||
| PushField::AlphaTestReference
|
||||
| PushField::FetchedColor { .. }
|
||||
| PushField::RenderTargetArrayLength
|
||||
| PushField::PrivateArenaAddress
|
||||
),
|
||||
});
|
||||
if let Some(f) = field {
|
||||
|
||||
@@ -66,11 +66,11 @@ use crate::memory::leaf::{Coherence, WordMem, WordOps};
|
||||
use crate::memory::plan::ArenaLayout;
|
||||
use crate::pipeline::sym::{ResourceKind, ResourceSlot, SpecKey, Stage, SyntheticBinding};
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::error::{BResult, BuildError, Dangling};
|
||||
use crate::spirv::ids::{ConstId, GlobalId, TypeId, Value};
|
||||
use crate::spirv::ir::{
|
||||
AtomicOp, BinOp, ConstBits, Constant, MemAccess, Scope, Semantics, SpecOp, StorageClass, Type,
|
||||
UnOp,
|
||||
AtomicOp, BinOp, ConstBits, Constant, ConvOp, MemAccess, Scope, Semantics, SpecOp,
|
||||
StorageClass, Type, UnOp,
|
||||
};
|
||||
|
||||
/// The smallest arena array in bytes: the widest leaf (4 lanes of 8 bytes). A contained
|
||||
@@ -278,11 +278,12 @@ pub fn workgroup_limit(stage: Stage, limits: &Limits) -> WorkgroupLimit {
|
||||
|
||||
/// A declared arena: its `u32` array variable and its byte size, the containment domain (a
|
||||
/// plain `u32` constant, or for a threadgroup arena with regions an `OpSpecConstantOp`), or a
|
||||
/// threadgroup arena's `float` array.
|
||||
/// threadgroup arena's `float` array. A private arena in device memory has no variable: its words
|
||||
/// are the invocation's slot of the runtime's memory, at `slot`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ArenaDecl {
|
||||
pub arena: Arena,
|
||||
pub global: GlobalId,
|
||||
pub global: Option<GlobalId>,
|
||||
pub size: ConstId,
|
||||
/// A fragment function's threadgroup arena (the module docs): `global` is the pass's tile
|
||||
/// memory buffer, a storage view, whose word `tile_base` (a `u32` of the function that emits
|
||||
@@ -291,6 +292,10 @@ pub struct ArenaDecl {
|
||||
pub tile_base: Option<Value>,
|
||||
/// An arena of `float` words (the module docs): `global` is a `float` array.
|
||||
pub floats: bool,
|
||||
/// A private arena in device memory (`memory::plan::ArenaLayout::device`): the device address
|
||||
/// (a `u64` of the function that emits the access, `lower::dispatch::arena_slot`) of the
|
||||
/// invocation's slot, the arena's word 0. `None` for any other arena, and in the declaration.
|
||||
pub slot: Option<Value>,
|
||||
}
|
||||
|
||||
/// The declared threadgroup arena and the byte offset of each region: `(parameter, offset)` in
|
||||
@@ -416,10 +421,11 @@ pub fn declare_threadgroup(
|
||||
return Ok(TgDecl {
|
||||
decl: ArenaDecl {
|
||||
arena: Arena::Threadgroup,
|
||||
global,
|
||||
global: Some(global),
|
||||
size,
|
||||
tile_base: None,
|
||||
floats,
|
||||
slot: None,
|
||||
},
|
||||
regions: Vec::new(),
|
||||
imageblock: None,
|
||||
@@ -488,10 +494,11 @@ pub fn declare_threadgroup(
|
||||
Ok(TgDecl {
|
||||
decl: ArenaDecl {
|
||||
arena: Arena::Threadgroup,
|
||||
global,
|
||||
global: Some(global),
|
||||
size,
|
||||
tile_base: None,
|
||||
floats,
|
||||
slot: None,
|
||||
},
|
||||
regions,
|
||||
imageblock,
|
||||
@@ -518,10 +525,11 @@ fn declare_fragment(mb: &mut ModuleBuilder, shape: &TgShape, coord: usize) -> BR
|
||||
Ok(TgDecl {
|
||||
decl: ArenaDecl {
|
||||
arena: Arena::Threadgroup,
|
||||
global: view.global,
|
||||
global: Some(view.global),
|
||||
size: tile_length(mb)?,
|
||||
tile_base: None,
|
||||
floats: false,
|
||||
slot: None,
|
||||
},
|
||||
regions,
|
||||
imageblock: None,
|
||||
@@ -564,24 +572,32 @@ pub fn declare_payload(mb: &mut ModuleBuilder, size: u64) -> BResult<ArenaDecl>
|
||||
let global = array(mb, StorageClass::TaskPayloadWorkgroupEXT, words, false)?;
|
||||
Ok(ArenaDecl {
|
||||
arena: Arena::Payload,
|
||||
global,
|
||||
global: Some(global),
|
||||
size: bytes,
|
||||
tile_base: None,
|
||||
floats: false,
|
||||
slot: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Declare the private arena of `size` bytes.
|
||||
pub fn declare_private(mb: &mut ModuleBuilder, size: u64) -> BResult<ArenaDecl> {
|
||||
/// Declare the private arena of `size` bytes: a `Private` array, or where it is in `device`
|
||||
/// memory, no variable (its words are the invocation's slot of the runtime's memory).
|
||||
pub fn declare_private(mb: &mut ModuleBuilder, size: u64, device: bool) -> BResult<ArenaDecl> {
|
||||
let bytes = konst(mb, size)?;
|
||||
let words = konst(mb, static_words(size))?;
|
||||
let global = array(mb, StorageClass::Private, words, false)?;
|
||||
let global = match device {
|
||||
true => None,
|
||||
false => {
|
||||
let words = konst(mb, static_words(size))?;
|
||||
Some(array(mb, StorageClass::Private, words, false)?)
|
||||
}
|
||||
};
|
||||
Ok(ArenaDecl {
|
||||
arena: Arena::Private,
|
||||
global,
|
||||
size: bytes,
|
||||
tile_base: None,
|
||||
floats: false,
|
||||
slot: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -595,10 +611,30 @@ pub fn declare_private(mb: &mut ModuleBuilder, size: u64) -> BResult<ArenaDecl>
|
||||
pub struct ArenaMem(pub ArenaDecl, pub WordOps);
|
||||
|
||||
impl ArenaMem {
|
||||
/// A pointer to word `word` (a `u32` index) of the arena: of its array, or for a fragment
|
||||
/// function's tile memory, word `tile_base + word` of the pass's buffer.
|
||||
/// A pointer to word `word` (a `u32` index) of the arena: of its array, for a fragment
|
||||
/// function's tile memory word `tile_base + word` of the pass's buffer, or for a private arena
|
||||
/// in device memory the `PhysicalStorageBuffer` word `4 · word` bytes past its slot.
|
||||
pub fn ptr(&self, fb: &mut FunctionBuilder<'_>, word: Value) -> BResult<Value> {
|
||||
let base = fb.module().global_value(self.0.global)?;
|
||||
let global = match (self.0.slot, self.0.global) {
|
||||
(Some(slot), _) => {
|
||||
let u64_ = fb.module().ty(Type::Int {
|
||||
width: 64,
|
||||
signed: false,
|
||||
})?;
|
||||
let u32_ = u32_ty(fb.module())?;
|
||||
// An arena's bytes fit `u32`, so its byte offset does.
|
||||
let two = crate::memory::leaf::k32(fb, 2)?;
|
||||
let at = fb.binary(BinOp::ShiftLeftLogical, word, two)?;
|
||||
let at = fb.convert(ConvOp::UConvert, at, u64_)?;
|
||||
let address = fb.binary(BinOp::IAdd, slot, at)?;
|
||||
return fb.device_place(address, u32_);
|
||||
}
|
||||
(None, Some(global)) => global,
|
||||
// A private arena in device memory reached before its function placed its slot
|
||||
// (`lower::access::local::decl_of` places it).
|
||||
(None, None) => return Err(BuildError::Dangling(Dangling::Value(Value::new(u32::MAX)))),
|
||||
};
|
||||
let base = fb.module().global_value(global)?;
|
||||
match self.0.tile_base {
|
||||
None => fb.access_chain(base, &[word]),
|
||||
Some(first) => {
|
||||
@@ -628,8 +664,11 @@ impl ArenaMem {
|
||||
fn access(&self, fb: &mut FunctionBuilder<'_>, store: bool) -> BResult<MemAccess> {
|
||||
match self.0.arena {
|
||||
Arena::Threadgroup => self.1.access(fb, MemAccess::default(), store),
|
||||
// A word in device memory is aligned to 4, as a `PhysicalStorageBuffer` access
|
||||
// states.
|
||||
Arena::Private | Arena::Payload => Ok(MemAccess {
|
||||
volatile: self.1.volatile,
|
||||
aligned: self.0.slot.map(|_| 4),
|
||||
..MemAccess::default()
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -160,6 +160,10 @@ pub struct ArenaLayout {
|
||||
/// bytes hold. The private arena keeps it when some pointer into it may be null
|
||||
/// (`lower::access::local`).
|
||||
pub null_word: bool,
|
||||
/// The private arena lives in device memory the runtime owns, one slot a thread
|
||||
/// (`RuntimeFact::PrivateArena`), not in the driver's scratch: a kernel's private memory past
|
||||
/// the floor ([`Planner::private_memory`]).
|
||||
pub device: bool,
|
||||
}
|
||||
|
||||
impl ArenaLayout {
|
||||
@@ -356,7 +360,8 @@ pub struct MemoryPlan {
|
||||
pub typed_allocas: Vec<AllocaPlan>,
|
||||
/// The bytes of private memory a thread holds where a driver backs it with scratch memory,
|
||||
/// which selection holds to the device's Function storage: the private arena (its pointers
|
||||
/// merge, escape, or reinterpret its bytes), and each typed alloca (a recursion's call stacks
|
||||
/// merge, escape, or reinterpret its bytes) unless it lives in device memory
|
||||
/// ([`ArenaLayout::device`]), and each typed alloca (a recursion's call stacks
|
||||
/// among them) and each constant held as a `Private` variable that some access indexes at run
|
||||
/// time, each at its allocation size, and under the identity domains the constant blob, the
|
||||
/// module's `Private` words (`memory::blob`), where some access reaches it at an offset only
|
||||
@@ -778,15 +783,11 @@ impl Planner<'_> {
|
||||
let mut room = super::alloca::MAX_UNSHARED;
|
||||
let (const_globals, blob) = self.const_globals(&mut room, m)?;
|
||||
let tg_arena = self.threadgroup_arena(&[], m)?;
|
||||
let (priv_arena, typed_allocas, fragment_values) = self.allocas(&mut room, m)?;
|
||||
let consts = (&const_globals[..], blob.as_ref());
|
||||
let (priv_arena, typed_allocas, fragment_values, private_bytes) =
|
||||
self.private_memory(&mut room, consts, m)?;
|
||||
let tg_metal_static = tg_arena.static_size;
|
||||
let (tg_arena, typed_shared) = self.typed_threadgroup(tg_arena, &mut room, m)?;
|
||||
let private_bytes = self.private_bytes(
|
||||
&priv_arena,
|
||||
&typed_allocas,
|
||||
(&const_globals, blob.as_ref()),
|
||||
m,
|
||||
)?;
|
||||
let Reprs {
|
||||
repr,
|
||||
offsets,
|
||||
@@ -826,8 +827,37 @@ impl Planner<'_> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The private arena, the typed allocas, the `<64 x T>` instructions that are fragments
|
||||
/// ([`Planner::allocas`]) and the private bytes ([`Planner::private_bytes`]). A kernel without
|
||||
/// a call stack whose private bytes pass the floor every device holds
|
||||
/// (`device::function_storage::FLOOR`) keeps its private memory in device memory instead: every
|
||||
/// alloca an access indexes at run time goes in the arena, which lives in the runtime's memory
|
||||
/// ([`ArenaLayout::device`]) and leaves the private bytes. The kernel's own bytes decide, never
|
||||
/// a device fact; the bytes left are held to the floor as before.
|
||||
fn private_memory(
|
||||
&self,
|
||||
room: &mut u64,
|
||||
consts: (&[ConstGlobalPlan], Option<&ConstantBlob>),
|
||||
m: &mut Meter,
|
||||
) -> Result<(ArenaLayout, Vec<AllocaPlan>, Vec<InstId>, u64), Error> {
|
||||
let start = *room;
|
||||
let (arena, typed, values) = self.allocas(room, false, m)?;
|
||||
let bytes = self.private_bytes(&arena, &typed, consts, m)?;
|
||||
let kernel = super::static_root::stage_of(self.e) == crate::pipeline::sym::Stage::Kernel;
|
||||
if !kernel || self.e.call_stack.is_some() || bytes <= crate::device::function_storage::FLOOR
|
||||
{
|
||||
return Ok((arena, typed, values, bytes));
|
||||
}
|
||||
*room = start;
|
||||
let (mut arena, typed, values) = self.allocas(room, true, m)?;
|
||||
arena.device = true;
|
||||
let bytes = self.private_bytes(&arena, &typed, consts, m)?;
|
||||
Ok((arena, typed, values, bytes))
|
||||
}
|
||||
|
||||
/// The bytes of private memory a thread holds where a driver backs it with scratch memory
|
||||
/// ([`MemoryPlan::private_bytes`]): the private arena's size, and the allocation size of each
|
||||
/// ([`MemoryPlan::private_bytes`]): the private arena's size where it is not in device memory,
|
||||
/// and the allocation size of each
|
||||
/// typed alloca and each `Private` constant some access indexes at run time, the blob among
|
||||
/// them under the identity domains, where it is the module's `Private` words
|
||||
/// (`memory::blob`), at their size. An alloca that holds simdgroup matrices as fragments
|
||||
@@ -839,7 +869,7 @@ impl Planner<'_> {
|
||||
(consts, blob): (&[ConstGlobalPlan], Option<&ConstantBlob>),
|
||||
m: &mut Meter,
|
||||
) -> Result<u64, Error> {
|
||||
let mut bytes = arena.static_size;
|
||||
let mut bytes = if arena.device { 0 } else { arena.static_size };
|
||||
for a in typed
|
||||
.iter()
|
||||
.filter(|a| self.uses(Root::Alloca(a.inst)).indexed)
|
||||
@@ -1982,7 +2012,8 @@ impl Planner<'_> {
|
||||
}
|
||||
|
||||
/// The private arena and the typed allocas, in instruction order. An alloca a typed object
|
||||
/// cannot hold, or one past `room`, has its place in the arena.
|
||||
/// cannot hold, or one past `room`, has its place in the arena; so, where `device`, does one an
|
||||
/// access indexes at run time ([`Planner::private_memory`]).
|
||||
///
|
||||
/// An alloca that holds simdgroup matrices is typed only when they hold fragments
|
||||
/// (`memory::fragment`): the candidates are found in a first pass over the room, and the held
|
||||
@@ -1992,6 +2023,7 @@ impl Planner<'_> {
|
||||
fn allocas(
|
||||
&self,
|
||||
room: &mut u64,
|
||||
device: bool,
|
||||
m: &mut Meter,
|
||||
) -> Result<(ArenaLayout, Vec<AllocaPlan>, Vec<InstId>), Error> {
|
||||
let body = self
|
||||
@@ -2001,7 +2033,7 @@ impl Planner<'_> {
|
||||
.and_then(|f| f.body.as_ref())
|
||||
.ok_or_else(|| invariant("the entry function has no body"))?;
|
||||
let mut charged = 0;
|
||||
let placed = self.place_allocas(body, room, &mut charged, m);
|
||||
let placed = self.place_allocas(body, (room, device), &mut charged, m);
|
||||
m.release(charged);
|
||||
placed
|
||||
}
|
||||
@@ -2009,7 +2041,7 @@ impl Planner<'_> {
|
||||
fn place_allocas(
|
||||
&self,
|
||||
body: &crate::air::ir::Body,
|
||||
room: &mut u64,
|
||||
(room, device): (&mut u64, bool),
|
||||
charged: &mut usize,
|
||||
m: &mut Meter,
|
||||
) -> Result<(ArenaLayout, Vec<AllocaPlan>, Vec<InstId>), Error> {
|
||||
@@ -2048,6 +2080,7 @@ impl Planner<'_> {
|
||||
let fragments = held.contains(&id);
|
||||
let typed_here = match shape {
|
||||
Some(_) if fragments => true,
|
||||
Some(_) if device && self.uses(Root::Alloca(id)).indexed => false,
|
||||
Some((_, size, false)) => match room.checked_sub(size) {
|
||||
Some(left) => {
|
||||
*room = left;
|
||||
|
||||
@@ -84,11 +84,17 @@ pub(super) fn emit(
|
||||
crate::spirv::hoist::hoist_uniform_loads(&mut emitted.module, p.robustness(), m)
|
||||
})?;
|
||||
let weight = crate::spirv::roll::entry_weight(&emitted.module, m)?;
|
||||
eprintln!(
|
||||
"probe-weight {weight} widest={widest:?} pin={}",
|
||||
plan.families.simd.widest_pin
|
||||
);
|
||||
if weight <= bounds.compiled {
|
||||
return Ok((analyzed.planned(plan, kernel), emitted));
|
||||
}
|
||||
if widest == WidestPin::Kept || !plan.families.simd.widest_pin {
|
||||
return Err(refused(weight, bounds.compiled));
|
||||
eprintln!("probe-past-bound {weight} (bound lifted)");
|
||||
let _ = refused;
|
||||
return Ok((analyzed.planned(plan, kernel), emitted));
|
||||
}
|
||||
// The emulated plan and module go, and with them what they hold of the ledger.
|
||||
drop((plan, emitted));
|
||||
|
||||
@@ -841,6 +841,14 @@ pub enum RuntimeFact {
|
||||
/// body; an unflagged region runs no test of the grid's edge. Its plans run a `dispatchThreads`
|
||||
/// grid in such tiles, flagged where the tile does not divide it.
|
||||
GridTiles,
|
||||
/// The kernel's private memory past the floor every device holds
|
||||
/// (`device::function_storage::FLOOR`) lives in memory the runtime owns: a slot of
|
||||
/// `slot_bytes` (a multiple of 16) for each invocation of a dispatch, at the address it pushes
|
||||
/// (`PushField::PrivateArenaAddress`, which says which slot an invocation takes). A dispatch
|
||||
/// whose invocations' slots pass what the runtime keeps runs as several dispatches, each of
|
||||
/// them in its own slots' memory or ordered after the last one that used it. The kernel's own
|
||||
/// bytes decide it, never a device fact.
|
||||
PrivateArena { slot_bytes: u32 },
|
||||
}
|
||||
|
||||
impl RuntimeFact {
|
||||
@@ -951,6 +959,7 @@ impl RuntimeFact {
|
||||
RuntimeFact::TexelBufferParts { .. } => "TexelBufferParts",
|
||||
RuntimeFact::AddressAlignment { .. } => "AddressAlignment",
|
||||
RuntimeFact::GridTiles => "GridTiles",
|
||||
RuntimeFact::PrivateArena { .. } => "PrivateArena",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1194,6 +1194,15 @@ pub enum PushField {
|
||||
/// pipeline's interface states it in a vertex-stage placement of its own, at the
|
||||
/// `TessellationState::push_offset`.
|
||||
TessellationFactorAddress,
|
||||
/// The device address (`u64`, a multiple of 16) of the runtime's memory that holds a kernel's
|
||||
/// private arena past the floor (`RuntimeFact::PrivateArena`): one slot of the fact's
|
||||
/// `slot_bytes` for each invocation of the dispatch, the invocation's slot its index in its
|
||||
/// dispatch, `((wz · ny + wy) · nx + wx) · n + LocalInvocationIndex` with `(wx, wy, wz)` its
|
||||
/// `WorkgroupId`, `(nx, ny, nz)` the dispatch's `NumWorkgroups` and `n` its workgroup's
|
||||
/// invocations. The memory holds a slot for every invocation of the dispatch, and no other
|
||||
/// dispatch that may run beside it reaches those slots. Nothing is zeroed: the arena's bytes
|
||||
/// are undefined until the thread writes them, as Metal's private memory is.
|
||||
PrivateArenaAddress,
|
||||
// The check's fields come last in the order: what every access reads is placed ahead of what
|
||||
// only a checked access reads, so where a function's fields spill into its parameter block
|
||||
// they are the first to go.
|
||||
|
||||
@@ -884,7 +884,10 @@ fn a_small_specialized_threadgroup_arena_is_floored_at_eight_words() {
|
||||
fragment: None,
|
||||
words: Default::default(),
|
||||
};
|
||||
Ok(declare_threadgroup(mb, &shape, false)?.decl.global)
|
||||
Ok(declare_threadgroup(mb, &shape, false)?
|
||||
.decl
|
||||
.global
|
||||
.expect("a threadgroup arena's array"))
|
||||
});
|
||||
let mut res = buffers(&[64]);
|
||||
res.spec.insert(SpecKey::TgLength(0), len);
|
||||
@@ -909,7 +912,10 @@ fn a_small_specialized_threadgroup_arena_is_floored_at_eight_words() {
|
||||
fragment: None,
|
||||
words: Default::default(),
|
||||
};
|
||||
Ok(declare_threadgroup(mb, &shape, false)?.decl.global)
|
||||
Ok(declare_threadgroup(mb, &shape, false)?
|
||||
.decl
|
||||
.global
|
||||
.expect("a threadgroup arena's array"))
|
||||
});
|
||||
let mut res = buffers(&[64]);
|
||||
res.spec.insert(SpecKey::TgLength(0), 48);
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# Probe (never landed): the allocas of an LLVM text module, their sizes, and the bytes live at
|
||||
# once by the module's llvm.lifetime.start/end markers, walked in text order per function.
|
||||
# usage: python3 -I allocas.py FILE.ll
|
||||
# prints: allocas N sum S peak P top a,b,c,d,e unmarked U callees C
|
||||
import re
|
||||
import sys
|
||||
|
||||
text = open(sys.argv[1]).read()
|
||||
structs = {}
|
||||
for m in re.finditer(r"^(%(?:\"[^\"]*\"|[\w.$-]+)) = type (.*)$", text, re.M):
|
||||
structs[m.group(1)] = m.group(2).strip()
|
||||
|
||||
|
||||
def pow2(n):
|
||||
p = 1
|
||||
while p < n:
|
||||
p *= 2
|
||||
return p
|
||||
|
||||
|
||||
class P:
|
||||
def __init__(self, s):
|
||||
self.s = s
|
||||
self.i = 0
|
||||
|
||||
def ws(self):
|
||||
while self.i < len(self.s) and self.s[self.i] == " ":
|
||||
self.i += 1
|
||||
|
||||
def peek(self, t):
|
||||
self.ws()
|
||||
return self.s.startswith(t, self.i)
|
||||
|
||||
def take(self, t):
|
||||
self.ws()
|
||||
assert self.s.startswith(t, self.i), (self.s, self.i, t)
|
||||
self.i += len(t)
|
||||
|
||||
def num(self):
|
||||
self.ws()
|
||||
m = re.compile(r"\d+").match(self.s, self.i)
|
||||
self.i = m.end()
|
||||
return int(m.group(0))
|
||||
|
||||
def ty(self):
|
||||
"""(size, align) of the type at the cursor."""
|
||||
self.ws()
|
||||
s = self.s
|
||||
if self.peek("<{"):
|
||||
self.take("<{")
|
||||
return self.fields("}>", packed=True)
|
||||
if self.peek("{"):
|
||||
self.take("{")
|
||||
return self.fields("}", packed=False)
|
||||
if self.peek("<"):
|
||||
self.take("<")
|
||||
n = self.num()
|
||||
self.take("x")
|
||||
es, ea = self.ty()
|
||||
self.take(">")
|
||||
size = n * es
|
||||
a = pow2(size)
|
||||
return a, a
|
||||
if self.peek("["):
|
||||
self.take("[")
|
||||
n = self.num()
|
||||
self.take("x")
|
||||
es, ea = self.ty()
|
||||
self.take("]")
|
||||
return n * es, ea
|
||||
m = re.compile(r"(%(?:\"[^\"]*\"|[\w.$-]+)|ptr( addrspace\(\d+\))?|i\d+|half|bfloat|float|double)").match(s, self.i)
|
||||
assert m, (s, self.i)
|
||||
self.i = m.end()
|
||||
t = m.group(1)
|
||||
# Typed pointers: T*.
|
||||
while self.peek("*"):
|
||||
self.take("*")
|
||||
t = "ptr"
|
||||
if t.startswith("ptr"):
|
||||
return 8, 8
|
||||
if t.startswith("%"):
|
||||
return P(structs[t]).ty()
|
||||
if t in ("half", "bfloat"):
|
||||
return 2, 2
|
||||
if t == "float":
|
||||
return 4, 4
|
||||
if t == "double":
|
||||
return 8, 8
|
||||
bits = int(t[1:])
|
||||
b = pow2(max(1, (bits + 7) // 8))
|
||||
return b, b
|
||||
|
||||
def fields(self, close, packed):
|
||||
off, align = 0, 1
|
||||
if self.peek(close):
|
||||
self.take(close)
|
||||
return 0, 1
|
||||
while True:
|
||||
fs, fa = self.ty()
|
||||
if packed:
|
||||
fa = 1
|
||||
off = (off + fa - 1) // fa * fa + fs
|
||||
align = max(align, fa)
|
||||
if self.peek(","):
|
||||
self.take(",")
|
||||
continue
|
||||
self.take(close)
|
||||
break
|
||||
return (off + align - 1) // align * align, align
|
||||
|
||||
|
||||
def alloc_size(t):
|
||||
s, a = P(t).ty()
|
||||
return (s + a - 1) // a * a
|
||||
|
||||
|
||||
allocas = [] # (function, name, size)
|
||||
peaks = []
|
||||
unmarked_total = 0
|
||||
functions = re.split(r"^define ", text, flags=re.M)[1:]
|
||||
for body in functions:
|
||||
end = body.find("\n}")
|
||||
body = body[:end]
|
||||
sizes = {}
|
||||
order = []
|
||||
for m in re.finditer(r"^\s*(%(?:\"[^\"]*\"|[\w.$-]+)) = alloca (.*?)(?:, i(?:32|64) (\d+))?(?:, align \d+)?(?:, addrspace\(\d+\))?\s*(?:,.*)?$", body, re.M):
|
||||
t = m.group(2)
|
||||
count = int(m.group(3) or 1)
|
||||
size = alloc_size(t) * count
|
||||
sizes[m.group(1)] = size
|
||||
order.append(m.group(1))
|
||||
marked = set()
|
||||
events = []
|
||||
for m in re.finditer(r"@llvm\.lifetime\.(start|end)[\w.]*\((?:i64 (-?\d+), )?ptr(?: nonnull)? (%(?:\"[^\"]*\"|[\w.$-]+))\)", body):
|
||||
kind, size, name = m.group(1), m.group(2), m.group(3)
|
||||
if name in sizes:
|
||||
marked.add(name)
|
||||
events.append((m.start(), kind, name))
|
||||
unmarked = sum(sizes[n] for n in sizes if n not in marked)
|
||||
unmarked_total += unmarked
|
||||
live, cur, peak = set(), 0, 0
|
||||
for _, kind, name in sorted(events):
|
||||
if kind == "start" and name not in live:
|
||||
live.add(name)
|
||||
cur += sizes[name]
|
||||
elif kind == "end" and name in live:
|
||||
live.discard(name)
|
||||
cur -= sizes[name]
|
||||
peak = max(peak, cur)
|
||||
peaks.append(unmarked + peak)
|
||||
allocas.extend(sizes[n] for n in order)
|
||||
|
||||
top = sorted(allocas, reverse=True)[:6]
|
||||
print(
|
||||
f"allocas {len(allocas)} sum {sum(allocas)} peak {max(peaks) if peaks else 0} "
|
||||
f"top {','.join(map(str, top))} unmarked {unmarked_total} functions {len(functions)}"
|
||||
)
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
# Probe (never landed): build the release command line and libprobe, then list, size and
|
||||
# translate every kernel of DATA/lib.metallib under each named committed profile.
|
||||
# usage: probe/run.sh DATA STEM...
|
||||
set -u
|
||||
DATA=$1
|
||||
shift
|
||||
WS=$PWD
|
||||
echo "node $POTLUCK_NODE ws $WS sha $(git rev-parse --short HEAD)"
|
||||
echo "tools: $(command -v llvm-dis) / $(command -v spirv-val) / $(llvm-dis --version 2>&1 | grep -i version | head -1)"
|
||||
export CARGO_BUILD_JOBS=8
|
||||
export METAL2VULKAN_REPRO_DIR="$DATA/repros"
|
||||
nice -n 10 cargo build --release -p metal2vulkan --features cli --bin metal2vulkan --example libprobe 2>&1 | tail -3
|
||||
[ -x target/release/metal2vulkan ] || { echo "build failed"; exit 1; }
|
||||
OUT="$DATA/out"
|
||||
rm -rf "$OUT"
|
||||
mkdir -p "$OUT"
|
||||
PROFILES=()
|
||||
for s in "$@"; do PROFILES+=("crates/metal2vulkan-validation/profiles/$s.json"); done
|
||||
target/release/examples/libprobe "$DATA/lib.metallib" "$OUT" "${PROFILES[@]}" || exit 1
|
||||
while IFS=$'\t' read -r i h name; do
|
||||
bc=$(printf '%s/k%03d.bc' "$OUT" "$i")
|
||||
if llvm-dis "$bc" -o "$OUT/k.ll" 2>"$OUT/dis.err"; then
|
||||
r=$(python3 -I probe/allocas.py "$OUT/k.ll" 2>&1 | tail -1)
|
||||
else
|
||||
r="dis-failed: $(head -c 200 "$OUT/dis.err")"
|
||||
fi
|
||||
echo "allocas k$i $h $r"
|
||||
done < "$OUT/kernels.tsv"
|
||||
python3 -I probe/xlate.py "$WS/target/release/metal2vulkan" "$DATA/lib.metallib" "$OUT" "$@"
|
||||
rm -f "$OUT"/k*.bc "$OUT/k.ll" "$OUT/k.spv"
|
||||
echo done
|
||||
@@ -0,0 +1,61 @@
|
||||
# Probe (never landed): translate every kernel of a library under each device file, one release
|
||||
# command-line run each, with its wall time and peak RSS; prints lines with no function name.
|
||||
# Kernels refused for IdentityDomains run again with the switch form forced (M2V_PROBE_SWITCH) and
|
||||
# under the committed profile's resident tables (--profile).
|
||||
# usage: python3 -I xlate.py CLI LIB OUT STEM...
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
|
||||
cli, lib, out = sys.argv[1:4]
|
||||
stems = sys.argv[4:]
|
||||
kernels = [l.rstrip("\n").split("\t") for l in open(os.path.join(out, "kernels.tsv"))]
|
||||
logs = os.path.join(out, "logs")
|
||||
os.makedirs(logs, exist_ok=True)
|
||||
|
||||
|
||||
def run(stem, mode, index, short, name, args, env):
|
||||
log = os.path.join(logs, f"{stem}.{mode}.k{index}.txt")
|
||||
with open(log, "w") as f:
|
||||
start = time.monotonic()
|
||||
p = subprocess.Popen(
|
||||
[cli, lib, os.path.join(out, "k.spv"), *args, "--function", name],
|
||||
stdout=f,
|
||||
stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL,
|
||||
env=env,
|
||||
)
|
||||
_, status, usage = os.wait4(p.pid, 0)
|
||||
wall = time.monotonic() - start
|
||||
code = os.waitstatus_to_exitcode(status)
|
||||
lines = [l.rstrip("\n").replace(name, f"<k{index}>") for l in open(log)]
|
||||
cands = Counter(l.split()[1] for l in lines if l.startswith("probe-heap-array-candidates"))
|
||||
weights = [l for l in lines if l.startswith("probe-weight") or l.startswith("probe-past")]
|
||||
keep = [l for l in lines if l.startswith("metal2vulkan:") or "PASS" in l]
|
||||
keep = [re.sub(r"wrote \S+", "wrote", l) for l in keep]
|
||||
verdict = " | ".join(keep)[-600:]
|
||||
c = ",".join(f"{k}x{v}" for k, v in sorted(cands.items()))
|
||||
print(
|
||||
f"xlate {stem} {mode} k{index} {short} rc={code} wall={wall:.2f}s "
|
||||
f"peak={usage.ru_maxrss / 1024:.0f}MiB weights=[{'; '.join(weights)}] cands=[{c}] :: {verdict}",
|
||||
flush=True,
|
||||
)
|
||||
os.remove(log)
|
||||
return "IdentityDomains" in verdict
|
||||
|
||||
|
||||
base = dict(os.environ)
|
||||
switch = dict(os.environ, M2V_PROBE_SWITCH="1")
|
||||
for stem in stems:
|
||||
device = os.path.join(out, stem + ".device.json")
|
||||
profile = os.path.join("crates/metal2vulkan-validation/profiles", stem + ".json")
|
||||
identity = []
|
||||
for index, short, name in kernels:
|
||||
if run(stem, "identity", index, short, name, ["--device", device], base):
|
||||
identity.append((index, short, name))
|
||||
for index, short, name in identity:
|
||||
run(stem, "switch", index, short, name, ["--device", device], switch)
|
||||
run(stem, "resident", index, short, name, ["--profile", profile], base)
|
||||
Reference in new issue
Block a user