Skip to content

Added DirectX 12 driver support - #108

Open
niy-ati wants to merge 25 commits into
libmir:masterfrom
niy-ati:targetDirectX-scaffold
Open

niy-ati wants to merge 25 commits into
libmir:masterfrom
niy-ati:targetDirectX-scaffold

Conversation

@niy-ati

@niy-ati niy-ati commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

This adds a DirectX 12 backend to DCompute, following the same driver architecture used by the existing CUDA and OpenCL backends.

What's included

Host driver (\dcompute.driver.d3d12):

  • D3D12/DXGI device enumeration and initialization
  • Buffer allocation with upload/readback via staging resources
  • Image/Texture support via \CopyTextureRegion\
  • Async command queue with ring-buffer allocator pooling and fence-based synchronization
  • PSO (Pipeline State Object) compilation and caching
  • Unified Shared Memory detection
  • SM 6.6 Bindless descriptor heap — resources are passed as 32-bit heap indices via a single CBV, removing per-dispatch descriptor table updates
  • Multi-device context management using thread-local storage (similar to CUDA's \cuCtxPushCurrent)
  • COM resource lifetime tracking with deferred release

Device-side standard library (\dcompute.std.directx):

  • Thread indexing mapped to DXIL intrinsics (\llvm.dx.thread.id, \llvm.dx.group.id, \llvm.dx.thread.id.in.group)
  • Device-side Image structs (\Image1D, \Image2D, \Image3D) mapped to texture load intrinsics

niy-ati added 24 commits August 8, 2026 20:44
…aces

Replace manual C-style vtable structs (IDXGIFactory4Vtbl, etc.) and
(*obj.lpVtbl).Method(cast(void*)&obj, ...) boilerplate with idiomatic
D extern(Windows) interface inheritance from IUnknown.

This eliminates ~120 lines of manual vtable layout and simplifies every
call site across the driver stack (device, platform, program, queue,
buffer, kernel) from:
  (*device.lpVtbl).CreateCommandQueue(cast(void*)&device, ...)
to:
  device.CreateCommandQueue(...)

The COM ABI is preserved exactly: D interfaces use the same vtable
pointer layout as COM, so the binary interface is identical.
- Buffer: Replace single 'stagingResource' pointer with separate
  'uploadResource' and 'readbackResource' pointers, and allocate them
  lazily. This prevents hostToDevice/deviceToHost copy interleaving
  from silently overwriting pointers and leaking UPLOAD/READBACK heaps.
- Queue: Ensure dynamically allocated Constant Buffers (cbResource)
  used for scalar arguments are released after the dispatch queue syncs,
  preventing massive VRAM leaks in compute loops.
… and bump-pointer descriptor heap

- Add Event struct for non-blocking GPU synchronization via fence values
- Replace synchronous wait() in enqueue with InFlightResource pool that
  tracks CommandAllocator/CommandList pairs tied to fence values
- Create single large SHADER_VISIBLE descriptor heap (65536 descriptors)
  with bump-pointer sub-allocation instead of per-dispatch heap creation
- Track pending resource releases per in-flight allocator for safe
  deferred cleanup of transient constant buffers
- Queue.enqueue now returns Event instead of blocking the CPU
- Split single staging pointer into separate uploadResource and
  readbackResource to prevent interleaved hostToDevice/deviceToHost
  copies from silently overwriting and leaking old heaps
- Add checkErrors(hr) for CreateCommittedResource and Map calls
- Add lazy allocation of staging buffers on first use
- Add backend-agnostic DriverStatus enum to dcompute.driver.error
  (success, invalidValue, outOfMemory, deviceLost, notSupported, etc.)
- Update DComputeDriverException to carry DriverStatus alongside
  native error message for rich diagnostics
- Create dcompute.driver.d3d12.error module with mapHRESULT() that
  translates native Windows HRESULTs to unified DriverStatus
- Sweep platform.d and device.d to replace silent if(FAILED(hr))
  returns with checkErrors(hr) calls
- Add checkKernelABI template to traits.d with compile-time validation:
  scalar args must be POD, total scalar size <= 64KB constant buffer limit
- Document formal ABI mapping in buildRootSignature: Buffers map to
  Space 0 u0+ (UAV Table), scalars pack into Space 0 c0 (CBV)
- Implement lazy-loading PSO cache (Kernel!void[string] _kernelCache)
  in Program to avoid re-invoking CreateComputePipelineState per dispatch
- Add proper cleanup in Program.unload() to Release all cached PSOs
  and Root Signatures, plugging the pipeline VRAM leak
- Add UnifiedBuffer!T using D3D12_HEAP_TYPE_CUSTOM with WRITE_BACK cache
  to mirror CUDA's cuMemAllocManaged functionality. Enables zero-copy
  host/device memory sharing seamlessly integrating with Queue dispatch.
- Fix buffer.d to actually execute GPU memory copies for hostToDevice
  and deviceToHost by dispatching commands to the Runtime's defaultQueue.
- Fix runtime.d defaultQueue to return a pointer so fence states correctly
  mutate across commands.
- Add Queue.wait(Event) mirroring cuda/queue.d's cuStreamWaitEvent.
- Maps to ID3D12CommandQueue::Wait, allowing a queue to stall on a fence
  value entirely on the GPU without blocking the CPU via WaitForSingleObject.
- This provides the necessary foundational API for multi-queue workflows
  such as overlapping dedicated copy and compute queues.
- CRITICAL FIX: executeCopy was calling CopyResource without inserting
  ResourceBarrier transitions. D3D12 requires explicit state transitions
  (e.g. UNORDERED_ACCESS -> COPY_SOURCE) or GPU caches are incoherent
  and the copy produces undefined results. Fixed by inserting proper
  transition barriers before and after the copy, then restoring original
  resource states.
- Add ID3D12CommandQueue::Wait to COM bindings (was completely missing,
  causing Queue.wait(Event) to fail at link time).
- Add ID3D12CommandQueue::GetTimestampFrequency binding for future
  GPU profiling/timestamp query support.
- Add Queue.finish() mirroring OpenCL's clFinish: drains all pending
  GPU work by signaling and waiting on the queue's fence.
- Update Buffer.copy to pass correct resource states to executeCopy
  (GENERIC_READ for upload heaps, COPY_DEST for readback heaps).
…to main.d

- Adds test-directx configuration in dub.json setting --mdcompute-targets=directx-660
- Implements DComputeTestDirectX block in tests/main.d
- Tests standard buffer allocation, execution, and host readback
- Tests Unified Shared Memory (UnifiedBuffer!T) allocation and execution
- NEW: image.d - Image!(uint Dim, T) struct supporting 1D/2D/3D textures
  with swizzled GPU layout (D3D12_TEXTURE_LAYOUT.UNKNOWN) for optimal
  GPU cache performance. Uses GetCopyableFootprints to compute proper
  row pitch alignment for staging buffer uploads/readbacks.
- NEW: executeTextureCopy in queue.d using CopyTextureRegion instead of
  CopyResource, with proper resource state transition barriers.
- Add D3D12_TEXTURE_COPY_LOCATION, D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
  D3D12_BOX, D3D12_SUBRESOURCE_FOOTPRINT structs to bindings.d.
- Add CopyTextureRegion to ID3D12GraphicsCommandList vtable.
- Add GetCopyableFootprints and GetDeviceRemovedReason to ID3D12Device.
- Expand DXGI_FORMAT with R8/R16/RGBA8/BGRA8 entries for texture use.
- Update package.d to export all modules (image, queue, event, error, runtime).
- Added abi_test to dummykernels.d containing interleaved structs,
  scalars, and buffers.
- Added ABI execution block to D3D12 test suite in main.d to validate
  dynamic descriptor table extraction logic matches compiler expectations.
- traits.d: Add isImageArg and update countUAVs, countScalars, and
  enforceABI to support Texture2D arguments.
- queue.d: Update descriptor table mapping logic to seamlessly generate
  Texture UAV descriptors alongside Buffer UAVs dynamically.
- tests: Added image_test dummy kernel to validate Texture unpacking.
- tests: Added e2e Image Descriptor Packing phase in main.d.
- Map CacheCoherentUMA through ID3D12Device::CheckFeatureSupport to correctly report supportsUnifiedMemory.

- Separate monolithic queue into dedicated Compute (DIRECT) and Copy (COPY) command queues.

- Synchronize cross-queue data transfers natively via D3D12 fences for async DMA overlap.

- Remove incomplete image_test to fix host compilation (LDC DXIL image intrinsics pending).
- D3D12 Copy Queues do not support transitions involving compute states (like UNORDERED_ACCESS).

- Modify Queue.executeCopy to rely on implicit promotion/decay.

- Update Buffer and Image copy routines to issue pre-copy COMMON transitions on the Compute queue.
- Added missing launch execution for auto_index_test.

- Added Image ABI signature validation test using dummy Texture2D.
- Implemented Queue.release() to safely teardown ID3D12CommandQueue, ID3D12Fence, and globalDescriptorHeaps.

- Added missing teardown hooks in test suite to prevent driver exhaustion.
- Implemented dcompute.driver.d3d12.memory

- Provides MemoryPointer and Memory structs

- Bridges parity with CUDA backend for manual allocation
…frastructure

Added D3D_SHADER_MODEL enum (SM 5.1 through 6.8), D3D12_RESOURCE_BINDING_TIER enum, D3D12_FEATURE_DATA_SHADER_MODEL and D3D12_FEATURE_DATA_D3D12_OPTIONS structs to bindings.d.

Expanded device.d with highestShaderModel(), resourceBindingTier(), supportsBindless(), and supportsWaveIntrinsics() capability queries using CheckFeatureSupport.

Added hardware capabilities discovery test to tests/main.d that reports SM version, binding tier, bindless support, wave intrinsics, and USM at runtime.
Modernized the D3D12 host driver backend. Implemented Bindless ABI SM 6.6 support toggled via config. Added full CUDA-parity context management and switching. Added device-side thread indexing intrinsics for DirectX.
@niy-ati niy-ati changed the title D3D12: Add DirectX 12 compute driver and device-side DXIL support Added DirectX 12 driver support Sep 30, 2026
@niy-ati
niy-ati marked this pull request as ready for review October 2, 2026 14:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant