Add bitfields

Consecutive bitfields pack into hidden storage fields as dxc lays them
out (DXIL by type size, SPIR-V by exact type); member reads shift and
mask, writes read-modify-write. Also: dxc's bitfield diagnostics, sizeof
evaluation, SPIR-V base-class layout as a nested struct, operator[]
results are not addressable, and the codegen oracle reports crashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peter Li 2026-10-31 11:50:22 -07:00
parent bdf7a2757a
commit 5ed31a6509
5 changed files with 336 additions and 41 deletions

View File

@ -719,7 +719,7 @@ pub const Parser = struct {
if (t.isIdent("typedef")) return p.parseTypedefInto(out);
if (t.isIdent("using")) return out.append(p.arena, try p.parseUsing(template_params));
if (t.isIdent("namespace")) return out.append(p.arena, try p.parseNamespace());
if (t.isIdent("enum")) return p.parseEnumInto(out);
if (t.isIdent("enum")) return p.parseEnumInto(out, ctx);
if (t.isIdent("_Static_assert")) {
const d = try p.parseStaticAssert();
_ = try p.expect(.semi, "';'");
@ -963,14 +963,21 @@ pub const Parser = struct {
return p.mk(ast.Decl, .{ .loc = kw.loc, .kind = .{ .namespace = .{ .name = name.text, .decls = decls.items } } });
}
fn parseEnumInto(p: *Parser, out: *std.ArrayList(*ast.Decl)) Error!void {
fn parseEnumInto(p: *Parser, out: *std.ArrayList(*ast.Decl), ctx: DeclContext) Error!void {
const kw = p.advance();
const scoped = p.eatIdent("class") or p.eatIdent("struct");
var name: ?[]const u8 = null;
var name_loc = kw.loc;
if (p.at(.identifier) and !isReserved(p.tok().text)) {
name_loc = p.tok().loc;
name = p.advance().text;
try p.declareName(name.?, .type);
}
// `enum E x;` / `enum E : 1;` (a bitfield): the enum used as a type.
if (name != null and !scoped and !p.at(.l_brace) and !(p.at(.colon) and p.isTypeStartAt(p.pos + 1))) {
const ty = try p.mk(ast.TypeRef, .{ .loc = name_loc, .name = try p.simpleName(name_loc, name.?) });
return p.parseDeclaratorsInto(out, &.{}, .{}, &.{}, ty, ctx);
}
if (name) |n| try p.declareName(n, .type);
var underlying: ?*ast.TypeRef = null;
if (p.eat(.colon)) underlying = try p.parseType();
_ = try p.expect(.l_brace, "'{'");
@ -1065,6 +1072,9 @@ pub const Parser = struct {
var name: Token = undefined;
if (first and qualified_var != null) {
name = .{ .kind = .identifier, .text = qualified_var.?, .loc = name_loc };
} else if (ctx == .member and p.at(.colon)) {
// Anonymous bitfield (`uint : 4;`).
name = .{ .kind = .identifier, .text = "", .loc = p.tok().loc };
} else name = try p.expectIdent("declarator name");
const first_spec = first;
first = false;

View File

@ -79,14 +79,7 @@ pub fn alignOf(t: *const TypeTable, ty: TypeId, row_major: bool, rules: Rules) E
.dx_legacy, .vk_relaxed => 16,
else => alignOf(t, a.elem, row_major, rules),
},
.@"struct" => |st| switch (rules) {
.dx_legacy, .vk_relaxed => return 16,
else => {
var al: u32 = 1;
for (st.fields.items) |f| al = @max(al, try alignOf(t, f.type, f.row_major, rules));
return al;
},
},
.@"struct" => |st| return structAlign(t, st, rules),
else => return error.Unsupported,
}
}
@ -111,15 +104,7 @@ pub fn sizeOf(t: *const TypeTable, ty: TypeId, row_major: bool, rules: Rules) Er
else => a.len * stride,
};
},
.@"struct" => |s| {
var off: u32 = 0;
for (s.fields.items) |f| off = try place(t, off, f.type, f.row_major, rules) + try sizeOf(t, f.type, f.row_major, rules);
return switch (rules) {
.dx_legacy, .dx_packed => off,
.vk_relaxed => roundUp(off, 16),
.std430 => roundUp(off, try alignOf(t, ty, false, rules)),
};
},
.@"struct" => |s| return structSize(t, s, rules),
else => return error.Unsupported,
}
}
@ -150,14 +135,52 @@ pub fn place(t: *const TypeTable, off: u32, ty: TypeId, row_major: bool, rules:
}
}
/// Offsets of a struct's fields.
pub fn fieldOffsets(a: Allocator, t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error![]u32 {
const out = try a.alloc(u32, info.fields.items.len);
fn structAlign(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error!u32 {
switch (rules) {
.dx_legacy, .vk_relaxed => return 16,
else => {
var al: u32 = 1;
for (info.fields.items) |f| al = @max(al, try alignOf(t, f.type, f.row_major, rules));
return al;
},
}
}
fn structSize(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error!u32 {
var buf: [256]u32 = undefined;
if (info.fields.items.len > buf.len) return error.Unsupported;
const off = try layoutFields(t, info, rules, buf[0..info.fields.items.len]);
return switch (rules) {
.dx_legacy, .dx_packed => off,
.vk_relaxed => roundUp(off, 16),
.std430 => roundUp(off, try structAlign(t, info, rules)),
};
}
/// Stores the offsets of `info`'s fields in `out`; returns where the last
/// one ends.
fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules, out: []u32) Error!u32 {
var off: u32 = 0;
for (info.fields.items, out) |f, *o| {
var first: usize = 0;
if (info.bases.items.len > 0 and (rules == .vk_relaxed or rules == .std430)) {
// dxc's SPIR-V keeps a base class as a nested struct (padded to
// its alignment); DXIL lays its fields out in place.
const base = info.bases.items[0];
first = base.fields.items.len;
_ = try layoutFields(t, base, rules, out[0..first]);
off = try structSize(t, base, rules);
}
for (info.fields.items[first..], out[first..]) |f, *o| {
o.* = try place(t, off, f.type, f.row_major, rules);
off = o.* + try sizeOf(t, f.type, f.row_major, rules);
}
return off;
}
/// Offsets of a struct's fields.
pub fn fieldOffsets(a: Allocator, t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error![]u32 {
const out = try a.alloc(u32, info.fields.items.len);
_ = try layoutFields(t, info, rules, out);
return out;
}

View File

@ -9,6 +9,7 @@ const ast = @import("../front/ast.zig");
const ir = @import("ir.zig");
const semamod = @import("../sema/sema.zig");
const types = @import("../sema/types.zig");
const Bitfield = types.Bitfield;
const Interp = types.Interp;
const Field = types.Field;
const table = @import("intrinsics_table");
@ -382,6 +383,10 @@ const Lowerer = struct {
try l.vars.put(l.arena, variable, try l.b.add(.{ .op = .{ .global = gi }, .ty = glob.ty, .ptr = glob.space }));
return;
}
if (v.init == null and isObject(&l.s.types, variable.type)) {
l.unsupported(d.loc, "uninitialized local resource '{s}' is not supported yet", .{variable.name});
return error.Unsupported;
}
const local = try l.b.add(.{ .op = .local_var, .ty = variable.type, .ptr = .function });
try l.vars.put(l.arena, variable, local);
if (v.init) |init_e| {
@ -540,7 +545,12 @@ const Lowerer = struct {
.scalar, .@"enum" => try out.append(l.arena, v),
.vector, .matrix => for (0..t.componentCount(ty).?) |k| try out.append(l.arena, try l.component(v, @intCast(k))),
.array => |a| for (0..a.len) |i| try l.flatten(try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = a.elem }), out),
.@"struct" => |st| for (st.fields.items, 0..) |f, i| try l.flatten(try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = f.type }), out),
.@"struct" => |st| for (st.fields.items, 0..) |f, i| {
const fv = try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = f.type });
if (f.bits) {
for (st.bitfieldsIn(@intCast(i))) |bf| try out.append(l.arena, try l.bitRead(fv, bf));
} else try l.flatten(fv, out);
},
else => {
l.unsupported(.none, "flattening values of type '{s}' is not supported yet", .{l.s.typeName(ty)});
return error.Unsupported;
@ -574,7 +584,15 @@ const Lowerer = struct {
},
.@"struct" => |st| {
const parts = try l.arena.alloc(Ref, st.fields.items.len);
for (parts, st.fields.items) |*p, f| p.* = try l.fromFlat(f.type, comps, next);
for (parts, st.fields.items, 0..) |*p, f, i| {
if (f.bits) {
p.* = try l.b.constInt(f.type, 0);
for (st.bitfieldsIn(@intCast(i))) |bf| {
p.* = try l.bitInsert(p.*, bf, try l.convert(comps[next.*], bf.type));
next.* += 1;
}
} else p.* = try l.fromFlat(f.type, comps, next);
}
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
},
else => {
@ -604,6 +622,10 @@ const Lowerer = struct {
const r = l.s.resolution(e) orelse return l.fail(e, "this name");
switch (r) {
.this_field => return l.b.load(try l.lvalue(e)),
.this_bitfield => |bf| {
if (l.this_ptr == .none) return l.fail(e, "this name");
return l.bitRead(try l.b.load(try l.bitStorage(l.this_ptr, bf)), bf);
},
.variable => |v| {
// Integer `static const` scalars are constants.
if (v.storage == .constant and v.init != null and l.s.types.get(v.type) == .scalar and !l.s.types.get(v.type).scalar.isFloat()) {
@ -664,7 +686,7 @@ const Lowerer = struct {
const idx = try l.indexValue(x.index, bt.resource.kind.indexDims());
return l.b.add(.{ .op = .{ .res_load = .{ .res = res, .index = idx } }, .ty = try l.concrete(e.ty) });
}
if (isAddressable(x.base)) return l.b.load(try l.lvalue(e));
if (isAddressable(l.s, x.base)) return l.b.load(try l.lvalue(e));
const base = try l.rvalue(x.base);
if (l.s.evalInt(x.index)) |k| return l.b.add(.{ .op = .{ .extract = .{ .agg = base, .index = @intCast(k) } }, .ty = try l.concrete(e.ty) });
// Dynamic index into a value: spill to storage.
@ -864,10 +886,18 @@ const Lowerer = struct {
for (parts, ks) |*p, k| p.* = try l.component(v, k);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = try l.concrete(e.ty) });
},
.@"struct" => {
if (isAddressable(base)) return l.b.load(try l.lvalue(e));
const v = try l.rvalue(base);
.@"struct" => |info| {
const r = l.s.resolution(e) orelse return l.fail(e, "this member");
if (r == .bitfield) {
const bf = r.bitfield;
const storage = if (isAddressable(l.s, base))
try l.b.load(try l.bitStorage(try l.lvalue(base), bf))
else
try l.b.add(.{ .op = .{ .extract = .{ .agg = try l.rvalue(base), .index = bf.storage } }, .ty = info.fields.items[bf.storage].type });
return l.bitRead(storage, bf);
}
if (isAddressable(l.s, base)) return l.b.load(try l.lvalue(e));
const v = try l.rvalue(base);
return l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = r.field } }, .ty = e.ty });
},
else => return l.fail(e, "this member access"),
@ -907,7 +937,7 @@ const Lowerer = struct {
var write_back: ?Ref = null;
const owner_ty = if (isMethod(f)) try l.s.types.intern(.{ .@"struct" = f.owner.? }) else TypeTable.void_type;
if (base_expr) |base| {
const direct = if (isAddressable(base)) try l.lvalue(base) else null;
const direct = if (isAddressable(l.s, base)) try l.lvalue(base) else null;
const plain = if (direct) |p| l.b.f.inst(p).op == .local_var or l.b.f.inst(p).op == .param else false;
if (direct != null and plain and base.ty == owner_ty) {
object = direct;
@ -1118,9 +1148,72 @@ const Lowerer = struct {
}
}
/// Pointer to the storage field holding bitfield `bf` of the struct
/// `ptr` points to.
fn bitStorage(l: *Lowerer, ptr: Ref, bf: Bitfield) Error!Ref {
const t = l.types();
const info = t.get(l.b.f.inst(ptr).ty).@"struct";
const idx = try l.b.constInt(try t.scalar(.uint), bf.storage);
return l.b.add(.{ .op = .{ .access = .{ .base = ptr, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = info.fields.items[bf.storage].type, .ptr = l.b.f.inst(ptr).ptr });
}
/// The value of bitfield `bf` in its storage word, zero- or
/// sign-extended.
fn bitRead(l: *Lowerer, storage: Ref, bf: Bitfield) Error!Ref {
const t = l.types();
const sc = t.component(bf.type).?;
const st = try t.scalar(if (sc == .bool) .uint else sc);
const bits: u8 = @intCast(sc.size() * 8);
const x = try l.convert(storage, st);
var v: Ref = undefined;
if (t.get(st).scalar.isUnsigned()) {
const shifted = if (bf.offset == 0) x else try l.b.add(.{ .op = .{ .binary = .{ .op = .shr, .lhs = x, .rhs = try l.b.constInt(st, bf.offset) } }, .ty = st });
v = if (bf.width == bits) shifted else try l.b.add(.{ .op = .{ .binary = .{ .op = .bit_and, .lhs = shifted, .rhs = try l.constBits(st, lowMask(bf.width)) } }, .ty = st });
} else {
// Shift the field to the top, then arithmetically back down.
const up = bits - bf.offset - bf.width;
const hi = if (up == 0) x else try l.b.add(.{ .op = .{ .binary = .{ .op = .shl, .lhs = x, .rhs = try l.b.constInt(st, up) } }, .ty = st });
v = if (bf.width == bits) hi else try l.b.add(.{ .op = .{ .binary = .{ .op = .shr, .lhs = hi, .rhs = try l.b.constInt(st, bits - bf.width) } }, .ty = st });
}
return l.convert(v, bf.type);
}
/// An integer constant of scalar type `ty` with bit pattern `v`.
fn constBits(l: *Lowerer, ty: TypeId, v: u64) Error!Ref {
const sc = l.types().component(ty).?;
const bits: u8 = @intCast(sc.size() * 8);
if (sc.isUnsigned()) return l.b.constInt(ty, @bitCast(v & lowMask(bits)));
return l.b.constInt(ty, signExtend(v, bits));
}
/// `storage` with bitfield `bf` replaced by `value`.
fn bitInsert(l: *Lowerer, storage: Ref, bf: Bitfield, value: Ref) Error!Ref {
const t = l.types();
const st = l.b.f.inst(storage).ty;
const bits: u8 = @intCast(t.component(st).?.size() * 8);
const mask = lowMask(bf.width);
const field_mask = mask << @intCast(bf.offset);
const keep_bits: u64 = if (bits == 64) ~field_mask else ~field_mask & lowMask(bits);
const keep = try l.b.add(.{ .op = .{ .binary = .{ .op = .bit_and, .lhs = storage, .rhs = try l.constBits(st, keep_bits) } }, .ty = st });
var v = try l.convert(value, st);
if (bf.width < bits) v = try l.b.add(.{ .op = .{ .binary = .{ .op = .bit_and, .lhs = v, .rhs = try l.constBits(st, mask) } }, .ty = st });
if (bf.offset > 0) v = try l.b.add(.{ .op = .{ .binary = .{ .op = .shl, .lhs = v, .rhs = try l.b.constInt(st, bf.offset) } }, .ty = st });
return l.b.add(.{ .op = .{ .binary = .{ .op = .bit_or, .lhs = keep, .rhs = v } }, .ty = st });
}
/// Stores `value` (already of `lhs`'s type) into what `lhs` designates.
fn storeTo(l: *Lowerer, lhs: *ast.Expr, value: Ref) Error!void {
const t = l.types();
if (lhs.kind == .member or lhs.kind == .name) if (l.s.resolution(lhs)) |r| switch (r) {
.bitfield, .this_bitfield => |bf| {
const struct_ptr = if (r == .bitfield) try l.lvalue(lhs.kind.member.base) else l.this_ptr;
if (struct_ptr == .none) return l.fail(lhs, "this assignment target");
const ptr = try l.bitStorage(struct_ptr, bf);
try l.b.store(ptr, try l.bitInsert(try l.b.load(ptr), bf, value));
return;
},
else => {},
};
switch (lhs.kind) {
.index => |x| if (t.get(x.base.ty) == .resource) {
const res = try l.rvalue(x.base);
@ -1605,11 +1698,24 @@ fn matrixSwizzle(a: Allocator, name: []const u8, cols: u8) ?[]const u32 {
return if (out.items.len == 0) null else out.items;
}
fn isAddressable(e: *const ast.Expr) bool {
fn lowMask(width: u8) u64 {
return if (width >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(width)) - 1;
}
/// `v`'s low `bits` bits as a sign-extended constant (ir.Constant.int).
fn signExtend(v: u64, bits: u8) i64 {
if (bits >= 64) return @bitCast(v);
const sh: u6 = @intCast(64 - bits);
return @as(i64, @bitCast(v << sh)) >> sh;
}
/// Whether `e` designates storage (a variable, or a part of one) rather
/// than a temporary such as an operator call's result.
fn isAddressable(s: *const Sema, e: *const ast.Expr) bool {
return switch (e.kind) {
.name, .this => true,
.member => |m| isAddressable(m.base),
.index => |x| isAddressable(x.base),
.member => |m| isAddressable(s, m.base),
.index => |x| if (s.resolution(e)) |r| r != .function and isAddressable(s, x.base) else isAddressable(s, x.base),
else => false,
};
}

View File

@ -13,6 +13,7 @@ const ast_clone = @import("../front/ast_clone.zig");
const source = @import("../front/source.zig");
const diag = @import("../diag.zig");
const types = @import("types.zig");
const layout = @import("../ir/layout.zig");
const intrinsics = @import("intrinsics.zig");
const Loc = source.Loc;
const TypeId = types.TypeId;
@ -72,6 +73,9 @@ pub const Resolution = union(enum) {
field: u32,
/// A field named without `this.` inside a method.
this_field: u32,
/// A bitfield member (`this_bitfield`: named without `this.`).
bitfield: types.Bitfield,
this_bitfield: types.Bitfield,
};
pub const Param = struct {
@ -1168,7 +1172,8 @@ pub const Sema = struct {
},
.cast => |c| s.evalConst(c.operand),
.construct => |c| if (c.args.len == 1) s.evalConst(c.args[0]) else null,
.sizeof_type, .sizeof_expr => null,
// Sizes are kept by Sema (plus one; zero: unknown).
.sizeof_type, .sizeof_expr => if (e.info != 0) .{ .int = e.info - 1 } else null,
else => null,
};
}
@ -1389,6 +1394,7 @@ pub const Sema = struct {
if (s.types.get(bt) == .@"struct") {
const base = s.types.get(bt).@"struct";
try info.fields.appendSlice(s.arena, base.fields.items);
try info.bitfields.appendSlice(s.arena, base.bitfields.items);
try info.bases.append(s.arena, base);
base_fields = info.fields.items.len;
if (base.sema) |bp| {
@ -1415,15 +1421,21 @@ pub const Sema = struct {
defer s.scope = saved;
// Fields and nested types first, then methods (which may use any
// field regardless of order).
const errors_before = s.diags.error_count;
// The storage field consecutive bitfields are packed into.
var unit: ?BitUnit = null;
for (members) |m| switch (m.kind) {
.@"var" => |v| {
if (v.quals.static) {
if (v.bitfield != null) s.err(v.name_loc, "static member '{s}' cannot be a bit-field", .{v.name});
try s.varDecl(m, &m.kind.@"var", .member);
continue;
}
if (v.bitfield != null) {
s.err(m.loc, "bitfields are not supported yet (planned for milestone 0.2)", .{});
if (v.bitfield) |width_e| {
try s.bitfieldDecl(info, &unit, v, width_e, base_fields);
continue;
}
unit = null;
const fbase = try s.resolveType(v.type);
const start = if (v.qual_words.len > 0) v.qual_words[0].loc else v.type.loc;
if (v.array_dims.len > 0 and v.array_dims[0] == null) {
@ -1434,7 +1446,7 @@ pub const Sema = struct {
const ft = try s.applyArrayDims(fbase, v.array_dims);
s.checkSemantics(.field, v.semantics, ft, false);
if (s.types.get(fbase) == .string) s.err(v.name_loc, "string declaration may only appear in global scope", .{});
for (info.fields.items[base_fields..]) |f| if (std.mem.eql(u8, f.name, v.name)) s.err(v.name_loc, "duplicate member '{s}'", .{v.name});
s.checkDuplicateMember(info, base_fields, v.name, v.name_loc);
var fsem: ?[]const u8 = null;
for (v.semantics) |sem| if (sem.kind == .semantic) {
fsem = sem.values[0];
@ -1444,6 +1456,7 @@ pub const Sema = struct {
.func => {},
else => try s.decl(m, .member),
};
if (s.diags.error_count != errors_before) info.invalid = true;
info.complete = true;
const saved_struct = s.current_struct;
s.current_struct = info;
@ -1814,6 +1827,7 @@ pub const Sema = struct {
s.err(v.name_loc, "array of type string is not supported", .{});
} else if (ctx != .global) s.err(v.name_loc, "string declaration may only appear in global scope", .{});
}
if (ctx == .local or (ctx == .global and v.quals.static)) s.checkBoolBitfield(ty, v.name_loc);
const q = v.quals;
const storage: Storage = switch (ctx) {
.cbuffer => .cbuffer,
@ -1919,6 +1933,7 @@ pub const Sema = struct {
const pt = try s.applyArrayDims(pbase, p.array_dims);
s.checkSemantics(.parameter, p.semantics, pt, false);
if (s.types.get(pbase) == .string) s.err(p.name_loc, "parameter of type string is not supported", .{});
s.checkBoolBitfield(pt, p.name_loc);
out.* = .{
.name = p.name,
.type = pt,
@ -2211,11 +2226,17 @@ pub const Sema = struct {
return err_typed; // typed by checkInitializer
},
.sizeof_type => |t| {
_ = try s.resolveType(t);
e.info = s.sizeInfo(try s.resolveType(t));
return rvalue(try s.types.scalar(.uint));
},
.sizeof_expr => |x| {
_ = try s.expr(x);
const xt = try s.expr(x);
const target = if (x.kind == .assign and x.kind.assign.op != .assign) x.kind.assign.lhs else x;
if (target.kind == .member or target.kind == .name) if (s.resolution(target)) |r| if (r == .bitfield or r == .this_bitfield) {
s.err(e.loc, "invalid application of 'sizeof' to bit-field", .{});
return rvalue(try s.types.scalar(.uint));
};
e.info = s.sizeInfo(xt.ty);
return rvalue(try s.types.scalar(.uint));
},
.is_same => |x| {
@ -2259,6 +2280,10 @@ pub const Sema = struct {
s.record(e, .{ .this_field = @intCast(k) });
return .{ .ty = f.type, .lvalue = true };
};
if (findBitfield(info, n.parts[0])) |bf| {
s.record(e, .{ .this_bitfield = bf });
return .{ .ty = bf.type, .lvalue = true };
}
}
}
if (n.parts.len > 1) {
@ -2599,6 +2624,108 @@ pub const Sema = struct {
return err_typed;
}
/// `sizeof(ty)` plus one, or zero when it has no size: HLSL sizes are
/// tightly packed at scalar alignment. A struct that had errors has
/// size 1, as in clang.
fn sizeInfo(s: *Sema, ty: TypeId) u32 {
if (ty == TypeTable.error_type) return 0;
if (s.types.get(ty) == .@"struct" and s.types.get(ty).@"struct".invalid) return 2;
const size = layout.sizeOf(&s.types, ty, false, .dx_packed) catch return 0;
return size + 1;
}
/// SPIR-V can only lay out bool bitfields in external (buffer) memory.
fn checkBoolBitfield(s: *Sema, ty: TypeId, loc: Loc) void {
if (!s.opts.spirv) return;
var elem = ty;
while (s.types.get(elem) == .array) elem = s.types.get(elem).array.elem;
if (s.hasBoolBitfield(elem)) s.err(loc, "type '{s}' contains a boolean bitfield which is not supported for variables that are not externally visible when targeting SPIR-V", .{s.typeName(elem)});
}
fn hasBoolBitfield(s: *Sema, ty: TypeId) bool {
switch (s.types.get(ty)) {
.array => |a| return s.hasBoolBitfield(a.elem),
.@"struct" => |info| {
for (info.bitfields.items) |bf| if (s.types.component(bf.type) == .bool) return true;
for (info.fields.items) |f| if (!f.bits and s.hasBoolBitfield(f.type)) return true;
return false;
},
else => return false,
}
}
const BitUnit = struct { field: u32, type: TypeId, used: u8, bits: u8 };
fn checkDuplicateMember(s: *Sema, info: *types.StructInfo, base_fields: usize, name: []const u8, loc: Loc) void {
for (info.fields.items[base_fields..]) |f| if (f.name.len > 0 and std.mem.eql(u8, f.name, name)) s.err(loc, "duplicate member '{s}'", .{name});
for (info.bitfields.items) |bf| if (bf.storage >= base_fields and std.mem.eql(u8, bf.name, name)) s.err(loc, "duplicate member '{s}'", .{name});
}
/// `T name : width;` in a struct. Consecutive bitfields share a storage
/// field of their type while they fit, as dxc lays them out: DXIL packs
/// bitfields of the same size together, SPIR-V only the same type.
fn bitfieldDecl(s: *Sema, info: *types.StructInfo, unit: *?BitUnit, v: ast.VarDecl, width_e: *ast.Expr, base_fields: usize) Allocator.Error!void {
const ty = try s.resolveType(v.type);
_ = try s.expr(width_e);
if (ty == TypeTable.error_type) return;
const sc = switch (s.types.get(ty)) {
.scalar => |x| x,
.@"enum" => |en| en.underlying,
else => null,
};
if (sc == null or !sc.?.isIntegral() or v.array_dims.len > 0) {
if (v.name.len == 0) {
s.err(v.type.loc, "anonymous bit-field has non-integral type '{s}'", .{s.typeName(ty)});
} else s.err(v.name_loc, "bit-field '{s}' has non-integral type '{s}'", .{ v.name, s.typeName(ty) });
return;
}
const bits: u8 = @intCast(sc.?.size() * 8);
const width = s.evalInt(width_e) orelse {
s.err(width_e.loc, "integer constant expression required", .{});
return;
};
if (width < 0) {
s.err(width_e.loc, "bit-field '{s}' has negative width ({d})", .{ v.name, width });
return;
}
if (width > bits) {
if (v.name.len == 0) {
s.err(width_e.loc, "size of anonymous bit-field ({d} bits) exceeds size of its type ({d} bits)", .{ width, bits });
} else s.err(width_e.loc, "size of bit-field '{s}' ({d} bits) exceeds size of its type ({d} bits)", .{ v.name, width, bits });
return;
}
if (width == 0) {
if (v.name.len > 0) s.err(v.name_loc, "named bit-field '{s}' has zero width", .{v.name});
unit.* = null;
return;
}
if (v.name.len > 0) s.checkDuplicateMember(info, base_fields, v.name, v.name_loc);
const w: u8 = @intCast(width);
const fits = if (unit.*) |u|
u.used + w <= u.bits and (if (s.opts.spirv) u.type == ty else u.bits == bits)
else
false;
if (!fits) {
// Bools are stored as uint.
const storage_ty = if (sc.? == .bool) try s.types.scalar(.uint) else ty;
try info.fields.append(s.arena, .{ .name = "", .type = storage_ty, .bits = true });
unit.* = .{ .field = @intCast(info.fields.items.len - 1), .type = ty, .used = 0, .bits = bits };
}
const u = &unit.*.?;
// Unnamed bitfields only take up space.
if (v.name.len > 0) try info.bitfields.append(s.arena, .{ .name = v.name, .type = ty, .storage = u.field, .offset = u.used, .width = w });
u.used += w;
}
fn findBitfield(info: *const types.StructInfo, name: []const u8) ?types.Bitfield {
var i = info.bitfields.items.len;
while (i > 0) {
i -= 1;
if (std.mem.eql(u8, info.bitfields.items[i].name, name)) return info.bitfields.items[i];
}
return null;
}
fn memberExpr(s: *Sema, e: *ast.Expr, base: *ast.Expr, name: []const u8, name_loc: Loc) Allocator.Error!Typed {
const b = try s.expr(base);
if (b.ty == TypeTable.error_type) return err_typed;
@ -2638,6 +2765,10 @@ pub const Sema = struct {
return .{ .ty = f.type, .lvalue = b.lvalue, .read_only = b.read_only };
}
}
if (findBitfield(info, name)) |bf| {
s.record(e, .{ .bitfield = bf });
return .{ .ty = bf.type, .lvalue = b.lvalue, .read_only = b.read_only };
}
if (info.sema) |p| {
const ss: *StructSema = @ptrCast(@alignCast(p));
if (structMember(ss, name)) |sym| switch (sym) {

View File

@ -321,6 +321,17 @@ pub const Field = struct {
semantic: ?[]const u8 = null,
/// Interpolation modifiers (for entry-point inputs and outputs).
interp: Interp = .{},
/// Hidden storage for consecutive bitfields (see StructInfo.bitfields).
bits: bool = false,
};
/// A bitfield member: `width` bits at `offset` in storage field `storage`.
pub const Bitfield = struct {
name: []const u8,
type: TypeId,
storage: u32,
offset: u8,
width: u8,
};
/// Interpolation modifiers written on a parameter, field or function.
@ -339,13 +350,27 @@ pub const StructInfo = struct {
fields: std.ArrayList(Field) = .empty,
/// Direct base structs (HLSL 2021 single inheritance, in practice).
bases: std.ArrayList(*StructInfo) = .empty,
/// Bitfield members, in declaration order (their storage fields are in
/// `fields`, unnamed).
bitfields: std.ArrayList(Bitfield) = .empty,
/// Opaque pointer to Sema's per-struct data (methods, base).
sema: ?*anyopaque = null,
complete: bool = false,
/// Had errors in its members (sizeof gives 1, as in clang).
invalid: bool = false,
/// Declares operator overloads (milestone 0.2): uses of operators on
/// it are not diagnosed.
has_operators: bool = false,
/// The bitfields stored in field `storage` (consecutive).
pub fn bitfieldsIn(info: *const StructInfo, storage: u32) []const Bitfield {
var lo: usize = 0;
while (lo < info.bitfields.items.len and info.bitfields.items[lo].storage != storage) lo += 1;
var hi = lo;
while (hi < info.bitfields.items.len and info.bitfields.items[hi].storage == storage) hi += 1;
return info.bitfields.items[lo..hi];
}
pub fn overloadsOperators(info: *const StructInfo) bool {
if (info.has_operators) return true;
for (info.bases.items) |b| if (b.overloadsOperators()) return true;
@ -579,7 +604,7 @@ pub const TypeTable = struct {
.array => |a| if (a.len == 0) null else if (t.componentCount(a.elem)) |n| n * a.len else null,
.@"struct" => |s| blk: {
var n: u32 = 0;
for (s.fields.items) |f| n += t.componentCount(f.type) orelse break :blk null;
for (s.fields.items, 0..) |f, i| n += if (f.bits) @as(u32, @intCast(s.bitfieldsIn(@intCast(i)).len)) else t.componentCount(f.type) orelse break :blk null;
break :blk n;
},
else => null,