Why doesn't Zig optimize this, whereas the C compiler does?

This kinda brings up if the programmer should be able to express this somehow for struct fields.
E.g. by defining Example like this:

const Example = struct {
    val: noalias [*]u32,
    fun: u32,
};

or this:

const Example = struct {
    val: [*noalias]u32,
    fun: u32,
};

or something alone these lines.

To be clear, Zig should absolutely be enhanced to add TBAA metadata for LLVM in certain cases. For example, auto-layout structs and unions (not packed, not extern) cannot alias any unequal types, so we should be telling LLVM about that fact, and currently not doing it. I don’t recall an issue open for this yet.

The good aliasing that people want to do is already being done with extern/packed struct and union, and @bitCast, which will continue to work fine. In fact, illegal aliasing will be safety-checked with add safety checks for pointer casting · Issue #2414 · ziglang/zig · GitHub which is a fairly straightforward check to add, so I think we can expect it to be done soon.

9 Likes