Merge pull request #2176 from oneandonlydean/up639/adjusted-regions

perf(agc): bind misaligned draw buffer regions in place through the view adjustment
This commit is contained in:
Dean
2026-10-10 10:49:12 +13:00
committed by GitHub
5 changed files with 101 additions and 2 deletions
@@ -189,6 +189,7 @@ public:
// calls RecordCopyBacks (a dispatch), since a staged region's results reach guest memory by
// that copy alone. Call before Upload.
void AllowDeviceStaging() { stagingAllowed = true; }
void AllowAdjustedRegions() { adjustedRegions = true; }
// Records the copy-in of every staged region anew for another use of this upload (a resource
// cache hit, from ShaderResources::Revalidate, under GuestMemory::GpuMutex, once the imports
// were confirmed unchanged): the previous use's copy-back left the shadow behind, and the next
@@ -338,12 +339,14 @@ private:
// and an atomic element or a size within the written-shadow window. Independent of the import,
// so UploadPrepare and UploadFinish decide alike.
bool stagingEligible(const Region& region, bool addressable) const;
bool bindableInPlace(std::uint64_t offset, bool addressable) const;
// Records the import-to-buffer copies of the given gpuCopy regions into the open batch, with
// the barriers that order them after earlier recorded writes and before the shaders reading them.
void recordGpuCopies(std::span<Region* const> copies, bool addressable);
void takeHeapReferences();
Context context;
bool stagingAllowed = false;
bool adjustedRegions = false;
GuestAllocations::Lease lease;
// The cached address space this build maps through (its lease pins the ranges); `regions` then
// holds only the regions outside it (V#s, snapshots, ranges copied per build).
@@ -417,6 +417,7 @@ private:
// Guest buffer elements bound read-only: each use of this object skips that many pending-write
// notes (counted in MarkGpuWrites for the [buffers] line).
std::size_t readOnlyBuffers = 0;
bool drawBuild = false;
std::vector<std::shared_ptr<Texture>> textures;
std::vector<bool> textureFirstLayer;
std::vector<std::shared_ptr<StorageTexture>> storageTextures;
@@ -2035,6 +2035,11 @@ bool GuestBufferMemory::gpuCopyEligible(const Region& region) const {
return region.end - region.begin <= gpuCopyLimit();
}
bool GuestBufferMemory::bindableInPlace(std::uint64_t offset, bool addressable) const {
if (adjustedRegions && !addressable) return offset % 4 == 0;
return offset % context.limits.minStorageBufferOffsetAlignment == 0;
}
bool GuestBufferMemory::stagingEligible(const Region& region, bool addressable) const {
if (!stagingAllowed || addressable || region.unstaged || !gpuCopiesEnabled() || region.sparse || region.mirror != nullptr) return false;
const auto bytes = region.end - region.begin;
@@ -2154,7 +2159,7 @@ void GuestBufferMemory::UploadPrepare(bool addressable) {
// device-local buffer that the CPU fallback replaces (none without a recorder to
// record the copies: UploadFinish then binds the region in place).
bool staged = Recorder::Active() != nullptr && stagingEligible(region, addressable);
const bool misaligned = (region.begin - entry->base) % context.limits.minStorageBufferOffsetAlignment != 0;
const bool misaligned = !bindableInPlace(region.begin - entry->base, addressable);
if (staged) {
const auto allocateStart = std::chrono::steady_clock::now();
region.buffer = stagingBuffer(context, static_cast<std::size_t>(region.end - region.begin), gpuCopyUsage(addressable));
@@ -2288,7 +2293,7 @@ void GuestBufferMemory::UploadFinish(bool addressable) {
// A staged region (see stagingEligible) is copied out of the import even when aligned;
// without a recorder to record the copies it binds in place like any other.
const bool staged = recorder != nullptr && stagingEligible(region, addressable);
if (entry != nullptr && !staged && (region.begin - entry->base) % context.limits.minStorageBufferOffsetAlignment == 0) {
if (entry != nullptr && !staged && bindableInPlace(region.begin - entry->base, addressable)) {
region.direct = entry;
region.snapshot.clear();
// A buffer UploadPrepare made for a GPU copy is not needed: the import serves the
@@ -899,6 +899,7 @@ bool SameAsPreviousStorageElement(const ShaderRecompiler::DescriptorBinding& bin
ShaderResources::ShaderResources(const Context& context, const ShaderRecompiler::RecompileResult& vertex, const ShaderRecompiler::RecompileResult& fragment, const ColorTarget& target, std::uint64_t indexAddress, std::size_t indexBytes) : ShaderResources(context, std::array<CompiledShader, 2>{{{ShaderRecompiler::ShaderStage::Vertex, &vertex, 0}, {ShaderRecompiler::ShaderStage::Fragment, &fragment, static_cast<std::uint32_t>(vertex.pushConstants.size())}}}, target, indexAddress, indexBytes) {}
ShaderResources::ShaderResources(const Context& context, std::span<const CompiledShader> shaders, const ColorTarget& target, std::uint64_t indexAddress, std::size_t indexBytes, std::span<const GuestMemorySnapshot> snapshots) : context(context), guestMemory(context) {
drawBuild = true;
prepareAddressBindings(shaders, snapshots);
build(shaders, &target, indexAddress, indexBytes);
}
@@ -1188,6 +1189,7 @@ void ShaderResources::buildPrepare(std::span<const CompiledShader> shaders, cons
// For every build, locked ones included: their stage B then takes the fast path too, and the
// collects cost the same wherever they run.
if (precollectImages()) phase(BuildPhase::Precollect);
if (drawBuild && !usesBda && std::all_of(allocations.begin(), allocations.end(), [&](const Allocation& allocation) { return !allocation.guest || allocation.pushByte >= 0 || (allocation.dataAllocation >= 0 && allocation.dataByte < allocations[static_cast<std::size_t>(allocation.dataAllocation)].size); })) guestMemory.AllowAdjustedRegions();
guestMemory.UploadPrepare(usesBda);
timing.uploadMs = phase(BuildPhase::Upload);
std::vector<VkDescriptorSetLayoutBinding> description;
@@ -1057,6 +1057,93 @@ void resourceReadTests(const Device& device, Recorder& recorder) {
HostImportFor(context, address, bytes);
}
void misalignedRegionTests(const Device& device, Recorder& recorder) {
const auto& context = device.GetContext();
const auto alignment = context.limits.minStorageBufferOffsetAlignment;
constexpr std::size_t bytes = 65536;
if (alignment < 8 || alignment > 256) {
std::cout << "storage buffer offset alignment " << alignment << ": misaligned draw regions not tested\n";
return;
}
void* block = context.hostImportAlignment != 0 ? AllocateWatched(bytes, 65536) : nullptr;
if (block == nullptr) {
std::cout << "host imports or write watching unavailable: misaligned draw regions not tested\n";
return;
}
struct Release {
void* block;
~Release() { ReleaseWatched(block, bytes); }
} release{block};
auto* guest = static_cast<std::uint8_t*>(block);
for (std::size_t at = 0; at < bytes; ++at) guest[at] = static_cast<std::uint8_t>(at * 5u + 1u);
const auto address = reinterpret_cast<std::uint64_t>(block);
{
GuestAllocations::Mutation mutation;
mutation.Add(block, bytes, true, true);
}
struct Unregister {
const Context& context;
void* block;
~Unregister() {
{
GuestAllocations::Mutation mutation;
mutation.Remove(block);
}
HostImportFor(context, reinterpret_cast<std::uint64_t>(block), bytes);
}
} unregister{context, block};
const auto* import = HostImportFor(context, address, bytes);
if (import == nullptr) {
std::cout << "host import of the watched block refused: misaligned draw regions not tested\n";
return;
}
constexpr std::uint32_t offset = 4096 + 4;
constexpr std::size_t elementBytes = 64;
const auto view = address + offset;
Require((view - import->base) % alignment != 0 && (view - import->base) % 4 == 0, "the test view is not a DWORD-aligned view off the storage buffer offset alignment");
ShaderRecompiler::RecompileResult vertex;
ShaderRecompiler::DescriptorBinding binding;
binding.kind = ShaderRecompiler::DescriptorKind::StorageBuffer;
binding.role = ShaderRecompiler::DescriptorRole::GuestBuffers;
binding.descriptorSet = 0;
binding.binding = 0;
binding.count = 1;
binding.guestDescriptor = {static_cast<std::uint32_t>(view), static_cast<std::uint32_t>(view >> 32u) & 0xffffu, static_cast<std::uint32_t>(elementBytes), 0x31000000u};
binding.bufferWritten = {false};
vertex.bindings.push_back(binding);
vertex.pushConstants.resize(16);
vertex.memoryOffsetDword = 0;
const ShaderRecompiler::RecompileResult fragment;
{
auto regionContext = context;
DescriptorCache cache(regionContext);
regionContext.descriptorCache = &cache;
Recorder regionRecorder(regionContext);
regionRecorder.Activate();
const ColorTarget target{};
ShaderResources resources(regionContext, vertex, fragment, target, 0, 0);
Require(resources.Reusable(), "a misaligned read-only draw region bound in place is not reusable");
const auto reads = resources.InPlaceReads();
Require(reads.size() == 1 && reads.front().first == view && reads.front().second == view + elementBytes, "the misaligned draw region is not read in place");
std::array<std::byte, PipelinePushConstantBytes> push{};
resources.PatchPushConstants(push);
const auto adjustment = static_cast<std::uint32_t>(push[0]);
Require(adjustment == (view - import->base) % alignment, "the misaligned region's push constant offset is not its distance from the aligned binding offset");
const auto check = [&] {
const auto bindings = resources.PrepareDrawBindings(regionRecorder);
Require(bindings != nullptr && bindings->snapshots.size() == 1, "the read-only misaligned draw input was not snapshotted");
const auto contents = bindings->snapshots.front().buffer->Bytes();
Require(bindings->snapshots.front().address == view - adjustment && contents.size() == adjustment + elementBytes, "the draw snapshot does not start at the aligned offset below the view");
Require(std::memcmp(contents.data() + adjustment, guest + offset, elementBytes) == 0, "the shader's patched offset into the draw snapshot misses the view's bytes");
};
check();
guest[offset + 8] ^= 0xffu;
check();
regionRecorder.Sync();
}
recorder.Activate();
}
void misalignedSnapshotTests(const Device& device, Recorder& recorder) {
const auto& context = device.GetContext();
const auto alignment = context.limits.minStorageBufferOffsetAlignment;
@@ -2904,6 +2991,7 @@ int main(int argc, char** argv) {
keyProofTests(device, recorder);
resourceReadTests(device, recorder);
misalignedSnapshotTests(device, recorder);
misalignedRegionTests(device, recorder);
drawSnapshotReuseTests(device, recorder);
drawSnapshotEvictionTests(device);
drawInputReuseTests(device, recorder);