#include "SpirvBackend/SpirvImageEmitter.hpp" #include "Optimization/ResourceMaterializer.hpp" #include "PipelineSpecialization.hpp" #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvBufferFormat.hpp" #include "SpirvBackend/SpirvEmitterInstructions.hpp" #include "SpirvBackend/SpirvMemory/SpirvDescriptors.hpp" #include "RdnaDecoder/RdnaDescriptorFormat.hpp" #include "RdnaDecoder/RdnaImageOpDecoder.hpp" #include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include "ImageTableAbi.hpp" #include "BindlessImageAbi.hpp" #include "DeviceImageTableAbi.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace ShaderRecompiler { namespace { void EmitImageAtomicOrdering(SpirvEmitterState& state) { #ifdef __APPLE__ state.module.AddFunction(spv::OpMemoryBarrier, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsAcquireReleaseMask | spv::MemorySemanticsImageMemoryMask)); #else static_cast(state); #endif } struct ImageEmitAccess { const IrValue& inst; const MemoryInfo& mem; const ImageResource& image; const IrValue& address; }; struct SampleSetup { const RdnaImageDimensionInfo& dimensionInfo; ImageSampleLayout layout; IrTextureNumericClass numericClass; bool dref; std::uint32_t coord; }; std::uint32_t RuntimeImageSwizzle(SpirvEmitterState& state, std::uint32_t resource, std::uint32_t component) { const bool table = state.program.Info().images.at(resource).table != NoTable; if (!table && !state.registrationModules) return state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::ImageBase + resource * PipelineSpecialization::ImageWords + 1u + component, component + 4u); if (table && !state.tableAccess.active) FailEmit("image table swizzle requested outside a table access"); const auto descriptor = table ? state.tableAccess.dword3 : RuntimeImageDword(state, resource, offsetof(RuntimeAbi::ResourceMetadata, descriptor) / sizeof(std::uint32_t) + 3u); return Binary(state, spv::OpBitwiseAnd, TypeU32(state), Binary(state, spv::OpShiftRightLogical, TypeU32(state), descriptor, ConstantU32(state, component * 3u)), ConstantU32(state, 7u)); } std::uint32_t RuntimeSwizzledComponent(SpirvEmitterState& state, std::uint32_t selector, const std::array& components) { auto result = Select(state, TypeU32(state), Binary(state, spv::OpIEqual, TypeBool(state), selector, ConstantU32(state, 1u)), ConstantU32(state, 1u), ConstantU32(state, 0u)); for (std::uint32_t index = 0u; index < components.size(); ++index) result = Select(state, TypeU32(state), Binary(state, spv::OpIEqual, TypeBool(state), selector, ConstantU32(state, index + 4u)), components[index], result); return result; } std::uint32_t EffectiveDmask(const MemoryInfo& mem) { return mem.dmask != 0u ? mem.dmask : 1u; } std::uint32_t DmaskComponentIndex(std::uint32_t dmask, std::uint32_t component) { std::uint32_t index = 0; for (std::uint32_t i = 0; i < component; i++) { index += (dmask >> i) & 1u; } return index; } std::uint32_t DmaskComponent(std::uint32_t dmask, std::uint32_t index) { for (std::uint32_t component = 0; component < 4u; component++) { if (((dmask >> component) & 1u) != 0u && index-- == 0u) { return component; } } throw std::runtime_error("image dmask has fewer components than requested"); } std::uint32_t ImageGatherComponent(std::uint32_t dmask) { switch (dmask) { case 0x1u: return 0; case 0x2u: return 1; case 0x4u: return 2; case 0x8u: return 3; default: throw std::runtime_error("image gather dmask must select exactly one component"); } } bool HasFlag(const MemoryInfo& mem, std::uint32_t flag) { return (mem.imageSampleFlags & flag) != 0u; } const RdnaImageDimensionInfo& AddressDimension(const ImageEmitAccess& access) { return RdnaImageDimensionInfoFor(access.mem.imageDimension); } std::uint32_t ZeroF32(SpirvEmitterState& state) { return ConstantF32(state, 0); } std::uint32_t F32BitsToU32(SpirvValueEmitContext& ctx, std::uint32_t value) { return Unary(ctx.state, spv::OpBitcast, TypeU32(ctx.state), value); } std::uint32_t AddressU32(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t component) { const auto layout = GetRdnaImageAddressComponentLayout(access.mem.imageSampleFlags, component); const auto packed = layout.bitOffset / 32u; if (packed >= access.address.ArgumentCount()) { ctx.Fail(access.inst, "has an image address component outside of the address operands"); } auto value = ctx.Def(access.address.Argument(packed)); if (layout.bitWidth == 16u) { if ((layout.bitOffset & 31u) != 0u) { value = Binary(ctx.state, spv::OpShiftRightLogical, TypeU32(ctx.state), value, ConstantU32(ctx.state, 16)); } value = Binary(ctx.state, spv::OpBitwiseAnd, TypeU32(ctx.state), value, ConstantU32(ctx.state, 0xffffu)); } return value; } std::uint32_t AddressF32(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t component) { const auto value = AddressU32(ctx, access, component); return GetRdnaImageAddressComponentLayout(access.mem.imageSampleFlags, component).bitWidth == 16u ? EmitF16BitsToF32(ctx.state, value) : Unary(ctx.state, spv::OpBitcast, TypeF32(ctx.state), value); } ImageSampleLayout Layout(const MemoryInfo& mem) { ImageSampleLayout layout; std::uint32_t cursor = 0; const auto& info = RdnaImageDimensionInfoFor(mem.imageDimension); if (HasFlag(mem, RdnaImageSampleFlagOffset)) { layout.offset = cursor++; } if (HasFlag(mem, RdnaImageSampleFlagBias)) { layout.bias = cursor++; } if (HasFlag(mem, RdnaImageSampleFlagCompare)) { layout.dref = cursor++; } if (HasFlag(mem, RdnaImageSampleFlagDerivative)) { layout.gradX = cursor; cursor += info.spatialComponents; layout.gradY = cursor; cursor += info.spatialComponents; } layout.coord = cursor; cursor += info.coordinateComponents; if (HasFlag(mem, RdnaImageSampleFlagLod)) { layout.lod = cursor++; } if (HasFlag(mem, RdnaImageSampleFlagLodClamp)) { layout.clamp = cursor++; } return layout; } std::uint32_t CubeAxis(SpirvEmitterState& state, std::uint32_t value) { return Binary(state, spv::OpFSub, TypeF32(state), value, ConstantF32(state, 0x3f800000u)); } std::uint32_t CubeLayer(SpirvEmitterState& state, const ImageEmitAccess& access, std::uint32_t value) { if (GcnGuestShaders()) { const auto guest = Unary(state, spv::OpConvertFToU, TypeU32(state), value); const auto padding = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), Binary(state, spv::OpShiftRightLogical, TypeU32(state), guest, ConstantU32(state, 3)), ConstantU32(state, 1)); return Unary(state, spv::OpConvertUToF, TypeF32(state), Binary(state, spv::OpISub, TypeU32(state), guest, padding)); } const auto i32 = TypeI32(state); const auto ext = [&](std::uint32_t op, std::uint32_t a, std::uint32_t b) { const auto id = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, i32, id, GlslStd450(state), op, a, b); return id; }; const auto guest = Unary(state, spv::OpConvertFToS, i32, value); const auto face = ext(GLSLstd450SMin, Binary(state, spv::OpBitwiseAnd, i32, guest, ConstantI32(state, 7)), ConstantI32(state, 5)); state.module.EmitCapability(spv::CapabilityImageQuery); const auto size = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySizeLod, TypeI32Vector(state, 3), size, LoadSampledImageDescriptor(state, access.mem.resource), ConstantU32(state, 0u)); const auto layers = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, i32, layers, size, 2u); const auto lastCube = ext(GLSLstd450SMax, Binary(state, spv::OpISub, i32, Binary(state, spv::OpSDiv, i32, layers, ConstantI32(state, 6)), ConstantI32(state, 1)), ConstantI32(state, 0)); const auto cube = ext(GLSLstd450SMin, ext(GLSLstd450SMax, Binary(state, spv::OpShiftRightArithmetic, i32, guest, ConstantI32(state, 3)), ConstantI32(state, 0)), lastCube); const auto host = Binary(state, spv::OpIAdd, i32, Binary(state, spv::OpIMul, i32, cube, ConstantI32(state, 6)), face); return Unary(state, spv::OpConvertSToF, TypeF32(state), host); } std::uint32_t CoordF32(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t first, std::uint32_t components, std::uint32_t encoded, bool gradient = false) { const bool cube = access.image.cube; const auto present = std::min(encoded, components); const bool cubeFace = cube && access.mem.imageDimension == RdnaImageDimension::Dim2D; if (first == NoImageComponent || (encoded < components && ((cube && !cubeFace) || encoded == 0u)) || access.mem.imageAddressComponents < first + present) { ctx.Fail(access.inst, "has an image address with too few coordinate components"); } const auto component = [&](std::uint32_t index) { return index < present ? AddressF32(ctx, access, first + index) : ZeroF32(ctx.state); }; auto x = component(0u); if (components == 1u) { return x; } auto y = component(1u); if (cube && !gradient) { x = CubeAxis(ctx.state, x); y = CubeAxis(ctx.state, y); } if (!gradient && access.image.depthCompare && (access.image.remappedDepth1D || access.mem.imageDimension == RdnaImageDimension::Dim1D || access.mem.imageDimension == RdnaImageDimension::Dim1DArray)) { y = ConstantF32(ctx.state, 0x3f000000u); } const auto result = ctx.state.module.AllocateId(); if (components == 3u) { auto z = (access.image.depthCompare && (access.mem.imageDimension == RdnaImageDimension::Dim1DArray || (access.image.remappedDepth1D && access.image.dimension == RdnaImageDimension::Dim2DArray))) ? component(1u) : component(2u); if (cube) { z = CubeLayer(ctx.state, access, z); } ctx.state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(ctx.state, 3), result, x, y, z); } else { ctx.state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(ctx.state, 2), result, x, y); } return result; } std::uint32_t LayerRowsCoord(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t coord) { auto& state = ctx.state; const auto f32 = TypeF32(state); const auto u32 = TypeU32(state); const auto extract = [&](std::uint32_t type, std::uint32_t composite, std::uint32_t index) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, type, value, composite, index); return value; }; state.module.EmitCapability(spv::CapabilityImageQuery); const auto size = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, RdnaImageDimension::Dim2D), size, LoadSampledImageDescriptor(state, access.mem.resource), ConstantU32(state, 0u)); const auto rows = extract(u32, size, 1u); const auto lastLayer = Binary(state, spv::OpISub, u32, Binary(state, spv::OpShiftRightLogical, u32, rows, ConstantU32(state, 1u)), ConstantU32(state, 1u)); const auto rounded = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, rounded, GlslStd450(state), GLSLstd450RoundEven, extract(f32, coord, 1u)); const auto clamped = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, clamped, GlslStd450(state), GLSLstd450NClamp, rounded, ConstantF32(state, 0u), Unary(state, spv::OpConvertUToF, f32, lastLayer)); const auto center = Binary(state, spv::OpFAdd, f32, Binary(state, spv::OpFMul, f32, clamped, ConstantF32(state, std::bit_cast(2.0f))), ConstantF32(state, std::bit_cast(1.0f))); const auto v = Binary(state, spv::OpFDiv, f32, center, Unary(state, spv::OpConvertUToF, f32, rows)); const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 2), result, extract(f32, coord, 0u), v); return result; } std::uint32_t CoordU32(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { const auto components = RdnaImageDimensionInfoFor(access.image.dimension).coordinateComponents; const auto encoded = std::min(components, AddressDimension(access).coordinateComponents); if (access.mem.imageAddressComponents < encoded) { ctx.Fail(access.inst, "has an image address with too few coordinate components"); } const auto component = [&](std::uint32_t index) { return index < encoded ? AddressU32(ctx, access, index) : ConstantU32(ctx.state, 0); }; const auto x = component(0); if (components == 1u) { return x; } const auto y = component(1); const auto result = ctx.state.module.AllocateId(); if (components == 3u) { const auto z = component(2); ctx.state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(ctx.state, 3), result, x, y, z); } else { ctx.state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(ctx.state, 2), result, x, y); } return result; } std::uint32_t LodU32(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { if (!access.mem.imageHasMip) { return ConstantU32(ctx.state, 0); } const auto component = AddressDimension(access).coordinateComponents; if (access.mem.imageAddressComponents <= component) { ctx.Fail(access.inst, "has an image address without the mip level component"); } return AddressU32(ctx, access, component); } bool VolumeSliceAddress(const ImageEmitAccess& access) { return access.mem.imageDimension == RdnaImageDimension::Dim2DArray && access.image.dimension == RdnaImageDimension::Dim3D; } bool ArraySliceAddress(const ImageEmitAccess& access) { return access.mem.imageDimension == RdnaImageDimension::Dim3D && access.image.dimension == RdnaImageDimension::Dim2DArray; } std::uint32_t VolumeSliceInRange(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t image, std::optional lod) { auto& state = ctx.state; state.module.EmitCapability(spv::CapabilityImageQuery); const auto size = state.module.AllocateId(); if (lod.has_value()) { state.module.AddFunction(spv::OpImageQuerySizeLod, TypeU32Vector(state, 3), size, image, *lod); } else { state.module.AddFunction(spv::OpImageQuerySize, TypeU32Vector(state, 3), size, image); } const auto depth = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), depth, size, 2u); return Binary(state, spv::OpULessThan, TypeBool(state), AddressU32(ctx, access, 2u), depth); } std::uint32_t DrefValueF32(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const ImageSampleLayout& layout) { if (layout.dref == NoImageComponent || access.mem.imageAddressComponents <= layout.dref) { ctx.Fail(access.inst, "has no depth reference in the image address"); } return AddressF32(ctx, access, layout.dref); } std::uint32_t SampledComponentBits(SpirvValueEmitContext& ctx, std::uint32_t value, IrTextureNumericClass numericClass) { if (numericClass == IrTextureNumericClass::Uint) { return value; } return Unary(ctx.state, spv::OpBitcast, TypeU32(ctx.state), value); } std::uint32_t SampledComponentZero(SpirvEmitterState& state, IrTextureNumericClass numericClass) { switch (numericClass) { case IrTextureNumericClass::Float: return ZeroF32(state); case IrTextureNumericClass::Uint: return ConstantU32(state, 0); case IrTextureNumericClass::Sint: return ConstantI32(state, 0); case IrTextureNumericClass::Unsupported: break; } throw std::runtime_error("invalid sampled image numeric class"); } std::uint32_t ResultVector(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t value, IrTextureNumericClass numericClass, bool dref, bool gather) { auto& state = ctx.state; const auto& mem = access.mem; auto valueClass = numericClass; if (dref) { valueClass = IrTextureNumericClass::Float; } const bool integer = valueClass == IrTextureNumericClass::Uint || valueClass == IrTextureNumericClass::Sint; if (mem.dataBits == 16u && access.image.depthBits) { ctx.Fail(access.inst, "reads the bits of a depth plane as 16-bit results"); } if (mem.dataBits == 16u) { if (mem.dataDwords > 4u) { ctx.Fail(access.inst, "has more than four packed image result dwords"); } std::uint32_t packed[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; const auto dmask = EffectiveDmask(mem); const auto scalar = [&](std::uint32_t index) -> std::uint32_t { if (dref) { return value; } const auto component = gather ? index : DmaskComponent(dmask, index); const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, ImageScalarType(state, valueClass), result, value, component); return result; }; for (std::uint32_t word = 0; word < mem.dataDwords; word++) { const auto lowIndex = word * 2u; const auto highIndex = lowIndex + 1u; const auto low = scalar(lowIndex); const auto high = highIndex < mem.componentCount ? scalar(highIndex) : SampledComponentZero(state, valueClass); if (integer) { const auto saturate = [&](std::uint32_t bits) { const auto clamped = state.module.AllocateId(); if (valueClass == IrTextureNumericClass::Uint) { state.module.AddFunction(spv::OpExtInst, TypeU32(state), clamped, GlslStd450(state), GLSLstd450UMin, bits, ConstantU32(state, 0xffffu)); return clamped; } state.module.AddFunction(spv::OpExtInst, TypeI32(state), clamped, GlslStd450(state), GLSLstd450SClamp, Unary(state, spv::OpBitcast, TypeI32(state), bits), ConstantI32(state, -32768), ConstantI32(state, 32767)); return Unary(state, spv::OpBitcast, TypeU32(state), clamped); }; const auto lowBits = saturate(SampledComponentBits(ctx, low, valueClass)); const auto highBits = saturate(SampledComponentBits(ctx, high, valueClass)); const auto mask = ConstantU32(state, 0xffffu); packed[word] = Binary(state, spv::OpBitwiseOr, TypeU32(state), Binary(state, spv::OpBitwiseAnd, TypeU32(state), lowBits, mask), Binary(state, spv::OpShiftLeftLogical, TypeU32(state), Binary(state, spv::OpBitwiseAnd, TypeU32(state), highBits, mask), ConstantU32(state, 16u))); } else { const auto pair = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 2), pair, low, high); const auto towardZero = access.image.table == NoTable && !state.registrationModules ? Binary(state, spv::OpINotEqual, TypeBool(state), state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::D16TowardZeroBase + mem.resource, 0u), ConstantU32(state, 0u)) : ConstantBool(state, false); const auto rounded = Select(state, TypeU32(state), towardZero, EmitPackFloat2x16Rtz(state, low, high), EmitPackHalf2x16(state, pair)); const auto keepNan = [&](std::uint32_t value, std::uint32_t half) { const auto bits = Unary(state, spv::OpBitcast, TypeU32(state), value); const auto mantissa = Binary(state, spv::OpBitwiseAnd, TypeU32(state), Binary(state, spv::OpShiftRightLogical, TypeU32(state), bits, ConstantU32(state, 13u)), ConstantU32(state, 0x3ffu)); const auto payload = Select(state, TypeU32(state), Binary(state, spv::OpIEqual, TypeBool(state), mantissa, ConstantU32(state, 0u)), ConstantU32(state, 1u), mantissa); const auto sign = Binary(state, spv::OpBitwiseAnd, TypeU32(state), Binary(state, spv::OpShiftRightLogical, TypeU32(state), bits, ConstantU32(state, 16u)), ConstantU32(state, 0x8000u)); const auto nan = Binary(state, spv::OpBitwiseOr, TypeU32(state), sign, Binary(state, spv::OpBitwiseOr, TypeU32(state), ConstantU32(state, 0x7c00u), payload)); return Select(state, TypeU32(state), Unary(state, spv::OpIsNan, TypeBool(state), value), nan, half); }; const auto lowHalf = keepNan(low, Binary(state, spv::OpBitwiseAnd, TypeU32(state), rounded, ConstantU32(state, 0xffffu))); const auto highHalf = keepNan(high, Binary(state, spv::OpShiftRightLogical, TypeU32(state), rounded, ConstantU32(state, 16u))); packed[word] = Binary(state, spv::OpBitwiseOr, TypeU32(state), lowHalf, Binary(state, spv::OpShiftLeftLogical, TypeU32(state), highHalf, ConstantU32(state, 16u))); } } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, packed[0], packed[1], packed[2], packed[3]); return result; } std::uint32_t constantComponents = 0u; if (mem.dataBits == 32u && !dref && !gather && access.inst.Opcode() == IrOpcode::ImageSampleRaw && access.image.table == NoTable) { constantComponents = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::ImageComponentBase + mem.resource, 0u); } std::uint32_t component[4] = {}; for (std::uint32_t index = 0; index < 4u; index++) { if (dref) { component[index] = F32BitsToU32(ctx, value); continue; } const auto scalar = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, ImageScalarType(state, valueClass), scalar, value, index); if (access.image.depthUnorm16) { const auto scaled = Binary(state, spv::OpFMul, TypeF32(state), scalar, ConstantF32Value(state, 65535.0f)); component[index] = Unary(state, spv::OpConvertFToU, TypeU32(state), Binary(state, spv::OpFAdd, TypeF32(state), scaled, ConstantF32Value(state, 0.5f))); } else { component[index] = SampledComponentBits(ctx, scalar, valueClass); } if (access.image.depthBits && !gather) { const auto selector = RuntimeImageSwizzle(state, mem.resource, index); const auto one = Binary(state, spv::OpLogicalOr, TypeBool(state), Binary(state, spv::OpIEqual, TypeBool(state), selector, ConstantU32(state, 1u)), Binary(state, spv::OpIEqual, TypeBool(state), selector, ConstantU32(state, 7u))); component[index] = Select(state, TypeU32(state), Binary(state, spv::OpIEqual, TypeBool(state), selector, ConstantU32(state, 4u)), component[index], Select(state, TypeU32(state), one, ConstantU32(state, 1u), ConstantU32(state, 0u))); } if (constantComponents != 0u) { using Component = PipelineSpecialization::ImageComponentConstant; const auto constant = state.module.AllocateId(); state.module.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), constant, constantComponents, ConstantU32(state, index * PipelineSpecialization::ImageComponentBits), ConstantU32(state, PipelineSpecialization::ImageComponentBits)); const auto equals = [&](Component kind) { return Binary(state, spv::OpIEqual, TypeBool(state), constant, ConstantU32(state, static_cast(kind))); }; const auto constantBits = Select(state, TypeU32(state), equals(Component::FloatOne), ConstantU32(state, 0x3f800000u), Select(state, TypeU32(state), equals(Component::IntegerOne), ConstantU32(state, 1u), ConstantU32(state, 0u))); component[index] = Select(state, TypeU32(state), equals(Component::None), component[index], constantBits); } } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, component[0], component[1], component[2], component[3]); return result; } constexpr std::array SrgbToLinear{ 0x00000000u, 0x399f0000u, 0x3a1f0000u, 0x3a6f0000u, 0x3a9f0000u, 0x3ac70000u, 0x3aef0000u, 0x3b0b0000u, 0x3b1f0000u, 0x3b330000u, 0x3b470000u, 0x3b5b0000u, 0x3b710000u, 0x3b840000u, 0x3b900000u, 0x3b9d0000u, 0x3baa0000u, 0x3bb80000u, 0x3bc60000u, 0x3bd50000u, 0x3be50000u, 0x3bf60000u, 0x3c030000u, 0x3c0c0000u, 0x3c160000u, 0x3c1f0000u, 0x3c290000u, 0x3c340000u, 0x3c3e0000u, 0x3c490000u, 0x3c550000u, 0x3c600000u, 0x3c6d0000u, 0x3c790000u, 0x3c830000u, 0x3c8a0000u, 0x3c910000u, 0x3c980000u, 0x3c9f0000u, 0x3ca60000u, 0x3cae0000u, 0x3cb60000u, 0x3cbe0000u, 0x3cc60000u, 0x3cce0000u, 0x3cd70000u, 0x3ce00000u, 0x3ce90000u, 0x3cf20000u, 0x3cfc0000u, 0x3d030000u, 0x3d080000u, 0x3d0d0000u, 0x3d120000u, 0x3d170000u, 0x3d1c0000u, 0x3d220000u, 0x3d280000u, 0x3d2d0000u, 0x3d330000u, 0x3d390000u, 0x3d3f0000u, 0x3d450000u, 0x3d4c0000u, 0x3d520000u, 0x3d590000u, 0x3d5f0000u, 0x3d660000u, 0x3d6d0000u, 0x3d740000u, 0x3d7b0000u, 0x3d810000u, 0x3d850000u, 0x3d880000u, 0x3d8c0000u, 0x3d900000u, 0x3d940000u, 0x3d980000u, 0x3d9c0000u, 0x3da00000u, 0x3da40000u, 0x3da90000u, 0x3dad0000u, 0x3db10000u, 0x3db60000u, 0x3dba0000u, 0x3dbf0000u, 0x3dc30000u, 0x3dc80000u, 0x3dcd0000u, 0x3dd10000u, 0x3dd60000u, 0x3ddb0000u, 0x3de00000u, 0x3de50000u, 0x3dea0000u, 0x3df00000u, 0x3df50000u, 0x3dfa0000u, 0x3e000000u, 0x3e020000u, 0x3e050000u, 0x3e080000u, 0x3e0b0000u, 0x3e0e0000u, 0x3e110000u, 0x3e140000u, 0x3e170000u, 0x3e1a0000u, 0x3e1d0000u, 0x3e200000u, 0x3e230000u, 0x3e260000u, 0x3e290000u, 0x3e2c0000u, 0x3e300000u, 0x3e330000u, 0x3e360000u, 0x3e3a0000u, 0x3e3d0000u, 0x3e400000u, 0x3e440000u, 0x3e470000u, 0x3e4b0000u, 0x3e4e0000u, 0x3e520000u, 0x3e560000u, 0x3e590000u, 0x3e5d0000u, 0x3e610000u, 0x3e650000u, 0x3e680000u, 0x3e6c0000u, 0x3e700000u, 0x3e740000u, 0x3e780000u, 0x3e7c0000u, 0x3e800000u, 0x3e820000u, 0x3e840000u, 0x3e860000u, 0x3e880000u, 0x3e8a0000u, 0x3e8d0000u, 0x3e8f0000u, 0x3e910000u, 0x3e930000u, 0x3e950000u, 0x3e980000u, 0x3e9a0000u, 0x3e9c0000u, 0x3e9e0000u, 0x3ea10000u, 0x3ea30000u, 0x3ea50000u, 0x3ea80000u, 0x3eaa0000u, 0x3ead0000u, 0x3eaf0000u, 0x3eb20000u, 0x3eb40000u, 0x3eb60000u, 0x3eb90000u, 0x3ebc0000u, 0x3ebe0000u, 0x3ec10000u, 0x3ec30000u, 0x3ec60000u, 0x3ec80000u, 0x3ecb0000u, 0x3ece0000u, 0x3ed10000u, 0x3ed30000u, 0x3ed60000u, 0x3ed90000u, 0x3edb0000u, 0x3ede0000u, 0x3ee10000u, 0x3ee40000u, 0x3ee70000u, 0x3eea0000u, 0x3eed0000u, 0x3ef00000u, 0x3ef20000u, 0x3ef50000u, 0x3ef80000u, 0x3efb0000u, 0x3efe0000u, 0x3f010000u, 0x3f020000u, 0x3f040000u, 0x3f050000u, 0x3f070000u, 0x3f090000u, 0x3f0a0000u, 0x3f0c0000u, 0x3f0d0000u, 0x3f0f0000u, 0x3f110000u, 0x3f120000u, 0x3f140000u, 0x3f160000u, 0x3f170000u, 0x3f190000u, 0x3f1b0000u, 0x3f1c0000u, 0x3f1e0000u, 0x3f200000u, 0x3f210000u, 0x3f230000u, 0x3f250000u, 0x3f270000u, 0x3f290000u, 0x3f2a0000u, 0x3f2c0000u, 0x3f2e0000u, 0x3f300000u, 0x3f320000u, 0x3f330000u, 0x3f350000u, 0x3f370000u, 0x3f390000u, 0x3f3b0000u, 0x3f3d0000u, 0x3f3f0000u, 0x3f410000u, 0x3f430000u, 0x3f450000u, 0x3f470000u, 0x3f490000u, 0x3f4b0000u, 0x3f4d0000u, 0x3f4f0000u, 0x3f510000u, 0x3f530000u, 0x3f550000u, 0x3f570000u, 0x3f590000u, 0x3f5b0000u, 0x3f5d0000u, 0x3f5f0000u, 0x3f610000u, 0x3f630000u, 0x3f650000u, 0x3f680000u, 0x3f6a0000u, 0x3f6c0000u, 0x3f6e0000u, 0x3f700000u, 0x3f730000u, 0x3f750000u, 0x3f770000u, 0x3f790000u, 0x3f7b0000u, 0x3f7e0000u, 0x3f800000u, }; std::uint32_t SrgbTable(SpirvEmitterState& state) { if (state.srgbTableVariable != 0u) return state.srgbTableVariable; std::array words{}; for (std::size_t index = 0; index < words.size(); ++index) words[index] = ConstantU32(state, SrgbToLinear[index]); const auto arrayType = state.module.Type(spv::OpTypeArray, TypeU32(state), ConstantU32(state, static_cast(words.size()))); const auto table = state.module.Constant(spv::OpConstantComposite, arrayType, std::span(words)); state.srgbTableVariable = state.module.DefineInitializedGlobalVariable(TypePointer(state, spv::StorageClassPrivate, arrayType), spv::StorageClassPrivate, table); return state.srgbTableVariable; } std::uint32_t DecodeSrgbTexel(SpirvEmitterState& state, std::uint32_t color) { const auto pointerType = TypePointer(state, spv::StorageClassPrivate, TypeU32(state)); const auto table = SrgbTable(state); std::uint32_t components[4] = {}; for (std::uint32_t index = 0; index < 4u; index++) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, color, index); const auto scaled = Binary(state, spv::OpFAdd, TypeF32(state), Binary(state, spv::OpFMul, TypeF32(state), value, ConstantF32Value(state, 255.0f)), ConstantF32Value(state, 0.5f)); const auto code = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, TypeU32(state), code, GlslStd450(state), GLSLstd450UMin, Unary(state, spv::OpConvertFToU, TypeU32(state), scaled), ConstantU32(state, 255u)); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, table, code); const auto bits = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, TypeU32(state), bits, pointer); components[index] = Unary(state, spv::OpBitcast, TypeF32(state), bits); } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 4), result, components[0], components[1], components[2], components[3]); return result; } std::uint32_t QueryDimensions(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto dimension = access.image.dimension; const auto& info = RdnaImageDimensionInfoFor(dimension); const auto image = LoadSampledImageDescriptor(state, access.mem.resource); const auto size = state.module.AllocateId(); if (info.multisampled != 0u) { state.module.AddFunction(spv::OpImageQuerySize, ImageViewSizeType(state, dimension), size, image); } else { state.module.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, dimension), size, image, AddressU32(ctx, access, 0)); } const auto components = info.coordinateComponents; std::uint32_t result[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, info.multisampled != 0u ? 1u : 0u)}; if (components == 1u) { result[0] = size; } else { for (std::uint32_t index = 0; index < components; index++) { result[index] = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), result[index], size, index); } } if (access.mem.imageDimension == RdnaImageDimension::Dim3D && dimension == RdnaImageDimension::Dim2D) { result[2] = ConstantU32(state, 1); } const auto requested = access.mem.imageDimension; if ((requested == RdnaImageDimension::Dim1D || requested == RdnaImageDimension::Dim2D || requested == RdnaImageDimension::Dim2DMsaa) && dimension != RdnaImageDimension::Dim3D && !(GcnGuestShaders() && access.image.cube)) { result[2] = ConstantU32(state, 0); } if (info.multisampled == 0u) { result[3] = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQueryLevels, TypeU32(state), result[3], image); } const auto vector = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), vector, result[0], result[1], result[2], result[3]); return vector; } std::uint32_t PackedOffset(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const ImageSampleLayout& layout) { auto& state = ctx.state; if (layout.offset == NoImageComponent || access.mem.imageAddressComponents <= layout.offset) { ctx.Fail(access.inst, "has no texel offset in the image address"); } const auto components = RdnaImageDimensionInfoFor(access.image.dimension).spatialComponents; const auto packed = Unary(state, spv::OpBitcast, TypeI32(state), AddressU32(ctx, access, layout.offset)); std::uint32_t values[3] = {}; for (std::uint32_t index = 0; index < components; index++) { values[index] = state.module.AllocateId(); state.module.AddFunction(spv::OpBitFieldSExtract, TypeI32(state), values[index], packed, ConstantU32(state, index * 8u), ConstantU32(state, 6)); } if (access.image.remappedDepth1D && components >= 2u) { values[1] = ConstantI32(state, 0); } if (components == 1u) { return values[0]; } const auto result = state.module.AllocateId(); if (components == 3u) { state.module.AddFunction(spv::OpCompositeConstruct, TypeI32Vector(state, 3), result, values[0], values[1], values[2]); } else { state.module.AddFunction(spv::OpCompositeConstruct, TypeI32Vector(state, 2), result, values[0], values[1]); } return result; } std::uint32_t FoldedOffsetCoord(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup) { auto& state = ctx.state; const auto components = setup.dimensionInfo.spatialComponents; const auto type = components == 1u ? TypeF32(state) : TypeF32Vector(state, components); const auto offset = Unary(state, spv::OpConvertSToF, type, PackedOffset(ctx, access, setup.layout)); if (state.fusedExactArithmetic) { auto one = ConstantF32(state, 0x3f800000u); if (components != 1u) { const auto ones = state.module.AllocateId(); std::vector words{spv::OpCompositeConstruct, type, ones}; words.insert(words.end(), components, one); state.module.AddFunction(words); one = ones; } const auto fused = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, type, fused, GlslStd450(state), GLSLstd450Fma, one, setup.coord, offset); state.module.AddAnnotation(spv::OpDecorate, fused, spv::DecorationNoContraction); return fused; } const auto sum = Binary(state, spv::OpFAdd, type, setup.coord, offset); state.module.AddAnnotation(spv::OpDecorate, sum, spv::DecorationNoContraction); return sum; } bool MirrorsSampleIfUnnormalized(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup) { const auto dimension = access.image.dimension; return !setup.dref && !access.image.cube && (dimension == RdnaImageDimension::Dim1D || dimension == RdnaImageDimension::Dim2D) && MirrorsIfUnnormalized(ctx.state.program.Info().samplers.at(access.mem.sampler)); } std::uint32_t MirroredUnnormalizedCoord(SpirvValueEmitContext& ctx, const SampleSetup& setup, std::uint32_t coord, std::uint32_t axes) { auto& state = ctx.state; const auto f32 = TypeF32(state); const auto u32 = TypeU32(state); const auto boolean = TypeBool(state); const auto components = setup.dimensionInfo.spatialComponents; std::array values{}; for (std::uint32_t index = 0; index < components; ++index) { auto x = coord; if (components != 1u) { x = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, f32, x, coord, index); } const auto mirrors = Binary(state, spv::OpINotEqual, boolean, Binary(state, spv::OpBitwiseAnd, u32, axes, ConstantU32(state, 1u << index)), ConstantU32(state, 0u)); const auto negative = Binary(state, spv::OpFOrdLessThan, boolean, x, ConstantF32(state, 0u)); const auto below = Unary(state, spv::OpBitcast, f32, Binary(state, spv::OpISub, u32, Unary(state, spv::OpBitcast, u32, Unary(state, spv::OpFNegate, f32, x)), ConstantU32(state, 1u))); const auto folded = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, folded, GlslStd450(state), GLSLstd450FMax, Select(state, f32, negative, below, x), ConstantF32(state, 0x3f000000u)); values[index] = Select(state, f32, mirrors, folded, x); } if (components == 1u) return values[0]; const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 2), result, values[0], values[1]); return result; } std::uint32_t HorizontalOffsets(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto components = RdnaImageDimensionInfoFor(access.image.dimension).spatialComponents; if (components != 1u && components != 2u) { ctx.Fail(access.inst, "has horizontal gather offsets for an unsupported image dimension"); } const auto count = ConstantU32(state, 4); const auto elementType = components == 1u ? TypeI32(state) : TypeI32Vector(state, 2); const auto arrayType = state.module.Type(spv::OpTypeArray, elementType, count); std::uint32_t offsets[4] = {}; for (std::uint32_t index = 0; index < 4u; index++) { const auto x = ConstantI32(state, static_cast(index) - 1); if (components == 1u) { offsets[index] = x; } else { offsets[index] = state.module.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, ConstantI32(state, 0)); } } return state.module.Constant(spv::OpConstantComposite, arrayType, offsets[0], offsets[1], offsets[2], offsets[3]); } SpirvBufferFormatInfo ImageConversionFormat(const ImageResource& image) { const auto format = image.conversionFormat; if (format == IrBufferFormat::Invalid) { return {}; } const auto info = GetImageFormatInfo(format); const auto remapped = image.resourceClass == ImageResourceClass::Storage ? RemapStorageTextureFormat(format) : RemapTextureFormat(format); if (SampledTextureNumericClass(remapped) != IrTextureNumericClass::Uint || remapped == format || (info.type != SpirvFormatComponentType::Uint && info.type != SpirvFormatComponentType::Unorm && info.type != SpirvFormatComponentType::Float) || !info.packedBitfield || (info.byteSize != 2u && info.byteSize != 4u) || info.componentCount == 0u || info.componentCount > 4u) { throw std::runtime_error("image conversion format is not a packed 16-bit or 32-bit unsigned integer, unorm or float format"); } return info; } void RequireConvertedUnormAccess(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SpirvBufferFormatInfo& info) { for (std::uint32_t component = 0; component < 4u; component++) { const auto selector = (access.image.shaderSwizzle >> (component * 3u)) & 7u; if (selector >= 4u && selector - 4u >= info.componentCount && info.byteSize != 2u) { ctx.Fail(access.inst, "selects a channel the converted image format does not have"); } } } std::uint32_t ExpandFmaskTexel(SpirvEmitterState& state, const ImageEmitAccess& access, std::uint32_t texel) { const auto resource = access.mem.resource; const auto u32 = TypeU32(state); const auto format = state.registrationModules ? Binary(state, spv::OpBitwiseAnd, u32, Binary(state, spv::OpShiftRightLogical, u32, RuntimeImageDword(state, resource, offsetof(RuntimeAbi::ResourceMetadata, descriptor) / sizeof(std::uint32_t) + 1u), ConstantU32(state, 20u)), ConstantU32(state, 0x1ffu)) : state.module.SpecializationConstant(u32, PipelineSpecialization::FmaskFormatBase + resource, 0u); auto layout = ConstantU32(state, 0u); for (auto value = static_cast(IrBufferFormat::Fmask8_S2_F1); value <= static_cast(IrBufferFormat::Fmask64_S16_F8); ++value) { const auto fmask = FmaskLayoutOf(static_cast(value)); if (!fmask.has_value()) continue; layout = Select(state, u32, Binary(state, spv::OpIEqual, TypeBool(state), format, ConstantU32(state, value)), ConstantU32(state, fmask->sampleBits | (fmask->samples << 8u) | (fmask->fragments << 16u)), layout); } const auto sampleBits = Binary(state, spv::OpBitwiseAnd, u32, layout, ConstantU32(state, 0xffu)); const auto samples = Binary(state, spv::OpBitwiseAnd, u32, Binary(state, spv::OpShiftRightLogical, u32, layout, ConstantU32(state, 8u)), ConstantU32(state, 0xffu)); const auto fragments = Binary(state, spv::OpShiftRightLogical, u32, layout, ConstantU32(state, 16u)); const auto fragmentMask = Binary(state, spv::OpISub, u32, fragments, ConstantU32(state, 1u)); const auto packedLow = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, packedLow, texel, 0u); const auto packedHigh = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, packedHigh, texel, 1u); auto expandedLow = ConstantU32(state, 0u); auto expandedHigh = ConstantU32(state, 0u); for (std::uint32_t sample = 0; sample < 16u; ++sample) { const auto offset = Binary(state, spv::OpIMul, u32, sampleBits, ConstantU32(state, sample)); const auto shift = Binary(state, spv::OpBitwiseAnd, u32, offset, ConstantU32(state, 31u)); const auto lowField = state.module.AllocateId(); state.module.AddFunction(spv::OpBitFieldUExtract, u32, lowField, packedLow, shift, sampleBits); const auto highField = state.module.AllocateId(); state.module.AddFunction(spv::OpBitFieldUExtract, u32, highField, packedHigh, shift, sampleBits); const auto field = Select(state, u32, Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), offset, ConstantU32(state, 32u)), highField, lowField); const auto index = Binary(state, spv::OpBitwiseAnd, u32, field, fragmentMask); const auto unknown = Binary(state, spv::OpINotEqual, TypeBool(state), Binary(state, spv::OpBitwiseAnd, u32, field, fragments), ConstantU32(state, 0u)); const auto nibbleValue = Select(state, u32, unknown, Binary(state, spv::OpBitwiseOr, u32, index, ConstantU32(state, 8u)), index); const auto nibble = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), ConstantU32(state, sample), samples), nibbleValue, ConstantU32(state, 0u)); const auto masked = Binary(state, spv::OpBitwiseAnd, u32, nibble, ConstantU32(state, 0xfu)); auto& expanded = sample < 8u ? expandedLow : expandedHigh; expanded = Binary(state, spv::OpBitwiseOr, u32, expanded, Binary(state, spv::OpShiftLeftLogical, u32, masked, ConstantU32(state, (sample & 7u) * 4u))); } const auto firstShift = Binary(state, spv::OpBitwiseAnd, u32, Binary(state, spv::OpIMul, u32, samples, ConstantU32(state, 4u)), ConstantU32(state, 31u)); const auto secondShift = Binary(state, spv::OpBitwiseAnd, u32, Binary(state, spv::OpIMul, u32, samples, ConstantU32(state, 8u)), ConstantU32(state, 31u)); const auto replicate = Binary(state, spv::OpINotEqual, TypeBool(state), format, ConstantU32(state, static_cast(IrBufferFormat::Fmask8_S2_F2))); const auto firstReplicationShift = Select(state, u32, replicate, firstShift, ConstantU32(state, 0u)); const auto secondReplicationShift = Select(state, u32, replicate, secondShift, ConstantU32(state, 0u)); auto replicatedLow = Binary(state, spv::OpBitwiseOr, u32, expandedLow, Binary(state, spv::OpShiftLeftLogical, u32, expandedLow, firstReplicationShift)); replicatedLow = Binary(state, spv::OpBitwiseOr, u32, replicatedLow, Binary(state, spv::OpShiftLeftLogical, u32, replicatedLow, secondReplicationShift)); const auto wide = Binary(state, spv::OpUGreaterThan, TypeBool(state), samples, ConstantU32(state, 8u)); const std::array components{replicatedLow, expandedHigh, Select(state, u32, wide, replicatedLow, ConstantU32(state, 0u)), Select(state, u32, wide, expandedHigh, ConstantU32(state, 0u))}; std::uint32_t selected[4] = {}; for (std::uint32_t component = 0; component < 4u; component++) selected[component] = RuntimeSwizzledComponent(state, RuntimeImageSwizzle(state, resource, component), components); const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, selected[0], selected[1], selected[2], selected[3]); return result; } std::uint32_t UnpackImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t texel) { auto& state = ctx.state; if (access.image.srgbDecode) { return DecodeSrgbTexel(state, texel); } if (access.image.conversionFormat == FmaskExpansion) { return ExpandFmaskTexel(state, access, texel); } const auto info = ImageConversionFormat(access.image); if (info.format == IrBufferFormat::Invalid) { return texel; } const bool unorm = info.type == SpirvFormatComponentType::Unorm || info.type == SpirvFormatComponentType::Float; if (unorm) { RequireConvertedUnormAccess(ctx, access, info); } const auto packed = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), packed, texel, 0u); std::array components{ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; for (std::uint32_t component = 0; component < info.componentCount; component++) { components[component] = state.module.AllocateId(); state.module.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), components[component], packed, ConstantU32(state, info.componentBitOffset[component]), ConstantU32(state, info.componentBits[component])); if (unorm) { components[component] = NormalizeFormatComponent(state, info, component, components[component]); } } for (std::uint32_t component = info.componentCount; component < 4u; component++) { components[component] = components[component % info.componentCount]; } std::uint32_t selected[4] = {}; for (std::uint32_t component = 0; component < 4u; component++) { const auto selector = RuntimeImageSwizzle(state, access.mem.resource, component); const auto value = RuntimeSwizzledComponent(state, selector, components); selected[component] = Select(state, TypeU32(state), Binary(state, spv::OpIEqual, TypeBool(state), selector, ConstantU32(state, 1u)), ConstantU32(state, FormattedConstantBits(info, SpirvFormattedSourceKind::One)), value); } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, selected[0], selected[1], selected[2], selected[3]); return result; } std::uint32_t LoadedTexelResult(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t texel, IrTextureNumericClass numericClass) { auto& state = ctx.state; const auto unpacked = UnpackImageTexel(ctx, access, texel); if (access.mem.dataBits != 16u || access.image.srgbDecode || access.image.conversionFormat == FmaskExpansion) { return ResultVector(ctx, access, unpacked, numericClass, false, false); } const auto info = ImageConversionFormat(access.image); if (info.format == IrBufferFormat::Invalid || (info.type != SpirvFormatComponentType::Unorm && info.type != SpirvFormatComponentType::Float)) { return ResultVector(ctx, access, unpacked, numericClass, false, false); } return ResultVector(ctx, access, Unary(state, spv::OpBitcast, TypeF32Vector(state, 4), unpacked), IrTextureNumericClass::Float, false, false); } SpirvBufferFormatInfo PackedTexelFormat(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { const auto format = access.image.packedFormat; if (format == IrBufferFormat::Invalid || access.image.depthBits || access.image.conversionFormat != IrBufferFormat::Invalid) { ctx.Fail(access.inst, "accesses packed texels of an image without a packed format"); } const auto info = GetImageFormatInfo(format); if (info.packedBitfield) { ctx.Fail(access.inst, "accesses packed texels of a bitfield format"); } return info; } std::uint32_t PackedImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t texel) { auto& state = ctx.state; const auto info = PackedTexelFormat(ctx, access); std::uint32_t texelBits = 0; for (std::uint32_t component = 0; component < info.componentCount; component++) { const auto bits = info.componentBits[component]; const bool exact = info.type == SpirvFormatComponentType::Uint || info.type == SpirvFormatComponentType::Sint || (info.type == SpirvFormatComponentType::Unorm && bits <= 16u) || (info.type == SpirvFormatComponentType::Float && bits == 32u); if (!exact) { ctx.Fail(access.inst, "reads packed texels of a format whose bits are not recoverable from the view"); } texelBits += bits; } const auto numericClass = access.image.numericClass; std::uint32_t words[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; std::uint32_t position = 0; for (std::uint32_t component = 0; component < info.componentCount; component++) { const auto bits = info.componentBits[component]; const auto scalar = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, ImageScalarType(state, numericClass), scalar, texel, component); std::uint32_t value; if (info.type == SpirvFormatComponentType::Unorm) { const auto scaled = Binary(state, spv::OpFMul, TypeF32(state), scalar, ConstantF32Value(state, static_cast((1u << bits) - 1u))); value = Unary(state, spv::OpConvertFToU, TypeU32(state), Binary(state, spv::OpFAdd, TypeF32(state), scaled, ConstantF32Value(state, 0.5f))); } else { value = SampledComponentBits(ctx, scalar, numericClass); } if (bits < 32u) { value = Binary(state, spv::OpBitwiseAnd, TypeU32(state), value, ConstantU32(state, (1u << bits) - 1u)); } const auto word = position / 32u; if (position % 32u != 0u) { value = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), value, ConstantU32(state, position % 32u)); } words[word] = Binary(state, spv::OpBitwiseOr, TypeU32(state), words[word], value); position += bits; } if (access.mem.dataSigned && texelBits < 32u) { const auto shift = ConstantU32(state, 32u - texelBits); words[0] = Binary(state, spv::OpShiftRightArithmetic, TypeU32(state), Binary(state, spv::OpShiftLeftLogical, TypeU32(state), words[0], shift), shift); } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, words[0], words[1], words[2], words[3]); return result; } std::uint32_t UnpackImageGather(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t gathered) { auto& state = ctx.state; const auto info = ImageConversionFormat(access.image); if (info.format == IrBufferFormat::Invalid) { return gathered; } const auto component = ImageGatherComponent(EffectiveDmask(access.mem)); const auto selector = RuntimeImageSwizzle(state, access.mem.resource, component); std::uint32_t values[4] = {}; for (std::uint32_t lane = 0; lane < 4u; lane++) { const auto packed = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), packed, gathered, lane); std::array components{}; for (std::uint32_t index = 0u; index < components.size(); ++index) { const auto physical = index % info.componentCount; components[index] = state.module.AllocateId(); state.module.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), components[index], packed, ConstantU32(state, info.componentBitOffset[physical]), ConstantU32(state, info.componentBits[physical])); } values[lane] = RuntimeSwizzledComponent(state, selector, components); } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, values[0], values[1], values[2], values[3]); return result; } std::uint32_t EmitOneDimensionalGatherLz(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup) { auto& state = ctx.state; const auto numericClass = access.image.numericClass; const bool arrayed = access.image.dimension == RdnaImageDimension::Dim1DArray; state.module.EmitCapability(spv::CapabilityImageQuery); const auto image = LoadSampledImageDescriptor(state, access.mem.resource); auto width = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySizeLod, arrayed ? TypeU32Vector(state, 2) : TypeU32(state), width, image, ConstantU32(state, 0)); auto coord = setup.coord; std::uint32_t layer = 0; if (arrayed) { const auto size = width; width = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), width, size, 0u); coord = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeF32(state), coord, setup.coord, 0u); layer = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeF32(state), layer, setup.coord, 1u); } const auto widthF32 = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), widthF32, width); auto left = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, TypeF32(state), left, GlslStd450(state), GLSLstd450Floor, Binary(state, spv::OpFSub, TypeF32(state), Binary(state, spv::OpFMul, TypeF32(state), coord, widthF32), ConstantF32(state, 0x3f000000u))); if (setup.layout.offset != NoImageComponent) { left = Binary(state, spv::OpFAdd, TypeF32(state), left, Unary(state, spv::OpConvertSToF, TypeF32(state), PackedOffset(ctx, access, setup.layout))); } const auto sampled = MakeSampledImage(state, access.mem.resource, access.mem.sampler); const auto vectorType = ImageVectorType(state, numericClass, 4); const auto scalarType = ImageScalarType(state, numericClass); const auto component = ImageConversionFormat(access.image).format == IrBufferFormat::Invalid ? ImageGatherComponent(EffectiveDmask(access.mem)) : 0u; std::uint32_t values[2] = {}; for (std::uint32_t index = 0; index < 2u; index++) { auto sampleCoord = Binary(state, spv::OpFDiv, TypeF32(state), Binary(state, spv::OpFAdd, TypeF32(state), left, ConstantF32(state, index == 0u ? 0x3f000000u : 0x3fc00000u)), widthF32); if (arrayed) { const auto pair = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 2), pair, sampleCoord, layer); sampleCoord = pair; } const auto texel = state.module.AllocateId(); state.module.AddFunction(spv::OpImageSampleExplicitLod, vectorType, texel, sampled, sampleCoord, spv::ImageOperandsLodMask, ZeroF32(state)); values[index] = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, scalarType, values[index], texel, component); } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, vectorType, result, values[0], values[1], values[1], values[0]); return result; } std::uint32_t EmitVolumeGatherLz(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup) { auto& state = ctx.state; const auto numericClass = access.image.numericClass; const auto f32 = TypeF32(state); const auto i32 = TypeI32(state); const auto u32 = TypeU32(state); const auto boolean = TypeBool(state); const auto gatherState = state.registrationModules ? EmitAndConstant(state, Binary(state, spv::OpShiftRightLogical, u32, RuntimeImageDword(state, access.mem.resource, offsetof(RuntimeAbi::ResourceMetadata, flags) / sizeof(std::uint32_t)), ConstantU32(state, RuntimeAbi::CompareStateShift)), RuntimeAbi::CompareStateMask) : state.module.SpecializationConstant(u32, PipelineSpecialization::VolumeGatherBase + access.mem.resource, 0u); const auto field = [&](std::uint32_t shift, std::uint32_t mask) { return EmitAndConstant(state, Binary(state, spv::OpShiftRightLogical, u32, gatherState, ConstantU32(state, shift)), mask); }; const auto equal = [&](std::uint32_t value, std::uint32_t literal) { return Binary(state, spv::OpIEqual, boolean, value, ConstantU32(state, literal)); }; state.module.EmitCapability(spv::CapabilityImageQuery); const auto image = LoadSampledImageDescriptor(state, access.mem.resource); const auto size = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySizeLod, TypeU32Vector(state, 3), size, image, ConstantU32(state, 0)); const std::uint32_t modes[3] = {field(VolumeGather::ClampXShift, 7u), field(VolumeGather::ClampYShift, 7u), field(VolumeGather::ClampZShift, 7u)}; const auto exact = [&](std::uint32_t op, std::uint32_t type, std::uint32_t lhs, std::uint32_t rhs) { const auto id = Binary(state, op, type, lhs, rhs); state.module.AddAnnotation(spv::OpDecorate, id, spv::DecorationNoContraction); return id; }; const auto floorOf = [&](std::uint32_t value) { const auto id = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, id, GlslStd450(state), GLSLstd450Floor, value); return id; }; const auto shifted = [&](std::uint32_t op, std::uint32_t value, std::uint32_t amount) { return Binary(state, op, u32, value, amount); }; const auto below = [&](std::uint32_t value, std::uint32_t literal) { return Binary(state, spv::OpULessThan, boolean, value, ConstantU32(state, literal)); }; std::uint32_t extents[3] = {}; std::uint32_t starts[3] = {}; for (std::uint32_t axis = 0; axis < 3u; axis++) { const auto queried = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, queried, size, axis); const auto extent = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, u32, extent, GlslStd450(state), GLSLstd450UMax, queried, ConstantU32(state, 1u)); extents[axis] = Unary(state, spv::OpBitcast, i32, extent); const auto raw = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, f32, raw, setup.coord, axis); const auto finite = Select(state, f32, Unary(state, spv::OpIsInf, boolean, raw), Select(state, f32, Binary(state, spv::OpFOrdLessThan, boolean, raw, ConstantF32(state, 0u)), ConstantF32(state, 0xc0800000u), ConstantF32(state, 0x40800000u)), raw); const auto coord = Select(state, f32, Unary(state, spv::OpIsNan, boolean, raw), ConstantF32(state, 0u), finite); const auto wrapped = exact(spv::OpFSub, f32, coord, floorOf(coord)); const auto mirrored = exact(spv::OpFSub, f32, coord, exact(spv::OpFMul, f32, floorOf(exact(spv::OpFMul, f32, coord, ConstantF32(state, 0x3f000000u))), ConstantF32(state, 0x40000000u))); const auto bounded = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, bounded, GlslStd450(state), GLSLstd450FClamp, coord, ConstantF32(state, 0xc0800000u), ConstantF32(state, 0x40800000u)); const auto reduced = Select(state, f32, equal(modes[axis], 0u), wrapped, Select(state, f32, equal(modes[axis], 1u), mirrored, bounded)); const auto bits = Unary(state, spv::OpBitcast, u32, reduced); const auto negative = Binary(state, spv::OpINotEqual, boolean, shifted(spv::OpShiftRightLogical, bits, ConstantU32(state, 31u)), ConstantU32(state, 0u)); const auto exponent = EmitAndConstant(state, shifted(spv::OpShiftRightLogical, bits, ConstantU32(state, 23u)), 0xffu); const auto normal = Binary(state, spv::OpINotEqual, boolean, exponent, ConstantU32(state, 0u)); const auto mantissa = Binary(state, spv::OpBitwiseOr, u32, EmitAndConstant(state, bits, 0x7fffffu), Select(state, u32, normal, ConstantU32(state, 0x800000u), ConstantU32(state, 0u))); const auto shift = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, u32, shift, GlslStd450(state), GLSLstd450UMin, Binary(state, spv::OpISub, u32, ConstantU32(state, 142u), Select(state, u32, normal, exponent, ConstantU32(state, 1u))), ConstantU32(state, 40u)); const auto product = state.module.AllocateId(); state.module.AddFunction(spv::OpUMulExtended, TypeU32Pair(state), product, mantissa, extent); const auto productLow = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, productLow, product, 0u); const auto productHigh = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, productHigh, product, 1u); const auto halfShift = Binary(state, spv::OpISub, u32, shift, ConstantU32(state, 1u)); const auto halfInLow = below(halfShift, 32u); const auto halfLow = Select(state, u32, halfInLow, shifted(spv::OpShiftLeftLogical, ConstantU32(state, 1u), halfShift), ConstantU32(state, 0u)); const auto halfHigh = Select(state, u32, halfInLow, ConstantU32(state, 0u), shifted(spv::OpShiftLeftLogical, ConstantU32(state, 1u), Binary(state, spv::OpISub, u32, halfShift, ConstantU32(state, 32u)))); const auto borrow = Select(state, u32, negative, ConstantU32(state, 1u), ConstantU32(state, 0u)); const auto biasLow = Binary(state, spv::OpISub, u32, halfLow, borrow); const auto biasHigh = Binary(state, spv::OpISub, u32, halfHigh, Select(state, u32, Binary(state, spv::OpLogicalAnd, boolean, negative, Unary(state, spv::OpLogicalNot, boolean, halfInLow)), ConstantU32(state, 1u), ConstantU32(state, 0u))); const auto sum = state.module.AllocateId(); state.module.AddFunction(spv::OpIAddCarry, TypeU32Pair(state), sum, productLow, biasLow); const auto sumLow = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, sumLow, sum, 0u); const auto carry = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, carry, sum, 1u); const auto sumHigh = Binary(state, spv::OpIAdd, u32, Binary(state, spv::OpIAdd, u32, productHigh, biasHigh), carry); const auto inLow = below(shift, 32u); const auto fromLow = Binary(state, spv::OpBitwiseOr, u32, shifted(spv::OpShiftRightLogical, sumLow, shift), shifted(spv::OpShiftLeftLogical, sumHigh, Binary(state, spv::OpISub, u32, ConstantU32(state, 32u), shift))); const auto fromHigh = shifted(spv::OpShiftRightLogical, sumHigh, Binary(state, spv::OpISub, u32, shift, ConstantU32(state, 32u))); const auto magnitude = Unary(state, spv::OpBitcast, i32, Select(state, u32, inLow, fromLow, fromHigh)); auto snapped = Select(state, i32, negative, Unary(state, spv::OpSNegate, i32, magnitude), magnitude); if (axis < 2u) { snapped = Binary(state, spv::OpISub, i32, snapped, ConstantI32(state, 128)); } starts[axis] = Binary(state, spv::OpShiftRightArithmetic, i32, snapped, ConstantI32(state, 8)); } const auto resolve = [&](std::initializer_list indices, std::uint32_t axis, std::uint32_t mode) { const auto extent = extents[axis]; const auto last = Binary(state, spv::OpISub, i32, extent, ConstantI32(state, 1)); const auto modulo = [&](std::uint32_t value, std::uint32_t period) { const auto lifted = Unary(state, spv::OpBitcast, u32, Binary(state, spv::OpIAdd, i32, value, period)); return Unary(state, spv::OpBitcast, i32, Binary(state, spv::OpUMod, u32, lifted, Unary(state, spv::OpBitcast, u32, period))); }; const auto extInst = [&](std::uint32_t op, std::uint32_t a, std::uint32_t b, std::uint32_t c) { const auto id = state.module.AllocateId(); if (c == 0u) { state.module.AddFunction(spv::OpExtInst, i32, id, GlslStd450(state), op, a, b); } else { state.module.AddFunction(spv::OpExtInst, i32, id, GlslStd450(state), op, a, b, c); } return id; }; const auto once = Binary(state, spv::OpINotEqual, boolean, EmitAndConstant(state, mode, 1u), ConstantU32(state, 0u)); const auto halfBorder = equal(EmitAndConstant(state, mode, 6u), 4u); const bool footprint = indices.size() == 2u; std::vector sources; for (const auto index : indices) { const auto folded = Select(state, i32, Binary(state, spv::OpSLessThan, boolean, index, ConstantI32(state, 0)), Binary(state, spv::OpISub, i32, ConstantI32(state, -1), index), index); sources.push_back(Select(state, i32, once, folded, index)); } std::uint32_t low = 0u; std::uint32_t pinned = 0u; if (footprint) { low = extInst(GLSLstd450SMin, sources[0], sources[1], 0u); pinned = extInst(GLSLstd450SClamp, low, ConstantI32(state, -1), last); } const auto period = Binary(state, spv::OpIMul, i32, extent, ConstantI32(state, 2)); std::vector> resolved; auto source = sources.begin(); for (const auto index : indices) { auto effective = *source++; if (footprint) { effective = Select(state, i32, halfBorder, Binary(state, spv::OpIAdd, i32, pinned, Binary(state, spv::OpISub, i32, effective, low)), effective); } const auto phase = modulo(index, period); const auto mirrored = Select(state, i32, Binary(state, spv::OpSLessThan, boolean, phase, extent), phase, Binary(state, spv::OpISub, i32, Binary(state, spv::OpISub, i32, period, ConstantI32(state, 1)), phase)); const auto clamped = extInst(GLSLstd450SClamp, effective, ConstantI32(state, 0), last); const auto coordinate = Select(state, i32, equal(mode, 0u), modulo(index, extent), Select(state, i32, equal(mode, 1u), mirrored, clamped)); const auto outside = Binary(state, spv::OpLogicalOr, boolean, Binary(state, spv::OpSLessThan, boolean, effective, ConstantI32(state, 0)), Binary(state, spv::OpSGreaterThan, boolean, effective, last)); const auto bordering = Binary(state, spv::OpUGreaterThanEqual, boolean, mode, ConstantU32(state, footprint ? 4u : 6u)); resolved.emplace_back(coordinate, Binary(state, spv::OpLogicalAnd, boolean, bordering, outside)); } return resolved; }; const auto border = field(VolumeGather::BorderShift, 3u); const auto columns = resolve({starts[0], Binary(state, spv::OpIAdd, i32, starts[0], ConstantI32(state, 1))}, 0u, modes[0]); const auto rows = resolve({starts[1], Binary(state, spv::OpIAdd, i32, starts[1], ConstantI32(state, 1))}, 1u, modes[1]); const auto slice = resolve({starts[2]}, 2u, modes[2])[0]; const auto vectorType = ImageVectorType(state, numericClass, 4); const auto scalarType = ImageScalarType(state, numericClass); const auto component = ImageConversionFormat(access.image).format == IrBufferFormat::Invalid ? ImageGatherComponent(EffectiveDmask(access.mem)) : 0u; std::uint32_t borderValue = 0u; if (numericClass == IrTextureNumericClass::Float) { const auto white = equal(border, VolumeGather::BorderOpaqueWhite); const auto opaque = component == 3u ? Binary(state, spv::OpLogicalOr, boolean, white, equal(border, VolumeGather::BorderOpaqueBlack)) : white; borderValue = Select(state, f32, opaque, ConstantF32(state, 0x3f800000u), ConstantF32(state, 0u)); } else { borderValue = numericClass == IrTextureNumericClass::Sint ? ConstantI32(state, 0) : ConstantU32(state, 0u); } constexpr std::uint32_t footprint[4][2] = {{0u, 1u}, {1u, 1u}, {1u, 0u}, {0u, 0u}}; std::uint32_t values[4] = {}; for (std::uint32_t index = 0; index < 4u; index++) { const auto& column = columns[footprint[index][0]]; const auto& row = rows[footprint[index][1]]; const auto coord = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeI32Vector(state, 3), coord, column.first, row.first, slice.first); const auto texel = state.module.AllocateId(); state.module.AddFunction(spv::OpImageFetch, vectorType, texel, image, coord, spv::ImageOperandsLodMask, ConstantU32(state, 0u)); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, scalarType, value, texel, component); const auto outside = Binary(state, spv::OpLogicalOr, boolean, Binary(state, spv::OpLogicalOr, boolean, column.second, row.second), slice.second); values[index] = Select(state, scalarType, outside, borderValue, value); } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, vectorType, result, values[0], values[1], values[2], values[3]); return result; } std::uint32_t GatherAddress(SpirvEmitterState& state, std::uint32_t mode, std::uint32_t texel, std::uint32_t extent) { const auto i32 = TypeI32(state); const auto boolean = TypeBool(state); const auto positiveRemainder = [&](std::uint32_t divisor) { const auto remainder = Binary(state, spv::OpSRem, i32, texel, divisor); return Select(state, i32, Binary(state, spv::OpSLessThan, boolean, remainder, ConstantI32(state, 0)), Binary(state, spv::OpIAdd, i32, remainder, divisor), remainder); }; const auto wrapped = positiveRemainder(extent); const auto period = Binary(state, spv::OpIMul, i32, extent, ConstantI32(state, 2)); const auto folded = positiveRemainder(period); const auto mirrored = Select(state, i32, Binary(state, spv::OpSLessThan, boolean, folded, extent), folded, Binary(state, spv::OpISub, i32, Binary(state, spv::OpISub, i32, period, ConstantI32(state, 1)), folded)); const auto last = Binary(state, spv::OpISub, i32, extent, ConstantI32(state, 1)); const auto clamped = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, i32, clamped, GlslStd450(state), GLSLstd450SClamp, texel, ConstantI32(state, 0), last); const auto reflected = Select(state, i32, Binary(state, spv::OpSLessThan, boolean, texel, ConstantI32(state, 0)), Binary(state, spv::OpISub, i32, ConstantI32(state, -1), texel), texel); const auto mirroredOnce = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, i32, mirroredOnce, GlslStd450(state), GLSLstd450SMin, reflected, last); const auto is = [&](std::uint32_t value) { return Binary(state, spv::OpIEqual, boolean, mode, ConstantU32(state, value)); }; return Select(state, i32, is(0u), wrapped, Select(state, i32, is(1u), mirrored, Select(state, i32, is(2u), clamped, mirroredOnce))); } std::uint32_t FloatClamp(SpirvEmitterState& state, std::uint32_t value, std::uint32_t low, std::uint32_t high) { const auto clamped = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state), GLSLstd450NClamp, value, low, high); return clamped; } std::uint32_t GatherLodSupported(SpirvEmitterState& state, std::uint32_t sampler) { const auto samplerState = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::GatherLodBase + sampler, 4u << 24u); const auto boolean = TypeBool(state); const auto supported = [&](std::uint32_t shift) { const auto mode = EmitAndConstant(state, Binary(state, spv::OpShiftRightLogical, TypeU32(state), samplerState, ConstantU32(state, shift)), 7u); return Binary(state, spv::OpLogicalAnd, boolean, Binary(state, spv::OpINotEqual, boolean, mode, ConstantU32(state, 4u)), Binary(state, spv::OpINotEqual, boolean, mode, ConstantU32(state, 6u))); }; return Binary(state, spv::OpLogicalAnd, boolean, supported(24u), supported(27u)); } std::uint32_t EmitTwoDimensionalGatherLod(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup) { auto& state = ctx.state; state.module.EmitCapability(spv::CapabilityImageQuery); const auto u32 = TypeU32(state); const auto i32 = TypeI32(state); const auto f32 = TypeF32(state); const auto boolean = TypeBool(state); const auto samplerState = state.module.SpecializationConstant(u32, PipelineSpecialization::GatherLodBase + access.mem.sampler, 4u << 24u); const auto bias = Unary(state, spv::OpBitcast, f32, state.module.SpecializationConstant(u32, PipelineSpecialization::GatherLodBiasBase + access.mem.sampler, 0u)); const auto field = [&](std::uint32_t shift, std::uint32_t mask) { return EmitAndConstant(state, Binary(state, spv::OpShiftRightLogical, u32, samplerState, ConstantU32(state, shift)), mask); }; const auto fixedLod = [&](std::uint32_t raw) { return Binary(state, spv::OpFMul, f32, Unary(state, spv::OpConvertUToF, f32, raw), ConstantF32(state, 0x3b800000u)); }; const auto image = LoadSampledImageDescriptor(state, access.mem.resource); const auto shape = state.module.SpecializationConstant(u32, PipelineSpecialization::GatherImageShapeBase + access.mem.resource, 0u); const auto shapeField = [&](std::uint32_t shift, std::uint32_t mask) { return EmitAndConstant(state, Binary(state, spv::OpShiftRightLogical, u32, shape, ConstantU32(state, shift)), mask); }; const auto queriedLevels = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQueryLevels, u32, queriedLevels, image); const auto levels = Select(state, u32, Binary(state, spv::OpIEqual, boolean, queriedLevels, ConstantU32(state, 0u)), Binary(state, spv::OpIAdd, u32, shapeField(0u, 0xfu), ConstantU32(state, 1u)), queriedLevels); const auto atLeastOne = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, u32, atLeastOne, GlslStd450(state), GLSLstd450UMax, levels, ConstantU32(state, 1u)); const auto lastLevel = Unary(state, spv::OpConvertUToF, f32, Binary(state, spv::OpISub, u32, atLeastOne, ConstantU32(state, 1u))); const auto biased = Binary(state, spv::OpFAdd, f32, AddressF32(ctx, access, setup.layout.lod), bias); const auto atLeastMin = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, atLeastMin, GlslStd450(state), GLSLstd450NMax, biased, fixedLod(field(0u, 0xfffu))); const auto ceiling = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, ceiling, GlslStd450(state), GLSLstd450NMin, atLeastMin, fixedLod(field(12u, 0xfffu))); const auto imageMinLod = fixedLod(state.module.SpecializationConstant(u32, PipelineSpecialization::GatherImageMinLodBase + access.mem.resource, 0u)); const auto raised = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, raised, GlslStd450(state), GLSLstd450NMax, ceiling, imageMinLod); const auto lod = FloatClamp(state, raised, ZeroF32(state), lastLevel); const auto rounded = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, rounded, GlslStd450(state), GLSLstd450Ceil, Binary(state, spv::OpFAdd, f32, lod, ConstantF32(state, 0x3f000000u))); const auto nearest = FloatClamp(state, Binary(state, spv::OpFSub, f32, rounded, ConstantF32(state, 0x3f800000u)), ZeroF32(state), lastLevel); const auto mipNone = Binary(state, spv::OpINotEqual, boolean, field(30u, 1u), ConstantU32(state, 0u)); const auto imageMinLevel = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, imageMinLevel, GlslStd450(state), GLSLstd450Floor, imageMinLod); const auto baseLevel = FloatClamp(state, imageMinLevel, ZeroF32(state), lastLevel); const auto level = Select(state, i32, mipNone, Unary(state, spv::OpConvertFToS, i32, baseLevel), Unary(state, spv::OpConvertFToS, i32, nearest)); const auto size = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySizeLod, TypeI32Vector(state, 2), size, image, ConstantI32(state, 0)); std::uint32_t extent[2] = {}; std::uint32_t first[2] = {}; for (std::uint32_t axis = 0; axis < 2u; axis++) { const auto queried = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, i32, queried, size, axis); const auto shifted = Binary(state, spv::OpShiftRightLogical, u32, Binary(state, spv::OpIAdd, u32, shapeField(axis == 0u ? 4u : 18u, 0x3fffu), ConstantU32(state, 1u)), Unary(state, spv::OpBitcast, u32, level)); const auto texels = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, u32, texels, GlslStd450(state), GLSLstd450UMax, shifted, ConstantU32(state, 1u)); const auto levelTexels = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, u32, levelTexels, GlslStd450(state), GLSLstd450UMax, Binary(state, spv::OpShiftRightLogical, u32, Unary(state, spv::OpBitcast, u32, queried), Unary(state, spv::OpBitcast, u32, level)), ConstantU32(state, 1u)); extent[axis] = Select(state, i32, Binary(state, spv::OpIEqual, boolean, queried, ConstantI32(state, 0)), Unary(state, spv::OpBitcast, i32, texels), Unary(state, spv::OpBitcast, i32, levelTexels)); const auto coord = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, f32, coord, setup.coord, axis); const auto scaled = Binary(state, spv::OpFSub, f32, Binary(state, spv::OpFMul, f32, coord, Unary(state, spv::OpConvertSToF, f32, extent[axis])), ConstantF32(state, 0x3f000000u)); const auto floored = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, floored, GlslStd450(state), GLSLstd450Floor, scaled); first[axis] = Unary(state, spv::OpConvertFToS, i32, FloatClamp(state, floored, ConstantF32(state, 0xcb800000u), ConstantF32(state, 0x4b800000u))); } const auto vectorType = ImageVectorType(state, setup.numericClass, 4); const auto scalarType = ImageScalarType(state, setup.numericClass); const auto component = ImageConversionFormat(access.image).format == IrBufferFormat::Invalid ? ImageGatherComponent(EffectiveDmask(access.mem)) : 0u; const std::int32_t corners[4][2] = {{0, 1}, {1, 1}, {1, 0}, {0, 0}}; std::uint32_t values[4] = {}; for (std::uint32_t index = 0; index < 4u; index++) { const auto x = GatherAddress(state, field(24u, 7u), Binary(state, spv::OpIAdd, i32, first[0], ConstantI32(state, corners[index][0])), extent[0]); const auto y = GatherAddress(state, field(27u, 7u), Binary(state, spv::OpIAdd, i32, first[1], ConstantI32(state, corners[index][1])), extent[1]); const auto texelCoord = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeI32Vector(state, 2), texelCoord, x, y); const auto texel = state.module.AllocateId(); state.module.AddFunction(spv::OpImageFetch, vectorType, texel, image, texelCoord, spv::ImageOperandsLodMask, level); values[index] = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, scalarType, values[index], texel, component); } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, vectorType, result, values[0], values[1], values[2], values[3]); return result; } std::uint32_t PackImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t texel) { auto& state = ctx.state; const auto info = ImageConversionFormat(access.image); if (info.format == IrBufferFormat::Invalid) { return texel; } if (info.format == IrBufferFormat::Format6E4Float) { ctx.Fail(access.inst, "stores a 10_10_10_2 float image, which is not implemented"); } const bool unorm = info.type == SpirvFormatComponentType::Unorm || info.type == SpirvFormatComponentType::Float; if (unorm) { RequireConvertedUnormAccess(ctx, access, info); } auto packed = ConstantU32(state, 0u); for (std::uint32_t component = 0; component < info.componentCount; component++) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), value, texel, component); auto clamped = value; if (unorm) { if (access.mem.dataBits == 16u) clamped = Unary(state, spv::OpBitcast, TypeU32(state), EmitF16BitsToF32(state, value)); clamped = EmitFormatStoreComponent(state, info, component, clamped); } else { const auto maximum = ConstantU32(state, info.componentBits[component] == 32u ? UINT32_MAX : (1u << info.componentBits[component]) - 1u); const auto within = Binary(state, spv::OpULessThan, TypeBool(state), value, maximum); clamped = Select(state, TypeU32(state), within, value, maximum); } const auto shifted = info.componentBitOffset[component] == 0u ? clamped : Binary(state, spv::OpShiftLeftLogical, TypeU32(state), clamped, ConstantU32(state, info.componentBitOffset[component])); packed = Binary(state, spv::OpBitwiseOr, TypeU32(state), packed, shifted); } const auto zero = ConstantU32(state, 0u); const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, packed, zero, zero, zero); return result; } SpirvBufferFormatInfo SintStorageFormat(const ImageResource& image) { const auto format = image.conversionFormat; if (image.resourceClass != ImageResourceClass::Storage || format == IrBufferFormat::Invalid || SampledTextureNumericClass(format) != IrTextureNumericClass::Sint) { return {}; } const auto info = GetImageFormatInfo(format); if (image.numericClass != IrTextureNumericClass::Uint || info.type != SpirvFormatComponentType::Sint || info.packedBitfield || info.componentCount == 0u || info.byteSize == 12u) { throw std::runtime_error("storage image conversion format is not a SINT format written through a UINT view"); } return info; } std::uint32_t StoreTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t data, bool integer) { auto& state = ctx.state; const auto& mem = access.mem; const auto sint = SintStorageFormat(access.image); const auto storageFormat = GetImageFormatInfo(access.image.conversionFormat); const auto float16 = access.image.resourceClass == ImageResourceClass::Storage && access.image.numericClass == IrTextureNumericClass::Uint && (access.image.conversionFormat == IrBufferFormat::Format16Float || access.image.conversionFormat == IrBufferFormat::Format16_16Float || access.image.conversionFormat == IrBufferFormat::Format16_16_16_16Float); std::uint32_t values[4] = {}; const auto dmask = EffectiveDmask(mem); for (std::uint32_t component = 0; component < 4u; component++) { auto raw = ConstantU32(state, 0); for (std::uint32_t reverse = 4u; reverse != 0u; --reverse) { const auto source = reverse - 1u; const auto packedIndex = DmaskComponentIndex(dmask, source); auto candidate = ConstantU32(state, 0u); if (((dmask >> source) & 1u) != 0u) { candidate = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), candidate, data, mem.dataBits == 16u ? packedIndex / 2u : packedIndex); } if (mem.dataBits == 16u && ((dmask >> source) & 1u) != 0u) { if ((packedIndex & 1u) != 0u) { candidate = Binary(state, spv::OpShiftRightLogical, TypeU32(state), candidate, ConstantU32(state, 16u)); } candidate = Binary(state, spv::OpBitwiseAnd, TypeU32(state), candidate, ConstantU32(state, 0xffffu)); } raw = Select(state, TypeU32(state), Binary(state, spv::OpIEqual, TypeBool(state), RuntimeImageSwizzle(state, mem.resource, source), ConstantU32(state, component + 4u)), candidate, raw); } values[component] = integer ? raw : mem.dataBits == 16u ? EmitF16BitsToF32(state, raw) : Unary(state, spv::OpBitcast, TypeF32(state), raw); if (float16 && component < storageFormat.componentCount && mem.dataBits != 16u) { values[component] = EmitFormatStoreComponent(state, storageFormat, component, values[component]); } if (component < sint.componentCount && (mem.dataBits == 16u || sint.componentBits[component] < 32u)) { values[component] = mem.dataBits == 16u ? EmitD16StoreComponent(state, sint, component, values[component]) : EmitFormatStoreComponent(state, sint, component, values[component]); } } const auto texel = state.module.AllocateId(); const bool rawUintStorage = sint.format != IrBufferFormat::Invalid || float16; state.module.AddFunction(spv::OpCompositeConstruct, integer || rawUintStorage ? TypeU32Vector(state, 4) : TypeF32Vector(state, 4), texel, values[0], values[1], values[2], values[3]); return rawUintStorage ? texel : PackImageTexel(ctx, access, texel); } std::uint32_t PackedStoreTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t data) { auto& state = ctx.state; const auto info = PackedTexelFormat(ctx, access); const auto numericClass = access.image.numericClass; if (info.byteSize == 12u) { ctx.Fail(access.inst, "stores packed texels of a format the hardware does not write"); } std::uint32_t words[4] = {}; for (std::uint32_t word = 0; word < 4u; word++) { if (((access.mem.dmask >> word) & 1u) == 0u) { words[word] = ConstantU32(state, 0u); continue; } words[word] = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), words[word], data, DmaskComponentIndex(access.mem.dmask, word)); } std::uint32_t values[4] = {}; for (std::uint32_t component = 0; component < 4u; component++) { if (component >= info.componentCount) { values[component] = numericClass == IrTextureNumericClass::Float ? ZeroF32(state) : ConstantU32(state, 0u); continue; } const auto bits = info.componentBits[component]; const auto offset = info.componentBitOffset[component]; const bool exact = numericClass == IrTextureNumericClass::Uint || (bits == 32u && info.type == SpirvFormatComponentType::Float && numericClass == IrTextureNumericClass::Float); if (!exact || offset % 32u + bits > 32u) { ctx.Fail(access.inst, "stores packed texels of a format whose bits are not reproducible through the view"); } auto value = words[offset / 32u]; if (offset % 32u != 0u) { value = Binary(state, spv::OpShiftRightLogical, TypeU32(state), value, ConstantU32(state, offset % 32u)); } if (bits < 32u) { value = Binary(state, spv::OpBitwiseAnd, TypeU32(state), value, ConstantU32(state, (1u << bits) - 1u)); } values[component] = numericClass == IrTextureNumericClass::Float ? Unary(state, spv::OpBitcast, TypeF32(state), value) : value; } const auto texel = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, numericClass == IrTextureNumericClass::Float ? TypeF32Vector(state, 4) : TypeU32Vector(state, 4), texel, values[0], values[1], values[2], values[3]); return texel; } std::uint32_t ImageAtomicOpcode(IrOpcode opcode) { switch (opcode) { case IrOpcode::ImageAtomicSwap32: case IrOpcode::ImageAtomicSwap64: return spv::OpAtomicExchange; case IrOpcode::ImageAtomicIAdd32: case IrOpcode::ImageAtomicIAdd64: return spv::OpAtomicIAdd; case IrOpcode::ImageAtomicUMin32: case IrOpcode::ImageAtomicUMin64: return spv::OpAtomicUMin; case IrOpcode::ImageAtomicUMax32: case IrOpcode::ImageAtomicUMax64: return spv::OpAtomicUMax; case IrOpcode::ImageAtomicAnd32: case IrOpcode::ImageAtomicAnd64: return spv::OpAtomicAnd; case IrOpcode::ImageAtomicOr32: case IrOpcode::ImageAtomicOr64: return spv::OpAtomicOr; case IrOpcode::ImageAtomicXor32: case IrOpcode::ImageAtomicXor64: return spv::OpAtomicXor; case IrOpcode::ImageAtomicISub32: case IrOpcode::ImageAtomicISub64: return spv::OpAtomicISub; case IrOpcode::ImageAtomicSMin32: case IrOpcode::ImageAtomicSMin64: return spv::OpAtomicSMin; case IrOpcode::ImageAtomicSMax32: case IrOpcode::ImageAtomicSMax64: return spv::OpAtomicSMax; default: throw std::runtime_error("opcode is not an image atomic"); } } const ImageResource& ImageResourceOf(const SpirvEmitterState& state, const MemoryInfo& mem) { return state.program.Resources().info.images.at(mem.resource); } void EmitQueryDimensionsOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { ctx.state.module.EmitCapability(spv::CapabilityImageQuery); ctx.Define(access.inst, QueryDimensions(ctx, access)); } void EmitQueryLodOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; if (ImageConversionFormat(access.image).type == SpirvFormatComponentType::Unorm) { ctx.Fail(access.inst, "queries the level of detail of a converted unorm image, which is not implemented"); } if (ImageConversionFormat(access.image).type == SpirvFormatComponentType::Float) { ctx.Fail(access.inst, "queries the level of detail of a converted float image, which is not implemented"); } state.module.EmitCapability(spv::CapabilityImageQuery); const auto sampled = MakeSampledImage(state, access.mem.resource, access.mem.sampler); const auto coord = CoordF32(ctx, access, 0, RdnaImageDimensionInfoFor(access.image.dimension).spatialComponents, AddressDimension(access).spatialComponents); const auto lod = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQueryLod, TypeF32Vector(state, 2), lod, sampled, coord); std::uint32_t values[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; for (std::uint32_t index = 0; index < 2u; index++) { const auto component = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeF32(state), component, lod, index); values[index] = F32BitsToU32(ctx, component); } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, values[0], values[1], values[2], values[3]); ctx.Define(access.inst, result); } void EmitByReadOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto elements = access.mem.imageByElements; const bool packed = access.mem.imagePacked; const auto components = packed ? 1u : access.mem.dataDwords / elements; if (access.image.dimension != RdnaImageDimension::Dim2D || components == 0u || (packed ? access.mem.dataDwords != 1u : components * elements != access.mem.dataDwords) || access.mem.dataBits != 32u) { ctx.Fail(access.inst, "is a MIMG BY2/BY4 load outside the measured 2D, 32-bit data subset"); } state.module.EmitCapability(spv::CapabilityImageQuery); const auto condition = ctx.Arg(access.inst, 2); ctx.Define(access.inst, EmitValueOrDefaultIfCondition(state, condition, TypeU32Vector(state, 4), ConstantU32CompositeZero(state, 4), [&]() { const auto image = LoadSampledImageDescriptor(state, access.mem.resource); const auto x = AddressU32(ctx, access, 0); const auto y = AddressU32(ctx, access, 1); const auto lod = LodU32(ctx, access); const auto levels = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQueryLevels, TypeU32(state), levels, image); const auto lodInside = Binary(state, spv::OpULessThan, TypeBool(state), lod, levels); const auto queryLod = Select(state, TypeU32(state), lodInside, lod, ConstantU32(state, 0)); const auto size = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, access.image.dimension), size, image, ConstantU32(state, 0)); const auto levelExtent = [&](std::uint32_t axis) { const auto base = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), base, size, axis); const auto shifted = Binary(state, spv::OpShiftRightLogical, TypeU32(state), base, queryLod); return Select(state, TypeU32(state), Binary(state, spv::OpUGreaterThan, TypeBool(state), shifted, ConstantU32(state, 1)), shifted, ConstantU32(state, 1)); }; const auto width = levelExtent(0u); const auto height = levelExtent(1u); auto inside = Binary(state, spv::OpLogicalAnd, TypeBool(state), lodInside, Binary(state, spv::OpULessThan, TypeBool(state), x, width)); inside = Binary(state, spv::OpLogicalAnd, TypeBool(state), inside, Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), Binary(state, spv::OpISub, TypeU32(state), width, x), ConstantU32(state, elements))); inside = Binary(state, spv::OpLogicalAnd, TypeBool(state), inside, Binary(state, spv::OpULessThan, TypeBool(state), y, height)); const auto first = Select(state, TypeU32(state), inside, Binary(state, spv::OpBitwiseAnd, TypeU32(state), x, ConstantU32(state, ~(elements - 1u))), ConstantU32(state, 0)); const auto row = Select(state, TypeU32(state), inside, y, ConstantU32(state, 0)); MemoryInfo texelMemory = access.mem; texelMemory.dmask = (1u << components) - 1u; texelMemory.dataDwords = components; texelMemory.componentCount = components; const ImageEmitAccess texelAccess{access.inst, texelMemory, access.image, access.address}; std::uint32_t words[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; for (std::uint32_t element = 0; element < elements; ++element) { const auto column = Binary(state, spv::OpIAdd, TypeU32(state), first, ConstantU32(state, element)); const auto coord = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 2), coord, column, row); const auto color = state.module.AllocateId(); state.module.AddFunction(spv::OpImageFetch, ImageVectorType(state, access.image.numericClass, 4), color, image, coord, spv::ImageOperandsLodMask, queryLod); if (packed) { const auto info = PackedTexelFormat(ctx, access); std::uint32_t texelBits = 0; for (std::uint32_t component = 0; component < info.componentCount; ++component) texelBits += info.componentBits[component]; if (texelBits * elements > 32u) ctx.Fail(access.inst, "is a MIMG PCK2/PCK4 load whose elements do not fit one dword"); const auto raw = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), raw, PackedImageTexel(ctx, access, color), 0u); const auto bits = Binary(state, spv::OpBitwiseAnd, TypeU32(state), raw, ConstantU32(state, texelBits == 32u ? 0xffffffffu : (1u << texelBits) - 1u)); const auto shifted = element == 0u ? bits : Binary(state, spv::OpShiftLeftLogical, TypeU32(state), bits, ConstantU32(state, element * texelBits)); words[0] = Binary(state, spv::OpBitwiseOr, TypeU32(state), words[0], Select(state, TypeU32(state), inside, shifted, ConstantU32(state, 0))); continue; } const auto texel = LoadedTexelResult(ctx, texelAccess, color, access.image.numericClass); for (std::uint32_t component = 0; component < components; ++component) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), value, texel, component); words[element * components + component] = Select(state, TypeU32(state), inside, value, ConstantU32(state, 0)); } } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, words[0], words[1], words[2], words[3]); return result; })); } struct StorageReadAlias { std::uint32_t image = NoTable; std::vector modes; }; StorageReadAlias StorageReadAliasFor(SpirvEmitterState& state, const ImageEmitAccess& access) { if (state.registrationModules || access.mem.imagePacked || access.mem.imageHasMip || access.mem.imageDimension != access.image.dimension || access.image.table != NoTable) return {}; if (std::ranges::find(state.supportedCapabilities, static_cast(spv::CapabilityStorageImageReadWithoutFormat)) == state.supportedCapabilities.end()) return {}; const auto& info = state.program.Info(); StorageReadAlias alias; alias.image = ResourceMaterializer::StorageReadImage(info, access.mem.resource); if (alias.image == NoTable || alias.image >= info.runtimeImageModes.size()) return {}; const auto& modes = info.runtimeImageModes[alias.image]; for (std::uint32_t index = 0u; index < modes.size(); ++index) { if (ResourceMaterializer::StorageReadCandidate(modes[index], access.image)) alias.modes.push_back(index); } return alias; } std::uint32_t StorageReadTexel(SpirvEmitterState& state, std::uint32_t image, const ImageResource& mode, std::uint32_t coord, IrTextureNumericClass numericClass) { const auto* sampled = state.runtimeImage; state.runtimeImage = &mode; const auto pointer = StorageImageDescriptorPointer(state, image); state.runtimeImage = sampled; state.module.EmitCapability(spv::CapabilityStorageImageReadWithoutFormat); const auto descriptor = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, ImageType(state, mode), descriptor, pointer); const auto raw = state.module.AllocateId(); state.module.AddFunction(spv::OpImageRead, ImageVectorType(state, mode.numericClass, 4), raw, descriptor, coord); if (mode.conversionFormat == IrBufferFormat::Invalid || GetImageFormatInfo(mode.conversionFormat).packedBitfield) return raw; const auto format = GetFormatInfo(mode.conversionFormat); const bool sint = numericClass == IrTextureNumericClass::Sint; const auto scalar = sint ? TypeI32(state) : TypeF32(state); std::array components{}; for (std::uint32_t component = 0u; component < 4u; ++component) { if (component >= format.componentCount) { components[component] = sint ? ConstantI32(state, component == 3u ? 1 : 0) : ConstantF32Value(state, component == 3u ? 1.0f : 0.0f); continue; } const auto word = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), word, raw, component); if (sint) { const auto shift = ConstantU32(state, 32u - format.componentBits[component]); const auto value = Unary(state, spv::OpBitcast, scalar, word); components[component] = format.componentBits[component] >= 32u ? value : Binary(state, spv::OpShiftRightArithmetic, scalar, Binary(state, spv::OpShiftLeftLogical, scalar, value, shift), shift); continue; } const auto pair = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, TypeF32Vector(state, 2u), pair, GlslStd450(state), GLSLstd450UnpackHalf2x16, word); const auto unpacked = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, scalar, unpacked, pair, 0u); const auto u32 = TypeU32(state); const auto special = Binary(state, spv::OpIEqual, TypeBool(state), Binary(state, spv::OpBitwiseAnd, u32, word, ConstantU32(state, 0x7c00u)), ConstantU32(state, 0x7c00u)); const auto sign = Binary(state, spv::OpShiftLeftLogical, u32, Binary(state, spv::OpBitwiseAnd, u32, word, ConstantU32(state, 0x8000u)), ConstantU32(state, 16u)); const auto mantissa = Binary(state, spv::OpShiftLeftLogical, u32, Binary(state, spv::OpBitwiseAnd, u32, word, ConstantU32(state, 0x3ffu)), ConstantU32(state, 13u)); const auto exact = Binary(state, spv::OpBitwiseOr, u32, Binary(state, spv::OpBitwiseOr, u32, sign, ConstantU32(state, 0x7f800000u)), mantissa); components[component] = Unary(state, spv::OpBitcast, scalar, Select(state, u32, special, exact, Unary(state, spv::OpBitcast, u32, unpacked))); } const auto texel = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, ImageVectorType(state, numericClass, 4), texel, components[0], components[1], components[2], components[3]); return texel; } void EmitReadOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { if (access.mem.imageByElements != 0u) { EmitByReadOp(ctx, access); return; } auto& state = ctx.state; const auto& dimensionInfo = RdnaImageDimensionInfoFor(access.image.dimension); const auto numericClass = access.image.numericClass; auto condition = ctx.Arg(access.inst, 2); if (access.mem.imageDimension == RdnaImageDimension::Dim3D && (access.image.dimension == RdnaImageDimension::Dim2D || access.image.dimension == RdnaImageDimension::Dim1D)) { condition = Binary(state, spv::OpLogicalAnd, TypeBool(state), condition, Binary(state, spv::OpIEqual, TypeBool(state), AddressU32(ctx, access, 2u), ConstantU32(state, 0u))); } const bool layeredAddress = access.mem.imageDimension == RdnaImageDimension::Dim1DArray || access.mem.imageDimension == RdnaImageDimension::Dim2DArray; if (layeredAddress && !GcnGuestShaders() && !access.image.layerRows && (access.image.dimension == RdnaImageDimension::Dim2D || access.image.dimension == RdnaImageDimension::Dim1D)) { const auto layer = AddressU32(ctx, access, AddressDimension(access).coordinateComponents - 1u); condition = Binary(state, spv::OpLogicalAnd, TypeBool(state), condition, Binary(state, spv::OpIEqual, TypeBool(state), layer, ConstantU32(state, 0u))); } if (VolumeSliceAddress(access)) { condition = Binary(state, spv::OpLogicalAnd, TypeBool(state), condition, VolumeSliceInRange(ctx, access, LoadSampledImageDescriptor(state, access.mem.resource), LodU32(ctx, access))); } ctx.Define(access.inst, EmitValueOrDefaultIfCondition(state, condition, TypeU32Vector(state, 4), ConstantU32CompositeZero(state, 4), [&]() { const auto descriptor = LoadSampledImageDescriptor(state, access.mem.resource); const auto color = state.module.AllocateId(); const auto coord = CoordU32(ctx, access); if (dimensionInfo.multisampled != 0u) { const auto& addressInfo = AddressDimension(access); if (addressInfo.multisampled == 0u || access.mem.imageAddressComponents <= addressInfo.coordinateComponents) { ctx.Fail(access.inst, "has no sample index in the image address"); } state.module.AddFunction(spv::OpImageFetch, ImageVectorType(state, numericClass, 4), color, descriptor, coord, spv::ImageOperandsSampleMask, AddressU32(ctx, access, addressInfo.coordinateComponents)); } else { state.module.AddFunction(spv::OpImageFetch, ImageVectorType(state, numericClass, 4), color, descriptor, coord, spv::ImageOperandsLodMask, LodU32(ctx, access)); } if (access.mem.imagePacked) { return PackedImageTexel(ctx, access, color); } const auto alias = dimensionInfo.multisampled == 0u ? StorageReadAliasFor(state, access) : StorageReadAlias{}; if (alias.modes.empty()) return LoadedTexelResult(ctx, access, color, numericClass); const auto vector = ImageVectorType(state, numericClass, 4); const auto selector = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::StorageReadBase + access.mem.resource, 0u); const auto& modes = state.program.Info().runtimeImageModes[alias.image]; auto texel = color; for (const auto mode : alias.modes) { const auto chosen = Binary(state, spv::OpIEqual, TypeBool(state), selector, ConstantU32(state, mode + 1u)); texel = EmitValueOrDefaultIfCondition(state, chosen, vector, texel, [&]() { return StorageReadTexel(state, alias.image, modes[mode], coord, numericClass); }); } return LoadedTexelResult(ctx, access, texel, numericClass); })); } std::uint32_t ImageSampleIndex(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { if (RdnaImageDimensionInfoFor(access.image.dimension).multisampled == 0u) return ConstantU32(ctx.state, 0u); const auto& addressInfo = AddressDimension(access); if (addressInfo.multisampled == 0u || access.mem.imageAddressComponents <= addressInfo.coordinateComponents) ctx.Fail(access.inst, "has no sample index in the image address"); return AddressU32(ctx, access, addressInfo.coordinateComponents); } std::array StoreQuantizeWordValues(SpirvEmitterState& state, std::uint32_t resource) { const auto u32 = TypeU32(state); std::array words{}; if (!state.registrationModules) { const auto first = PipelineSpecialization::StoreQuantizeBase + resource * PipelineSpecialization::StoreQuantizeWords; for (std::uint32_t index = 0; index < words.size(); ++index) words[index] = state.module.SpecializationConstant(u32, first + index, 0u); return words; } words.fill(ConstantU32(state, 0u)); const auto& image = state.program.Info().images.at(resource); if (image.resourceClass != ImageResourceClass::Storage || !image.written || image.atomic) return words; const auto code = EmitAndConstant(state, Binary(state, spv::OpShiftRightLogical, u32, RuntimeImageDword(state, resource, offsetof(RuntimeAbi::ResourceMetadata, descriptor) / sizeof(std::uint32_t) + 1u), ConstantU32(state, 20u)), 0x1ffu); const auto unquantized = StoreQuantizeValues(0u); for (std::uint32_t index = 0; index < words.size(); ++index) words[index] = ConstantU32(state, unquantized[index]); for (std::uint32_t value = 0; value <= 0x1ffu; ++value) { const auto values = StoreQuantizeValues(value); if (values[0] == 0u) continue; const auto match = Binary(state, spv::OpIEqual, TypeBool(state), code, ConstantU32(state, value)); for (std::uint32_t index = 0; index < words.size(); ++index) words[index] = Select(state, u32, match, ConstantU32(state, values[index]), words[index]); } return words; } std::uint32_t QuantizeStoreTexel(SpirvEmitterState& state, std::uint32_t resource, std::uint32_t texel) { const auto words = StoreQuantizeWordValues(state, resource); const auto f32 = TypeF32(state); const auto vec4 = TypeF32Vector(state, 4u); const auto bvec4 = state.module.Type(spv::OpTypeVector, TypeBool(state), 4u); const auto splat = [&](std::uint32_t type, std::uint32_t scalar) { const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, type, result, scalar, scalar, scalar, scalar); return result; }; const auto word = [&](std::uint32_t index) { return words.at(index); }; const auto enabled = Binary(state, spv::OpINotEqual, TypeBool(state), word(0u), ConstantU32(state, 0u)); const auto scale = splat(vec4, Unary(state, spv::OpBitcast, f32, word(1u))); const auto reciprocal = splat(vec4, Unary(state, spv::OpBitcast, f32, word(2u))); const auto snorm = Binary(state, spv::OpINotEqual, TypeBool(state), word(3u), ConstantU32(state, 0u)); const auto lower = splat(vec4, Select(state, f32, snorm, ConstantF32(state, std::bit_cast(-1.0f)), ConstantF32(state, 0u))); const auto zero = splat(vec4, ConstantF32(state, 0u)); const auto one = splat(vec4, ConstantF32(state, std::bit_cast(1.0f))); const auto finite = state.module.AllocateId(); state.module.AddFunction(spv::OpSelect, vec4, finite, Unary(state, spv::OpIsNan, bvec4, texel), zero, texel); const auto clamped = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, vec4, clamped, GlslStd450(state), GLSLstd450FClamp, finite, lower, one); const auto product = Binary(state, spv::OpFMul, vec4, clamped, scale); state.module.AddAnnotation(spv::OpDecorate, product, spv::DecorationNoContraction); const auto ext = [&](GLSLstd450 op, const auto&... operands) { const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, vec4, result, GlslStd450(state), static_cast(op), operands...); return result; }; const auto exact = [&](spv::Op opcode, std::uint32_t lhs, std::uint32_t rhs) { const auto value = Binary(state, opcode, vec4, lhs, rhs); state.module.AddAnnotation(spv::OpDecorate, value, spv::DecorationNoContraction); return value; }; const auto spreadFactor = splat(vec4, ConstantF32(state, std::bit_cast(4097.0f))); const auto high = [&](std::uint32_t value) { const auto spread = exact(spv::OpFMul, value, spreadFactor); return exact(spv::OpFSub, spread, exact(spv::OpFSub, spread, value)); }; const auto clampedHigh = high(clamped); const auto scaleHigh = high(scale); const auto clampedLow = exact(spv::OpFSub, clamped, clampedHigh); const auto scaleLow = exact(spv::OpFSub, scale, scaleHigh); auto error = exact(spv::OpFSub, exact(spv::OpFMul, clampedHigh, scaleHigh), product); error = exact(spv::OpFAdd, error, exact(spv::OpFMul, clampedHigh, scaleLow)); error = exact(spv::OpFAdd, error, exact(spv::OpFMul, clampedLow, scaleHigh)); error = exact(spv::OpFAdd, error, exact(spv::OpFMul, clampedLow, scaleLow)); const auto below = ext(GLSLstd450Floor, product); const auto fraction = Binary(state, spv::OpFSub, vec4, product, below); state.module.AddAnnotation(spv::OpDecorate, fraction, spv::DecorationNoContraction); const auto tie = Binary(state, spv::OpFOrdEqual, bvec4, fraction, splat(vec4, ConstantF32(state, std::bit_cast(0.5f)))); const auto above = Binary(state, spv::OpFAdd, vec4, below, one); const auto even = ext(GLSLstd450RoundEven, product); const auto broken = Select(state, vec4, Binary(state, spv::OpFOrdGreaterThan, bvec4, error, zero), above, Select(state, vec4, Binary(state, spv::OpFOrdLessThan, bvec4, error, zero), below, even)); const auto level = Select(state, vec4, tie, broken, even); const auto quantized = Binary(state, spv::OpFMul, vec4, level, reciprocal); const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpSelect, vec4, result, splat(bvec4, enabled), quantized, texel); return result; } void EmitPackedByStoreOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto elements = access.mem.imageByElements; if (access.image.dimension != RdnaImageDimension::Dim2D || access.mem.dataDwords != 1u || access.mem.dmask != 1u || access.mem.dataBits != 32u) { ctx.Fail(access.inst, "is a MIMG PCK2/PCK4 store outside the measured 2D, one-dword subset"); } const auto info = PackedTexelFormat(ctx, access); std::uint32_t texelBits = 0; for (std::uint32_t component = 0; component < info.componentCount; ++component) texelBits += info.componentBits[component]; if (texelBits == 0u || texelBits % 8u != 0u || texelBits * elements > 32u) ctx.Fail(access.inst, "is a MIMG PCK2/PCK4 store whose elements do not fit one dword"); const auto groupTexels = 32u / texelBits; state.module.EmitCapability(spv::CapabilityImageQuery); EmitIfCondition(state, ctx.Arg(access.inst, 3), [&]() { const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, ImageType(state, access.image), image, StorageImageDescriptorPointer(state, access.mem.resource)); const auto x = AddressU32(ctx, access, 0); const auto y = AddressU32(ctx, access, 1); const auto lod = access.mem.imageHasMip ? LodU32(ctx, access) : ConstantU32(state, 0u); const auto shiftLod = Select(state, TypeU32(state), Binary(state, spv::OpUGreaterThan, TypeBool(state), lod, ConstantU32(state, 31u)), ConstantU32(state, 31u), lod); const auto size = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySize, ImageViewSizeType(state, access.image.dimension), size, image); const auto levelExtent = [&](std::uint32_t axis) { const auto base = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), base, size, axis); const auto shifted = Binary(state, spv::OpShiftRightLogical, TypeU32(state), base, shiftLod); return Select(state, TypeU32(state), Binary(state, spv::OpUGreaterThan, TypeBool(state), shifted, ConstantU32(state, 1)), shifted, ConstantU32(state, 1)); }; const auto width = levelExtent(0u); const auto height = levelExtent(1u); auto inside = Binary(state, spv::OpLogicalAnd, TypeBool(state), Binary(state, spv::OpULessThan, TypeBool(state), x, width), Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), Binary(state, spv::OpISub, TypeU32(state), width, x), ConstantU32(state, elements))); inside = Binary(state, spv::OpLogicalAnd, TypeBool(state), inside, Binary(state, spv::OpULessThan, TypeBool(state), y, height)); const auto lane = Binary(state, spv::OpBitwiseAnd, TypeU32(state), x, ConstantU32(state, groupTexels - 1u)); const auto word = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), word, ctx.Arg(access.inst, 2), 0u); const auto mipLod = access.image.mipMode == ImageMipMode::DynamicStorage ? lod : 0u; for (std::uint32_t element = 0; element < elements; ++element) { const auto enabled = Binary(state, spv::OpLogicalAnd, TypeBool(state), inside, Binary(state, spv::OpULessThan, TypeBool(state), Binary(state, spv::OpIAdd, TypeU32(state), lane, ConstantU32(state, element)), ConstantU32(state, groupTexels))); EmitIfCondition(state, enabled, [&]() { const auto coord = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 2), coord, Binary(state, spv::OpIAdd, TypeU32(state), x, ConstantU32(state, element)), y); const auto shifted = element == 0u ? word : Binary(state, spv::OpShiftRightLogical, TypeU32(state), word, ConstantU32(state, element * texelBits)); const auto bits = Binary(state, spv::OpBitwiseAnd, TypeU32(state), shifted, ConstantU32(state, (1u << texelBits) - 1u)); const auto source = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), source, bits, ConstantU32(state, 0u), ConstantU32(state, 0u), ConstantU32(state, 0u)); EmitStorageImageWrite(state, access.mem.resource, mipLod, coord, PackedStoreTexel(ctx, access, source), ImageSampleIndex(ctx, access)); }); } }); } void EmitWriteOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { if (access.mem.imagePacked && access.mem.imageByElements != 0u) { EmitPackedByStoreOp(ctx, access); return; } auto& state = ctx.state; const bool uintImage = access.image.numericClass == IrTextureNumericClass::Uint; auto condition = ctx.Arg(access.inst, 3); if ((access.mem.imageDimension == RdnaImageDimension::Dim2DArray && access.image.dimension == RdnaImageDimension::Dim1D) || (access.mem.imageDimension == RdnaImageDimension::Dim3D && access.image.dimension == RdnaImageDimension::Dim2D)) { condition = Binary(state, spv::OpLogicalAnd, TypeBool(state), condition, Binary(state, spv::OpIEqual, TypeBool(state), AddressU32(ctx, access, 2u), ConstantU32(state, 0u))); } const bool layeredAddress = access.mem.imageDimension == RdnaImageDimension::Dim1DArray || access.mem.imageDimension == RdnaImageDimension::Dim2DArray; if (layeredAddress && !GcnGuestShaders() && !access.image.layerRows && (access.image.dimension == RdnaImageDimension::Dim2D || (access.image.dimension == RdnaImageDimension::Dim1D && access.mem.imageDimension == RdnaImageDimension::Dim1DArray))) { const auto layer = AddressU32(ctx, access, AddressDimension(access).coordinateComponents - 1u); condition = Binary(state, spv::OpLogicalAnd, TypeBool(state), condition, Binary(state, spv::OpIEqual, TypeBool(state), layer, ConstantU32(state, 0u))); } if (VolumeSliceAddress(access) || ArraySliceAddress(access)) { if (access.image.mipMode == ImageMipMode::DynamicStorage) ctx.Fail(access.inst, "stores a 2D-array address to a 3D image or a 3D address to a 2D-array image with dynamic mips, which is not implemented"); const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, ImageType(state, access.image), image, StorageImageDescriptorPointer(state, access.mem.resource)); condition = Binary(state, spv::OpLogicalAnd, TypeBool(state), condition, VolumeSliceInRange(ctx, access, image, std::nullopt)); } EmitIfCondition(state, condition, [&]() { const auto mipLod = access.image.mipMode == ImageMipMode::DynamicStorage ? LodU32(ctx, access) : 0u; const auto coord = CoordU32(ctx, access); auto texel = access.mem.imagePacked ? PackedStoreTexel(ctx, access, ctx.Arg(access.inst, 2)) : StoreTexel(ctx, access, ctx.Arg(access.inst, 2), uintImage); if (!uintImage && !access.mem.imagePacked && !access.image.atomic && access.image.table == NoTable && access.image.conversionFormat == IrBufferFormat::Invalid) texel = QuantizeStoreTexel(state, access.mem.resource, texel); EmitStorageImageWrite(state, access.mem.resource, mipLod, coord, texel, ImageSampleIndex(ctx, access)); }); } std::uint32_t ImageTexelLockIndex(SpirvEmitterState& state, std::uint32_t coord, std::uint32_t components) { constexpr std::array factors{0x9e3779b1u, 0x85ebca77u, 0xc2b2ae3du}; std::uint32_t hash = ConstantU32(state, 0u); for (std::uint32_t component = 0; component < components; ++component) { auto value = coord; if (components > 1u) { value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), value, coord, component); } hash = Binary(state, spv::OpBitwiseXor, TypeU32(state), hash, Binary(state, spv::OpIMul, TypeU32(state), value, ConstantU32(state, factors[component]))); } return Binary(state, spv::OpBitwiseXor, TypeU32(state), hash, Binary(state, spv::OpShiftRightLogical, TypeU32(state), hash, ConstantU32(state, 16u))); } std::uint32_t ImageAtomicNextScalar64(SpirvEmitterState& state, IrOpcode opcode, std::uint32_t current, std::uint32_t data, std::uint32_t comparator) { const auto u64 = TypeScalarU64(state); const auto constant = [&](std::uint32_t low) { return state.module.Constant(spv::OpConstant, u64, low, 0u); }; const auto pick = [&](spv::Op compare) { return Select(state, u64, Binary(state, compare, TypeBool(state), data, current), data, current); }; std::uint32_t next = 0; switch (opcode) { case IrOpcode::ImageAtomicSwap64: next = data; break; case IrOpcode::ImageAtomicCmpSwap64: next = Select(state, u64, Binary(state, spv::OpIEqual, TypeBool(state), current, comparator), data, current); break; case IrOpcode::ImageAtomicIAdd64: next = Binary(state, spv::OpIAdd, u64, current, data); break; case IrOpcode::ImageAtomicISub64: next = Binary(state, spv::OpISub, u64, current, data); break; case IrOpcode::ImageAtomicSMin64: next = pick(spv::OpSLessThan); break; case IrOpcode::ImageAtomicUMin64: next = pick(spv::OpULessThan); break; case IrOpcode::ImageAtomicSMax64: next = pick(spv::OpSGreaterThan); break; case IrOpcode::ImageAtomicUMax64: next = pick(spv::OpUGreaterThan); break; case IrOpcode::ImageAtomicAnd64: next = Binary(state, spv::OpBitwiseAnd, u64, current, data); break; case IrOpcode::ImageAtomicOr64: next = Binary(state, spv::OpBitwiseOr, u64, current, data); break; case IrOpcode::ImageAtomicXor64: next = Binary(state, spv::OpBitwiseXor, u64, current, data); break; case IrOpcode::ImageAtomicInc64: next = Select(state, u64, Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), current, data), constant(0u), Binary(state, spv::OpIAdd, u64, current, constant(1u))); break; case IrOpcode::ImageAtomicDec64: next = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, u64, next, GlslStd450(state), GLSLstd450UMin, Binary(state, spv::OpISub, u64, current, constant(1u)), data); break; default: throw std::runtime_error("opcode is not a 64-bit image atomic"); } return next; } std::uint32_t ImageAtomicNext64(SpirvEmitterState& state, IrOpcode opcode, std::uint32_t old, std::uint32_t value, std::uint32_t comparator) { const auto u64 = TypeScalarU64(state); const auto scalarComparator = opcode == IrOpcode::ImageAtomicCmpSwap64 ? Unary(state, spv::OpBitcast, u64, comparator) : 0u; return Unary(state, spv::OpBitcast, TypeU64(state), ImageAtomicNextScalar64(state, opcode, Unary(state, spv::OpBitcast, u64, old), Unary(state, spv::OpBitcast, u64, value), scalarComparator)); } std::uint32_t LockedImageAtomic64(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto opcode = access.inst.Opcode(); if (RdnaImageDimensionInfoFor(access.image.dimension).multisampled != 0u) ctx.Fail(access.inst, "is a 64-bit atomic on a multisampled image, which is not implemented"); const auto coord = CoordU32(ctx, access); const auto value = ctx.Arg(access.inst, 2); const auto comparator = opcode == IrOpcode::ImageAtomicCmpSwap64 ? ctx.Arg(access.inst, 3) : 0u; const auto lock = EmitAtomicLockPointer(state, ImageTexelLockIndex(state, coord, RdnaImageDimensionInfoFor(access.image.dimension).coordinateComponents)); return LockedDeviceUpdate(state, lock, TypeU64(state), ConstantU64(state, 0u), [&]() { const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, ImageType(state, access.image), image, StorageImageDescriptorPointer(state, access.mem.resource)); if (access.image.table != NoTable) DecorateTableNonUniform(state, image); const auto texel = state.module.AllocateId(); state.module.AddFunction(spv::OpImageRead, TypeU32Vector(state, 4), texel, image, coord); const auto old = state.module.AllocateId(); state.module.AddFunction(spv::OpVectorShuffle, TypeU64(state), old, texel, texel, 0u, 1u); auto next = ImageAtomicNext64(state, opcode, old, value, comparator); if (opcode == IrOpcode::ImageAtomicSwap64) { const auto held = state.module.AllocateId(); state.module.AddFunction(spv::OpAtomicLoad, TypeU32(state), held, lock, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone)); const auto zero = Binary(state, spv::OpISub, TypeU32(state), held, ConstantU32(state, 1u)); const auto mask = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU64(state), mask, zero, zero); next = Binary(state, spv::OpBitwiseOr, TypeU64(state), next, Binary(state, spv::OpBitwiseAnd, TypeU64(state), old, mask)); } const auto stored = state.module.AllocateId(); state.module.AddFunction(spv::OpVectorShuffle, TypeU32Vector(state, 4), stored, next, next, 0u, 1u, 0u, 1u); state.module.AddFunction(spv::OpImageWrite, image, coord, stored); return old; }); } void EmitAtomicOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto opcode = access.inst.Opcode(); auto condition = ctx.Arg(access.inst, access.inst.ArgumentCount() - 1u); const bool layeredAddress = access.mem.imageDimension == RdnaImageDimension::Dim1DArray || access.mem.imageDimension == RdnaImageDimension::Dim2DArray; if (layeredAddress && !GcnGuestShaders() && !access.image.layerRows && (access.image.dimension == RdnaImageDimension::Dim2D || access.image.dimension == RdnaImageDimension::Dim1D)) { const auto layer = AddressU32(ctx, access, AddressDimension(access).coordinateComponents - 1u); condition = Binary(state, spv::OpLogicalAnd, TypeBool(state), condition, Binary(state, spv::OpIEqual, TypeBool(state), layer, ConstantU32(state, 0u))); } if (IsImageAtomic64Opcode(opcode) && state.requirements.imageAtomicLocks) { ctx.Define(access.inst, EmitValueOrDefaultIfCondition(state, condition, TypeU64(state), ConstantU64(state, 0u), [&]() { return LockedImageAtomic64(ctx, access); })); return; } if (IsImageAtomic64Opcode(opcode)) { ctx.Define(access.inst, EmitValueOrDefaultIfCondition(state, condition, TypeU64(state), ConstantU64(state, 0u), [&]() { const auto scalar = TypeScalarU64(state); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpImageTexelPointer, TypePointer(state, spv::StorageClassImage, scalar), pointer, StorageImageDescriptorPointer(state, access.mem.resource), CoordU32(ctx, access), ConstantU32(state, 0)); const auto value = Unary(state, spv::OpBitcast, scalar, ctx.Arg(access.inst, 2)); if (opcode == IrOpcode::ImageAtomicInc64 || opcode == IrOpcode::ImageAtomicDec64) { const auto updated = AtomicUpdateTyped(state, pointer, ResourceKind::Image, scalar, [&](std::uint32_t current) { return ImageAtomicNextScalar64(state, opcode, current, value, 0u); }); return Unary(state, spv::OpBitcast, TypeU64(state), updated); } const auto old = state.module.AllocateId(); EmitImageAtomicOrdering(state); if (opcode == IrOpcode::ImageAtomicCmpSwap64) { const auto comparator = Unary(state, spv::OpBitcast, scalar, ctx.Arg(access.inst, 3)); state.module.AddFunction(spv::OpAtomicCompareExchange, scalar, old, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone), ConstantU32(state, spv::MemorySemanticsMaskNone), value, comparator); } else { state.module.AddFunction(ImageAtomicOpcode(opcode), scalar, old, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone), value); } EmitDeviceAtomicMemoryBarrier(state); return Unary(state, spv::OpBitcast, TypeU64(state), old); })); return; } const auto value = ctx.Arg(access.inst, 2); ctx.Define(access.inst, EmitValueOrZeroIfCondition(state, condition, [&]() { const auto pointer = state.module.AllocateId(); const auto pointerType = TypePointer(state, spv::StorageClassImage, TypeU32(state)); state.module.AddFunction(spv::OpImageTexelPointer, pointerType, pointer, StorageImageDescriptorPointer(state, access.mem.resource), CoordU32(ctx, access), ImageSampleIndex(ctx, access)); if (opcode == IrOpcode::ImageAtomicInc32 || opcode == IrOpcode::ImageAtomicDec32) { return AtomicUpdate(state, pointer, ResourceKind::Image, [&](std::uint32_t current) { return opcode == IrOpcode::ImageAtomicInc32 ? AtomicIncrement(state, current, value) : AtomicDecrement(state, current, value); }); } if (opcode == IrOpcode::ImageAtomicFMin32 || opcode == IrOpcode::ImageAtomicFMax32) { return AtomicUpdate(state, pointer, ResourceKind::Image, [&](std::uint32_t current) { return AtomicFloatMinMax(state, current, value, opcode == IrOpcode::ImageAtomicFMax32, access.mem.flushDenormals); }); } if (opcode == IrOpcode::ImageAtomicFCmpSwap32) { const auto comparator = ctx.Arg(access.inst, 3); return AtomicUpdate(state, pointer, ResourceKind::Image, [&](std::uint32_t current) { return AtomicFloatCompareSwap(state, current, value, comparator, access.mem.flushDenormals); }); } EmitImageAtomicOrdering(state); const auto old = state.module.AllocateId(); if (opcode == IrOpcode::ImageAtomicCmpSwap32) { state.module.AddFunction(spv::OpAtomicCompareExchange, TypeU32(state), old, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone), ConstantU32(state, spv::MemorySemanticsMaskNone), value, ctx.Arg(access.inst, 3)); } else { state.module.AddFunction(ImageAtomicOpcode(opcode), TypeU32(state), old, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone), value); } EmitDeviceAtomicMemoryBarrier(state); return old; })); } SampleSetup MakeSampleSetup(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { const auto& dimensionInfo = RdnaImageDimensionInfoFor(access.image.dimension); auto layout = Layout(access.mem); if (access.image.cube) layout.offset = NoImageComponent; const bool dref = HasFlag(access.mem, RdnaImageSampleFlagCompare); if (dref && access.image.conversionFormat != IrBufferFormat::Invalid) { ctx.Fail(access.inst, "uses depth comparison with a packed integer image"); } const bool filtered = !dref && access.inst.Opcode() == IrOpcode::ImageSampleRaw; if (!filtered && ImageConversionFormat(access.image).type == SpirvFormatComponentType::Unorm) { ctx.Fail(access.inst, "samples or gathers a converted unorm image, which needs filtering in the shader and is not implemented"); } if (ImageConversionFormat(access.image).type == SpirvFormatComponentType::Float) { ctx.Fail(access.inst, "samples or gathers a converted float image, which needs filtering in the shader and is not implemented"); } auto coord = CoordF32(ctx, access, layout.coord, dimensionInfo.coordinateComponents, AddressDimension(access).coordinateComponents); if (access.image.layerRows) { if (dref || access.inst.Opcode() != IrOpcode::ImageSampleRaw || (access.mem.imageSampleFlags != RdnaImageSampleFlagLevelZero && access.mem.imageSampleFlags != RdnaImageSampleFlagLod)) ctx.Fail(access.inst, "reads a 1D array laid out as rows of a 2D image other than by image_sample_lz or image_sample_l"); coord = LayerRowsCoord(ctx, access, coord); } return {dimensionInfo, layout, access.image.numericClass, dref, coord}; } void EmitPackedHorizontalGatherOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto& mem = access.mem; const auto dimension = access.image.dimension; if (dimension != RdnaImageDimension::Dim1D && dimension != RdnaImageDimension::Dim2D) { ctx.Fail(access.inst, "is a packed horizontal gather of an image dimension whose row and slice rules are not measured"); } if (Layout(mem).clamp != NoImageComponent || HasFlag(mem, RdnaImageSampleFlagCompare)) { ctx.Fail(access.inst, "is a packed horizontal gather with depth comparison or an LOD clamp, which is not implemented"); } if (AddressDimension(access).coordinateComponents < RdnaImageDimensionInfoFor(dimension).coordinateComponents) { ctx.Fail(access.inst, "has an image address with too few coordinate components"); } const auto info = PackedTexelFormat(ctx, access); std::uint32_t texelBits = 0; for (std::uint32_t component = 0; component < info.componentCount; component++) { texelBits += info.componentBits[component]; } std::uint32_t streamWords[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; std::uint32_t rowInside = 0; const bool twoDimensional = dimension == RdnaImageDimension::Dim2D; if (texelBits <= 32u) { state.module.EmitCapability(spv::CapabilityImageQuery); const auto image = LoadSampledImageDescriptor(state, mem.resource); const auto size = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySizeLod, twoDimensional ? TypeI32Vector(state, 2) : TypeI32(state), size, image, ConstantU32(state, 0)); const auto extent = [&](std::uint32_t axis) { if (!twoDimensional) { return size; } const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeI32(state), value, size, axis); return value; }; const auto texelFloor = [&](std::uint32_t address, std::uint32_t length, bool centre) { const auto addressF32 = AddressF32(ctx, access, address); const auto lengthF32 = Unary(state, spv::OpConvertSToF, TypeF32(state), length); std::uint32_t scaled = 0; if (state.fusedExactArithmetic) { scaled = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, TypeF32(state), scaled, GlslStd450(state), GLSLstd450Fma, addressF32, lengthF32, ConstantF32(state, 0x80000000u)); state.module.AddAnnotation(spv::OpDecorate, scaled, spv::DecorationNoContraction); } else { scaled = Binary(state, spv::OpFMul, TypeF32(state), addressF32, lengthF32); state.module.AddAnnotation(spv::OpDecorate, scaled, spv::DecorationNoContraction); } if (centre) { scaled = Binary(state, spv::OpFSub, TypeF32(state), scaled, ConstantF32(state, 0x3f000000u)); } const auto floored = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, TypeF32(state), floored, GlslStd450(state), GLSLstd450Floor, scaled); return Unary(state, spv::OpConvertFToS, TypeI32(state), floored); }; const auto clampInto = [&](std::uint32_t value, std::uint32_t length) { const auto last = Binary(state, spv::OpISub, TypeI32(state), length, ConstantI32(state, 1)); const auto low = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), value, ConstantI32(state, 0)), ConstantI32(state, 0), value); return Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), last, low), last, low); }; const auto width = extent(0u); const auto anchor = texelFloor(0u, width, true); std::uint32_t row = 0; if (twoDimensional) { const auto height = extent(1u); const auto rawRow = texelFloor(1u, height, false); rowInside = Binary(state, spv::OpSLessThan, TypeBool(state), rawRow, height); row = clampInto(rawRow, height); } for (std::uint32_t element = 0; element < 4u; element++) { const auto column = clampInto(Binary(state, spv::OpIAdd, TypeI32(state), anchor, ConstantI32(state, static_cast(element) - 1)), width); std::uint32_t coord = column; if (twoDimensional) { coord = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeI32Vector(state, 2), coord, column, row); } const auto color = state.module.AllocateId(); state.module.AddFunction(spv::OpImageFetch, ImageVectorType(state, access.image.numericClass, 4), color, image, coord, spv::ImageOperandsLodMask, ConstantI32(state, 0)); const auto packed = PackedImageTexel(ctx, access, color); const auto bits = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), bits, packed, 0u); const auto position = element * texelBits; const auto word = position / 32u; const auto shift = position % 32u; streamWords[word] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[word], shift == 0u ? bits : Binary(state, spv::OpShiftLeftLogical, TypeU32(state), bits, ConstantU32(state, shift))); if (shift != 0u && shift + texelBits > 32u) { streamWords[word + 1u] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[word + 1u], Binary(state, spv::OpShiftRightLogical, TypeU32(state), bits, ConstantU32(state, 32u - shift))); } } } std::uint32_t selected[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; std::uint32_t next = 0; for (std::uint32_t bit = 0; bit < 4u; bit++) { if (((mem.dmask >> bit) & 1u) == 0u) { continue; } if (texelBits <= 32u) { selected[next] = rowInside != 0u ? Select(state, TypeU32(state), rowInside, streamWords[bit], ConstantU32(state, 0)) : streamWords[bit]; } next++; } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, selected[0], selected[1], selected[2], selected[3]); ctx.Define(access.inst, result); } void EmitEmulatedSample(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup, bool converted, bool gather); void EmitGatherOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup) { auto& state = ctx.state; const auto& mem = access.mem; const auto dimension = access.image.dimension; if (setup.layout.clamp != NoImageComponent) { ctx.Fail(access.inst, "is a gather with an LOD clamp, which is not implemented"); } if (setup.dref && (access.image.emulatedCompare & EmulatedCompare::Enabled) != 0u) { if (HasFlag(mem, RdnaImageSampleFlagGatherHorizontal)) ctx.Fail(access.inst, "is a horizontal comparison gather of a color texture, which is not implemented"); EmitEmulatedSample(ctx, access, setup, false, true); return; } if (dimension == RdnaImageDimension::Dim1D || dimension == RdnaImageDimension::Dim1DArray || access.image.remappedDepth1D) { if (setup.dref || !HasFlag(mem, RdnaImageSampleFlagLevelZero) || HasFlag(mem, RdnaImageSampleFlagGatherHorizontal) || access.image.remappedDepth1D) { ctx.Fail(access.inst, "has an unsupported 1D gather variant"); } const auto sample = EmitOneDimensionalGatherLz(ctx, access, setup); ctx.Define(access.inst, ResultVector(ctx, access, UnpackImageGather(ctx, access, sample), setup.numericClass, false, true)); return; } if (dimension == RdnaImageDimension::Dim3D) { if (setup.dref || !HasFlag(mem, RdnaImageSampleFlagLevelZero) || HasFlag(mem, RdnaImageSampleFlagGatherHorizontal) || setup.layout.offset != NoImageComponent) { ctx.Fail(access.inst, "has an unsupported 3D gather variant"); } const auto sample = EmitVolumeGatherLz(ctx, access, setup); ctx.Define(access.inst, ResultVector(ctx, access, UnpackImageGather(ctx, access, sample), setup.numericClass, false, true)); return; } const auto sampled = MakeSampledImage(state, mem.resource, mem.sampler); const auto sample = state.module.AllocateId(); std::vector words; if (setup.dref) { const auto drefValue = DrefValueF32(ctx, access, setup.layout); words = {spv::OpImageDrefGather, TypeF32Vector(state, 4), sample, sampled, setup.coord, drefValue}; } else { std::uint32_t component = 0; if (ImageConversionFormat(access.image).format == IrBufferFormat::Invalid) { component = ImageGatherComponent(EffectiveDmask(mem)); } words = {spv::OpImageGather, ImageVectorType(state, setup.numericClass, 4), sample, sampled, setup.coord, ConstantU32(state, component)}; } if (HasFlag(mem, RdnaImageSampleFlagGatherHorizontal)) { words.push_back(spv::ImageOperandsConstOffsetsMask); words.push_back(HorizontalOffsets(ctx, access)); } else if (setup.layout.offset != NoImageComponent) { words.push_back(spv::ImageOperandsOffsetMask); words.push_back(PackedOffset(ctx, access, setup.layout)); } state.module.AddFunction(words); auto resultNumericClass = setup.numericClass; if (setup.dref) { resultNumericClass = IrTextureNumericClass::Float; } // Debug aid: APS5_GATHER_CONST= makes every non-depth gather return that integer (or its // float value) in all four texels, to separate a wrong gather result from wrong math after it. static const char* gatherConstText = std::getenv("APS5_GATHER_CONST"); auto gathered = sample; if (gatherConstText != nullptr && !setup.dref) { const auto value = static_cast(std::strtoul(gatherConstText, nullptr, 0)); const bool integer = resultNumericClass == IrTextureNumericClass::Uint || resultNumericClass == IrTextureNumericClass::Sint; const auto component = resultNumericClass == IrTextureNumericClass::Sint ? ConstantI32(state, std::bit_cast(value)) : integer ? ConstantU32(state, value) : ConstantF32(state, std::bit_cast(static_cast(value))); gathered = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, ImageVectorType(state, resultNumericClass, 4), gathered, component, component, component, component); } if (HasFlag(mem, RdnaImageSampleFlagLod) && setup.layout.lod != NoImageComponent && !setup.dref && dimension == RdnaImageDimension::Dim2D && !access.image.cube && !access.image.remappedDepth1D && setup.layout.offset == NoImageComponent && !HasFlag(mem, RdnaImageSampleFlagGatherHorizontal) && state.program.Info().images.at(mem.resource).table == NoTable && state.program.Info().samplers.at(mem.sampler).table == NoTable) { const auto fetched = EmitTwoDimensionalGatherLod(ctx, access, setup); const auto supported = GatherLodSupported(state, mem.sampler); const auto scalarType = ImageScalarType(state, resultNumericClass); std::uint32_t lanes[4] = {}; for (std::uint32_t lane = 0; lane < 4u; lane++) { const auto fromFetch = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, scalarType, fromFetch, fetched, lane); const auto fromGather = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, scalarType, fromGather, gathered, lane); lanes[lane] = Select(state, scalarType, supported, fromFetch, fromGather); } gathered = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, ImageVectorType(state, resultNumericClass, 4), gathered, lanes[0], lanes[1], lanes[2], lanes[3]); } ctx.Define(access.inst, ResultVector(ctx, access, UnpackImageGather(ctx, access, gathered), resultNumericClass, false, true)); } void EmitEmulatedSample(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup, bool converted, bool gather) { auto& state = ctx.state; const auto& mem = access.mem; const auto& image = access.image; const auto compare = state.registrationModules ? EmitAndConstant(state, Binary(state, spv::OpShiftRightLogical, TypeU32(state), RuntimeImageDword(state, mem.resource, offsetof(RuntimeAbi::ResourceMetadata, flags) / sizeof(std::uint32_t)), ConstantU32(state, RuntimeAbi::CompareStateShift)), RuntimeAbi::CompareStateMask) : 0u; const auto parameter = [&](std::uint32_t word) { if (!state.registrationModules) return state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::CompareBase + mem.resource * PipelineSpecialization::CompareWords + word, 0u); constexpr std::array, 6> fields{{{EmulatedCompare::FunctionShift, 7u}, {4u, 1u}, {EmulatedCompare::ClampXShift, 3u}, {EmulatedCompare::ClampYShift, 3u}, {EmulatedCompare::ReferenceShift, 3u}, {12u, 1u}}}; return EmitAndConstant(state, Binary(state, spv::OpShiftRightLogical, TypeU32(state), compare, ConstantU32(state, fields.at(word).first)), fields.at(word).second); }; const auto equal = [&](std::uint32_t value, std::uint32_t literal) { return Binary(state, spv::OpIEqual, TypeBool(state), value, ConstantU32(state, literal)); }; if (!converted && (HasFlag(mem, RdnaImageSampleFlagDerivative) || HasFlag(mem, RdnaImageSampleFlagLod))) ctx.Fail(access.inst, "compares against a color texture with gradients or an explicit LOD, which is not implemented"); const bool arrayed = image.dimension == RdnaImageDimension::Dim2DArray; if (image.dimension != RdnaImageDimension::Dim2D && !arrayed) ctx.Fail(access.inst, converted ? "samples a converted image that is not a 2D or 2D array view, which is not implemented" : "compares against a color texture that is not a 2D or 2D array view, which is not implemented"); const auto f32 = TypeF32(state); const auto i32 = TypeI32(state); const auto u32 = TypeU32(state); const auto ext = [&](std::uint32_t type, std::uint32_t op, std::initializer_list args) { const auto value = state.module.AllocateId(); std::array words{spv::OpExtInst, type, value, GlslStd450(state), op}; std::copy(args.begin(), args.end(), words.begin() + 5); state.module.AddFunction(std::span(words.data(), 5u + args.size())); return value; }; const auto extract = [&](std::uint32_t type, std::uint32_t composite, std::uint32_t index) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, type, value, composite, index); return value; }; const auto f32Constant = [&](float value) { return ConstantF32(state, std::bit_cast(value)); }; const auto descriptor = LoadSampledImageDescriptor(state, mem.resource); state.module.EmitCapability(spv::CapabilityImageQuery); const auto size = state.module.AllocateId(); state.module.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, image.dimension), size, descriptor, ConstantU32(state, 0u)); const auto width = Unary(state, spv::OpBitcast, i32, extract(u32, size, 0u)); const auto height = Unary(state, spv::OpBitcast, i32, extract(u32, size, 1u)); auto layer = ConstantU32(state, 0u); if (arrayed) { const auto layers = Unary(state, spv::OpBitcast, i32, extract(u32, size, 2u)); const auto rounded = Unary(state, spv::OpConvertFToS, i32, ext(f32, GLSLstd450RoundEven, {extract(f32, setup.coord, 2u)})); layer = Unary(state, spv::OpBitcast, u32, ext(i32, GLSLstd450SClamp, {rounded, ConstantI32(state, 0), Binary(state, spv::OpISub, i32, layers, ConstantI32(state, 1))})); } auto reference = converted ? 0u : DrefValueF32(ctx, access, setup.layout); if (!converted) { reference = Select(state, f32, equal(parameter(4u), EmulatedCompare::ReferenceUnorm), ext(f32, GLSLstd450FClamp, {reference, f32Constant(0.0f), f32Constant(1.0f)}), reference); reference = Select(state, f32, equal(parameter(4u), EmulatedCompare::ReferenceSnorm), ext(f32, GLSLstd450FClamp, {reference, f32Constant(-1.0f), f32Constant(1.0f)}), reference); } const auto address = [&](std::uint32_t index, std::uint32_t extent, std::uint32_t mode) { const auto remainder = Binary(state, spv::OpSRem, i32, index, extent); const auto negative = Binary(state, spv::OpSLessThan, TypeBool(state), remainder, ConstantI32(state, 0)); const auto correction = Select(state, i32, negative, extent, ConstantI32(state, 0)); const auto wrapped = Binary(state, spv::OpIAdd, i32, remainder, correction); const auto clamped = ext(i32, GLSLstd450SClamp, {index, ConstantI32(state, 0), Binary(state, spv::OpISub, i32, extent, ConstantI32(state, 1))}); return Select(state, i32, equal(mode, EmulatedCompare::AddressWrap), wrapped, clamped); }; const auto inside = [&](std::uint32_t index, std::uint32_t extent) { const auto notBelow = Binary(state, spv::OpSGreaterThanEqual, TypeBool(state), index, ConstantI32(state, 0)); const auto below = Binary(state, spv::OpSLessThan, TypeBool(state), index, extent); return Binary(state, spv::OpLogicalAnd, TypeBool(state), notBelow, below); }; const auto one = f32Constant(1.0f); const auto zero = f32Constant(0.0f); const auto borderRed = Select(state, f32, equal(parameter(5u), 1u), one, zero); const auto compareTexel = [&](std::uint32_t x, std::uint32_t y) -> std::array { const auto modeX = parameter(2u); const auto modeY = parameter(3u); const auto ux = Unary(state, spv::OpBitcast, u32, address(x, width, modeX)); const auto uy = Unary(state, spv::OpBitcast, u32, address(y, height, modeY)); const auto coord = state.module.AllocateId(); if (arrayed) state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 3), coord, ux, uy, layer); else state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 2), coord, ux, uy); if (converted) { const auto raw = state.module.AllocateId(); state.module.AddFunction(spv::OpImageFetch, ImageVectorType(state, IrTextureNumericClass::Uint, 4), raw, descriptor, coord, spv::ImageOperandsLodMask, ConstantU32(state, 0u)); const auto unpacked = UnpackImageTexel(ctx, access, raw); std::array channels{}; for (std::uint32_t channel = 0; channel < 4u; ++channel) channels[channel] = Unary(state, spv::OpBitcast, f32, extract(u32, unpacked, channel)); return channels; } const auto texel = state.module.AllocateId(); state.module.AddFunction(spv::OpImageFetch, ImageVectorType(state, IrTextureNumericClass::Float, 4), texel, descriptor, coord, spv::ImageOperandsLodMask, ConstantU32(state, 0u)); auto red = extract(f32, texel, 3u); for (std::uint32_t channel = 3u; channel-- > 0u;) red = Select(state, f32, equal(RuntimeImageSwizzle(state, mem.resource, channel), 4u), extract(f32, texel, channel), red); red = Select(state, f32, equal(modeX, EmulatedCompare::AddressBorder), Select(state, f32, inside(x, width), red, borderRed), red); red = Select(state, f32, equal(modeY, EmulatedCompare::AddressBorder), Select(state, f32, inside(y, height), red, borderRed), red); constexpr std::array operations{spv::OpFOrdLessThan, spv::OpFOrdEqual, spv::OpFOrdLessThanEqual, spv::OpFOrdGreaterThan, spv::OpFUnordNotEqual, spv::OpFOrdGreaterThanEqual}; auto result = Select(state, f32, equal(parameter(0u), 7u), one, zero); for (std::uint32_t index = 0; index < operations.size(); ++index) { const auto compared = Select(state, f32, Binary(state, operations[index], TypeBool(state), reference, red), one, zero); result = Select(state, f32, equal(parameter(0u), index + 1u), compared, result); } result = Select(state, f32, equal(parameter(4u), EmulatedCompare::ReferenceZero), zero, result); return {result, result, result, result}; }; const auto scaledU = Binary(state, spv::OpFMul, f32, extract(f32, setup.coord, 0u), Unary(state, spv::OpConvertSToF, f32, width)); const auto scaledV = Binary(state, spv::OpFMul, f32, extract(f32, setup.coord, 1u), Unary(state, spv::OpConvertSToF, f32, height)); auto offsetX = ConstantI32(state, 0); auto offsetY = ConstantI32(state, 0); if (setup.layout.offset != NoImageComponent) { const auto offset = PackedOffset(ctx, access, setup.layout); offsetX = extract(i32, offset, 0u); offsetY = extract(i32, offset, 1u); } const auto texelIndex = [&](std::uint32_t coordinate, std::uint32_t offset) { return Binary(state, spv::OpIAdd, i32, Unary(state, spv::OpConvertFToS, i32, ext(f32, GLSLstd450Floor, {coordinate})), offset); }; const auto filteredType = converted ? TypeF32Vector(state, 4) : f32; const auto vector = [&](const std::array& channels) { if (!converted) return channels[0]; const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, filteredType, value, channels[0], channels[1], channels[2], channels[3]); return value; }; const auto mix = [&](std::uint32_t first, std::uint32_t second, std::uint32_t weight) { return ext(filteredType, GLSLstd450FMix, {first, second, vector({weight, weight, weight, weight})}); }; if (gather) { const auto half = f32Constant(0.5f); const auto x0 = Binary(state, spv::OpIAdd, i32, Unary(state, spv::OpConvertFToS, i32, ext(f32, GLSLstd450Floor, {Binary(state, spv::OpFSub, f32, scaledU, half)})), offsetX); const auto y0 = Binary(state, spv::OpIAdd, i32, Unary(state, spv::OpConvertFToS, i32, ext(f32, GLSLstd450Floor, {Binary(state, spv::OpFSub, f32, scaledV, half)})), offsetY); const auto x1 = Binary(state, spv::OpIAdd, i32, x0, ConstantI32(state, 1)); const auto y1 = Binary(state, spv::OpIAdd, i32, y0, ConstantI32(state, 1)); const auto gathered = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 4), gathered, compareTexel(x0, y1)[0], compareTexel(x1, y1)[0], compareTexel(x1, y0)[0], compareTexel(x0, y0)[0]); ctx.Define(access.inst, ResultVector(ctx, access, gathered, IrTextureNumericClass::Float, false, true)); return; } const auto filtered = EmitValueIfElse(state, equal(parameter(1u), 0u), filteredType, [&] { return vector(compareTexel(texelIndex(scaledU, offsetX), texelIndex(scaledV, offsetY))); }, [&] { const auto half = f32Constant(0.5f); const auto centreU = Binary(state, spv::OpFSub, f32, scaledU, half); const auto centreV = Binary(state, spv::OpFSub, f32, scaledV, half); const auto floorU = ext(f32, GLSLstd450Floor, {centreU}); const auto floorV = ext(f32, GLSLstd450Floor, {centreV}); const auto weight = [&](std::uint32_t centre, std::uint32_t floored) { const auto fraction = Binary(state, spv::OpFSub, f32, centre, floored); if (!converted) return fraction; const auto steps = ext(f32, GLSLstd450RoundEven, {Binary(state, spv::OpFMul, f32, fraction, f32Constant(256.0f))}); return Binary(state, spv::OpFMul, f32, steps, f32Constant(1.0f / 256.0f)); }; const auto weightU = weight(centreU, floorU); const auto weightV = weight(centreV, floorV); const auto x0 = Binary(state, spv::OpIAdd, i32, Unary(state, spv::OpConvertFToS, i32, floorU), offsetX); const auto y0 = Binary(state, spv::OpIAdd, i32, Unary(state, spv::OpConvertFToS, i32, floorV), offsetY); const auto x1 = Binary(state, spv::OpIAdd, i32, x0, ConstantI32(state, 1)); const auto y1 = Binary(state, spv::OpIAdd, i32, y0, ConstantI32(state, 1)); const auto topLeft = vector(compareTexel(x0, y0)); const auto topRight = vector(compareTexel(x1, y0)); const auto top = mix(topLeft, topRight, weightU); const auto bottomLeft = vector(compareTexel(x0, y1)); const auto bottomRight = vector(compareTexel(x1, y1)); const auto bottom = mix(bottomLeft, bottomRight, weightU); return mix(top, bottom, weightV); }); if (converted) { ctx.Define(access.inst, ResultVector(ctx, access, filtered, IrTextureNumericClass::Float, false, false)); return; } const auto result = filtered; const auto channelResult = [&](std::uint32_t channel) { const auto selector = RuntimeImageSwizzle(state, mem.resource, channel); return Select(state, f32, equal(selector, 0u), zero, Select(state, f32, equal(selector, 1u), one, result)); }; std::uint32_t channels[4] = {}; for (std::uint32_t channel = 0; channel < 4u; ++channel) channels[channel] = channelResult(channel); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 4), value, channels[0], channels[1], channels[2], channels[3]); ctx.Define(access.inst, ResultVector(ctx, access, value, IrTextureNumericClass::Float, false, false)); } void EmitSampleOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup) { auto& state = ctx.state; const auto& mem = access.mem; const auto& image = access.image; if (setup.dref && (image.emulatedCompare & EmulatedCompare::Enabled) != 0u) { EmitEmulatedSample(ctx, access, setup, false, false); return; } if (!setup.dref && IsConvertedUnormTextureFormat(image.conversionFormat)) { EmitEmulatedSample(ctx, access, setup, true, false); return; } const bool explicitLod = ImageSampleExplicitLod(mem.imageSampleFlags, state.program.Resources().stage); std::uint32_t opcode = spv::OpImageSampleImplicitLod; if (explicitLod) { opcode = setup.dref ? spv::OpImageSampleDrefExplicitLod : spv::OpImageSampleExplicitLod; } else if (setup.dref) { opcode = spv::OpImageSampleDrefImplicitLod; } std::uint32_t resultType = ImageVectorType(state, setup.numericClass, 4); std::uint32_t drefValue = 0; if (setup.dref) { resultType = TypeF32(state); drefValue = DrefValueF32(ctx, access, setup.layout); } std::uint32_t operandMask = 0; std::vector operands; if (HasFlag(mem, RdnaImageSampleFlagDerivative)) { operandMask |= spv::ImageOperandsGradMask; operands.push_back(CoordF32(ctx, access, setup.layout.gradX, setup.dimensionInfo.spatialComponents, AddressDimension(access).spatialComponents, true)); operands.push_back(CoordF32(ctx, access, setup.layout.gradY, setup.dimensionInfo.spatialComponents, AddressDimension(access).spatialComponents, true)); } else if (explicitLod) { operandMask |= spv::ImageOperandsLodMask; operands.push_back(HasFlag(mem, RdnaImageSampleFlagLod) ? AddressF32(ctx, access, setup.layout.lod) : ZeroF32(state)); } else if (setup.layout.bias != NoImageComponent) { operandMask |= spv::ImageOperandsBiasMask; operands.push_back(AddressF32(ctx, access, setup.layout.bias)); } const auto unclampedLod = (operandMask & spv::ImageOperandsLodMask) != 0u ? operands.back() : 0u; std::uint32_t lodClamp = 0; std::uint32_t lodViewClamp = 0; const auto fmax = [&](std::uint32_t left, std::uint32_t right) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, TypeF32(state), value, GlslStd450(state), GLSLstd450FMax, left, right); return value; }; const auto clampLod = [&](std::uint32_t lod) { if (lodClamp != 0u) lod = fmax(lod, lodClamp); if (lodViewClamp != 0u) lod = Select(state, TypeF32(state), Binary(state, spv::OpFOrdGreaterThan, TypeBool(state), lodViewClamp, ZeroF32(state)), fmax(lod, lodViewClamp), lod); return lod; }; const bool descriptorClamp = state.shaderImageMinLod && state.program.Info().images.at(mem.resource).table == NoTable; if (descriptorClamp && state.registrationModules) ctx.Fail(access.inst, "applies its T#'s minimum LOD clamp in the shader, which registration modules do not implement"); if (setup.layout.clamp != NoImageComponent || descriptorClamp) { const auto& capabilities = state.supportedCapabilities; if (std::find(capabilities.begin(), capabilities.end(), static_cast(spv::CapabilityMinLod)) == capabilities.end()) ctx.Fail(access.inst, "clamps its LOD, which needs the device's shaderResourceMinLod"); lodClamp = setup.layout.clamp != NoImageComponent ? AddressF32(ctx, access, setup.layout.clamp) : 0u; lodViewClamp = descriptorClamp ? Unary(state, spv::OpBitcast, TypeF32(state), state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::MinLodBase + mem.resource, 0u)) : 0u; if ((operandMask & spv::ImageOperandsLodMask) != 0u) { operands.back() = clampLod(operands.back()); } else { state.module.EmitCapability(spv::CapabilityMinLod); operandMask |= spv::ImageOperandsMinLodMask; operands.push_back(lodClamp == 0u ? lodViewClamp : lodViewClamp == 0u ? lodClamp : fmax(lodClamp, lodViewClamp)); } } const auto constantOffset = [&]() -> const IrValue* { const auto component = GetRdnaImageAddressComponentLayout(mem.imageSampleFlags, setup.layout.offset); const auto argument = component.bitOffset / 32u; if (component.bitWidth != 32u || argument >= access.address.ArgumentCount()) return nullptr; const auto* value = access.address.Argument(argument)->Resolve(); return value->HasImmediate() ? value : nullptr; }; const bool hasOffset = setup.layout.offset != NoImageComponent; const bool foldOffset = hasOffset && FoldsTexelOffsets(state.program.Info().samplers.at(mem.sampler)) && ResourceMaterializer::UnnormalizedSampleMismatch(image) == nullptr; const auto foldedMask = operandMask; const auto foldedOperands = operands; const bool gatherExtended = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), static_cast(spv::CapabilityImageGatherExtended)) != state.supportedCapabilities.end(); const bool offsetOperand = hasOffset && (constantOffset() != nullptr || (state.nonConstantImageOffsets && gatherExtended)); if (hasOffset && !offsetOperand && !foldOffset) { ctx.Fail(access.inst, "has a texel offset that is not a constant, which image sampling takes only with VK_KHR_maintenance8 and shaderImageGatherExtended"); } if (offsetOperand && constantOffset() == nullptr) { state.module.EmitCapability(spv::CapabilityImageGatherExtended); operandMask |= spv::ImageOperandsOffsetMask; operands.insert(operands.end() - ((operandMask & spv::ImageOperandsMinLodMask) != 0u ? 1 : 0), PackedOffset(ctx, access, setup.layout)); } else if (offsetOperand) { const auto bits = constantOffset()->ImmediateU32(); std::array values{}; for (std::uint32_t index = 0; index < setup.dimensionInfo.spatialComponents; index++) { const auto field = (bits >> (index * 8u)) & 0x3fu; values[index] = ConstantI32(state, static_cast(field ^ 0x20u) - 0x20); } if (access.image.remappedDepth1D && setup.dimensionInfo.spatialComponents >= 2u) { values[1] = ConstantI32(state, 0); } const auto count = setup.dimensionInfo.spatialComponents; const auto offset = count == 1u ? values[0] : count == 2u ? state.module.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), values[0], values[1]) : state.module.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), values[0], values[1], values[2]); operandMask |= spv::ImageOperandsConstOffsetMask; operands.insert(operands.end() - ((operandMask & spv::ImageOperandsMinLodMask) != 0u ? 1 : 0), offset); } const auto emitDirectSample = [&](std::uint32_t coord, std::uint32_t mask, const std::vector& arguments, std::uint32_t sampleOpcode) { const auto sampled = MakeSampledImage(state, mem.resource, mem.sampler); const auto sample = state.module.AllocateId(); std::vector words = {sampleOpcode, resultType, sample, sampled, coord}; if (setup.dref) { words.push_back(drefValue); } if (mask != 0u) { words.push_back(mask); words.insert(words.end(), arguments.begin(), arguments.end()); } state.module.AddFunction(words); return sample; }; const bool mirrors = MirrorsSampleIfUnnormalized(ctx, access, setup); const auto emitSample = [&](std::uint32_t coord, std::uint32_t mask, const std::vector& arguments, std::uint32_t sampleOpcode) { if (!mirrors) return emitDirectSample(coord, mask, arguments, sampleOpcode); const auto axes = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::MirrorUnnormalizedBase + mem.sampler, 0u); const auto mirrored = Binary(state, spv::OpINotEqual, TypeBool(state), axes, ConstantU32(state, 0u)); return EmitValueIfElse(state, mirrored, resultType, [&] { return emitDirectSample(MirroredUnnormalizedCoord(ctx, setup, coord, axes), mask, arguments, sampleOpcode); }, [&] { return emitDirectSample(coord, mask, arguments, sampleOpcode); }); }; const auto emitBiasedSample = [&](std::uint32_t coord, std::uint32_t mask, const std::vector& arguments, std::uint32_t sampleOpcode) { if (!AppliesLodBiasInShader(state.program.Info().samplers.at(mem.sampler))) return emitSample(coord, mask, arguments, sampleOpcode); const auto f32 = TypeF32(state); const auto selector = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::SamplerLodBiasBase + mem.sampler, 0u); const auto beyondLimit = Binary(state, spv::OpINotEqual, TypeBool(state), selector, ConstantU32(state, 0u)); return EmitValueIfElse(state, beyondLimit, resultType, [&] { const auto bias = Unary(state, spv::OpBitcast, f32, selector); auto biased = arguments; if ((mask & spv::ImageOperandsLodMask) != 0u) { biased.front() = clampLod(Binary(state, spv::OpFAdd, f32, unclampedLod, bias)); return emitSample(coord, mask, biased, sampleOpcode); } auto gradMask = mask; auto total = bias; if ((mask & spv::ImageOperandsBiasMask) != 0u) { total = Binary(state, spv::OpFAdd, f32, total, biased.front()); biased.erase(biased.begin()); gradMask &= ~static_cast(spv::ImageOperandsBiasMask); } const auto components = setup.dimensionInfo.spatialComponents; const auto gradientType = components == 1u ? f32 : TypeF32Vector(state, components); if ((mask & spv::ImageOperandsGradMask) == 0u) { const auto spatial = CoordF32(ctx, access, setup.layout.coord, components, AddressDimension(access).spatialComponents); biased.insert(biased.begin(), {Unary(state, spv::OpDPdx, gradientType, spatial), Unary(state, spv::OpDPdy, gradientType, spatial)}); gradMask |= spv::ImageOperandsGradMask; } const auto scale = state.module.AllocateId(); state.module.AddFunction(spv::OpExtInst, f32, scale, GlslStd450(state), GLSLstd450Pow, ConstantF32(state, 0x40000000u), total); for (std::size_t index = 0; index < 2u; ++index) { biased[index] = Binary(state, components == 1u ? spv::OpFMul : spv::OpVectorTimesScalar, gradientType, biased[index], scale); } return emitSample(coord, gradMask, biased, setup.dref ? spv::OpImageSampleDrefExplicitLod : spv::OpImageSampleExplicitLod); }, [&] { return emitSample(coord, mask, arguments, sampleOpcode); }); }; std::uint32_t sample = 0; const bool alreadyBaseLevel = !hasOffset && opcode == spv::OpImageSampleExplicitLod && operandMask == spv::ImageOperandsLodMask && !HasFlag(mem, RdnaImageSampleFlagLod) && setup.layout.clamp == NoImageComponent; const bool baseLevelIfUnnormalized = !setup.dref && !alreadyBaseLevel && SamplesBaseLevelIfUnnormalized(state.program.Info().samplers.at(mem.sampler)); if (baseLevelIfUnnormalized) { const auto selector = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::UnnormalizedBaseLevelBase + mem.sampler, 0u); const auto unnormalized = Binary(state, spv::OpINotEqual, TypeBool(state), selector, ConstantU32(state, 0u)); sample = EmitValueIfElse(state, unnormalized, resultType, [&] { return emitSample(hasOffset ? FoldedOffsetCoord(ctx, access, setup) : setup.coord, spv::ImageOperandsLodMask, {ZeroF32(state)}, spv::OpImageSampleExplicitLod); }, [&] { return emitBiasedSample(setup.coord, operandMask, operands, opcode); }); } else if (!foldOffset) { sample = emitBiasedSample(setup.coord, operandMask, operands, opcode); } else if (!offsetOperand) { sample = emitBiasedSample(FoldedOffsetCoord(ctx, access, setup), foldedMask, foldedOperands, opcode); } else { const auto selector = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::FoldOffsetBase + mem.sampler, 0u); const auto folded = Binary(state, spv::OpINotEqual, TypeBool(state), selector, ConstantU32(state, 0u)); const auto foldLabel = state.module.AllocateId(); const auto operandLabel = state.module.AllocateId(); const auto merge = state.module.AllocateId(); state.module.AddFunction(spv::OpSelectionMerge, merge, spv::SelectionControlMaskNone); state.module.AddFunction(spv::OpBranchConditional, folded, foldLabel, operandLabel); EmitLabel(state, foldLabel); const auto foldSample = emitBiasedSample(FoldedOffsetCoord(ctx, access, setup), foldedMask, foldedOperands, opcode); const auto foldEnd = state.currentLabel; state.module.AddFunction(spv::OpBranch, merge); EmitLabel(state, operandLabel); const auto operandSample = emitBiasedSample(setup.coord, operandMask, operands, opcode); const auto operandEnd = state.currentLabel; state.module.AddFunction(spv::OpBranch, merge); EmitLabel(state, merge); sample = state.module.AllocateId(); state.module.AddFunction(spv::OpPhi, resultType, sample, foldSample, foldEnd, operandSample, operandEnd); } const auto result = setup.dref ? sample : UnpackImageTexel(ctx, access, sample); ctx.Define(access.inst, ResultVector(ctx, access, result, setup.numericClass, setup.dref, false)); } void EmitConstantSwizzleSample(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto numericClass = access.image.numericClass; const bool gather = access.inst.Opcode() == IrOpcode::ImageGatherRaw; const auto scalarType = ImageScalarType(state, numericClass); const auto one = numericClass == IrTextureNumericClass::Float ? ConstantF32(state, 0x3f800000u) : numericClass == IrTextureNumericClass::Sint ? ConstantI32(state, 1) : ConstantU32(state, 1u); const auto zero = SampledComponentZero(state, numericClass); std::uint32_t channels[4] = {}; for (std::uint32_t channel = 0; channel < 4u; channel++) { const auto selector = RuntimeImageSwizzle(state, access.mem.resource, gather ? ImageGatherComponent(EffectiveDmask(access.mem)) : channel); channels[channel] = Select(state, scalarType, Binary(state, spv::OpIEqual, TypeBool(state), selector, ConstantU32(state, 1u)), one, zero); } const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, ImageVectorType(state, numericClass, 4), value, channels[0], channels[1], channels[2], channels[3]); ctx.Define(access.inst, ResultVector(ctx, access, value, numericClass, false, gather)); } void EmitSamplingOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { if (access.image.constantSwizzle) { EmitConstantSwizzleSample(ctx, access); return; } if (access.image.srgbDecode) { ctx.Fail(access.inst, "samples or gathers an sRGB image the device cannot sample, which is not implemented"); } if (access.mem.imagePacked) { EmitPackedHorizontalGatherOp(ctx, access); return; } const auto setup = MakeSampleSetup(ctx, access); if (access.inst.Opcode() == IrOpcode::ImageGatherRaw) { EmitGatherOp(ctx, access, setup); } else { EmitSampleOp(ctx, access, setup); } } constexpr std::uint32_t InvalidTableSelector = 0xffffffffu; struct ScalarBufferDword { std::uint32_t byte = 0; std::uint32_t inRange = 0; }; ScalarBufferDword EmitScalarBufferDword(SpirvEmitterState& state, std::uint32_t offset, std::uint32_t immediate, std::uint32_t sizeLow, std::uint32_t sizeHigh) { const auto u32 = TypeU32(state); const auto boolean = TypeBool(state); const auto sum = state.module.AllocateId(); state.module.AddFunction(spv::OpIAddCarry, TypeU32Pair(state), sum, offset, immediate); const auto address = state.module.AllocateId(); const auto carry = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, address, sum, 0u); state.module.AddFunction(spv::OpCompositeExtract, u32, carry, sum, 1u); ScalarBufferDword dword; dword.byte = Binary(state, spv::OpBitwiseAnd, u32, address, ConstantU32(state, ~3u)); const auto below = Binary(state, spv::OpLogicalOr, boolean, Binary(state, spv::OpINotEqual, boolean, sizeHigh, ConstantU32(state, 0u)), Binary(state, spv::OpULessThan, boolean, dword.byte, Binary(state, spv::OpBitwiseAnd, u32, sizeLow, ConstantU32(state, ~3u)))); dword.inRange = Binary(state, spv::OpLogicalAnd, boolean, Binary(state, spv::OpIEqual, boolean, carry, ConstantU32(state, 0u)), below); return dword; } std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index) { const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.tableMapVariable, ConstantU32(state, 0u), index); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); return value; } std::uint32_t TableMapAt(SpirvEmitterState& state, std::uint32_t base, std::uint32_t offset) { return LoadTableMap(state, offset == 0u ? base : Binary(state, spv::OpIAdd, TypeU32(state), base, ConstantU32(state, offset))); } struct TableWord { std::uint32_t code = 0; std::uint32_t addressLow = 0; std::uint32_t addressHigh = 0; std::uint32_t poisoned = 0; }; TableWord LookupTableWord(SpirvEmitterState& state, const TableColumn& column, std::uint32_t offset, std::uint32_t header, bool dynamicHeader = false) { const auto u32 = TypeU32(state); const auto boolean = TypeBool(state); const auto field = [&](std::uint32_t index) { return dynamicHeader ? TableMapAt(state, header, index) : LoadTableMap(state, ConstantU32(state, header + index)); }; const auto mapStart = field(ImageTableAbi::TableMapStart); const auto keys = field(ImageTableAbi::TableKeyCount); const auto sizeLow = field(ImageTableAbi::TableSizeLow); const auto sizeHigh = field(ImageTableAbi::TableSizeHigh); const auto baseLow = field(ImageTableAbi::TableBaseLow); const auto baseHigh = field(ImageTableAbi::TableBaseHigh); const auto outsideCode = field(ImageTableAbi::TableOutsideCode); const auto tableFault = field(ImageTableAbi::TableFault); const auto relative = Binary(state, spv::OpISub, u32, offset, ConstantU32(state, column.addend)); const auto record = Binary(state, spv::OpUDiv, u32, relative, ConstantU32(state, column.stride)); const auto remainder = Binary(state, spv::OpISub, u32, relative, Binary(state, spv::OpIMul, u32, record, ConstantU32(state, column.stride))); const auto aligned = Binary(state, spv::OpIEqual, boolean, remainder, ConstantU32(state, 0u)); const auto inMap = Binary(state, spv::OpLogicalAnd, boolean, aligned, Binary(state, spv::OpULessThan, boolean, record, keys)); const auto mapped = LoadTableMap(state, Select(state, u32, inMap, Binary(state, spv::OpIAdd, u32, mapStart, record), ConstantU32(state, 0u))); if (column.address) { TableWord word; word.code = Select(state, u32, Binary(state, spv::OpINotEqual, boolean, tableFault, ConstantU32(state, 0u)), tableFault, Select(state, u32, inMap, mapped, ConstantU32(state, ImageTableAbi::PoisonCode(ImageTableAbi::OutsideSnapshotPoison)))); const auto immediate = column.offset & ~3u; const auto first = state.module.AllocateId(); state.module.AddFunction(spv::OpIAddCarry, TypeU32Pair(state), first, baseLow, Binary(state, spv::OpBitwiseAnd, u32, offset, ConstantU32(state, ~3u))); const auto firstLow = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, firstLow, first, 0u); const auto firstCarry = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, firstCarry, first, 1u); const auto second = state.module.AllocateId(); state.module.AddFunction(spv::OpIAddCarry, TypeU32Pair(state), second, firstLow, ConstantU32(state, immediate)); word.addressLow = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, word.addressLow, second, 0u); const auto secondCarry = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, secondCarry, second, 1u); const auto extension = ConstantU32(state, (immediate & 0x80000000u) != 0u ? 0xffffffffu : 0u); word.addressHigh = Binary(state, spv::OpIAdd, u32, Binary(state, spv::OpIAdd, u32, baseHigh, extension), Binary(state, spv::OpIAdd, u32, firstCarry, secondCarry)); word.poisoned = Binary(state, spv::OpINotEqual, boolean, Binary(state, spv::OpBitwiseAnd, u32, word.code, ConstantU32(state, ImageTableAbi::PoisonFlag)), ConstantU32(state, 0u)); return word; } const auto dword = EmitScalarBufferDword(state, offset, ConstantU32(state, column.offset), sizeLow, sizeHigh); const auto outside = Select(state, u32, dword.inRange, ConstantU32(state, ImageTableAbi::PoisonCode(ImageTableAbi::OutsideSnapshotPoison)), outsideCode); TableWord word; word.code = Select(state, u32, Binary(state, spv::OpINotEqual, boolean, tableFault, ConstantU32(state, 0u)), tableFault, Select(state, u32, inMap, mapped, outside)); const auto low = state.module.AllocateId(); state.module.AddFunction(spv::OpIAddCarry, TypeU32Pair(state), low, baseLow, dword.byte); const auto carry = state.module.AllocateId(); word.addressLow = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, word.addressLow, low, 0u); state.module.AddFunction(spv::OpCompositeExtract, u32, carry, low, 1u); word.addressHigh = Binary(state, spv::OpIAdd, u32, baseHigh, carry); word.poisoned = Binary(state, spv::OpINotEqual, boolean, Binary(state, spv::OpBitwiseAnd, u32, word.code, ConstantU32(state, ImageTableAbi::PoisonFlag)), ConstantU32(state, 0u)); return word; } TableWord LookupTablePointer(SpirvEmitterState& state, std::uint32_t pointerLow, std::uint32_t pointerHigh, std::uint32_t tableHeader) { const auto u32 = TypeU32(state); const auto boolean = TypeBool(state); const auto constant = [&](std::uint32_t value) { return ConstantU32(state, value); }; const auto field = [&](std::uint32_t offset) { return LoadTableMap(state, constant(tableHeader + offset)); }; const auto both = [&](std::uint32_t left, std::uint32_t right) { return Binary(state, spv::OpLogicalAnd, boolean, left, right); }; const auto mapStart = field(ImageTableAbi::TableMapStart); const auto storedCount = field(ImageTableAbi::TableKeyCount); const auto fault = field(ImageTableAbi::TableFault); const auto usable = both(Binary(state, spv::OpULessThanEqual, boolean, storedCount, constant(ImageTableAbi::MaxParentKeys)), Binary(state, spv::OpIEqual, boolean, fault, constant(0u))); const auto count = Select(state, u32, usable, storedCount, constant(0u)); const auto recordAt = [&](std::uint32_t index) { return Binary(state, spv::OpIAdd, u32, mapStart, Binary(state, spv::OpIMul, u32, index, constant(ImageTableAbi::PointerRecordWords))); }; const auto header = state.module.AllocateId(); const auto body = state.module.AllocateId(); const auto continuation = state.module.AllocateId(); const auto merge = state.module.AllocateId(); const auto entryLabel = state.currentLabel; const auto lower = state.module.AllocateId(); const auto upper = state.module.AllocateId(); const auto newLower = state.module.AllocateId(); const auto newUpper = state.module.AllocateId(); state.module.AddFunction(spv::OpBranch, header); EmitLabel(state, header); state.module.AddFunction(spv::OpPhi, u32, lower, constant(0u), entryLabel, newLower, continuation); state.module.AddFunction(spv::OpPhi, u32, upper, count, entryLabel, newUpper, continuation); const auto search = Binary(state, spv::OpULessThan, boolean, lower, upper); state.module.AddFunction(spv::OpLoopMerge, merge, continuation, spv::LoopControlMaskNone); state.module.AddFunction(spv::OpBranchConditional, search, body, merge); EmitLabel(state, body); const auto midpoint = Binary(state, spv::OpIAdd, u32, lower, Binary(state, spv::OpShiftRightLogical, u32, Binary(state, spv::OpISub, u32, upper, lower), constant(1u))); const auto record = recordAt(midpoint); const auto low = TableMapAt(state, record, 0u); const auto high = TableMapAt(state, record, 1u); const auto less = Binary(state, spv::OpLogicalOr, boolean, Binary(state, spv::OpULessThan, boolean, high, pointerHigh), both(Binary(state, spv::OpIEqual, boolean, high, pointerHigh), Binary(state, spv::OpULessThan, boolean, low, pointerLow))); state.module.AddFunction(spv::OpSelect, u32, newLower, less, Binary(state, spv::OpIAdd, u32, midpoint, constant(1u)), lower); state.module.AddFunction(spv::OpSelect, u32, newUpper, less, upper, midpoint); state.module.AddFunction(spv::OpBranch, continuation); EmitLabel(state, continuation); state.module.AddFunction(spv::OpBranch, header); EmitLabel(state, merge); const auto inBounds = Binary(state, spv::OpULessThan, boolean, lower, count); const auto selected = Select(state, u32, inBounds, recordAt(lower), constant(tableHeader)); const auto same = both(Binary(state, spv::OpIEqual, boolean, TableMapAt(state, selected, 0u), pointerLow), Binary(state, spv::OpIEqual, boolean, TableMapAt(state, selected, 1u), pointerHigh)); const auto nullPointer = both(Binary(state, spv::OpIEqual, boolean, pointerLow, constant(0u)), Binary(state, spv::OpIEqual, boolean, pointerHigh, constant(0u))); const auto missing = Select(state, u32, nullPointer, field(ImageTableAbi::TableOutsideCode), constant(ImageTableAbi::PoisonCode(ImageTableAbi::OutsideSnapshotPoison))); const auto code = Select(state, u32, both(inBounds, same), TableMapAt(state, selected, 2u), missing); TableWord word; word.code = Select(state, u32, Binary(state, spv::OpINotEqual, boolean, fault, constant(0u)), fault, code); word.addressLow = pointerLow; word.addressHigh = pointerHigh; word.poisoned = Binary(state, spv::OpINotEqual, boolean, Binary(state, spv::OpBitwiseAnd, u32, word.code, constant(ImageTableAbi::PoisonFlag)), constant(0u)); return word; } TableWord EmitTableWord(SpirvValueEmitContext& ctx, const IrValue& inst, std::uint32_t source, std::uint32_t table, std::size_t argument) { auto& state = ctx.state; const IrValue* handle = inst.Argument(argument)->Resolve(); const auto& sources = state.program.Resources().descriptorSources; if (handle->ArgumentCount() == 0u || source >= sources.size() || !sources[source].tableColumn.has_value()) ctx.Fail(inst, "has an image table handle without its column"); const auto& column = *sources[source].tableColumn; if (column.dynamic) ctx.Fail(inst, "reads a descriptor whose address is known only at run time outside the bindless heap"); const auto offset = ctx.Def(handle->Argument(0)); const auto header = ImageTableAbi::TableHeader(table); const auto& parent = sources.at(column.heapSource).tableColumn; if (!parent.has_value() && column.pointerKeyed) { if (!column.indirect || handle->ArgumentCount() < 3u) ctx.Fail(inst, "has a pointer-keyed image table without its pointer"); return LookupTablePointer(state, ctx.Def(handle->Argument(1)), ctx.Def(handle->Argument(2)), header); } if (!parent.has_value()) return LookupTableWord(state, column, offset, header); if (!parent->buffer || !parent->indirect || handle->ArgumentCount() < 3u) ctx.Fail(inst, "has a nested image table without its buffer pointer"); const auto root = LookupTablePointer(state, ctx.Def(handle->Argument(1)), ctx.Def(handle->Argument(2)), header); const auto u32 = TypeU32(state); const auto childHeader = Select(state, u32, root.poisoned, ConstantU32(state, header), root.code); auto word = LookupTableWord(state, column, offset, childHeader, true); word.code = Select(state, u32, root.poisoned, root.code, word.code); word.addressLow = Select(state, u32, root.poisoned, root.addressLow, word.addressLow); word.addressHigh = Select(state, u32, root.poisoned, root.addressHigh, word.addressHigh); word.poisoned = Binary(state, spv::OpLogicalOr, TypeBool(state), root.poisoned, word.poisoned); return word; } void EmitTableFault(SpirvValueEmitContext& ctx, const IrValue& inst, const TableWord& word, std::uint32_t poison, std::uint32_t condition) { auto& state = ctx.state; EmitIfCondition(state, condition, [&] { RecordBdaFaultWords(state, word.addressLow, word.addressHigh, Binary(state, spv::OpBitwiseAnd, TypeU32(state), poison, ConstantU32(state, ~ImageTableAbi::PoisonFlag)), ConstantU32(state, inst.Flags().pc), BdaAbi::FaultReason::ImageTable); }); } std::uint32_t ZeroResult(SpirvValueEmitContext& ctx, const IrValue& inst) { auto& state = ctx.state; switch (inst.Type()) { case IrType::U32: return ConstantU32(state, 0u); case IrType::U64: return ConstantU64(state, 0u); case IrType::U32x4: return ConstantU32CompositeZero(state, 4u); default: break; } ctx.Fail(inst, "has no zero result for an image table access"); } struct TableAccessResult { std::uint32_t valid = 0; std::uint32_t flags = 0; bool unsupported = false; }; TableAccessResult EmitTableAccess(SpirvValueEmitContext& ctx, const IrValue& inst, const MemoryInfo& memory, const ImageResource& base, bool tableSampler) { auto& state = ctx.state; if (state.tableMapVariable == 0 || state.faultBufferVariable == 0) ctx.Fail(inst, "reads an image table without its map or fault buffer"); const auto u32 = TypeU32(state); const auto boolean = TypeBool(state); const auto both = [&](std::uint32_t left, std::uint32_t right) { return Binary(state, spv::OpLogicalAnd, boolean, left, right); }; const auto negate = [&](std::uint32_t value) { return Unary(state, spv::OpLogicalNot, boolean, value); }; const auto flagged = [&](std::uint32_t value) { return Binary(state, spv::OpINotEqual, boolean, Binary(state, spv::OpBitwiseAnd, u32, value, ConstantU32(state, ImageTableAbi::PoisonFlag)), ConstantU32(state, 0u)); }; const auto exec = ctx.Arg(inst, inst.ArgumentCount() - 1u); TableAccessResult result; result.valid = ConstantBool(state, true); auto live = ConstantBool(state, true); state.tableAccess = {}; if (base.table != NoTable) { const auto word = EmitTableWord(ctx, inst, base.source, base.table, 0u); EmitTableFault(ctx, inst, word, word.code, both(exec, word.poisoned)); if (base.tableOperation == TableOperation::Unsupported || state.program.Info().runtimeImageModes.at(memory.resource).empty()) { if (inst.Type() != IrType::Void) ctx.Define(inst, ZeroResult(ctx, inst)); result.unsupported = true; return result; } const auto selected = both(Binary(state, spv::OpINotEqual, boolean, word.code, ConstantU32(state, ImageTableAbi::NullCode)), negate(word.poisoned)); const auto record = Select(state, u32, selected, word.code, ConstantU32(state, 0u)); const auto flags = TableMapAt(state, record, ImageTableAbi::ImageRecordFlags); const auto dword3 = TableMapAt(state, record, ImageTableAbi::ImageRecordDword3); const auto element = TableMapAt(state, record, ImageTableAbi::ImageRecordElement); const auto rejected = both(selected, flagged(flags)); EmitTableFault(ctx, inst, word, flags, both(exec, rejected)); const auto inBounds = Binary(state, spv::OpULessThan, boolean, element, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementCount))); const auto outside = both(both(selected, negate(rejected)), negate(inBounds)); EmitTableFault(ctx, inst, word, ConstantU32(state, ImageTableAbi::OutsideSnapshotPoison), both(exec, outside)); const auto checked = both(both(selected, negate(rejected)), inBounds); const auto faults = LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementFaults)); const auto driverFault = LoadTableMap(state, Select(state, u32, checked, Binary(state, spv::OpIAdd, u32, faults, element), ConstantU32(state, 0u))); const auto driverRejected = both(checked, flagged(driverFault)); EmitTableFault(ctx, inst, word, driverFault, both(exec, driverRejected)); result.valid = both(checked, negate(driverRejected)); result.flags = flags; live = selected; state.tableAccess.element = Binary(state, spv::OpIAdd, u32, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)), element); const auto& sources = state.program.Resources().descriptorSources; state.tableAccess.uniform = base.source < sources.size() && sources[base.source].tableColumn.has_value() && sources[base.source].tableColumn->selected; if (!state.tableAccess.uniform) DecorateTableNonUniform(state, state.tableAccess.element); state.tableAccess.dword3 = dword3; } if (tableSampler) { const auto& sampler = state.program.Info().samplers.at(memory.sampler); const auto word = EmitTableWord(ctx, inst, sampler.source, sampler.table, 1u); EmitTableFault(ctx, inst, word, word.code, both(both(exec, live), word.poisoned)); const auto selected = negate(word.poisoned); const auto record = Select(state, u32, selected, word.code, ConstantU32(state, 0u)); const auto flags = TableMapAt(state, record, ImageTableAbi::SamplerRecordFlags); const auto element = TableMapAt(state, record, ImageTableAbi::SamplerRecordElement); const auto rejected = both(selected, flagged(flags)); EmitTableFault(ctx, inst, word, flags, both(both(exec, live), rejected)); const auto end = Binary(state, spv::OpIAdd, u32, element, ConstantU32(state, ImageTableAbi::SamplerEntryElements)); const auto inBounds = Binary(state, spv::OpULessThanEqual, boolean, end, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderSamplerCount))); const auto outside = both(both(selected, negate(rejected)), negate(inBounds)); EmitTableFault(ctx, inst, word, ConstantU32(state, ImageTableAbi::OutsideSnapshotPoison), both(both(exec, live), outside)); const auto checked = both(both(selected, negate(rejected)), inBounds); const auto entry = Binary(state, spv::OpShiftRightLogical, u32, element, ConstantU32(state, 2u)); const auto driverFault = LoadTableMap(state, Select(state, u32, checked, Binary(state, spv::OpIAdd, u32, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderSamplerFaults)), entry), ConstantU32(state, 0u))); const auto driverRejected = both(checked, flagged(driverFault)); EmitTableFault(ctx, inst, word, driverFault, both(both(exec, live), driverRejected)); result.valid = both(result.valid, both(checked, negate(driverRejected))); state.tableAccess.samplerElement = element; DecorateTableNonUniform(state, state.tableAccess.samplerElement); } state.tableAccess.active = true; return result; } constexpr std::uint32_t BindlessOk = 0u; constexpr std::uint32_t BindlessNull = 1u; constexpr std::uint32_t BindlessMiss = 2u; constexpr std::uint32_t BindlessRefused = 3u; constexpr std::uint32_t BindlessSlow = 4u; constexpr std::uint32_t BindlessStatusShift = 24u; struct BindlessColumn { const TableColumn* column = nullptr; const IrValue* offset = nullptr; std::vector heap; }; BindlessColumn BindlessColumnOf(SpirvValueEmitContext& ctx, const IrValue& inst, std::uint32_t source, std::size_t argument, std::uint32_t width) { const auto& sources = ctx.state.program.Resources().descriptorSources; const IrValue* handle = inst.Argument(argument)->Resolve(); if (source >= sources.size() || !sources[source].tableColumn.has_value()) ctx.Fail(inst, "has a bindless table handle without its column"); const auto& column = *sources[source].tableColumn; if (column.heapSource >= sources.size()) ctx.Fail(inst, "has a bindless table column without its heap source"); const auto& kept = ctx.state.program.Metadata().bindlessHandleWords; const auto words = kept.find(handle); const auto heapWords = column.dynamic ? (column.address ? 2u : 4u) : sources[column.heapSource].dwordCount; if (handle->ArgumentCount() != width || words == kept.end() || words->second.size() != heapWords) ctx.Fail(inst, "has a bindless table handle without its local heap dwords"); BindlessColumn found{&column, handle->Argument(0), {}}; for (const auto* reference : words->second) found.heap.push_back(reference->Argument(0)); return found; } std::array BindlessDirectSampler(SpirvValueEmitContext& ctx, const IrValue& inst) { const IrValue* handle = inst.Argument(1)->Resolve(); const auto& kept = ctx.state.program.Metadata().bindlessHandleWords; const auto words = kept.find(handle); if (handle->Opcode() != IrOpcode::GetSamplerResource || words == kept.end() || words->second.size() != 4u) ctx.Fail(inst, "has a bindless direct sampler handle without its canonical S# dwords"); return {words->second[0]->Argument(0), words->second[1]->Argument(0), words->second[2]->Argument(0), words->second[3]->Argument(0)}; } std::uint32_t BindlessWide(SpirvEmitterState& state, std::uint32_t value) { return Unary(state, spv::OpUConvert, TypeScalarU64(state), value); } std::uint32_t BindlessPair(SpirvEmitterState& state, std::uint32_t low, std::uint32_t high) { const auto u64 = TypeScalarU64(state); return Binary(state, spv::OpBitwiseOr, u64, BindlessWide(state, low), Binary(state, spv::OpShiftLeftLogical, u64, BindlessWide(state, high), BdaConstant(state, 32u))); } std::uint32_t BindlessLow(SpirvEmitterState& state, std::uint32_t value) { return Unary(state, spv::OpUConvert, TypeU32(state), value); } std::uint32_t BindlessHigh(SpirvEmitterState& state, std::uint32_t value) { return Unary(state, spv::OpUConvert, TypeU32(state), Binary(state, spv::OpShiftRightLogical, TypeScalarU64(state), value, BdaConstant(state, 32u))); } std::uint32_t BindlessAddSigned(SpirvEmitterState& state, std::uint32_t address, std::uint32_t immediate) { const auto delta = static_cast(immediate & ~3u); if (delta == 0) return address; const auto magnitude = static_cast(delta < 0 ? -static_cast(delta) : static_cast(delta)); return Binary(state, delta < 0 ? spv::OpISub : spv::OpIAdd, TypeScalarU64(state), address, BdaConstant(state, magnitude)); } std::uint32_t BindlessMin(SpirvEmitterState& state, std::uint32_t left, std::uint32_t right) { return Select(state, TypeScalarU64(state), Binary(state, spv::OpULessThan, TypeBool(state), left, right), left, right); } struct BindlessAddress { std::uint32_t address = 0; std::uint32_t count = 0; std::uint32_t invalid = 0; std::uint32_t base = 0; }; BindlessAddress EmitBindlessAddress(SpirvValueEmitContext& ctx, const IrValue& inst, const BindlessColumn& column) { auto& state = ctx.state; const auto u32 = TypeU32(state); const auto u64 = TypeScalarU64(state); const auto boolean = TypeBool(state); const auto& info = *column.column; const auto& heap = column.heap; const auto word = [&](std::uint32_t index) { return ctx.Def(heap[index]); }; const auto offset = ctx.Def(column.offset); const auto dwords = BdaConstant(state, info.dwordCount); if (info.address) { if (heap.size() != 2u) ctx.Fail(inst, "has a bindless pointer column without its two address dwords"); auto address = Binary(state, spv::OpIAdd, u64, BindlessPair(state, word(0), word(1)), BindlessWide(state, Binary(state, spv::OpBitwiseAnd, u32, offset, ConstantU32(state, ~3u)))); address = Binary(state, spv::OpBitwiseAnd, u64, BindlessAddSigned(state, address, info.offset), BdaConstant(state, ~std::uint64_t{3u})); return {address, ConstantU32(state, info.dwordCount), 0u, address}; } if (heap.size() != 4u) ctx.Fail(inst, "has a bindless buffer column without its four V# dwords"); const auto base = Binary(state, spv::OpBitwiseAnd, u64, BindlessPair(state, word(0), word(1)), BdaConstant(state, 0xffffffffffffull)); const auto stride = EmitBitFieldUExtract(state, word(1), ConstantU32(state, 16u), ConstantU32(state, 14u)); const auto records = BindlessWide(state, word(2)); const auto size = Select(state, u64, Binary(state, spv::OpIEqual, boolean, stride, ConstantU32(state, 0u)), records, Binary(state, spv::OpIMul, u64, BindlessWide(state, stride), records)); const auto invalid = Binary(state, spv::OpINotEqual, boolean, Binary(state, spv::OpShiftRightLogical, u32, word(3), ConstantU32(state, 30u)), ConstantU32(state, 0u)); const auto inRange = [&](std::uint32_t immediate) { const auto start = Binary(state, spv::OpIAdd, u64, BindlessWide(state, offset), BdaConstant(state, immediate)); const auto aligned = Binary(state, spv::OpBitwiseAnd, u64, start, BdaConstant(state, ~std::uint64_t{3u})); const auto limit = BdaConstant(state, 0xffffffffull); const auto carried = Select(state, u64, Binary(state, spv::OpULessThanEqual, boolean, start, limit), Binary(state, spv::OpIAdd, u64, Binary(state, spv::OpShiftRightLogical, u64, Binary(state, spv::OpISub, u64, limit, start), BdaConstant(state, 2u)), BdaConstant(state, 1u)), BdaConstant(state, 0u)); const auto end = Binary(state, spv::OpIAdd, u64, aligned, BdaConstant(state, 4u)); const auto sized = Select(state, u64, Binary(state, spv::OpUGreaterThanEqual, boolean, size, end), Binary(state, spv::OpIAdd, u64, Binary(state, spv::OpShiftRightLogical, u64, Binary(state, spv::OpISub, u64, size, end), BdaConstant(state, 2u)), BdaConstant(state, 1u)), BdaConstant(state, 0u)); return std::pair{aligned, BindlessMin(state, carried, sized)}; }; if (!info.indirect) { const auto [aligned, count] = inRange(info.offset); const auto clamped = Select(state, u64, invalid, BdaConstant(state, 0u), BindlessMin(state, count, dwords)); return {Binary(state, spv::OpIAdd, u64, base, aligned), BindlessLow(state, clamped), invalid, base}; } const auto [aligned, count] = inRange(info.offset); const auto readable = Binary(state, spv::OpLogicalAnd, boolean, Unary(state, spv::OpLogicalNot, boolean, invalid), Binary(state, spv::OpUGreaterThanEqual, boolean, count, BdaConstant(state, 2u))); const auto readPointer = [&](std::uint32_t at) { return EmitValueOrDefaultIfCondition(state, readable, TypeU32Vector(state, 2u), state.module.Constant(spv::OpConstantComposite, TypeU32Vector(state, 2u), ConstantU32(state, 0u), ConstantU32(state, 0u)), [&] { const auto read = EmitBdaDwordReads(ctx, inst, at, 0u, 2u, true); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 2u), value, read[0], read[1]); return value; }); }; auto pair = readPointer(Binary(state, spv::OpIAdd, u64, base, aligned)); const auto part = [&](std::uint32_t index) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, value, pair, index); return value; }; auto address = BindlessPair(state, part(0u), part(1u)); for (const auto& hop : info.pointerHops) { pair = readPointer(BindlessAddSigned(state, Binary(state, spv::OpIAdd, u64, address, BdaConstant(state, hop.offset & ~3u)), hop.immediate)); address = BindlessPair(state, part(0u), part(1u)); } address = BindlessAddSigned(state, Binary(state, spv::OpIAdd, u64, address, BdaConstant(state, info.indirectOffset & ~3u)), info.indirectImmediate); return {address, Select(state, u32, readable, ConstantU32(state, info.dwordCount), ConstantU32(state, 0u)), invalid, base}; } std::uint32_t BindlessSamplerClass(const SpirvEmitterState& state, const MemoryInfo& memory, const IrValue& inst) { if (!ImageOpcodeInfoOf(inst.Opcode()).needsSampler) return BindlessImageAbi::NoSamplerClass; const auto& samplers = state.program.Info().samplers; if (memory.sampler >= samplers.size()) return BindlessImageAbi::NoSamplerClass; return samplers[memory.sampler].table != NoTable ? BindlessImageAbi::TableSamplerClass : BindlessImageAbi::DirectSamplerClass; } struct BindlessInputs { std::vector scalars; std::vector values; bool indirect = false; }; BindlessInputs BindlessInputsOf(SpirvValueEmitContext& ctx, const IrValue& inst, const MemoryInfo& memory) { auto& state = ctx.state; const auto& info = state.program.Info(); BindlessInputs inputs; const auto column = [&](std::uint32_t source, std::size_t argument, std::uint32_t width) { const auto found = BindlessColumnOf(ctx, inst, source, argument, width); inputs.indirect = inputs.indirect || found.column->indirect; inputs.scalars.push_back(source); inputs.values.push_back(found.offset); inputs.values.insert(inputs.values.end(), found.heap.begin(), found.heap.end()); }; inputs.scalars.push_back(memory.resource); column(info.images.at(memory.resource).source, 0u, 8u); const auto samplerClass = BindlessSamplerClass(state, memory, inst); inputs.scalars.push_back(samplerClass); if (samplerClass == BindlessImageAbi::TableSamplerClass) { column(info.samplers.at(memory.sampler).source, 1u, 4u); } else if (samplerClass == BindlessImageAbi::DirectSamplerClass) { for (const auto* word : BindlessDirectSampler(ctx, inst)) inputs.values.push_back(word); } return inputs; } std::vector BindlessKeyOf(SpirvValueEmitContext& ctx, const BindlessInputs& inputs) { auto key = inputs.scalars; for (const auto* value : inputs.values) key.push_back(ctx.Def(value)); return key; } std::uint32_t BindlessVector(SpirvEmitterState& state, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint32_t w) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4u), value, x, y, z, w); return value; } std::uint32_t BindlessExtract(SpirvEmitterState& state, std::uint32_t vector, std::uint32_t index) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), value, vector, index); return value; } std::uint32_t BindlessElect(SpirvEmitterState& state) { state.module.EmitCapability(spv::CapabilityGroupNonUniform); const auto elected = state.module.AllocateId(); state.module.AddFunction(spv::OpGroupNonUniformElect, TypeBool(state), elected, ConstantU32(state, spv::ScopeSubgroup)); return elected; } std::uint32_t BindlessSameAsFirst(SpirvEmitterState& state, std::uint32_t type, std::uint32_t value, std::uint32_t components) { state.module.EmitCapability(spv::CapabilityGroupNonUniformBallot); const auto first = state.module.AllocateId(); state.module.AddFunction(spv::OpGroupNonUniformBroadcastFirst, type, first, ConstantU32(state, spv::ScopeSubgroup), value); if (components == 1u) return Binary(state, spv::OpIEqual, TypeBool(state), value, first); const auto all = state.module.AllocateId(); state.module.AddFunction(spv::OpAll, TypeBool(state), all, Binary(state, spv::OpIEqual, TypeBoolVector(state, components), value, first)); return all; } std::uint32_t BindlessSubgroupAll(SpirvEmitterState& state, std::uint32_t condition) { const auto ballot = state.module.AllocateId(); state.module.AddFunction(spv::OpGroupNonUniformBallot, TypeU32Vector(state, 4u), ballot, ConstantU32(state, spv::ScopeSubgroup), Unary(state, spv::OpLogicalNot, TypeBool(state), condition)); const auto none = state.module.AllocateId(); state.module.AddFunction(spv::OpAll, TypeBool(state), none, Binary(state, spv::OpIEqual, TypeBoolVector(state, 4u), ballot, ConstantU32CompositeZero(state, 4u))); return none; } SpirvBindlessProbe EmitBindlessProbe(SpirvValueEmitContext& ctx, const IrValue& inst, const MemoryInfo& memory) { auto& state = ctx.state; const auto& info = state.program.Info(); const auto u32 = TypeU32(state); const auto boolean = TypeBool(state); const auto uvec4 = TypeU32Vector(state, 4u); const auto image = EmitBindlessAddress(ctx, inst, BindlessColumnOf(ctx, inst, info.images.at(memory.resource).source, 0u, 8u)); const auto samplerClass = BindlessSamplerClass(state, memory, inst); auto samplerAddress = BdaConstant(state, 0u); auto samplerCount = ConstantU32(state, 0u); auto samplerWords = ConstantU32CompositeZero(state, 4u); std::uint32_t addressed = 0u; if (samplerClass == BindlessImageAbi::TableSamplerClass) { const auto sampler = EmitBindlessAddress(ctx, inst, BindlessColumnOf(ctx, inst, info.samplers.at(memory.sampler).source, 1u, 4u)); samplerAddress = sampler.address; samplerCount = sampler.count; addressed = 1u; } else if (samplerClass == BindlessImageAbi::DirectSamplerClass) { const auto words = BindlessDirectSampler(ctx, inst); samplerWords = BindlessVector(state, ctx.Def(words[0]), ctx.Def(words[1]), ctx.Def(words[2]), ctx.Def(words[3])); } const auto id = ResourceMaterializer::BindlessInterfaceId(info.images.at(memory.resource), info.runtimeImageModes.at(memory.resource)); const auto counts = Binary(state, spv::OpBitwiseOr, u32, image.count, Binary(state, spv::OpShiftLeftLogical, u32, samplerCount, ConstantU32(state, 4u))); SpirvBindlessProbe probe; probe.image = image.address; probe.sampler = samplerAddress; probe.samplerWords = samplerWords; probe.extra = BindlessVector(state, ConstantU32(state, static_cast(id)), ConstantU32(state, static_cast(id >> 32u)), ConstantU32(state, samplerClass), counts); probe.invalid = image.invalid; probe.base = image.base; const auto call = [&] { const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpFunctionCall, uvec4, result, state.bindlessProbeFunctions[addressed], probe.image, probe.sampler, probe.samplerWords, probe.extra, ConstantU32(state, 0u), ConstantBool(state, false)); return result; }; if (!state.bindlessWaveUniform) { probe.uniform = ConstantBool(state, false); probe.result = call(); return probe; } const auto words = [&](std::uint32_t address) { return Unary(state, spv::OpBitcast, TypeU32Vector(state, 2u), address); }; auto same = Binary(state, spv::OpLogicalAnd, boolean, BindlessSameAsFirst(state, TypeU32Vector(state, 2u), words(probe.image), 2u), BindlessSameAsFirst(state, u32, counts, 1u)); if (samplerClass == BindlessImageAbi::TableSamplerClass) same = Binary(state, spv::OpLogicalAnd, boolean, same, BindlessSameAsFirst(state, TypeU32Vector(state, 2u), words(samplerAddress), 2u)); if (samplerClass == BindlessImageAbi::DirectSamplerClass) same = Binary(state, spv::OpLogicalAnd, boolean, same, BindlessSameAsFirst(state, uvec4, samplerWords, 4u)); const auto uniform = BindlessSubgroupAll(state, same); const auto lead = Binary(state, spv::OpLogicalOr, boolean, Unary(state, spv::OpLogicalNot, boolean, uniform), BindlessElect(state)); const auto looked = EmitValueOrDefaultIfCondition(state, lead, uvec4, ConstantU32CompositeZero(state, 4u), call); state.module.EmitCapability(spv::CapabilityGroupNonUniformBallot); const auto broadcast = state.module.AllocateId(); state.module.AddFunction(spv::OpGroupNonUniformBroadcastFirst, uvec4, broadcast, ConstantU32(state, spv::ScopeSubgroup), looked); const auto selector = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeBoolVector(state, 4u), selector, uniform, uniform, uniform, uniform); probe.uniform = uniform; probe.result = Select(state, uvec4, selector, broadcast, looked); return probe; } bool BindlessDominates(const SpirvEmitterState& state, const IrBlock* dominator, const IrBlock* block); const SpirvBindlessProbe& BindlessProbeFor(SpirvValueEmitContext& ctx, const IrValue& inst, const MemoryInfo& memory) { auto& state = ctx.state; const auto key = BindlessKeyOf(ctx, BindlessInputsOf(ctx, inst, memory)); if (const auto found = state.bindlessHoisted.find(key); found != state.bindlessHoisted.end()) { for (const auto& [block, probe] : found->second) { if (BindlessDominates(state, block, state.currentBlock)) return probe; } } if (state.bindlessProbeBlock != state.currentBlock) { state.bindlessBlockProbes.clear(); state.bindlessProbeBlock = state.currentBlock; } if (const auto found = state.bindlessBlockProbes.find(key); found != state.bindlessBlockProbes.end()) return found->second; return state.bindlessBlockProbes.emplace(key, EmitBindlessProbe(ctx, inst, memory)).first->second; } struct BindlessAccess { std::uint32_t valid = 0; std::uint32_t selector = 0; }; BindlessAccess EmitBindlessAccess(SpirvValueEmitContext& ctx, const IrValue& inst, const MemoryInfo& memory) { auto& state = ctx.state; const auto addressed = BindlessSamplerClass(state, memory, inst) == BindlessImageAbi::TableSamplerClass ? 1u : 0u; if (state.bindlessProbeFunctions[addressed] == 0 || state.bindlessLookupFunctions[addressed] == 0 || state.faultBufferVariable == 0) ctx.Fail(inst, "reads a bindless image without its lookup functions or fault buffer"); const auto u32 = TypeU32(state); const auto boolean = TypeBool(state); const auto uvec4 = TypeU32Vector(state, 4u); const auto probe = BindlessProbeFor(ctx, inst, memory); const auto exec = ctx.Arg(inst, inst.ArgumentCount() - 1u); const auto pc = ConstantU32(state, inst.Flags().pc); const auto status = Binary(state, spv::OpShiftRightLogical, u32, BindlessExtract(state, probe.result, 0u), ConstantU32(state, BindlessStatusShift)); const auto redo = Binary(state, spv::OpLogicalAnd, boolean, exec, Binary(state, spv::OpUGreaterThanEqual, boolean, status, ConstantU32(state, BindlessMiss))); const auto result = EmitValueOrDefaultIfCondition(state, redo, uvec4, probe.result, [&] { const auto record = state.bindlessWaveUniform ? Binary(state, spv::OpLogicalOr, boolean, Unary(state, spv::OpLogicalNot, boolean, probe.uniform), BindlessElect(state)) : ConstantBool(state, true); const auto looked = state.module.AllocateId(); state.module.AddFunction(spv::OpFunctionCall, uvec4, looked, state.bindlessLookupFunctions[addressed], probe.image, probe.sampler, probe.samplerWords, probe.extra, pc, record); return looked; }); if (probe.invalid != 0u) { EmitIfCondition(state, Binary(state, spv::OpLogicalAnd, boolean, exec, probe.invalid), [&] { RecordBdaFaultWords(state, BindlessLow(state, probe.base), BindlessHigh(state, probe.base), ConstantU32(state, 0u), pc, BdaAbi::FaultReason::InvalidDescriptor); }); } const auto first = BindlessExtract(state, result, 0u); BindlessAccess access; access.valid = Binary(state, spv::OpIEqual, boolean, Binary(state, spv::OpShiftRightLogical, u32, first, ConstantU32(state, BindlessStatusShift)), ConstantU32(state, BindlessOk)); access.selector = BindlessExtract(state, result, 1u); state.tableAccess = {}; state.tableAccess.element = Binary(state, spv::OpBitwiseAnd, u32, first, ConstantU32(state, BindlessImageAbi::SlotMask)); DecorateTableNonUniform(state, state.tableAccess.element); state.tableAccess.dword3 = BindlessExtract(state, result, 2u); if (BindlessSamplerClass(state, memory, inst) != BindlessImageAbi::NoSamplerClass) { state.tableAccess.samplerElement = BindlessExtract(state, result, 3u); DecorateTableNonUniform(state, state.tableAccess.samplerElement); } state.tableAccess.active = true; state.tableAccess.bindless = true; return access; } bool BindlessQuadUniform(const SpirvEmitterState& state, const IrValue& inst) { return state.bindlessQuadUniform && (inst.Opcode() == IrOpcode::ImageSampleRaw || inst.Opcode() == IrOpcode::ImageQueryLod); } std::uint32_t BindlessQuadSelector(SpirvEmitterState& state, const BindlessAccess& access) { state.module.EmitCapability(spv::CapabilityGroupNonUniformQuad); const auto u32 = TypeU32(state); const auto invalid = ConstantU32(state, InvalidTableSelector); auto fallback = invalid; for (std::uint32_t lane = 4u; lane-- > 0u;) { const auto neighbour = state.module.AllocateId(); state.module.AddFunction(spv::OpGroupNonUniformQuadBroadcast, u32, neighbour, ConstantU32(state, spv::ScopeSubgroup), access.selector, ConstantU32(state, lane)); fallback = Select(state, u32, Binary(state, spv::OpINotEqual, TypeBool(state), neighbour, invalid), neighbour, fallback); } return Select(state, u32, access.valid, access.selector, fallback); } std::uint32_t BindlessHash(SpirvEmitterState& state, std::span key) { namespace Table = DeviceImageTableAbi; const auto u32 = TypeU32(state); const auto constant = [&](std::uint32_t value) { return ConstantU32(state, value); }; const auto rotate = [&](std::uint32_t value, std::uint32_t bits) { return Binary(state, spv::OpBitwiseOr, u32, Binary(state, spv::OpShiftLeftLogical, u32, value, constant(bits)), Binary(state, spv::OpShiftRightLogical, u32, value, constant(32u - bits))); }; auto hash = constant(Table::HashSeed); for (const auto word : key) { const auto mixed = Binary(state, spv::OpIMul, u32, rotate(Binary(state, spv::OpIMul, u32, word, constant(Table::HashC1)), 15u), constant(Table::HashC2)); hash = Binary(state, spv::OpIAdd, u32, Binary(state, spv::OpIMul, u32, rotate(Binary(state, spv::OpBitwiseXor, u32, hash, mixed), 13u), constant(5u)), constant(Table::HashRound)); } const auto shiftXor = [&](std::uint32_t value, std::uint32_t bits) { return Binary(state, spv::OpBitwiseXor, u32, value, Binary(state, spv::OpShiftRightLogical, u32, value, constant(bits))); }; hash = Binary(state, spv::OpBitwiseXor, u32, hash, constant(Table::KeyWords * 4u)); hash = Binary(state, spv::OpIMul, u32, shiftXor(hash, 16u), constant(Table::HashMix1)); hash = Binary(state, spv::OpIMul, u32, shiftXor(hash, 13u), constant(Table::HashMix2)); return shiftXor(hash, 16u); } std::uint32_t BindlessPhysicalPointer(SpirvEmitterState& state, std::uint32_t base, std::uint32_t word) { const auto pointer = state.module.AllocateId(); const auto address = Binary(state, spv::OpIAdd, TypeScalarU64(state), base, BindlessWide(state, Binary(state, spv::OpShiftLeftLogical, TypeU32(state), word, ConstantU32(state, 2u)))); state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, address); return pointer; } std::uint32_t BindlessPhysicalLoad(SpirvEmitterState& state, std::uint32_t base, std::uint32_t word) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BindlessPhysicalPointer(state, base, word), spv::MemoryAccessAlignedMask, 4u); return value; } std::uint32_t BindlessHeaderWord(SpirvEmitterState& state, std::uint32_t index) { const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.bindlessHeaderVariable, ConstantU32(state, 0u), ConstantU32(state, index)); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); return value; } std::uint32_t DefineBindlessLookup(SpirvEmitterState& state, bool full, bool addressed) { namespace Table = DeviceImageTableAbi; const auto u32 = TypeU32(state); const auto u64 = TypeScalarU64(state); const auto uvec4 = TypeU32Vector(state, 4u); const auto boolean = TypeBool(state); const auto constant = [&](std::uint32_t value) { return ConstantU32(state, value); }; const auto binary = [&](std::uint32_t op, std::uint32_t type, std::uint32_t left, std::uint32_t right) { return Binary(state, op, type, left, right); }; const auto equal = [&](std::uint32_t left, std::uint32_t right) { return binary(spv::OpIEqual, boolean, left, right); }; const auto both = [&](std::uint32_t left, std::uint32_t right) { return binary(spv::OpLogicalAnd, boolean, left, right); }; const auto either = [&](std::uint32_t left, std::uint32_t right) { return binary(spv::OpLogicalOr, boolean, left, right); }; const auto negate = [&](std::uint32_t value) { return Unary(state, spv::OpLogicalNot, boolean, value); }; const auto load = [&](std::uint32_t variable, std::uint32_t type) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, type, value, variable); return value; }; const auto function = state.module.AllocateId(); state.module.AddName(function, std::string(full ? "bindless_lookup" : "bindless_probe") + (addressed ? "_table_sampler" : "")); state.module.AddFunction(spv::OpFunction, uvec4, function, spv::FunctionControlDontInlineMask, state.module.Type(spv::OpTypeFunction, uvec4, u64, u64, uvec4, uvec4, u32, boolean)); const auto image = state.module.AllocateId(); const auto sampler = state.module.AllocateId(); const auto samplerParameter = state.module.AllocateId(); const auto extra = state.module.AllocateId(); const auto pc = state.module.AllocateId(); const auto record = state.module.AllocateId(); state.module.AddFunction(spv::OpFunctionParameter, u64, image); state.module.AddFunction(spv::OpFunctionParameter, u64, sampler); state.module.AddFunction(spv::OpFunctionParameter, uvec4, samplerParameter); state.module.AddFunction(spv::OpFunctionParameter, uvec4, extra); state.module.AddFunction(spv::OpFunctionParameter, u32, pc); state.module.AddFunction(spv::OpFunctionParameter, boolean, record); EmitLabel(state, state.module.AllocateId()); const auto stepVariable = state.module.AllocateId(); const auto doneVariable = state.module.AllocateId(); const auto foundVariable = state.module.AllocateId(); state.module.AddFunction(spv::OpVariable, TypePointer(state, spv::StorageClassFunction, u32), stepVariable, spv::StorageClassFunction); state.module.AddFunction(spv::OpVariable, TypePointer(state, spv::StorageClassFunction, boolean), doneVariable, spv::StorageClassFunction); state.module.AddFunction(spv::OpVariable, TypePointer(state, spv::StorageClassFunction, uvec4), foundVariable, spv::StorageClassFunction); const auto hashVariable = full ? state.module.AllocateId() : 0u; const auto claimVariable = full ? state.module.AllocateId() : 0u; const auto settledVariable = full ? state.module.AllocateId() : 0u; if (full) { state.module.AddFunction(spv::OpVariable, TypePointer(state, spv::StorageClassFunction, u32), hashVariable, spv::StorageClassFunction); state.module.AddFunction(spv::OpVariable, TypePointer(state, spv::StorageClassFunction, boolean), claimVariable, spv::StorageClassFunction); state.module.AddFunction(spv::OpVariable, TypePointer(state, spv::StorageClassFunction, boolean), settledVariable, spv::StorageClassFunction); state.module.AddFunction(spv::OpStore, hashVariable, constant(0u)); } const auto counts = BindlessExtract(state, extra, 3u); const auto imageCount = binary(spv::OpBitwiseAnd, u32, counts, constant(0xfu)); const auto samplerCount = binary(spv::OpBitwiseAnd, u32, binary(spv::OpShiftRightLogical, u32, counts, constant(4u)), constant(0xfu)); const auto read = [&](std::uint32_t address, std::uint32_t count, std::uint32_t dwords, std::array& words) { if (full) { const auto span = state.bdaSpanReadFunctions[0][0]; for (std::uint32_t quad = 0; quad < dwords / 4u; ++quad) { if (span != 0u) { const auto first = constant(quad * 4u); const auto clamped = Select(state, u32, binary(spv::OpUGreaterThan, boolean, count, first), binary(spv::OpISub, u32, count, first), constant(0u)); const auto limited = Select(state, u32, binary(spv::OpUGreaterThan, boolean, clamped, constant(4u)), constant(4u), clamped); const auto used = binary(spv::OpISub, u32, binary(spv::OpShiftLeftLogical, u32, constant(1u), limited), constant(1u)); const auto values = EmitValueOrDefaultIfCondition(state, binary(spv::OpINotEqual, boolean, used, constant(0u)), uvec4, ConstantU32CompositeZero(state, 4u), [&] { const auto loaded = state.module.AllocateId(); state.module.AddFunction(spv::OpFunctionCall, uvec4, loaded, span, address, constant(quad * 16u), used, pc); return loaded; }); for (std::uint32_t dword = 0; dword < 4u; ++dword) words[quad * 4u + dword] = BindlessExtract(state, values, dword); continue; } for (std::uint32_t dword = 0; dword < 4u; ++dword) { const auto index = quad * 4u + dword; words[index] = EmitValueOrZeroIfCondition(state, binary(spv::OpULessThan, boolean, constant(index), count), [&] { const auto pair = state.module.AllocateId(); state.module.AddFunction(spv::OpFunctionCall, TypeU32Vector(state, 2u), pair, state.bdaDwordReadFunctions[0][0], binary(spv::OpIAdd, u64, address, BdaConstant(state, index * 4u)), pc); return BindlessExtract(state, pair, 0u); }); } } return ConstantBool(state, true); } if (state.bdaProbeFunction == 0u) { for (std::uint32_t dword = 0; dword < dwords; ++dword) words[dword] = constant(0u); return binary(spv::OpIEqual, boolean, count, constant(0u)); } const auto present = binary(spv::OpINotEqual, boolean, count, constant(0u)); const auto physical = EmitValueOrDefaultIfCondition(state, present, u64, BdaConstant(state, 0u), [&] { const auto found = state.module.AllocateId(); state.module.AddFunction(spv::OpFunctionCall, u64, found, state.bdaProbeFunction, address, binary(spv::OpShiftLeftLogical, u32, count, constant(2u)), pc); return found; }); const auto usable = either(negate(present), both(binary(spv::OpINotEqual, boolean, physical, BdaConstant(state, 0u)), binary(spv::OpIEqual, boolean, binary(spv::OpBitwiseAnd, u64, physical, BdaConstant(state, 3u)), BdaConstant(state, 0u)))); for (std::uint32_t dword = 0; dword < dwords; ++dword) { words[dword] = EmitValueOrZeroIfCondition(state, both(usable, binary(spv::OpULessThan, boolean, constant(dword), count)), [&] { return BindlessPhysicalLoad(state, physical, constant(dword)); }); } return usable; }; std::array words{}; const auto imageUsable = read(image, imageCount, 8u, words); std::array samplerRead{}; const auto samplerUsable = addressed ? read(sampler, samplerCount, 4u, samplerRead) : ConstantBool(state, true); std::array key{}; for (std::uint32_t word = 0; word < Table::DescriptorWords; ++word) { const auto mask = BindlessImageAbi::MaskedDescriptorWord(word, 0xffffffffu); key[word] = mask == 0xffffffffu ? words[word] : binary(spv::OpBitwiseAnd, u32, words[word], constant(mask)); } key[Table::InterfaceWord] = BindlessExtract(state, extra, 0u); key[Table::InterfaceWord + 1u] = BindlessExtract(state, extra, 1u); key[Table::SamplerClassWord] = BindlessExtract(state, extra, 2u); for (std::uint32_t word = 0; word < Table::SamplerWords; ++word) key[Table::SamplerWord + word] = addressed ? samplerRead[word] : BindlessExtract(state, samplerParameter, word); const auto slow = negate(both(imageUsable, samplerUsable)); const auto null = either(equal(imageCount, constant(0u)), both(equal(words[0], constant(0u)), equal(binary(spv::OpBitwiseAnd, u32, words[1], constant(0xffu)), constant(0u)))); state.module.AddFunction(spv::OpStore, foundVariable, ConstantU32CompositeZero(state, 4u)); EmitIfCondition(state, both(negate(slow), negate(null)), [&] { const auto hash = BindlessHash(state, key); if (full) state.module.AddFunction(spv::OpStore, hashVariable, hash); const auto table = BindlessPair(state, BindlessHeaderWord(state, Table::HeaderTableLow), BindlessHeaderWord(state, Table::HeaderTableHigh)); const auto mask = BindlessHeaderWord(state, Table::HeaderMask); const auto home = binary(spv::OpBitwiseAnd, u32, hash, mask); state.module.AddFunction(spv::OpStore, stepVariable, constant(0u)); state.module.AddFunction(spv::OpStore, doneVariable, ConstantBool(state, false)); const auto loopHeader = state.module.AllocateId(); const auto body = state.module.AllocateId(); const auto continuation = state.module.AllocateId(); const auto merge = state.module.AllocateId(); state.module.AddFunction(spv::OpBranch, loopHeader); EmitLabel(state, loopHeader); const auto step = load(stepVariable, u32); const auto done = load(doneVariable, boolean); const auto searching = both(negate(done), binary(spv::OpULessThan, boolean, step, constant(Table::ProbeSteps))); state.module.AddFunction(spv::OpLoopMerge, merge, continuation, spv::LoopControlMaskNone); state.module.AddFunction(spv::OpBranchConditional, searching, body, merge); EmitLabel(state, body); const auto bucket = binary(spv::OpIMul, u32, binary(spv::OpBitwiseAnd, u32, binary(spv::OpIAdd, u32, home, step), mask), constant(Table::BucketWords)); const auto at = [&](std::uint32_t word) { return BindlessPhysicalLoad(state, table, binary(spv::OpIAdd, u32, bucket, constant(word))); }; const auto live = equal(at(Table::StateWord), constant(Table::LiveState)); auto same = live; for (std::uint32_t word = 0; word < Table::KeyWords; ++word) same = both(same, equal(at(word), key[word])); const auto hit = BindlessVector(state, at(Table::SlotWord), at(Table::ModeWord), at(Table::FaultWord), binary(spv::OpIAdd, u32, at(Table::SamplerSlotWord), constant(1u))); const auto previous = load(foundVariable, uvec4); const auto selector = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeBoolVector(state, 4u), selector, same, same, same, same); state.module.AddFunction(spv::OpStore, foundVariable, Select(state, uvec4, selector, hit, previous)); state.module.AddFunction(spv::OpStore, doneVariable, either(negate(live), same)); state.module.AddFunction(spv::OpBranch, continuation); EmitLabel(state, continuation); state.module.AddFunction(spv::OpStore, stepVariable, binary(spv::OpIAdd, u32, step, constant(1u))); state.module.AddFunction(spv::OpBranch, loopHeader); EmitLabel(state, merge); }); const auto found = load(foundVariable, uvec4); const auto present = binary(spv::OpINotEqual, boolean, BindlessExtract(state, found, 3u), constant(0u)); const auto fault = BindlessExtract(state, found, 2u); const auto refused = binary(spv::OpINotEqual, boolean, fault, constant(0u)); auto status = Select(state, u32, refused, constant(BindlessRefused), constant(BindlessOk)); status = Select(state, u32, present, status, constant(BindlessMiss)); status = Select(state, u32, null, constant(BindlessNull), status); status = Select(state, u32, slow, constant(BindlessSlow), status); if (full) { EmitIfCondition(state, both(record, equal(status, constant(BindlessMiss))), [&] { const auto seen = BindlessPair(state, BindlessHeaderWord(state, Table::HeaderSeenLow), BindlessHeaderWord(state, Table::HeaderSeenHigh)); const auto seenSlots = BindlessHeaderWord(state, Table::HeaderSeenSlots); auto tag = constant(Table::SeenTagSeed); for (const auto word : key) tag = binary(spv::OpIMul, u32, binary(spv::OpBitwiseXor, u32, tag, word), constant(Table::SeenTagPrime)); tag = binary(spv::OpBitwiseOr, u32, tag, constant(1u)); const auto unset = equal(seenSlots, constant(0u)); state.module.AddFunction(spv::OpStore, claimVariable, unset); state.module.AddFunction(spv::OpStore, settledVariable, unset); state.module.AddFunction(spv::OpStore, stepVariable, constant(0u)); const auto seenHash = load(hashVariable, u32); const auto seenMask = binary(spv::OpISub, u32, seenSlots, constant(1u)); const auto seenHeader = state.module.AllocateId(); const auto seenBody = state.module.AllocateId(); const auto seenContinue = state.module.AllocateId(); const auto seenMerge = state.module.AllocateId(); state.module.AddFunction(spv::OpBranch, seenHeader); EmitLabel(state, seenHeader); const auto seenStep = load(stepVariable, u32); const auto settled = load(settledVariable, boolean); const auto probing = both(negate(settled), binary(spv::OpULessThan, boolean, seenStep, constant(Table::SeenProbeSteps))); state.module.AddFunction(spv::OpLoopMerge, seenMerge, seenContinue, spv::LoopControlMaskNone); state.module.AddFunction(spv::OpBranchConditional, probing, seenBody, seenMerge); EmitLabel(state, seenBody); const auto slotIndex = binary(spv::OpBitwiseAnd, u32, binary(spv::OpIAdd, u32, seenHash, seenStep), seenMask); const auto current = state.module.AllocateId(); state.module.AddFunction(spv::OpAtomicLoad, u32, current, BindlessPhysicalPointer(state, seen, slotIndex), constant(spv::ScopeDevice), constant(spv::MemorySemanticsMaskNone)); const auto previous = EmitValueOrDefaultIfCondition(state, equal(current, constant(0u)), u32, current, [&] { const auto exchanged = state.module.AllocateId(); state.module.AddFunction(spv::OpAtomicCompareExchange, u32, exchanged, BindlessPhysicalPointer(state, seen, slotIndex), constant(spv::ScopeDevice), constant(spv::MemorySemanticsMaskNone), constant(spv::MemorySemanticsMaskNone), tag, constant(0u)); return exchanged; }); const auto won = equal(previous, constant(0u)); state.module.AddFunction(spv::OpStore, claimVariable, won); state.module.AddFunction(spv::OpStore, settledVariable, either(won, equal(previous, tag))); state.module.AddFunction(spv::OpBranch, seenContinue); EmitLabel(state, seenContinue); state.module.AddFunction(spv::OpStore, stepVariable, binary(spv::OpIAdd, u32, seenStep, constant(1u))); state.module.AddFunction(spv::OpBranch, seenHeader); EmitLabel(state, seenMerge); const auto report = either(load(claimVariable, boolean), negate(load(settledVariable, boolean))); EmitIfCondition(state, report, [&] { const auto ring = BindlessPair(state, BindlessHeaderWord(state, Table::HeaderRingLow), BindlessHeaderWord(state, Table::HeaderRingHigh)); const auto capacity = BindlessHeaderWord(state, Table::HeaderRingCapacity); const auto index = state.module.AllocateId(); state.module.AddFunction(spv::OpAtomicIAdd, u32, index, BindlessPhysicalPointer(state, ring, constant(Table::RingCountWord)), constant(spv::ScopeDevice), constant(spv::MemorySemanticsMaskNone), constant(1u)); EmitIfCondition(state, binary(spv::OpULessThan, boolean, index, capacity), [&] { const auto first = binary(spv::OpIAdd, u32, constant(Table::RingRecordsWord), binary(spv::OpIMul, u32, index, constant(Table::RecordWords))); const auto store = [&](std::uint32_t word, std::uint32_t value) { state.module.AddFunction(spv::OpStore, BindlessPhysicalPointer(state, ring, binary(spv::OpIAdd, u32, first, constant(word))), value, spv::MemoryAccessAlignedMask, 4u); }; for (std::uint32_t word = 0; word < Table::KeyWords; ++word) store(word, key[word]); store(Table::RecordPcWord, pc); }); }); }); EmitIfCondition(state, both(record, equal(status, constant(BindlessRefused))), [&] { RecordBdaFaultWords(state, BindlessLow(state, image), BindlessHigh(state, image), binary(spv::OpISub, u32, fault, constant(1u)), pc, BdaAbi::FaultReason::BindlessRefused); }); } const auto ok = equal(status, constant(BindlessOk)); const auto slot = Select(state, u32, ok, binary(spv::OpBitwiseAnd, u32, BindlessExtract(state, found, 0u), constant(BindlessImageAbi::SlotMask)), constant(0u)); const auto samplerSlot = Select(state, u32, ok, binary(spv::OpBitwiseAnd, u32, binary(spv::OpISub, u32, BindlessExtract(state, found, 3u), constant(1u)), constant(BindlessImageAbi::SlotMask)), constant(0u)); const auto result = BindlessVector(state, binary(spv::OpBitwiseOr, u32, binary(spv::OpShiftLeftLogical, u32, status, constant(BindlessStatusShift)), slot), Select(state, u32, ok, BindlessExtract(state, found, 1u), constant(InvalidTableSelector)), words[3], samplerSlot); state.module.AddFunction(spv::OpReturnValue, result); state.module.AddFunction(spv::OpFunctionEnd); return function; } std::unordered_map BindlessLoopComponents(const IrProgram& program) { const auto& order = program.BlockOrder(); std::unordered_map index; for (std::uint32_t at = 0; at < order.size(); ++at) index.emplace(order[at], at); std::vector number(order.size(), 0u); std::vector low(order.size(), 0u); std::vector stacked(order.size(), false); std::vector stack; std::unordered_map cyclic; std::uint32_t components = 0; std::uint32_t counter = 0; struct Frame { std::uint32_t block; std::size_t next; }; for (std::uint32_t root = 0; root < order.size(); ++root) { if (number[root] != 0u) continue; std::vector frames{{root, 0u}}; number[root] = low[root] = ++counter; stack.push_back(root); stacked[root] = true; while (!frames.empty()) { auto& frame = frames.back(); const auto& successors = order[frame.block]->Successors(); if (frame.next < successors.size()) { const auto found = index.find(successors[frame.next++]); if (found == index.end()) continue; const auto successor = found->second; if (number[successor] == 0u) { number[successor] = low[successor] = ++counter; stack.push_back(successor); stacked[successor] = true; frames.push_back({successor, 0u}); } else if (stacked[successor]) { low[frame.block] = std::min(low[frame.block], number[successor]); } continue; } const auto block = frame.block; frames.pop_back(); if (!frames.empty()) low[frames.back().block] = std::min(low[frames.back().block], low[block]); if (low[block] != number[block]) continue; std::vector component; for (;;) { const auto member = stack.back(); stack.pop_back(); stacked[member] = false; component.push_back(member); if (member == block) break; } const auto& own = order[block]->Successors(); const bool selfLoop = std::find(own.begin(), own.end(), order[block]) != own.end(); if (component.size() > 1u || selfLoop) { for (const auto member : component) cyclic.emplace(order[member], components); ++components; } } } return cyclic; } bool BindlessDominates(const SpirvEmitterState& state, const IrBlock* dominator, const IrBlock* block) { while (block != nullptr) { if (block == dominator) return true; const auto found = state.bindlessDominators.find(block); if (found == state.bindlessDominators.end() || found->second == block) return false; block = found->second; } return false; } void PlanBindlessHoists(SpirvValueEmitContext& ctx) { auto& state = ctx.state; state.bindlessHoistPlanned = true; const auto& order = state.program.BlockOrder(); if (order.empty() || !order.front()->Predecessors().empty()) return; std::vector postorder; std::unordered_map number; std::vector> stack{{order.front(), 0u}}; std::unordered_map seen{{order.front(), true}}; while (!stack.empty()) { auto& [block, next] = stack.back(); const auto& successors = block->Successors(); if (next < successors.size()) { const IrBlock* successor = successors[next++]; if (!seen[successor]) { seen[successor] = true; stack.push_back({successor, 0u}); } continue; } number[block] = static_cast(postorder.size()); postorder.push_back(block); stack.pop_back(); } auto& idom = state.bindlessDominators; idom[order.front()] = order.front(); const auto intersect = [&](const IrBlock* left, const IrBlock* right) { while (left != right) { while (number.at(left) < number.at(right)) left = idom.at(left); while (number.at(right) < number.at(left)) right = idom.at(right); } return left; }; for (bool changed = true; changed;) { changed = false; for (auto at = postorder.rbegin(); at != postorder.rend(); ++at) { const IrBlock* block = *at; if (block == order.front()) continue; const IrBlock* chosen = nullptr; for (const IrBlock* predecessor : block->Predecessors()) { if (!idom.contains(predecessor)) continue; chosen = chosen == nullptr ? predecessor : intersect(predecessor, chosen); } if (chosen != nullptr && (!idom.contains(block) || idom.at(block) != chosen)) { idom[block] = chosen; changed = true; } } } const auto components = BindlessLoopComponents(state.program); const auto& info = state.program.Info(); const auto stage = state.program.Resources().stage; for (const auto& [block, component] : components) { const IrBlock* target = block; while (target != nullptr && components.contains(target) && components.at(target) == component) { const auto found = idom.find(target); target = found == idom.end() || found->second == target ? nullptr : found->second; } if (target == nullptr) continue; for (const IrValue* inst : block->Instructions()) { if (ImageOpcodeInfoOf(inst->Opcode()).access == ImageAccess::None) continue; const auto& memory = ctx.Memory(*inst); if (!ResourceMaterializer::BindlessImage(info, stage, memory.resource)) continue; const auto inputs = BindlessInputsOf(ctx, *inst, memory); const auto available = [&](const IrValue* value) { const IrValue* resolved = value->Resolve(); return resolved->HasImmediate() || (resolved->Parent() != nullptr && BindlessDominates(state, resolved->Parent(), target)); }; const bool hoist = !inputs.indirect && std::all_of(inputs.values.begin(), inputs.values.end(), available); if (!hoist) continue; state.bindlessHoistAt[target].push_back(inst); } } } } void DefineBindlessFunctions(SpirvEmitterState& state) { if (!state.bindlessImages) return; if (state.bindlessHeaderVariable == 0u || state.bdaDwordReadFunctions[0][0] == 0u || state.bdaFaultFunction == 0u) throw std::runtime_error("bindless images need the heap header, the BDA read functions and the fault buffer"); const auto& info = state.program.Info(); const auto stage = state.program.Resources().stage; bool tableSamplers = false; for (const auto& pair : info.sampledPairs) tableSamplers = tableSamplers || (ResourceMaterializer::BindlessImage(info, stage, pair.image) && info.samplers.at(pair.sampler).table != NoTable); state.bindlessProbeFunctions[0] = DefineBindlessLookup(state, false, false); state.bindlessLookupFunctions[0] = DefineBindlessLookup(state, true, false); if (!tableSamplers) return; state.bindlessProbeFunctions[1] = DefineBindlessLookup(state, false, true); state.bindlessLookupFunctions[1] = DefineBindlessLookup(state, true, true); } void EmitBindlessEntryProbes(SpirvValueEmitContext& ctx) { auto& state = ctx.state; if (!state.bindlessImages) return; if (!state.bindlessHoistPlanned) PlanBindlessHoists(ctx); const auto planned = state.bindlessHoistAt.find(state.currentBlock); if (planned == state.bindlessHoistAt.end()) return; for (const IrValue* inst : planned->second) { const auto& memory = ctx.Memory(*inst); const auto key = BindlessKeyOf(ctx, BindlessInputsOf(ctx, *inst, memory)); auto& probes = state.bindlessHoisted[key]; if (std::any_of(probes.begin(), probes.end(), [&](const auto& probe) { return BindlessDominates(state, probe.first, state.currentBlock); })) continue; probes.emplace_back(state.currentBlock, EmitBindlessProbe(ctx, *inst, memory)); } } void EmitImageOperation(SpirvModule& module, const IrValue& value, std::uint32_t resultId) { throw std::logic_error("EmitImageOperation(SpirvModule&) is not used: image instructions are emitted per opcode through EmitImage"); } void EmitImageOperation(SpirvValueEmitContext& context, const IrValue& value, std::uint32_t resultId) { throw std::logic_error("EmitImageOperation(SpirvValueEmitContext&) is not used: image instructions are emitted per opcode through EmitImage"); } void EmitImageMode(SpirvValueEmitContext& ctx, const IrValue& inst, const ImageResource& image) { const auto irOpcode = inst.Opcode(); const auto imageInfo = ImageOpcodeInfoOf(irOpcode); const auto& mem = ctx.Memory(inst); ctx.ResourceIndex(inst.Argument(0), IrOpcode::GetImageResource); const auto* address = ctx.ImageAddress(inst.Argument(imageInfo.needsSampler ? 2 : 1)); if (address == nullptr) { ctx.Fail(inst, "has no image address"); } MemoryInfo gcnMemory = mem; if (GcnGuestShaders() && irOpcode != IrOpcode::ImageQueryDimensions) { const bool line = image.dimension == RdnaImageDimension::Dim1D || image.dimension == RdnaImageDimension::Dim1DArray; const auto addressed = mem.imageDimension != RdnaImageDimension::Dim2DArray ? image.dimension : line ? RdnaImageDimension::Dim1DArray : mem.imageDimension; const auto& from = RdnaImageDimensionInfoFor(mem.imageDimension); const auto& to = RdnaImageDimensionInfoFor(addressed); const bool gradients = (mem.imageSampleFlags & RdnaImageSampleFlagDerivative) != 0u; const auto removed = from.coordinateComponents + (gradients ? 2u * from.spatialComponents : 0u); const auto added = to.coordinateComponents + to.multisampled + (gradients ? 2u * to.spatialComponents : 0u); if (mem.imageAddressComponents < removed) ctx.Fail(inst, "has fewer GCN image address components than its coordinates"); gcnMemory.imageDimension = addressed; gcnMemory.imageAddressComponents = mem.imageAddressComponents - removed + added; } const ImageEmitAccess access{inst, gcnMemory, image, *address}; if (imageInfo.access == ImageAccess::Atomic) { EmitAtomicOp(ctx, access); return; } switch (irOpcode) { case IrOpcode::ImageQueryDimensions: EmitQueryDimensionsOp(ctx, access); return; case IrOpcode::ImageQueryLod: EmitQueryLodOp(ctx, access); return; case IrOpcode::ImageRead: EmitReadOp(ctx, access); return; case IrOpcode::ImageWrite: EmitWriteOp(ctx, access); return; case IrOpcode::ImageSampleRaw: case IrOpcode::ImageGatherRaw: EmitSamplingOp(ctx, access); return; default: ctx.Fail(inst, "has no image SPIR-V emitter"); } } bool SameImageModeForInstruction(const IrValue& inst, const MemoryInfo& memory, const ImageResource& a, const ImageResource& b) { if (a.resourceClass != b.resourceClass || a.dimension != b.dimension || a.numericClass != b.numericClass || a.depthCompare != b.depthCompare || a.atomic != b.atomic || a.atomic64 != b.atomic64 || a.table != b.table || a.depthBits != b.depthBits) { return false; } const auto opcode = inst.Opcode(); if (ImageOpcodeInfoOf(opcode).access == ImageAccess::Atomic || opcode == IrOpcode::ImageQueryDimensions) { return true; } if (opcode == IrOpcode::ImageQueryLod) { const bool pointA = a.table != NoTable ? TablePointSampled(a) : (a.numericClass == IrTextureNumericClass::Sint || a.conversionFormat != IrBufferFormat::Invalid || a.depthBits); const bool pointB = b.table != NoTable ? TablePointSampled(b) : (b.numericClass == IrTextureNumericClass::Sint || b.conversionFormat != IrBufferFormat::Invalid || b.depthBits); return a.cube == b.cube && pointA == pointB && ImageConversionFormat(a).type == ImageConversionFormat(b).type; } if (opcode == IrOpcode::ImageRead) { if (a.depthUnorm16 != b.depthUnorm16 || a.srgbDecode != b.srgbDecode) { return false; } if (memory.imagePacked) { return a.packedFormat == b.packedFormat && (a.conversionFormat != IrBufferFormat::Invalid) == (b.conversionFormat != IrBufferFormat::Invalid); } return a.conversionFormat == b.conversionFormat && (a.conversionFormat == IrBufferFormat::Invalid || a.shaderSwizzle == b.shaderSwizzle); } if (opcode == IrOpcode::ImageWrite) { if (a.mipMode != b.mipMode) { return false; } if (memory.imagePacked) { return a.packedFormat == b.packedFormat && (a.conversionFormat != IrBufferFormat::Invalid) == (b.conversionFormat != IrBufferFormat::Invalid); } const auto formatForWrite = [&](const ImageResource& image) { if (memory.dataBits != 16u && (image.conversionFormat == IrBufferFormat::Format32SInt || image.conversionFormat == IrBufferFormat::Format32_32SInt || image.conversionFormat == IrBufferFormat::Format32_32_32_32SInt)) { return IrBufferFormat::Invalid; } return image.conversionFormat; }; return formatForWrite(a) == formatForWrite(b); } return false; } void EmitImage(SpirvValueEmitContext& ctx, const IrValue& inst) { auto& state = ctx.state; const auto& memory = ctx.Memory(inst); const auto& base = ImageResourceOf(state, memory); const auto imageInfo = ImageOpcodeInfoOf(inst.Opcode()); const auto& samplers = state.program.Info().samplers; const bool tableSampler = imageInfo.needsSampler && memory.sampler < samplers.size() && samplers[memory.sampler].table != NoTable; const bool tables = base.table != NoTable || tableSampler; const auto modes = base.table != NoTable ? state.program.Info().runtimeImageModes.at(memory.resource) : ResourceMaterializer::RuntimeImageModes(base); std::uint32_t tableSelector = 0u; std::uint32_t samplerGuard = 0u; std::uint32_t quadValid = 0u; if (state.bindlessImages && ResourceMaterializer::BindlessImage(state.program.Info(), state.program.Resources().stage, memory.resource)) { const auto access = EmitBindlessAccess(ctx, inst, memory); tableSelector = access.selector; if (BindlessQuadUniform(state, inst)) { tableSelector = BindlessQuadSelector(state, access); quadValid = access.valid; } } else if (tables) { const auto access = EmitTableAccess(ctx, inst, memory, base, tableSampler); if (access.unsupported) { state.tableAccess = {}; return; } if (base.table != NoTable) { const auto mode = Binary(state, spv::OpBitwiseAnd, TypeU32(state), Binary(state, spv::OpShiftRightLogical, TypeU32(state), access.flags, ConstantU32(state, ImageTableAbi::ModeShift)), ConstantU32(state, ImageTableAbi::ModeMask)); tableSelector = Select(state, TypeU32(state), access.valid, mode, ConstantU32(state, InvalidTableSelector)); } else { tableSelector = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::ImageBase + memory.resource * PipelineSpecialization::ImageWords, 0u); samplerGuard = access.valid; } } const auto emitMode = [&](const ImageResource& mode) { state.runtimeImage = &mode; if (mode.depthBits && memory.dataBits == 16u) { ctx.Fail(inst, "depth bits require a 32-bit image result"); } else { EmitImageMode(ctx, inst, mode); } }; if (modes.size() == 1u && !tables) { emitMode(modes.front()); state.runtimeImage = nullptr; return; } const auto selector = tables ? tableSelector : state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::ImageBase + memory.resource * PipelineSpecialization::ImageWords, 0u); const bool returnsValue = inst.Opcode() != IrOpcode::ImageWrite; const auto guardedId = returnsValue ? ctx.Result(inst) : 0u; ctx.definitions.Erase(&inst); const bool exits = !state.continueTarget; const auto guardMerge = samplerGuard != 0u ? state.module.AllocateId() : 0u; const auto guardSkip = samplerGuard != 0u ? state.module.AllocateId() : 0u; if (samplerGuard != 0u) { const auto guardBody = state.module.AllocateId(); state.module.AddFunction(spv::OpSelectionMerge, guardMerge, spv::SelectionControlMaskNone); state.module.AddFunction(spv::OpBranchConditional, samplerGuard, guardBody, guardSkip); EmitLabel(state, guardBody); } const auto resultId = returnsValue && (samplerGuard != 0u || quadValid != 0u) ? state.module.AllocateId() : guardedId; const auto merge = state.module.AllocateId(); const auto invalid = tables || exits ? state.module.AllocateId() : merge; const auto undefined = returnsValue && !tables && !exits ? state.module.AllocateId() : 0u; std::vector labels(modes.size()); std::vector emitLabel(modes.size(), false); std::vector words{spv::OpSwitch, selector, invalid}; for (std::uint32_t index = 0u; index < modes.size(); ++index) { if (base.table != NoTable && !TableModeEmitted(modes[index])) continue; std::uint32_t reused = 0u; for (std::uint32_t prev = 0u; prev < index; ++prev) { if (emitLabel[prev] && SameImageModeForInstruction(inst, memory, modes[prev], modes[index])) { reused = labels[prev]; break; } } if (reused != 0u) { labels[index] = reused; } else { labels[index] = state.module.AllocateId(); emitLabel[index] = true; } words.insert(words.end(), {index, labels[index]}); } std::vector incoming; if (undefined != 0u) { state.module.AddFunction(spv::OpUndef, TypeId(state, inst.Type()), undefined); incoming.insert(incoming.end(), {undefined, state.currentLabel}); } state.module.AddFunction(spv::OpSelectionMerge, merge, spv::SelectionControlMaskNone); state.module.AddFunction(words); for (std::uint32_t index = 0u; index < modes.size(); ++index) { if (!emitLabel[index]) continue; EmitLabel(state, labels[index]); emitMode(modes[index]); if (returnsValue) incoming.insert(incoming.end(), {ctx.Def(&inst), state.currentLabel}); ctx.definitions.Erase(&inst); state.module.AddFunction(spv::OpBranch, merge); } state.runtimeImage = nullptr; state.tableAccess = {}; if (tables) { EmitLabel(state, invalid); if (returnsValue) incoming.insert(incoming.end(), {ZeroResult(ctx, inst), invalid}); state.module.AddFunction(spv::OpBranch, merge); } else if (exits) { EmitLabel(state, invalid); state.module.AddFunction(spv::OpUnreachable); } EmitLabel(state, merge); if (returnsValue) { std::vector phi{spv::OpPhi, TypeId(state, inst.Type()), resultId}; phi.insert(phi.end(), incoming.begin(), incoming.end()); state.module.AddFunction(phi); if (quadValid != 0u) { const auto mask = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeBoolVector(state, 4u), mask, quadValid, quadValid, quadValid, quadValid); state.module.AddFunction(spv::OpSelect, TypeId(state, inst.Type()), guardedId, mask, resultId, ConstantU32CompositeZero(state, 4u)); } } if (samplerGuard != 0u) { state.module.AddFunction(spv::OpBranch, guardMerge); EmitLabel(state, guardSkip); state.module.AddFunction(spv::OpBranch, guardMerge); EmitLabel(state, guardMerge); if (returnsValue) state.module.AddFunction(spv::OpPhi, TypeId(state, inst.Type()), guardedId, resultId, merge, ZeroResult(ctx, inst), guardSkip); } if (returnsValue) ctx.definitions.Emplace(&inst, guardedId); } void EmitGetImageResource(SpirvValueEmitContext& context) { EmitVoid(context); } void EmitGetSamplerResource(SpirvValueEmitContext& context) { EmitVoid(context); } void EmitMakeImageAddress(SpirvValueEmitContext& context) { EmitVoid(context); } void EmitImageQueryDimensions(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageQueryLod(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageRead(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageWrite(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageSampleRaw(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageGatherRaw(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicSwap32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicIAdd32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicUMin32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicUMax32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicAnd32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicOr32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicXor32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicCmpSwap32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicISub32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicSMin32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicSMax32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicInc32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicDec32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicFCmpSwap32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicFMin32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicFMax32(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicSwap64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicIAdd64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicISub64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicUMin64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicUMax64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicSMin64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicSMax64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicAnd64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicOr64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicXor64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicInc64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicDec64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageAtomicCmpSwap64(SpirvValueEmitContext& ctx, const IrValue& inst) { EmitImage(ctx, inst); } void EmitImageBvhIntersectRay(SpirvValueEmitContext& ctx, const IrValue& inst) { auto& state = ctx.state; const auto u32 = TypeU32(state); const auto u64 = TypeScalarU64(state); const auto f32 = TypeF32(state); const auto boolean = TypeBool(state); const auto result4 = TypeU32Composite(state, 4u); const auto invalid = ConstantU32(state, 0xffffffffu); const auto uint = [&](std::uint32_t value) { return ConstantU32(state, value); }; const auto real = [&](std::uint32_t bits) { return ConstantF32(state, bits); }; const auto op = [&](spv::Op opcode, std::uint32_t type, std::uint32_t lhs, std::uint32_t rhs) { return Binary(state, opcode, type, lhs, rhs); }; const auto compose = [&](const std::array& values) { const auto id = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, result4, id, values[0], values[1], values[2], values[3]); return id; }; const auto asFloat = [&](std::uint32_t value) { return Unary(state, spv::OpBitcast, f32, value); }; const auto asUint = [&](std::uint32_t value) { return Unary(state, spv::OpBitcast, u32, value); }; const auto selectF = [&](std::uint32_t condition, std::uint32_t whenTrue, std::uint32_t whenFalse) { return Select(state, f32, condition, whenTrue, whenFalse); }; const auto selectU = [&](std::uint32_t condition, std::uint32_t whenTrue, std::uint32_t whenFalse) { return Select(state, u32, condition, whenTrue, whenFalse); }; const auto both = [&](std::uint32_t lhs, std::uint32_t rhs) { return op(spv::OpLogicalAnd, boolean, lhs, rhs); }; const auto either = [&](std::uint32_t lhs, std::uint32_t rhs) { return op(spv::OpLogicalOr, boolean, lhs, rhs); }; const auto isNan = [&](std::uint32_t value) { return Unary(state, spv::OpIsNan, boolean, value); }; const auto widen = [&](std::uint32_t value) { return Unary(state, spv::OpUConvert, u64, value); }; const auto pair = [&](std::uint32_t low, std::uint32_t high) { return op(spv::OpBitwiseOr, u64, widen(low), op(spv::OpShiftLeftLogical, u64, widen(high), BdaConstant(state, 32u))); }; const auto query = [&] { const auto descriptor = ctx.Arg(inst, 0); std::array word{}; for (std::uint32_t i = 0; i < 4u; ++i) { word[i] = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, word[i], descriptor, i); } const IrValue* address = ctx.ImageAddress(inst.Argument(1)); const auto component = [&](std::uint32_t index) { return ctx.Arg(*address, index); }; const bool a16 = (ctx.Memory(inst).imageSampleFlags & RdnaImageSampleFlagA16) != 0u; const bool node64 = ctx.Memory(inst).addressIsFull; const std::uint32_t ray = node64 ? 2u : 1u; const auto nodeLow = component(0); const auto node = node64 ? pair(nodeLow, component(1)) : widen(nodeLow); const auto type = op(spv::OpBitwiseAnd, u32, nodeLow, uint(7u)); const auto nodeIndex = op(spv::OpShiftRightLogical, u64, node, BdaConstant(state, 3u)); const auto baseUnits = pair(word[0], op(spv::OpBitwiseAnd, u32, word[1], uint(0xffu))); const auto lastNode = pair(word[2], op(spv::OpBitwiseAnd, u32, word[3], uint(0x3ffu))); const auto boxGrow = op(spv::OpBitwiseAnd, u32, op(spv::OpShiftRightLogical, u32, word[1], uint(23u)), uint(0xffu)); const auto boxSort = op(spv::OpINotEqual, boolean, op(spv::OpBitwiseAnd, u32, word[1], uint(0x80000000u)), uint(0u)); const auto barycentrics = op(spv::OpINotEqual, boolean, op(spv::OpBitwiseAnd, u32, word[3], uint(1u << 24u)), uint(0u)); const auto nodeAddress = op(spv::OpIAdd, u64, op(spv::OpShiftLeftLogical, u64, baseUnits, BdaConstant(state, 8u)), op(spv::OpShiftLeftLogical, u64, op(spv::OpBitwiseAnd, u64, node, BdaConstant(state, ~std::uint64_t{7u})), BdaConstant(state, 3u))); const auto within = [&](spv::Op compare) { const auto inRange = op(compare, boolean, nodeIndex, lastNode); return node64 ? inRange : both(op(spv::OpINotEqual, boolean, baseUnits, BdaConstant(state, 0u)), inRange); }; const auto valid = within(spv::OpULessThanEqual); const auto isTriangle = both(valid, op(spv::OpULessThanEqual, boolean, type, uint(3u))); const auto isBox16 = both(valid, op(spv::OpIEqual, boolean, type, uint(4u))); const auto isBox32 = both(within(spv::OpULessThan), op(spv::OpIEqual, boolean, type, uint(5u))); const auto extent = asFloat(component(ray)); std::array origin{}; std::array direction{}; std::array inverse{}; for (std::uint32_t axis = 0; axis < 3u; ++axis) { origin[axis] = asFloat(component(ray + 1u + axis)); if (!a16) { direction[axis] = asFloat(component(ray + 4u + axis)); inverse[axis] = asFloat(component(ray + 7u + axis)); continue; } const auto half = [&](std::uint32_t index) { const auto packed = component(ray + 4u + index / 2u); return EmitF16BitsToF32(state, index % 2u == 0u ? op(spv::OpBitwiseAnd, u32, packed, uint(0xffffu)) : op(spv::OpShiftRightLogical, u32, packed, uint(16u))); }; direction[axis] = half(axis); inverse[axis] = half(3u + axis); } const auto nodeDwords = [&](std::uint32_t count) { std::vector dwords; if (state.bdaProbeFunction == 0) { for (std::uint32_t first = 0; first < count; first += 4u) { const auto read = EmitBdaDwordReads(ctx, inst, nodeAddress, first * 4u, 4u, true); dwords.insert(dwords.end(), read.begin(), read.end()); } return dwords; } const auto pc = uint(inst.Flags().pc); const auto bytes = uint(count * 4u); const auto physical = state.module.AllocateId(); state.module.AddFunction(spv::OpFunctionCall, u64, physical, state.bdaProbeFunction, nodeAddress, bytes, pc); const auto mapped = both(op(spv::OpINotEqual, boolean, physical, BdaConstant(state, 0u)), op(spv::OpIEqual, boolean, op(spv::OpBitwiseAnd, u64, physical, BdaConstant(state, 3u)), BdaConstant(state, 0u))); EmitIfCondition(state, Unary(state, spv::OpLogicalNot, boolean, mapped), [&] { RecordBdaFault(state, nodeAddress, bytes, pc, BdaAbi::FaultReason::Unmapped); }); for (std::uint32_t first = 0; first < count; first += 4u) { const auto quad = EmitValueOrDefaultIfCondition(state, mapped, result4, ConstantU32CompositeZero(state, 4u), [&] { std::array values{}; for (std::uint32_t i = 0; i < 4u; ++i) { const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, op(spv::OpIAdd, u64, physical, BdaConstant(state, (first + i) * 4u))); values[i] = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, u32, values[i], pointer, spv::MemoryAccessAlignedMask, 4u); } return compose(values); }); for (std::uint32_t i = 0; i < 4u; ++i) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeExtract, u32, value, quad, i); dwords.push_back(value); } } return dwords; }; const auto sub = [&](const std::array& a, const std::array& b) { return std::array{op(spv::OpFSub, f32, a[0], b[0]), op(spv::OpFSub, f32, a[1], b[1]), op(spv::OpFSub, f32, a[2], b[2])}; }; const auto cross = [&](const std::array& a, const std::array& b) { const auto term = [&](std::uint32_t i, std::uint32_t j) { return op(spv::OpFSub, f32, op(spv::OpFMul, f32, a[i], b[j]), op(spv::OpFMul, f32, a[j], b[i])); }; return std::array{term(1, 2), term(2, 0), term(0, 1)}; }; const auto dot = [&](const std::array& a, const std::array& b) { return op(spv::OpFAdd, f32, op(spv::OpFAdd, f32, op(spv::OpFMul, f32, a[0], b[0]), op(spv::OpFMul, f32, a[1], b[1])), op(spv::OpFMul, f32, a[2], b[2])); }; const auto triangle = [&] { const auto d = nodeDwords(16u); const auto isType = [&](std::uint32_t value) { return op(spv::OpIEqual, boolean, type, uint(value)); }; const auto vertex = [&](std::array byType, std::uint32_t axis) { const auto at = [&](std::uint32_t index) { return asFloat(d[index * 3u + axis]); }; return selectF(isType(3u), at(byType[3]), selectF(isType(2u), at(byType[2]), selectF(isType(1u), at(byType[1]), at(byType[0])))); }; std::array v1{}; std::array v2{}; std::array v3{}; for (std::uint32_t axis = 0; axis < 3u; ++axis) { v1[axis] = vertex({0u, 1u, 2u, 2u}, axis); v2[axis] = vertex({1u, 3u, 3u, 4u}, axis); v3[axis] = vertex({2u, 2u, 4u, 0u}, axis); } const auto e1 = sub(v2, v1); const auto e2 = sub(v3, v1); const auto e3 = sub(origin, v1); const auto s1 = cross(direction, e2); const auto s2 = cross(e3, e1); auto tNum = dot(e2, s2); auto tDenom = dot(s1, e1); const auto iNum = dot(e3, s1); const auto jNum = dot(direction, s2); const auto t = op(spv::OpFDiv, f32, tNum, tDenom); const auto u = op(spv::OpFDiv, f32, iNum, tDenom); const auto v = op(spv::OpFDiv, f32, jNum, tDenom); const auto zero = real(0u); const auto one = real(0x3f800000u); const auto missed = either(either(either(op(spv::OpFOrdLessThan, boolean, u, zero), op(spv::OpFOrdGreaterThan, boolean, u, one)), either(op(spv::OpFOrdLessThan, boolean, v, zero), op(spv::OpFOrdGreaterThan, boolean, op(spv::OpFAdd, f32, u, v), one))), op(spv::OpFOrdLessThan, boolean, t, zero)); const auto signedInfinity = asFloat(op(spv::OpBitwiseOr, u32, op(spv::OpBitwiseAnd, u32, asUint(tDenom), uint(0x80000000u)), uint(0x7f800000u))); const auto baryNum = selectF(missed, signedInfinity, tNum); tNum = selectF(missed, real(0x7f800000u), tNum); const auto realDenom = tDenom; tDenom = selectF(missed, one, tDenom); const auto triangleId = d[15]; const auto shift = op(spv::OpShiftLeftLogical, u32, type, uint(3u)); const auto barycentric = [&](std::uint32_t sourceShift) { const auto source = op(spv::OpBitwiseAnd, u32, op(spv::OpShiftRightLogical, u32, triangleId, op(spv::OpIAdd, u32, shift, uint(sourceShift))), uint(3u)); const auto rest = op(spv::OpFSub, f32, op(spv::OpFSub, f32, realDenom, iNum), jNum); return selectF(op(spv::OpIEqual, boolean, source, uint(1u)), iNum, selectF(op(spv::OpIEqual, boolean, source, uint(2u)), jNum, rest)); }; const auto hit = Unary(state, spv::OpLogicalNot, boolean, missed); return compose({selectU(barycentrics, asUint(baryNum), asUint(tNum)), selectU(barycentrics, asUint(realDenom), asUint(tDenom)), selectU(barycentrics, asUint(barycentric(0u)), op(spv::OpIAdd, u32, triangleId, type)), selectU(barycentrics, asUint(barycentric(2u)), selectU(hit, uint(1u), uint(0u)))}); }; const auto boxes = [&](bool fp16) { const auto d = nodeDwords(fp16 ? 16u : 28u); const auto bound = [&](std::uint32_t child, std::uint32_t index) { const auto position = child * 6u + index; if (!fp16) { return asFloat(d[4u + position]); } const auto packed = d[4u + position / 2u]; return EmitF16BitsToF32(state, position % 2u == 0u ? op(spv::OpBitwiseAnd, u32, packed, uint(0xffffu)) : op(spv::OpShiftRightLogical, u32, packed, uint(16u))); }; const auto nanMax = [&](std::uint32_t a, std::uint32_t b) { return selectF(either(isNan(b), op(spv::OpFOrdGreaterThan, boolean, a, b)), a, b); }; const auto nanMin = [&](std::uint32_t a, std::uint32_t b) { return selectF(either(isNan(b), op(spv::OpFOrdLessThan, boolean, a, b)), a, b); }; const auto zero = real(0u); const auto growFactor = op(spv::OpFAdd, f32, real(0x3f800000u), op(spv::OpFMul, f32, Unary(state, spv::OpConvertUToF, f32, boxGrow), real(0x33800000u))); std::array children{}; std::array keys{}; auto rayNan = either(isNan(origin[0]), isNan(inverse[0])); for (std::uint32_t axis = 1; axis < 3u; ++axis) rayNan = either(rayNan, either(isNan(origin[axis]), isNan(inverse[axis]))); for (std::uint32_t child = 0; child < 4u; ++child) { std::uint32_t enter = 0; std::uint32_t leave = 0; for (std::uint32_t axis = 0; axis < 3u; ++axis) { const auto planeMin = op(spv::OpFMul, f32, op(spv::OpFSub, f32, bound(child, axis), origin[axis]), inverse[axis]); const auto planeMax = op(spv::OpFMul, f32, op(spv::OpFSub, f32, bound(child, axis + 3u), origin[axis]), inverse[axis]); const auto positive = op(spv::OpFOrdGreaterThanEqual, boolean, inverse[axis], zero); const auto near = selectF(positive, planeMin, planeMax); const auto far = selectF(positive, planeMax, planeMin); enter = axis == 0u ? near : nanMax(enter, near); leave = axis == 0u ? far : nanMin(leave, far); } const auto nan = either(rayNan, either(isNan(enter), isNan(leave))); const auto minT = selectF(nan, real(0x7f800000u), selectF(op(spv::OpFOrdGreaterThan, boolean, enter, zero), enter, zero)); const auto maxT = selectF(nan, real(0xff800000u), selectF(op(spv::OpFOrdLessThan, boolean, leave, extent), leave, extent)); const auto hit = op(spv::OpFOrdLessThanEqual, boolean, minT, op(spv::OpFMul, f32, maxT, growFactor)); children[child] = selectU(hit, d[child], invalid); keys[child] = minT; } auto sorted = children; for (const auto [a, b] : std::array, 5>{{{0, 2}, {1, 3}, {0, 1}, {2, 3}, {1, 2}}}) { const auto bValid = op(spv::OpINotEqual, boolean, sorted[b], invalid); const auto aInvalid = op(spv::OpIEqual, boolean, sorted[a], invalid); const auto swap = either(both(bValid, op(spv::OpFOrdLessThan, boolean, keys[b], keys[a])), aInvalid); const auto sortedA = selectU(swap, sorted[b], sorted[a]); const auto sortedB = selectU(swap, sorted[a], sorted[b]); const auto keyA = selectF(swap, keys[b], keys[a]); const auto keyB = selectF(swap, keys[a], keys[b]); sorted[a] = sortedA; sorted[b] = sortedB; keys[a] = keyA; keys[b] = keyB; } for (std::uint32_t child = 0; child < 4u; ++child) { children[child] = selectU(boxSort, sorted[child], children[child]); } return compose(children); }; const auto none = compose({invalid, invalid, invalid, invalid}); const auto tested = EmitValueOrDefaultIfCondition(state, isTriangle, result4, none, triangle); const auto box16 = EmitValueOrDefaultIfCondition(state, isBox16, result4, tested, [&] { return boxes(true); }); return EmitValueOrDefaultIfCondition(state, isBox32, result4, box16, [&] { return boxes(false); }); }; const auto inactive = compose({invalid, invalid, invalid, invalid}); ctx.Define(inst, EmitValueOrDefaultIfCondition(state, ctx.Arg(inst, 2), result4, inactive, query)); } }