M0.0: DXIL container, hash, bitcode writer and SPIR-V builder
- Port of DXC's container hash (ComputeHashRetail); matches dxc-signed containers on both padding paths. - DXIL container reader/writer that signs its output. - LLVM bitstream writer and a minimal LLVM 3.7 IR model that encodes types, constants, functions, core instructions and metadata as bitcode. - An empty compute shader that dxv accepts for SM 6.0 through 6.9. - SPIR-V builder; the empty compute module passes spirv-val (Vulkan 1.0). - `zig build oracle` runs these checks against the DXC build. - Zig 0.17 skill in .claude/skills/zig. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8e38009a69
commit
be9b6908cf
|
|
@ -0,0 +1,26 @@
|
|||
---
|
||||
name: zig
|
||||
description: Work on Zig 0.17 code and build files using the documentation and standard-library source shipped with the active compiler. Use for writing, reviewing, debugging, or migrating Zig in this repository.
|
||||
---
|
||||
|
||||
# Zig 0.17
|
||||
|
||||
Use the installed Zig toolchain as the source of truth. Do not rely on remembered
|
||||
APIs or hand-maintained summaries when the compiler distribution can answer the
|
||||
question directly.
|
||||
|
||||
- Run `zig env` to locate `zig_exe`, `lib_dir`, and `std_dir`; do not assume a
|
||||
particular installation path.
|
||||
- Consult `<directory containing zig_exe>/doc/langref.html` for language syntax,
|
||||
semantics, and builtins.
|
||||
- Search `std_dir` for exact APIs, implementations, and tests. Use them as
|
||||
examples of both correct usage and Zig coding style; follow standard-library
|
||||
conventions.
|
||||
- Use compiler and test failures to verify any inferred API usage.
|
||||
|
||||
For `if` conditions, put continuation `and`/`or` operators at the start of
|
||||
the next line. Run `zig fmt` on changed Zig files.
|
||||
|
||||
If the installed documentation is unavailable, use the versioned official
|
||||
reference at <https://ziglang.org/documentation/0.17.0/>; download a copy once and
|
||||
avoid unnecessary traffic.
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
//! LLVM bitstream writer (the container format under LLVM bitcode).
|
||||
//! Only unabbreviated records are emitted for now; they are always valid and
|
||||
//! the LLVM 3.7 reader accepts them everywhere.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub const abbrev_end_block = 0;
|
||||
pub const abbrev_enter_subblock = 1;
|
||||
pub const abbrev_define = 2;
|
||||
pub const abbrev_unabbrev_record = 3;
|
||||
|
||||
pub const Writer = struct {
|
||||
gpa: Allocator,
|
||||
bytes: std.ArrayList(u8) = .empty,
|
||||
cur: u64 = 0,
|
||||
cur_bits: u6 = 0,
|
||||
abbrev_width: u32 = 2,
|
||||
blocks: std.ArrayList(Block) = .empty,
|
||||
|
||||
const Block = struct { prev_width: u32, size_word_index: usize };
|
||||
|
||||
pub fn init(gpa: Allocator) Writer {
|
||||
return .{ .gpa = gpa };
|
||||
}
|
||||
|
||||
pub fn deinit(w: *Writer) void {
|
||||
w.bytes.deinit(w.gpa);
|
||||
w.blocks.deinit(w.gpa);
|
||||
}
|
||||
|
||||
pub fn emit(w: *Writer, value: u64, width: u32) !void {
|
||||
std.debug.assert(width <= 32);
|
||||
if (width == 0) return;
|
||||
std.debug.assert(width == 32 or value >> @intCast(width) == 0);
|
||||
w.cur |= value << w.cur_bits;
|
||||
const total = @as(u32, w.cur_bits) + width;
|
||||
if (total >= 32) {
|
||||
var word: [4]u8 = undefined;
|
||||
std.mem.writeInt(u32, &word, @truncate(w.cur), .little);
|
||||
try w.bytes.appendSlice(w.gpa, &word);
|
||||
w.cur >>= 32;
|
||||
w.cur_bits = @intCast(total - 32);
|
||||
} else {
|
||||
w.cur_bits = @intCast(total);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn emitVbr(w: *Writer, value: u64, width: u32) !void {
|
||||
const threshold: u64 = @as(u64, 1) << @intCast(width - 1);
|
||||
var v = value;
|
||||
while (v >= threshold) {
|
||||
try w.emit((v & (threshold - 1)) | threshold, width);
|
||||
v >>= @intCast(width - 1);
|
||||
}
|
||||
try w.emit(v, width);
|
||||
}
|
||||
|
||||
pub fn alignTo32(w: *Writer) !void {
|
||||
if (w.cur_bits > 0) try w.emit(0, 32 - @as(u32, w.cur_bits));
|
||||
}
|
||||
|
||||
pub fn enterBlock(w: *Writer, block_id: u32, abbrev_width: u32) !void {
|
||||
try w.emit(abbrev_enter_subblock, w.abbrev_width);
|
||||
try w.emitVbr(block_id, 8);
|
||||
try w.emitVbr(abbrev_width, 4);
|
||||
try w.alignTo32();
|
||||
const idx = w.bytes.items.len;
|
||||
try w.emit(0, 32); // block size in words, patched in endBlock
|
||||
try w.blocks.append(w.gpa, .{ .prev_width = w.abbrev_width, .size_word_index = idx });
|
||||
w.abbrev_width = abbrev_width;
|
||||
}
|
||||
|
||||
pub fn endBlock(w: *Writer) !void {
|
||||
try w.emit(abbrev_end_block, w.abbrev_width);
|
||||
try w.alignTo32();
|
||||
const blk = w.blocks.pop().?;
|
||||
const words: u32 = @intCast((w.bytes.items.len - blk.size_word_index - 4) / 4);
|
||||
std.mem.writeInt(u32, w.bytes.items[blk.size_word_index..][0..4], words, .little);
|
||||
w.abbrev_width = blk.prev_width;
|
||||
}
|
||||
|
||||
pub fn record(w: *Writer, code: u32, ops: []const u64) !void {
|
||||
try w.emit(abbrev_unabbrev_record, w.abbrev_width);
|
||||
try w.emitVbr(code, 6);
|
||||
try w.emitVbr(ops.len, 6);
|
||||
for (ops) |op| try w.emitVbr(op, 6);
|
||||
}
|
||||
|
||||
/// Record whose operands are the bytes of `str`, optionally prefixed.
|
||||
pub fn recordString(w: *Writer, code: u32, prefix: []const u64, str: []const u8) !void {
|
||||
try w.emit(abbrev_unabbrev_record, w.abbrev_width);
|
||||
try w.emitVbr(code, 6);
|
||||
try w.emitVbr(prefix.len + str.len, 6);
|
||||
for (prefix) |op| try w.emitVbr(op, 6);
|
||||
for (str) |c| try w.emitVbr(c, 6);
|
||||
}
|
||||
|
||||
/// Flush pending bits and return the finished stream (caller owns it).
|
||||
pub fn finish(w: *Writer) ![]u8 {
|
||||
std.debug.assert(w.blocks.items.len == 0);
|
||||
try w.alignTo32();
|
||||
return w.bytes.toOwnedSlice(w.gpa);
|
||||
}
|
||||
};
|
||||
|
||||
test "vbr and fixed fields pack little-endian" {
|
||||
var w = Writer.init(std.testing.allocator);
|
||||
defer w.deinit();
|
||||
try w.emit('B', 8);
|
||||
try w.emit('C', 8);
|
||||
try w.emit(0x0, 4);
|
||||
try w.emit(0xC, 4);
|
||||
try w.emit(0xE, 4);
|
||||
try w.emit(0xD, 4);
|
||||
const out = try w.finish();
|
||||
defer std.testing.allocator.free(out);
|
||||
try std.testing.expectEqualSlices(u8, &.{ 'B', 'C', 0xC0, 0xDE }, out);
|
||||
}
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
//! DXIL container ("DXBC" header + parts). See
|
||||
//! include/dxc/DxilContainer/DxilContainer.h.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const hash = @import("hash.zig");
|
||||
|
||||
pub fn fourcc(comptime s: *const [4]u8) u32 {
|
||||
return std.mem.readInt(u32, s, .little);
|
||||
}
|
||||
|
||||
pub const Part = struct {
|
||||
fourcc: u32,
|
||||
data: []const u8,
|
||||
};
|
||||
|
||||
const header_size = 32; // FourCC, hash[16], version, size, part count
|
||||
|
||||
/// Assemble parts into a container and sign it (as the validator would).
|
||||
pub fn assemble(gpa: Allocator, parts: []const Part) ![]u8 {
|
||||
var size: usize = header_size + 4 * parts.len;
|
||||
for (parts) |p| size += 8 + std.mem.alignForward(usize, p.data.len, 4);
|
||||
const out = try gpa.alloc(u8, size);
|
||||
@memset(out, 0);
|
||||
|
||||
std.mem.writeInt(u32, out[0..4], fourcc("DXBC"), .little);
|
||||
std.mem.writeInt(u16, out[20..22], 1, .little); // version major
|
||||
std.mem.writeInt(u16, out[22..24], 0, .little); // version minor
|
||||
std.mem.writeInt(u32, out[24..28], @intCast(size), .little);
|
||||
std.mem.writeInt(u32, out[28..32], @intCast(parts.len), .little);
|
||||
|
||||
var off: usize = header_size + 4 * parts.len;
|
||||
for (parts, 0..) |p, i| {
|
||||
std.mem.writeInt(u32, out[header_size + 4 * i ..][0..4], @intCast(off), .little);
|
||||
std.mem.writeInt(u32, out[off..][0..4], p.fourcc, .little);
|
||||
const padded = std.mem.alignForward(usize, p.data.len, 4);
|
||||
std.mem.writeInt(u32, out[off + 4 ..][0..4], @intCast(padded), .little);
|
||||
@memcpy(out[off + 8 ..][0..p.data.len], p.data);
|
||||
off += 8 + padded;
|
||||
}
|
||||
hash.signContainer(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
pub const ParseError = error{InvalidContainer};
|
||||
|
||||
/// Parsed view into a container; part data slices alias `bytes`.
|
||||
pub const View = struct {
|
||||
bytes: []const u8,
|
||||
parts: std.ArrayList(Part),
|
||||
|
||||
pub fn deinit(v: *View, gpa: Allocator) void {
|
||||
v.parts.deinit(gpa);
|
||||
}
|
||||
|
||||
pub fn find(v: *const View, cc: u32) ?[]const u8 {
|
||||
for (v.parts.items) |p| if (p.fourcc == cc) return p.data;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
pub fn parse(gpa: Allocator, bytes: []const u8) !View {
|
||||
if (bytes.len < header_size) return error.InvalidContainer;
|
||||
if (std.mem.readInt(u32, bytes[0..4], .little) != fourcc("DXBC")) return error.InvalidContainer;
|
||||
const size = std.mem.readInt(u32, bytes[24..28], .little);
|
||||
const count = std.mem.readInt(u32, bytes[28..32], .little);
|
||||
if (size > bytes.len or header_size + 4 * @as(usize, count) > size) return error.InvalidContainer;
|
||||
var parts: std.ArrayList(Part) = .empty;
|
||||
errdefer parts.deinit(gpa);
|
||||
for (0..count) |i| {
|
||||
const off = std.mem.readInt(u32, bytes[header_size + 4 * i ..][0..4], .little);
|
||||
if (@as(usize, off) + 8 > size) return error.InvalidContainer;
|
||||
const cc = std.mem.readInt(u32, bytes[off..][0..4], .little);
|
||||
const len = std.mem.readInt(u32, bytes[off + 4 ..][0..4], .little);
|
||||
if (@as(usize, off) + 8 + len > size) return error.InvalidContainer;
|
||||
try parts.append(gpa, .{ .fourcc = cc, .data = bytes[off + 8 ..][0..len] });
|
||||
}
|
||||
return .{ .bytes = bytes[0..size], .parts = parts };
|
||||
}
|
||||
|
||||
/// True if the stored hash matches a fresh ComputeHashRetail of the container.
|
||||
pub fn hashMatches(bytes: []const u8) bool {
|
||||
const digest = hash.computeRetail(bytes[hash.hash_start_offset..]);
|
||||
return std.mem.eql(u8, &digest, bytes[4..20]);
|
||||
}
|
||||
|
||||
test "assemble round-trips through parse and verifies its hash" {
|
||||
const gpa = std.testing.allocator;
|
||||
const parts = [_]Part{
|
||||
.{ .fourcc = fourcc("SFI0"), .data = &@as([8]u8, @splat(0)) },
|
||||
.{ .fourcc = fourcc("PRIV"), .data = "abc" },
|
||||
};
|
||||
const out = try assemble(gpa, &parts);
|
||||
defer gpa.free(out);
|
||||
try std.testing.expect(hashMatches(out));
|
||||
var view = try parse(gpa, out);
|
||||
defer view.deinit(gpa);
|
||||
try std.testing.expectEqual(@as(usize, 2), view.parts.items.len);
|
||||
try std.testing.expectEqualSlices(u8, "abc\x00", view.find(fourcc("PRIV")).?);
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
const std = @import("std");
|
||||
|
||||
const padding = [_]u8{0x80} ++ [_]u8{0} ** 63;
|
||||
const padding: [64]u8 = .{0x80} ++ @as([63]u8, @splat(0));
|
||||
|
||||
const shifts = [64]u5{
|
||||
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,571 @@
|
|||
//! A minimal LLVM 3.7 IR model plus its bitcode encoder: just enough of LLVM
|
||||
//! to express DXIL. Mirrors lib/Bitcode/Writer/BitcodeWriter.cpp, emitting
|
||||
//! unabbreviated records only.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const bitstream = @import("bitstream.zig");
|
||||
|
||||
pub const TypeId = u32;
|
||||
pub const ConstId = u32;
|
||||
pub const MdId = u32;
|
||||
|
||||
pub const Type = union(enum) {
|
||||
void,
|
||||
label,
|
||||
metadata,
|
||||
half,
|
||||
float,
|
||||
double,
|
||||
int: u32,
|
||||
pointer: struct { elem: TypeId, addr_space: u32 = 0 },
|
||||
function: struct { ret: TypeId, params: []const TypeId },
|
||||
@"struct": struct { name: []const u8, elems: []const TypeId, @"packed": bool = false },
|
||||
array: struct { len: u64, elem: TypeId },
|
||||
vector: struct { len: u32, elem: TypeId },
|
||||
|
||||
fn eql(a: Type, b: Type) bool {
|
||||
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
|
||||
return switch (a) {
|
||||
.void, .label, .metadata, .half, .float, .double => true,
|
||||
.int => |w| w == b.int,
|
||||
.pointer => |p| p.elem == b.pointer.elem and p.addr_space == b.pointer.addr_space,
|
||||
.function => |f| f.ret == b.function.ret and std.mem.eql(TypeId, f.params, b.function.params),
|
||||
// Named structs are nominal.
|
||||
.@"struct" => |s| std.mem.eql(u8, s.name, b.@"struct".name),
|
||||
.array => |x| x.len == b.array.len and x.elem == b.array.elem,
|
||||
.vector => |x| x.len == b.vector.len and x.elem == b.vector.elem,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Constant = struct {
|
||||
ty: TypeId,
|
||||
kind: union(enum) {
|
||||
int: i64,
|
||||
/// Raw IEEE bits (f16/f32/f64 per type).
|
||||
float_bits: u64,
|
||||
undef,
|
||||
null,
|
||||
},
|
||||
};
|
||||
|
||||
pub const Linkage = enum(u32) { external = 0, internal = 3 };
|
||||
|
||||
/// Attribute group for function declarations (e.g. dx.op functions).
|
||||
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly };
|
||||
|
||||
pub const Value = union(enum) {
|
||||
/// Index into Module.functions.
|
||||
function: u32,
|
||||
constant: ConstId,
|
||||
arg: u32,
|
||||
/// Index into Function.insts; must produce a value.
|
||||
inst: u32,
|
||||
};
|
||||
|
||||
pub const BinOp = enum(u32) { add = 0, sub = 1, mul = 2, udiv = 3, sdiv = 4, urem = 5, srem = 6, shl = 7, lshr = 8, ashr = 9, @"and" = 10, @"or" = 11, xor = 12 };
|
||||
pub const CastOp = enum(u32) { trunc = 0, zext = 1, sext = 2, fptoui = 3, fptosi = 4, uitofp = 5, sitofp = 6, fptrunc = 7, fpext = 8, ptrtoint = 9, inttoptr = 10, bitcast = 11 };
|
||||
|
||||
pub const Inst = struct {
|
||||
/// Result type; `void` for instructions without a result.
|
||||
ty: TypeId,
|
||||
op: union(enum) {
|
||||
ret: ?Value,
|
||||
br: struct { then: u32, @"else": ?u32 = null, cond: ?Value = null },
|
||||
call: struct { callee: u32, args: []const Value },
|
||||
binop: struct { op: BinOp, lhs: Value, rhs: Value, flags: u32 = 0 },
|
||||
cast: struct { op: CastOp, val: Value },
|
||||
cmp: struct { pred: u32, lhs: Value, rhs: Value },
|
||||
select: struct { cond: Value, t: Value, f: Value },
|
||||
extractvalue: struct { agg: Value, index: u32 },
|
||||
phi: struct { incoming: []const struct { val: Value, block: u32 } },
|
||||
},
|
||||
};
|
||||
|
||||
pub const Function = struct {
|
||||
name: []const u8,
|
||||
ty: TypeId,
|
||||
linkage: Linkage = .external,
|
||||
attrs: FnAttrs = .none,
|
||||
/// Declarations have no blocks.
|
||||
num_blocks: u32 = 0,
|
||||
/// Instructions in block order; a terminator ends each block.
|
||||
insts: std.ArrayList(Inst) = .empty,
|
||||
};
|
||||
|
||||
pub const Metadata = union(enum) {
|
||||
string: []const u8,
|
||||
value: struct { ty: TypeId, val: Value },
|
||||
/// Operands: null entries encode as 0 (no metadata).
|
||||
node: []const ?MdId,
|
||||
};
|
||||
|
||||
pub const Module = struct {
|
||||
arena: std.heap.ArenaAllocator,
|
||||
triple: []const u8 = "dxil-ms-dx",
|
||||
datalayout: []const u8 = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
|
||||
types: std.ArrayList(Type) = .empty,
|
||||
constants: std.ArrayList(Constant) = .empty,
|
||||
functions: std.ArrayList(Function) = .empty,
|
||||
metadata: std.ArrayList(Metadata) = .empty,
|
||||
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
|
||||
|
||||
pub fn init(gpa: Allocator) Module {
|
||||
return .{ .arena = .init(gpa) };
|
||||
}
|
||||
|
||||
pub fn deinit(m: *Module) void {
|
||||
m.arena.deinit();
|
||||
}
|
||||
|
||||
pub fn allocator(m: *Module) Allocator {
|
||||
return m.arena.allocator();
|
||||
}
|
||||
|
||||
pub fn getType(m: *Module, t: Type) !TypeId {
|
||||
for (m.types.items, 0..) |existing, i| {
|
||||
if (existing.eql(t)) return @intCast(i);
|
||||
}
|
||||
const a = m.allocator();
|
||||
var owned = t;
|
||||
switch (owned) {
|
||||
.function => |*f| f.params = try a.dupe(TypeId, f.params),
|
||||
.@"struct" => |*s| {
|
||||
s.name = try a.dupe(u8, s.name);
|
||||
s.elems = try a.dupe(TypeId, s.elems);
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
try m.types.append(a, owned);
|
||||
return @intCast(m.types.items.len - 1);
|
||||
}
|
||||
|
||||
pub fn intType(m: *Module, bits: u32) !TypeId {
|
||||
return m.getType(.{ .int = bits });
|
||||
}
|
||||
|
||||
pub fn fnType(m: *Module, ret: TypeId, params: []const TypeId) !TypeId {
|
||||
return m.getType(.{ .function = .{ .ret = ret, .params = params } });
|
||||
}
|
||||
|
||||
pub fn ptrType(m: *Module, elem: TypeId) !TypeId {
|
||||
return m.getType(.{ .pointer = .{ .elem = elem } });
|
||||
}
|
||||
|
||||
/// Lookup of an existing pointer type, used while encoding. Function
|
||||
/// pointer types are created by addFunction.
|
||||
fn ptrTypeConst(m: *const Module, elem: TypeId) TypeId {
|
||||
for (m.types.items, 0..) |t, i| {
|
||||
if (t == .pointer and t.pointer.elem == elem and t.pointer.addr_space == 0) return @intCast(i);
|
||||
}
|
||||
unreachable;
|
||||
}
|
||||
|
||||
pub fn constant(m: *Module, c: Constant) !Value {
|
||||
for (m.constants.items, 0..) |existing, i| {
|
||||
if (existing.ty == c.ty and std.meta.eql(existing.kind, c.kind)) return .{ .constant = @intCast(i) };
|
||||
}
|
||||
try m.constants.append(m.allocator(), c);
|
||||
return .{ .constant = @intCast(m.constants.items.len - 1) };
|
||||
}
|
||||
|
||||
pub fn constInt(m: *Module, bits: u32, v: i64) !Value {
|
||||
return m.constant(.{ .ty = try m.intType(bits), .kind = .{ .int = v } });
|
||||
}
|
||||
|
||||
pub fn addFunction(m: *Module, f: Function) !u32 {
|
||||
var owned = f;
|
||||
owned.name = try m.allocator().dupe(u8, f.name);
|
||||
_ = try m.ptrType(f.ty);
|
||||
try m.functions.append(m.allocator(), owned);
|
||||
return @intCast(m.functions.items.len - 1);
|
||||
}
|
||||
|
||||
pub fn findFunction(m: *Module, name: []const u8) ?u32 {
|
||||
for (m.functions.items, 0..) |f, i| if (std.mem.eql(u8, f.name, name)) return @intCast(i);
|
||||
return null;
|
||||
}
|
||||
|
||||
pub fn addInst(m: *Module, func: u32, inst: Inst) !Value {
|
||||
const f = &m.functions.items[func];
|
||||
try f.insts.append(m.allocator(), inst);
|
||||
return .{ .inst = @intCast(f.insts.items.len - 1) };
|
||||
}
|
||||
|
||||
pub fn mdString(m: *Module, s: []const u8) !MdId {
|
||||
for (m.metadata.items, 0..) |md, i| {
|
||||
if (md == .string and std.mem.eql(u8, md.string, s)) return @intCast(i);
|
||||
}
|
||||
try m.metadata.append(m.allocator(), .{ .string = try m.allocator().dupe(u8, s) });
|
||||
return @intCast(m.metadata.items.len - 1);
|
||||
}
|
||||
|
||||
pub fn mdValue(m: *Module, ty: TypeId, val: Value) !MdId {
|
||||
for (m.metadata.items, 0..) |md, i| {
|
||||
if (md == .value and md.value.ty == ty and std.meta.eql(md.value.val, val)) return @intCast(i);
|
||||
}
|
||||
try m.metadata.append(m.allocator(), .{ .value = .{ .ty = ty, .val = val } });
|
||||
return @intCast(m.metadata.items.len - 1);
|
||||
}
|
||||
|
||||
pub fn mdI32(m: *Module, v: i64) !MdId {
|
||||
return m.mdValue(try m.intType(32), try m.constInt(32, v));
|
||||
}
|
||||
|
||||
pub fn mdNode(m: *Module, ops: []const ?MdId) !MdId {
|
||||
try m.metadata.append(m.allocator(), .{ .node = try m.allocator().dupe(?MdId, ops) });
|
||||
return @intCast(m.metadata.items.len - 1);
|
||||
}
|
||||
|
||||
pub fn addNamedMetadata(m: *Module, name: []const u8, nodes: []const MdId) !void {
|
||||
const a = m.allocator();
|
||||
try m.named_metadata.append(a, .{ .name = try a.dupe(u8, name), .nodes = try a.dupe(MdId, nodes) });
|
||||
}
|
||||
|
||||
/// Encode the module as raw LLVM bitcode (starting with 'BC' 0xC0DE).
|
||||
pub fn writeBitcode(m: *Module, gpa: Allocator) ![]u8 {
|
||||
var enc: Encoder = .{ .m = m, .w = .init(gpa) };
|
||||
defer enc.w.deinit();
|
||||
return enc.write();
|
||||
}
|
||||
};
|
||||
|
||||
const block_module = 8;
|
||||
const block_paramattr = 9;
|
||||
const block_paramattr_group = 10;
|
||||
const block_constants = 11;
|
||||
const block_function = 12;
|
||||
const block_value_symtab = 14;
|
||||
const block_metadata = 15;
|
||||
const block_type = 17;
|
||||
|
||||
const Encoder = struct {
|
||||
m: *Module,
|
||||
w: bitstream.Writer,
|
||||
ops: std.ArrayList(u64) = .empty,
|
||||
|
||||
fn gpa(e: *Encoder) Allocator {
|
||||
return e.w.gpa;
|
||||
}
|
||||
|
||||
fn rec(e: *Encoder, code: u32) !void {
|
||||
try e.w.record(code, e.ops.items);
|
||||
e.ops.clearRetainingCapacity();
|
||||
}
|
||||
|
||||
fn push(e: *Encoder, v: u64) !void {
|
||||
try e.ops.append(e.gpa(), v);
|
||||
}
|
||||
|
||||
fn moduleValueCount(e: *Encoder) u32 {
|
||||
return @intCast(e.m.functions.items.len + e.m.constants.items.len);
|
||||
}
|
||||
|
||||
/// Absolute value ID. Module values: functions, then constants.
|
||||
fn valueId(e: *Encoder, f: ?*const Function, v: Value) u32 {
|
||||
const nfuncs: u32 = @intCast(e.m.functions.items.len);
|
||||
return switch (v) {
|
||||
.function => |i| i,
|
||||
.constant => |c| nfuncs + c,
|
||||
.arg => |a| e.moduleValueCount() + a,
|
||||
.inst => |i| blk: {
|
||||
const func = f.?;
|
||||
const nargs: u32 = @intCast(e.m.types.items[func.ty].function.params.len);
|
||||
var n: u32 = 0;
|
||||
for (func.insts.items[0..i]) |prev| {
|
||||
if (e.m.types.items[prev.ty] != .void) n += 1;
|
||||
}
|
||||
break :blk e.moduleValueCount() + nargs + n;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
fn typeOf(e: *Encoder, f: ?*const Function, v: Value) TypeId {
|
||||
return switch (v) {
|
||||
.function => |i| e.m.ptrTypeConst(e.m.functions.items[i].ty),
|
||||
.constant => |c| e.m.constants.items[c].ty,
|
||||
.arg => |a| e.m.types.items[f.?.ty].function.params[a],
|
||||
.inst => |i| f.?.insts.items[i].ty,
|
||||
};
|
||||
}
|
||||
|
||||
fn pushValueAndType(e: *Encoder, f: *const Function, inst_id: u32, v: Value) !void {
|
||||
const id = e.valueId(f, v);
|
||||
try e.push(inst_id -% id);
|
||||
if (id >= inst_id) try e.push(e.typeOf(f, v));
|
||||
}
|
||||
|
||||
fn pushValue(e: *Encoder, f: *const Function, inst_id: u32, v: Value) !void {
|
||||
try e.push(inst_id -% e.valueId(f, v));
|
||||
}
|
||||
|
||||
fn write(e: *Encoder) ![]u8 {
|
||||
defer e.ops.deinit(e.gpa());
|
||||
const w = &e.w;
|
||||
try w.emit('B', 8);
|
||||
try w.emit('C', 8);
|
||||
try w.emit(0x0, 4);
|
||||
try w.emit(0xC, 4);
|
||||
try w.emit(0xE, 4);
|
||||
try w.emit(0xD, 4);
|
||||
|
||||
try w.enterBlock(block_module, 3);
|
||||
try e.push(1);
|
||||
try e.rec(1); // MODULE_CODE_VERSION: relative value IDs
|
||||
|
||||
try e.writeAttributes();
|
||||
try e.writeTypes();
|
||||
try w.recordString(2, &.{}, e.m.triple);
|
||||
try w.recordString(3, &.{}, e.m.datalayout);
|
||||
for (e.m.functions.items) |f| {
|
||||
// FUNCTION: [type, cc, isproto, linkage, paramattr, align, section,
|
||||
// visibility, gc, unnamed_addr, prologue, dllstorage,
|
||||
// comdat, prefix, personality]
|
||||
const is_proto: u64 = @intFromBool(f.num_blocks == 0);
|
||||
try e.ops.appendSlice(e.gpa(), &.{ f.ty, 0, is_proto, @backingInt(f.linkage), attrId(f.attrs), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
try e.rec(8);
|
||||
}
|
||||
try e.writeConstants();
|
||||
try e.writeMetadata();
|
||||
try e.writeSymtab();
|
||||
for (e.m.functions.items) |*f| {
|
||||
if (f.num_blocks != 0) try e.writeFunction(f);
|
||||
}
|
||||
try w.endBlock();
|
||||
return w.finish();
|
||||
}
|
||||
|
||||
fn attrId(a: FnAttrs) u64 {
|
||||
return @backingInt(a);
|
||||
}
|
||||
|
||||
fn writeAttributes(e: *Encoder) !void {
|
||||
// Groups 1..3 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
|
||||
// Attribute kinds: nounwind = 18, readnone = 20, readonly = 21.
|
||||
const w = &e.w;
|
||||
try w.enterBlock(block_paramattr_group, 3);
|
||||
const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 } };
|
||||
for (groups, 1..) |kinds, id| {
|
||||
try e.push(id);
|
||||
try e.push(0xFFFFFFFF);
|
||||
for (kinds) |k| {
|
||||
try e.push(0); // enum attribute
|
||||
try e.push(k);
|
||||
}
|
||||
try e.rec(3); // PARAMATTR_GRP_CODE_ENTRY
|
||||
}
|
||||
try w.endBlock();
|
||||
try w.enterBlock(block_paramattr, 3);
|
||||
for (0..groups.len) |i| {
|
||||
try e.push(i + 1);
|
||||
try e.rec(2); // PARAMATTR_CODE_ENTRY: [group ids]
|
||||
}
|
||||
try w.endBlock();
|
||||
}
|
||||
|
||||
fn writeTypes(e: *Encoder) !void {
|
||||
const w = &e.w;
|
||||
try w.enterBlock(block_type, 4);
|
||||
try e.push(e.m.types.items.len);
|
||||
try e.rec(1); // NUMENTRY
|
||||
for (e.m.types.items) |t| {
|
||||
switch (t) {
|
||||
.void => try e.rec(2),
|
||||
.float => try e.rec(3),
|
||||
.double => try e.rec(4),
|
||||
.label => try e.rec(5),
|
||||
.half => try e.rec(10),
|
||||
.metadata => try e.rec(16),
|
||||
.int => |bits| {
|
||||
try e.push(bits);
|
||||
try e.rec(7);
|
||||
},
|
||||
.pointer => |p| {
|
||||
try e.push(p.elem);
|
||||
try e.push(p.addr_space);
|
||||
try e.rec(8);
|
||||
},
|
||||
.function => |f| {
|
||||
try e.push(0);
|
||||
try e.push(f.ret);
|
||||
for (f.params) |p| try e.push(p);
|
||||
try e.rec(21);
|
||||
},
|
||||
.@"struct" => |s| {
|
||||
if (s.name.len != 0) try w.recordString(19, &.{}, s.name);
|
||||
try e.push(@intFromBool(s.@"packed"));
|
||||
for (s.elems) |el| try e.push(el);
|
||||
try e.rec(if (s.name.len != 0) 20 else 18);
|
||||
},
|
||||
.array => |a| {
|
||||
try e.push(a.len);
|
||||
try e.push(a.elem);
|
||||
try e.rec(11);
|
||||
},
|
||||
.vector => |v| {
|
||||
try e.push(v.len);
|
||||
try e.push(v.elem);
|
||||
try e.rec(12);
|
||||
},
|
||||
}
|
||||
}
|
||||
try w.endBlock();
|
||||
}
|
||||
|
||||
fn writeConstants(e: *Encoder) !void {
|
||||
if (e.m.constants.items.len == 0) return;
|
||||
const w = &e.w;
|
||||
try w.enterBlock(block_constants, 4);
|
||||
var cur_ty: ?TypeId = null;
|
||||
for (e.m.constants.items) |c| {
|
||||
if (cur_ty != c.ty) {
|
||||
try e.push(c.ty);
|
||||
try e.rec(1); // SETTYPE
|
||||
cur_ty = c.ty;
|
||||
}
|
||||
switch (c.kind) {
|
||||
.int => |v| {
|
||||
try e.push(encodeSigned(v));
|
||||
try e.rec(4);
|
||||
},
|
||||
.float_bits => |b| {
|
||||
try e.push(b);
|
||||
try e.rec(6);
|
||||
},
|
||||
.undef => try e.rec(3),
|
||||
.null => try e.rec(2),
|
||||
}
|
||||
}
|
||||
try w.endBlock();
|
||||
}
|
||||
|
||||
fn writeMetadata(e: *Encoder) !void {
|
||||
const m = e.m;
|
||||
if (m.metadata.items.len == 0 and m.named_metadata.items.len == 0) return;
|
||||
const w = &e.w;
|
||||
try w.enterBlock(block_metadata, 3);
|
||||
for (m.metadata.items) |md| {
|
||||
switch (md) {
|
||||
.string => |s| try w.recordString(1, &.{}, s),
|
||||
.value => |v| {
|
||||
try e.push(v.ty);
|
||||
try e.push(e.valueId(null, v.val));
|
||||
try e.rec(2);
|
||||
},
|
||||
.node => |ops| {
|
||||
for (ops) |op| try e.push(if (op) |id| id + 1 else 0);
|
||||
try e.rec(3);
|
||||
},
|
||||
}
|
||||
}
|
||||
for (m.named_metadata.items) |nmd| {
|
||||
try w.recordString(4, &.{}, nmd.name);
|
||||
for (nmd.nodes) |n| try e.push(n);
|
||||
try e.rec(10);
|
||||
}
|
||||
try w.endBlock();
|
||||
}
|
||||
|
||||
fn writeSymtab(e: *Encoder) !void {
|
||||
const w = &e.w;
|
||||
// dxc sorts entries by name for deterministic output.
|
||||
const order = try e.gpa().alloc(u32, e.m.functions.items.len);
|
||||
defer e.gpa().free(order);
|
||||
for (order, 0..) |*o, i| o.* = @intCast(i);
|
||||
const funcs = e.m.functions.items;
|
||||
std.mem.sort(u32, order, funcs, struct {
|
||||
fn lt(fs: []const Function, a: u32, b: u32) bool {
|
||||
return std.mem.lessThan(u8, fs[a].name, fs[b].name);
|
||||
}
|
||||
}.lt);
|
||||
try w.enterBlock(block_value_symtab, 4);
|
||||
for (order) |i| try w.recordString(1, &.{i}, funcs[i].name); // VST_ENTRY
|
||||
try w.endBlock();
|
||||
}
|
||||
|
||||
fn writeFunction(e: *Encoder, f: *const Function) !void {
|
||||
const w = &e.w;
|
||||
try w.enterBlock(block_function, 4);
|
||||
try e.push(f.num_blocks);
|
||||
try e.rec(1); // DECLAREBLOCKS
|
||||
|
||||
const nargs: u32 = @intCast(e.m.types.items[f.ty].function.params.len);
|
||||
var inst_id: u32 = e.moduleValueCount() + nargs;
|
||||
for (f.insts.items) |inst| {
|
||||
switch (inst.op) {
|
||||
.ret => |v| {
|
||||
if (v) |val| try e.pushValueAndType(f, inst_id, val);
|
||||
try e.rec(10);
|
||||
},
|
||||
.br => |b| {
|
||||
try e.push(b.then);
|
||||
if (b.@"else") |el| {
|
||||
try e.push(el);
|
||||
try e.pushValue(f, inst_id, b.cond.?);
|
||||
}
|
||||
try e.rec(11);
|
||||
},
|
||||
.call => |c| {
|
||||
const callee = e.m.functions.items[c.callee];
|
||||
try e.push(0); // paramattrs on the call site
|
||||
try e.push(1 << 15); // explicit function type, ccc
|
||||
try e.push(callee.ty);
|
||||
try e.pushValueAndType(f, inst_id, .{ .function = c.callee });
|
||||
for (c.args) |arg| try e.pushValue(f, inst_id, arg);
|
||||
try e.rec(34);
|
||||
},
|
||||
.binop => |b| {
|
||||
try e.pushValueAndType(f, inst_id, b.lhs);
|
||||
try e.pushValue(f, inst_id, b.rhs);
|
||||
try e.push(@backingInt(b.op));
|
||||
if (b.flags != 0) try e.push(b.flags);
|
||||
try e.rec(2);
|
||||
},
|
||||
.cast => |c| {
|
||||
try e.pushValueAndType(f, inst_id, c.val);
|
||||
try e.push(inst.ty);
|
||||
try e.push(@backingInt(c.op));
|
||||
try e.rec(3);
|
||||
},
|
||||
.cmp => |c| {
|
||||
try e.pushValueAndType(f, inst_id, c.lhs);
|
||||
try e.pushValue(f, inst_id, c.rhs);
|
||||
try e.push(c.pred);
|
||||
try e.rec(28);
|
||||
},
|
||||
.select => |s| {
|
||||
try e.pushValueAndType(f, inst_id, s.t);
|
||||
try e.pushValue(f, inst_id, s.f);
|
||||
try e.pushValueAndType(f, inst_id, s.cond);
|
||||
try e.rec(29);
|
||||
},
|
||||
.extractvalue => |x| {
|
||||
try e.pushValueAndType(f, inst_id, x.agg);
|
||||
try e.push(x.index);
|
||||
try e.rec(26);
|
||||
},
|
||||
.phi => |p| {
|
||||
try e.push(inst.ty);
|
||||
for (p.incoming) |in| {
|
||||
const diff = @as(i64, inst_id) - @as(i64, e.valueId(f, in.val));
|
||||
try e.push(encodeSigned(diff));
|
||||
try e.push(in.block);
|
||||
}
|
||||
try e.rec(16);
|
||||
},
|
||||
}
|
||||
if (e.m.types.items[inst.ty] != .void) inst_id += 1;
|
||||
}
|
||||
try w.endBlock();
|
||||
}
|
||||
};
|
||||
|
||||
fn encodeSigned(v: i64) u64 {
|
||||
return if (v >= 0) @as(u64, @intCast(v)) << 1 else (@as(u64, @intCast(-v)) << 1) | 1;
|
||||
}
|
||||
|
||||
test "encodeSigned" {
|
||||
try std.testing.expectEqual(@as(u64, 4), encodeSigned(2));
|
||||
try std.testing.expectEqual(@as(u64, 3), encodeSigned(-1));
|
||||
}
|
||||
|
|
@ -0,0 +1,161 @@
|
|||
//! Builds a complete DXIL container for a shader entry point. For now this
|
||||
//! only covers an empty compute shader; later milestones feed it from the IR.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const Module = @import("module.zig").Module;
|
||||
const container = @import("container.zig");
|
||||
|
||||
pub const ShaderKind = enum(u8) {
|
||||
pixel = 0,
|
||||
vertex = 1,
|
||||
geometry = 2,
|
||||
hull = 3,
|
||||
domain = 4,
|
||||
compute = 5,
|
||||
|
||||
pub fn profilePrefix(k: ShaderKind) []const u8 {
|
||||
return switch (k) {
|
||||
.pixel => "ps",
|
||||
.vertex => "vs",
|
||||
.geometry => "gs",
|
||||
.hull => "hs",
|
||||
.domain => "ds",
|
||||
.compute => "cs",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Profile = struct {
|
||||
kind: ShaderKind,
|
||||
major: u8,
|
||||
minor: u8,
|
||||
|
||||
pub fn parse(s: []const u8) ?Profile {
|
||||
if (s.len != 6 or s[2] != '_' or s[4] != '_') return null;
|
||||
const kind: ShaderKind = for (std.enums.values(ShaderKind)) |k| {
|
||||
if (std.mem.eql(u8, s[0..2], k.profilePrefix())) break k;
|
||||
} else return null;
|
||||
if (s[3] != '6' or s[5] < '0' or s[5] > '9') return null;
|
||||
return .{ .kind = kind, .major = 6, .minor = s[5] - '0' };
|
||||
}
|
||||
};
|
||||
|
||||
pub const ComputeInfo = struct {
|
||||
entry: []const u8 = "main",
|
||||
profile: Profile,
|
||||
num_threads: [3]u32,
|
||||
};
|
||||
|
||||
/// Validator version we claim in !dx.valver (matches the oracle dxc).
|
||||
const valver = .{ 1, 11 };
|
||||
|
||||
pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
|
||||
var m = Module.init(gpa);
|
||||
defer m.deinit();
|
||||
|
||||
const void_ty = try m.getType(.void);
|
||||
const fn_ty = try m.fnType(void_ty, &.{});
|
||||
const main_fn = try m.addFunction(.{ .name = info.entry, .ty = fn_ty, .num_blocks = 1 });
|
||||
_ = try m.addInst(main_fn, .{ .ty = void_ty, .op = .{ .ret = null } });
|
||||
|
||||
// Metadata, in the same shape dxc emits.
|
||||
const ident = try m.mdNode(&.{try m.mdString("zdxc 0.0.0")});
|
||||
const version = try m.mdNode(&.{ try m.mdI32(1), try m.mdI32(info.profile.minor) });
|
||||
const val_ver = try m.mdNode(&.{ try m.mdI32(valver[0]), try m.mdI32(valver[1]) });
|
||||
const sm = try m.mdNode(&.{ try m.mdString(info.profile.kind.profilePrefix()), try m.mdI32(info.profile.major), try m.mdI32(info.profile.minor) });
|
||||
const threads = try m.mdNode(&.{ try m.mdI32(info.num_threads[0]), try m.mdI32(info.num_threads[1]), try m.mdI32(info.num_threads[2]) });
|
||||
const props = try m.mdNode(&.{ try m.mdI32(4), threads }); // kDxilNumThreadsTag
|
||||
const fn_ref = try m.mdValue(try m.ptrType(fn_ty), .{ .function = main_fn });
|
||||
const entry = try m.mdNode(&.{ fn_ref, try m.mdString(info.entry), null, null, props });
|
||||
|
||||
try m.addNamedMetadata("llvm.ident", &.{ident});
|
||||
try m.addNamedMetadata("dx.version", &.{version});
|
||||
try m.addNamedMetadata("dx.valver", &.{val_ver});
|
||||
try m.addNamedMetadata("dx.shaderModel", &.{sm});
|
||||
try m.addNamedMetadata("dx.entryPoints", &.{entry});
|
||||
|
||||
const bitcode = try m.writeBitcode(gpa);
|
||||
defer gpa.free(bitcode);
|
||||
|
||||
const dxil_part = try programPart(gpa, info.profile, bitcode);
|
||||
defer gpa.free(dxil_part);
|
||||
const psv = try psvCompute(gpa, info.entry, info.num_threads);
|
||||
defer gpa.free(psv);
|
||||
const empty_sig = [_]u8{ 0, 0, 0, 0, 8, 0, 0, 0 }; // ParamCount 0, ParamOffset 8
|
||||
|
||||
const parts = [_]container.Part{
|
||||
.{ .fourcc = container.fourcc("SFI0"), .data = &@as([8]u8, @splat(0)) },
|
||||
.{ .fourcc = container.fourcc("ISG1"), .data = &empty_sig },
|
||||
.{ .fourcc = container.fourcc("OSG1"), .data = &empty_sig },
|
||||
.{ .fourcc = container.fourcc("PSV0"), .data = psv },
|
||||
.{ .fourcc = container.fourcc("DXIL"), .data = dxil_part },
|
||||
};
|
||||
return container.assemble(gpa, &parts);
|
||||
}
|
||||
|
||||
/// DxilProgramHeader + DxilBitcodeHeader + bitcode.
|
||||
fn programPart(gpa: Allocator, profile: Profile, bitcode: []const u8) ![]u8 {
|
||||
const padded = std.mem.alignForward(usize, bitcode.len, 4);
|
||||
const out = try gpa.alloc(u8, 24 + padded);
|
||||
@memset(out, 0);
|
||||
const program_version: u32 = (@as(u32, @backingInt(profile.kind)) << 16) | (@as(u32, profile.major) << 4) | profile.minor;
|
||||
std.mem.writeInt(u32, out[0..4], program_version, .little);
|
||||
std.mem.writeInt(u32, out[4..8], @intCast(out.len / 4), .little);
|
||||
std.mem.writeInt(u32, out[8..12], container.fourcc("DXIL"), .little);
|
||||
std.mem.writeInt(u32, out[12..16], (1 << 8) | @as(u32, profile.minor), .little); // DXIL version
|
||||
std.mem.writeInt(u32, out[16..20], 16, .little); // bitcode offset from bitcode header
|
||||
std.mem.writeInt(u32, out[20..24], @intCast(bitcode.len), .little);
|
||||
@memcpy(out[24..][0..bitcode.len], bitcode);
|
||||
return out;
|
||||
}
|
||||
|
||||
/// PSV0 with PSVRuntimeInfo4 (60 bytes), as produced for validator 1.11.
|
||||
fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32) ![]u8 {
|
||||
var buf: std.ArrayList(u8) = .empty;
|
||||
errdefer buf.deinit(gpa);
|
||||
const w = struct {
|
||||
fn u32_(b: *std.ArrayList(u8), a: Allocator, v: u32) !void {
|
||||
var tmp: [4]u8 = undefined;
|
||||
std.mem.writeInt(u32, &tmp, v, .little);
|
||||
try b.appendSlice(a, &tmp);
|
||||
}
|
||||
}.u32_;
|
||||
|
||||
try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4)
|
||||
// PSVRuntimeInfo0
|
||||
try buf.appendNTimes(gpa, 0, 16); // stage-specific union
|
||||
try w(&buf, gpa, 0); // MinimumExpectedWaveLaneCount
|
||||
try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount
|
||||
// PSVRuntimeInfo1
|
||||
try buf.appendSlice(gpa, &.{ @backingInt(ShaderKind.compute), 0, 0, 0 }); // stage, UsesViewID, union
|
||||
try buf.appendNTimes(gpa, 0, 4); // sig element counts, SigInputVectors
|
||||
try buf.appendNTimes(gpa, 0, 4); // SigOutputVectors[4]
|
||||
// PSVRuntimeInfo2
|
||||
for (num_threads) |t| try w(&buf, gpa, t);
|
||||
// PSVRuntimeInfo3: EntryFunctionName offset into string table (after leading NUL)
|
||||
try w(&buf, gpa, 1);
|
||||
// PSVRuntimeInfo4
|
||||
try w(&buf, gpa, 0); // NumBytesGroupSharedMemory
|
||||
try w(&buf, gpa, 0); // Flags
|
||||
|
||||
try w(&buf, gpa, 0); // resource count
|
||||
|
||||
// String table: "\0" ++ entry ++ "\0", padded to 4 bytes.
|
||||
const strtab_len = std.mem.alignForward(usize, entry.len + 2, 4);
|
||||
try w(&buf, gpa, @intCast(strtab_len));
|
||||
try buf.append(gpa, 0);
|
||||
try buf.appendSlice(gpa, entry);
|
||||
try buf.appendNTimes(gpa, 0, strtab_len - entry.len - 1);
|
||||
|
||||
try w(&buf, gpa, 0); // semantic index table count
|
||||
return buf.toOwnedSlice(gpa);
|
||||
}
|
||||
|
||||
test "profile parsing" {
|
||||
const p = Profile.parse("cs_6_6").?;
|
||||
try std.testing.expectEqual(ShaderKind.compute, p.kind);
|
||||
try std.testing.expectEqual(@as(u8, 6), p.minor);
|
||||
try std.testing.expect(Profile.parse("cs_5_0") == null);
|
||||
try std.testing.expect(Profile.parse("lib_6_3") == null);
|
||||
}
|
||||
181
src/main.zig
181
src/main.zig
|
|
@ -1,71 +1,124 @@
|
|||
const std = @import("std");
|
||||
const Io = std.Io;
|
||||
|
||||
const zdxc = @import("zdxc");
|
||||
const shader = zdxc.dxil.shader;
|
||||
const container = zdxc.dxil.container;
|
||||
|
||||
pub fn main(init: std.process.Init) !void {
|
||||
// Prints to stderr, unbuffered, ignoring potential errors.
|
||||
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
|
||||
const usage =
|
||||
\\OVERVIEW: zdxc - HLSL 2021 to DXIL / SPIR-V compiler
|
||||
\\
|
||||
\\USAGE: zdxc [options] <input>
|
||||
\\
|
||||
\\OPTIONS:
|
||||
\\ -T <profile> Target profile (cs_6_0 .. cs_6_9, vs_, ps_, gs_)
|
||||
\\ -E <name> Entry point name (default: main)
|
||||
\\ -Fo <file> Output object file
|
||||
\\ -spirv Generate SPIR-V
|
||||
\\ --version Print version
|
||||
\\
|
||||
\\DEVELOPMENT (temporary, until the frontend lands):
|
||||
\\ -zdxc-empty Emit an empty shader for -T instead of compiling <input>
|
||||
\\ -zdxc-check-hash Verify the container hash of <input>
|
||||
\\
|
||||
;
|
||||
|
||||
// This is appropriate for anything that lives as long as the process.
|
||||
const arena: std.mem.Allocator = init.arena.allocator();
|
||||
|
||||
// Accessing command line arguments:
|
||||
const args = try init.minimal.args.toSlice(arena);
|
||||
for (args) |arg| {
|
||||
std.log.info("arg: {s}", .{arg});
|
||||
}
|
||||
|
||||
// In order to do I/O operations need an `Io` instance.
|
||||
const io = init.io;
|
||||
|
||||
// Stdout is for the actual output of your application, for example if you
|
||||
// are implementing gzip, then only the compressed bytes should be sent to
|
||||
// stdout, not any debugging messages.
|
||||
var stdout_buffer: [1024]u8 = undefined;
|
||||
var stdout_file_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer);
|
||||
const stdout_writer = &stdout_file_writer.interface;
|
||||
|
||||
try zdxc.printAnotherMessage(stdout_writer);
|
||||
|
||||
try stdout_writer.flush(); // Don't forget to flush!
|
||||
}
|
||||
|
||||
test "simple test" {
|
||||
const gpa = std.testing.allocator;
|
||||
var list: std.ArrayList(i32) = .empty;
|
||||
defer list.deinit(gpa); // Try commenting this out and see if zig detects the memory leak!
|
||||
try list.append(gpa, 42);
|
||||
try std.testing.expectEqual(@as(i32, 42), list.pop());
|
||||
}
|
||||
|
||||
test "fuzz example" {
|
||||
try std.testing.fuzz({}, testOne, .{});
|
||||
}
|
||||
|
||||
fn testOne(context: void, smith: *std.testing.Smith) !void {
|
||||
_ = context;
|
||||
// Try command `zig build test --fuzz -Doptimize=ReleaseFast` to see if it manages to fail this test case!
|
||||
|
||||
const gpa = std.testing.allocator;
|
||||
var list: std.ArrayList(u8) = .empty;
|
||||
defer list.deinit(gpa);
|
||||
while (!smith.eos()) switch (smith.value(enum { add_data, dup_data })) {
|
||||
.add_data => {
|
||||
const slice = try list.addManyAsSlice(gpa, smith.value(u4));
|
||||
smith.bytes(slice);
|
||||
},
|
||||
.dup_data => {
|
||||
if (list.items.len == 0) continue;
|
||||
if (list.items.len > std.math.maxInt(u32)) return error.SkipZigTest;
|
||||
const len = smith.valueRangeAtMost(u32, 1, @min(32, list.items.len));
|
||||
const off = smith.valueRangeAtMost(u32, 0, @intCast(list.items.len - len));
|
||||
try list.appendSlice(gpa, list.items[off..][0..len]);
|
||||
try std.testing.expectEqualSlices(
|
||||
u8,
|
||||
list.items[off..][0..len],
|
||||
list.items[list.items.len - len ..],
|
||||
);
|
||||
},
|
||||
const Options = struct {
|
||||
profile: ?[]const u8 = null,
|
||||
entry: []const u8 = "main",
|
||||
output: ?[]const u8 = null,
|
||||
input: ?[]const u8 = null,
|
||||
spirv: bool = false,
|
||||
empty: bool = false,
|
||||
check_hash: bool = false,
|
||||
};
|
||||
|
||||
const Cli = struct {
|
||||
io: Io,
|
||||
stderr: *Io.Writer,
|
||||
|
||||
fn fail(cli: Cli, comptime fmt: []const u8, args: anytype) error{Fatal} {
|
||||
cli.stderr.print("zdxc: error: " ++ fmt ++ "\n", args) catch {};
|
||||
cli.stderr.flush() catch {};
|
||||
return error.Fatal;
|
||||
}
|
||||
};
|
||||
|
||||
pub fn main(init: std.process.Init) !u8 {
|
||||
const arena = init.arena.allocator();
|
||||
const io = init.io;
|
||||
var stderr_buf: [1024]u8 = undefined;
|
||||
var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buf);
|
||||
var stdout_buf: [1024]u8 = undefined;
|
||||
var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
|
||||
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
|
||||
|
||||
run(cli, arena, try init.minimal.args.toSlice(arena), &stdout_writer.interface) catch |err| switch (err) {
|
||||
error.Fatal => return 1,
|
||||
else => return err,
|
||||
};
|
||||
try stdout_writer.interface.flush();
|
||||
return 0;
|
||||
}
|
||||
|
||||
fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer) !void {
|
||||
var opts: Options = .{};
|
||||
var i: usize = 1;
|
||||
while (i < args.len) : (i += 1) {
|
||||
const a = args[i];
|
||||
const next = struct {
|
||||
fn get(c: Cli, as: []const [:0]const u8, idx: *usize, name: []const u8) ![]const u8 {
|
||||
idx.* += 1;
|
||||
if (idx.* >= as.len) return c.fail("missing argument to '{s}'", .{name});
|
||||
return as[idx.*];
|
||||
}
|
||||
}.get;
|
||||
if (std.mem.eql(u8, a, "-T")) {
|
||||
opts.profile = try next(cli, args, &i, a);
|
||||
} else if (std.mem.eql(u8, a, "-E")) {
|
||||
opts.entry = try next(cli, args, &i, a);
|
||||
} else if (std.mem.eql(u8, a, "-Fo")) {
|
||||
opts.output = try next(cli, args, &i, a);
|
||||
} else if (std.mem.eql(u8, a, "-spirv")) {
|
||||
opts.spirv = true;
|
||||
} else if (std.mem.eql(u8, a, "-zdxc-empty")) {
|
||||
opts.empty = true;
|
||||
} else if (std.mem.eql(u8, a, "-zdxc-check-hash")) {
|
||||
opts.check_hash = true;
|
||||
} else if (std.mem.eql(u8, a, "--version")) {
|
||||
try stdout.print("zdxc {s}\n", .{zdxc.version});
|
||||
return;
|
||||
} else if (std.mem.eql(u8, a, "-help") or std.mem.eql(u8, a, "--help")) {
|
||||
try stdout.writeAll(usage);
|
||||
return;
|
||||
} else if (a.len > 0 and a[0] == '-') {
|
||||
return cli.fail("unknown argument: '{s}'", .{a});
|
||||
} else {
|
||||
if (opts.input != null) return cli.fail("more than one input file", .{});
|
||||
opts.input = a;
|
||||
}
|
||||
}
|
||||
|
||||
if (opts.check_hash) {
|
||||
const path = opts.input orelse return cli.fail("no input file", .{});
|
||||
const bytes = try Io.Dir.cwd().readFileAlloc(cli.io, path, arena, .limited(1 << 30));
|
||||
var view = container.parse(arena, bytes) catch return cli.fail("{s}: not a DXIL container", .{path});
|
||||
_ = &view;
|
||||
if (!container.hashMatches(view.bytes)) return cli.fail("{s}: hash mismatch", .{path});
|
||||
try stdout.print("{s}: hash ok ({d} parts)\n", .{ path, view.parts.items.len });
|
||||
return;
|
||||
}
|
||||
|
||||
const profile_str = opts.profile orelse return cli.fail("missing -T <profile>", .{});
|
||||
const profile = shader.Profile.parse(profile_str) orelse return cli.fail("unknown profile '{s}'", .{profile_str});
|
||||
|
||||
if (!opts.empty) return cli.fail("compiling HLSL is not implemented yet (use -zdxc-empty)", .{});
|
||||
if (profile.kind != .compute) return cli.fail("-zdxc-empty supports compute profiles only", .{});
|
||||
|
||||
const bytes = if (opts.spirv)
|
||||
try zdxc.spirv.builder.buildEmptyCompute(arena, .{ .entry = opts.entry, .num_threads = .{ 1, 1, 1 } })
|
||||
else
|
||||
try shader.buildEmptyCompute(arena, .{ .entry = opts.entry, .profile = profile, .num_threads = .{ 1, 1, 1 } });
|
||||
|
||||
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
|
||||
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = bytes });
|
||||
}
|
||||
|
|
|
|||
35
src/root.zig
35
src/root.zig
|
|
@ -1,18 +1,21 @@
|
|||
//! By convention, root.zig is the root source file when making a package.
|
||||
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V.
|
||||
|
||||
pub const dxil = struct {
|
||||
pub const bitstream = @import("dxil/bitstream.zig");
|
||||
pub const container = @import("dxil/container.zig");
|
||||
pub const hash = @import("dxil/hash.zig");
|
||||
pub const module = @import("dxil/module.zig");
|
||||
pub const shader = @import("dxil/shader.zig");
|
||||
};
|
||||
|
||||
pub const spirv = struct {
|
||||
pub const builder = @import("spirv/builder.zig");
|
||||
};
|
||||
|
||||
pub const version = "0.0.0";
|
||||
|
||||
test {
|
||||
const std = @import("std");
|
||||
const Io = std.Io;
|
||||
|
||||
/// This is a documentation comment to explain the `printAnotherMessage` function below.
|
||||
///
|
||||
/// Accepting an `Io.Writer` instance is a handy way to write reusable code.
|
||||
pub fn printAnotherMessage(writer: *Io.Writer) Io.Writer.Error!void {
|
||||
try writer.print("Run `zig build test` to run the tests.\n", .{});
|
||||
}
|
||||
|
||||
pub fn add(a: i32, b: i32) i32 {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
test "basic add functionality" {
|
||||
try std.testing.expect(add(3, 7) == 10);
|
||||
std.testing.refAllDecls(dxil);
|
||||
std.testing.refAllDecls(spirv);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,145 @@
|
|||
//! SPIR-V module builder. Instructions go into per-section buffers that are
|
||||
//! concatenated in the order required by the SPIR-V logical layout.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub const Id = u32;
|
||||
|
||||
/// Opcodes used so far. Will be replaced by tables generated from
|
||||
/// vendor/spirv grammar JSON.
|
||||
pub const Op = enum(u16) {
|
||||
name = 5,
|
||||
memory_model = 14,
|
||||
entry_point = 15,
|
||||
execution_mode = 16,
|
||||
capability = 17,
|
||||
type_void = 19,
|
||||
type_function = 33,
|
||||
function = 54,
|
||||
function_end = 56,
|
||||
label = 248,
|
||||
@"return" = 253,
|
||||
};
|
||||
|
||||
pub const Section = enum {
|
||||
capabilities,
|
||||
extensions,
|
||||
ext_inst_imports,
|
||||
memory_model,
|
||||
entry_points,
|
||||
execution_modes,
|
||||
debug_names,
|
||||
annotations,
|
||||
types_globals,
|
||||
functions,
|
||||
};
|
||||
|
||||
pub const Builder = struct {
|
||||
gpa: Allocator,
|
||||
sections: std.EnumArray(Section, std.ArrayList(u32)) = .initFill(.empty),
|
||||
next_id: Id = 1,
|
||||
|
||||
pub fn init(gpa: Allocator) Builder {
|
||||
return .{ .gpa = gpa };
|
||||
}
|
||||
|
||||
pub fn deinit(b: *Builder) void {
|
||||
for (&b.sections.values) |*s| s.deinit(b.gpa);
|
||||
}
|
||||
|
||||
pub fn newId(b: *Builder) Id {
|
||||
defer b.next_id += 1;
|
||||
return b.next_id;
|
||||
}
|
||||
|
||||
/// Emit an instruction; `operands` are raw words.
|
||||
pub fn emit(b: *Builder, section: Section, op: Op, operands: []const u32) !void {
|
||||
const s = b.sections.getPtr(section);
|
||||
const count: u32 = @intCast(operands.len + 1);
|
||||
try s.append(b.gpa, (count << 16) | @backingInt(op));
|
||||
try s.appendSlice(b.gpa, operands);
|
||||
}
|
||||
|
||||
/// Emit an instruction with a literal string operand placed after `pre`
|
||||
/// and followed by `post`.
|
||||
pub fn emitWithString(b: *Builder, section: Section, op: Op, pre: []const u32, str: []const u8, post: []const u32) !void {
|
||||
const str_words = str.len / 4 + 1;
|
||||
const s = b.sections.getPtr(section);
|
||||
const count: u32 = @intCast(1 + pre.len + str_words + post.len);
|
||||
try s.append(b.gpa, (count << 16) | @backingInt(op));
|
||||
try s.appendSlice(b.gpa, pre);
|
||||
for (0..str_words) |wi| {
|
||||
var word: [4]u8 = @splat(0);
|
||||
for (0..4) |ci| {
|
||||
const idx = wi * 4 + ci;
|
||||
if (idx < str.len) word[ci] = str[idx];
|
||||
}
|
||||
try s.append(b.gpa, std.mem.readInt(u32, &word, .little));
|
||||
}
|
||||
try s.appendSlice(b.gpa, post);
|
||||
}
|
||||
|
||||
/// Serialize as little-endian bytes.
|
||||
pub fn finish(b: *Builder, version: u32) ![]u8 {
|
||||
var total: usize = 5;
|
||||
for (b.sections.values) |s| total += s.items.len;
|
||||
const out = try b.gpa.alloc(u8, total * 4);
|
||||
const header = [5]u32{ 0x07230203, version, generator_magic, b.next_id, 0 };
|
||||
var off: usize = 0;
|
||||
for (header) |word| {
|
||||
std.mem.writeInt(u32, out[off..][0..4], word, .little);
|
||||
off += 4;
|
||||
}
|
||||
for (b.sections.values) |s| {
|
||||
for (s.items) |word| {
|
||||
std.mem.writeInt(u32, out[off..][0..4], word, .little);
|
||||
off += 4;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
/// Unregistered generator ID (tool 0), version 0.
|
||||
const generator_magic = 0;
|
||||
|
||||
pub const spv_1_0: u32 = 0x00010000;
|
||||
|
||||
pub const ComputeInfo = struct {
|
||||
entry: []const u8 = "main",
|
||||
num_threads: [3]u32,
|
||||
};
|
||||
|
||||
pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
|
||||
var b = Builder.init(gpa);
|
||||
defer b.deinit();
|
||||
|
||||
const void_ty = b.newId();
|
||||
const fn_ty = b.newId();
|
||||
const main_fn = b.newId();
|
||||
const entry_label = b.newId();
|
||||
|
||||
try b.emit(.capabilities, .capability, &.{1}); // Shader
|
||||
try b.emit(.memory_model, .memory_model, &.{ 0, 1 }); // Logical GLSL450
|
||||
try b.emitWithString(.entry_points, .entry_point, &.{ 5, main_fn }, info.entry, &.{}); // GLCompute
|
||||
try b.emit(.execution_modes, .execution_mode, &.{ main_fn, 17, info.num_threads[0], info.num_threads[1], info.num_threads[2] }); // LocalSize
|
||||
try b.emitWithString(.debug_names, .name, &.{main_fn}, info.entry, &.{});
|
||||
try b.emit(.types_globals, .type_void, &.{void_ty});
|
||||
try b.emit(.types_globals, .type_function, &.{ fn_ty, void_ty });
|
||||
try b.emit(.functions, .function, &.{ void_ty, main_fn, 0, fn_ty });
|
||||
try b.emit(.functions, .label, &.{entry_label});
|
||||
try b.emit(.functions, .@"return", &.{});
|
||||
try b.emit(.functions, .function_end, &.{});
|
||||
|
||||
return b.finish(spv_1_0);
|
||||
}
|
||||
|
||||
test "string operands are NUL-terminated and padded" {
|
||||
var b = Builder.init(std.testing.allocator);
|
||||
defer b.deinit();
|
||||
try b.emitWithString(.debug_names, .name, &.{7}, "main", &.{});
|
||||
const words = b.sections.get(.debug_names).items;
|
||||
try std.testing.expectEqual(@as(usize, 4), words.len); // opcode, id, "main", "\0\0\0\0"
|
||||
try std.testing.expectEqual(@as(u32, 0), words[3]);
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
#!/bin/sh
|
||||
# M0.0 oracle checks: zdxc output must be accepted by DXC's validator (dxv)
|
||||
# and spirv-val, and zdxc's container hash must match dxc-signed containers.
|
||||
#
|
||||
# Usage: test/oracle/m0.sh <path-to-zdxc>
|
||||
# Oracles default to the DXC build next to this repo; override with
|
||||
# DXC_BUILD=<dir> (needs bin/dxc, bin/dxv, oracle-spirv-tools/tools/spirv-val).
|
||||
set -u
|
||||
|
||||
ZDXC=$1
|
||||
DXC_BUILD=${DXC_BUILD:-../build}
|
||||
DXC=$DXC_BUILD/bin/dxc
|
||||
DXV=$DXC_BUILD/bin/dxv
|
||||
SPIRV_VAL=$DXC_BUILD/oracle-spirv-tools/tools/spirv-val
|
||||
TMP=$(mktemp -d)
|
||||
trap 'rm -rf "$TMP"' EXIT
|
||||
|
||||
pass=0
|
||||
fail=0
|
||||
ok() { pass=$((pass + 1)); }
|
||||
bad() { fail=$((fail + 1)); echo "FAIL: $*"; }
|
||||
|
||||
for tool in "$DXC" "$DXV" "$SPIRV_VAL"; do
|
||||
[ -x "$tool" ] || { echo "missing oracle: $tool"; exit 1; }
|
||||
done
|
||||
|
||||
# 1. Hash: re-verify dxc-signed containers with zdxc's DxilHash port.
|
||||
printf '[numthreads(1,1,1)] void main() {}\n' > "$TMP/empty.hlsl"
|
||||
printf 'RWStructuredBuffer<float> o : register(u0);\n[numthreads(64,1,1)] void main(uint i : SV_DispatchThreadID) { o[i] = sqrt((float)i) * 3.0; }\n' > "$TMP/sqrt.hlsl"
|
||||
for src in empty sqrt; do
|
||||
for t in cs_6_0 cs_6_6; do
|
||||
"$DXC" -T $t -E main "$TMP/$src.hlsl" -Fo "$TMP/ref.dxo" >/dev/null 2>&1 || { bad "dxc failed on $src $t"; continue; }
|
||||
if "$ZDXC" -zdxc-check-hash "$TMP/ref.dxo" >/dev/null; then ok; else bad "hash mismatch on dxc output ($src, $t)"; fi
|
||||
done
|
||||
done
|
||||
|
||||
# 2. DXIL: empty compute shader for every shader model must pass dxv.
|
||||
for m in 0 1 2 3 4 5 6 7 8 9; do
|
||||
out="$TMP/cs_6_$m.dxo"
|
||||
if "$ZDXC" -zdxc-empty -T cs_6_$m -Fo "$out" \
|
||||
&& "$DXV" "$out" >/dev/null 2>&1 \
|
||||
&& "$ZDXC" -zdxc-check-hash "$out" >/dev/null; then ok; else bad "dxv rejected cs_6_$m"; fi
|
||||
done
|
||||
|
||||
# 3. SPIR-V: empty compute shader must pass spirv-val.
|
||||
if "$ZDXC" -zdxc-empty -spirv -T cs_6_0 -Fo "$TMP/cs.spv" \
|
||||
&& "$SPIRV_VAL" --target-env vulkan1.0 "$TMP/cs.spv"; then ok; else bad "spirv-val rejected cs"; fi
|
||||
|
||||
echo "oracle m0: $pass passed, $fail failed"
|
||||
[ "$fail" -eq 0 ]
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
# Vendored data
|
||||
|
||||
zdxc vendors **data files only** from the DXC tree (never C++ sources).
|
||||
Each entry records the source path and the DXC commit it was copied from.
|
||||
|
||||
| File | Source in DXC | DXC commit | License |
|
||||
|---|---|---|---|
|
||||
| _(none yet; the HLSL intrinsic table and SPIR-V grammar arrive with M0.1)_ | | | |
|
||||
|
||||
DXC is distributed under the University of Illinois/NCSA license (LICENSE.TXT
|
||||
in the DXC tree); SPIRV-Headers files are under the Khronos MIT-style license.
|
||||
Loading…
Reference in New Issue