Skip to content

Commit

Permalink
compiler: rework comptime pointer representation and access
Browse files Browse the repository at this point in the history
We've got a big one here! This commit reworks how we represent pointers
in the InternPool, and rewrites the logic for loading and storing from
them at comptime.

Firstly, the pointer representation. Previously, pointers were
represented in a highly structured manner: pointers to fields, array
elements, etc, were explicitly represented. This works well for simple
cases, but is quite difficult to handle in the cases of unusual
reinterpretations, pointer casts, offsets, etc. Therefore, pointers are
now represented in a more "flat" manner. For types without well-defined
layouts -- such as comptime-only types, automatic-layout aggregates, and
so on -- we still use this "hierarchical" structure. However, for types
with well-defined layouts, we use a byte offset associated with the
pointer. This allows the comptime pointer access logic to deal with
reinterpreted pointers far more gracefully, because the "base address"
of a pointer -- for instance a `field` -- is a single value which
pointer accesses cannot exceed since the parent has undefined layout.
This strategy is also more useful to most backends -- see the updated
logic in `codegen.zig` and `codegen/llvm.zig`. For backends which do
prefer a chain of field and elements accesses for lowering pointer
values, such as SPIR-V, there is a helpful function in `Value` which
creates a strategy to derive a pointer value using ideally only field
and element accesses. This is actually more correct than the previous
logic, since it correctly handles pointer casts which, after the dust
has settled, end up referring exactly to an aggregate field or array
element.

In terms of the pointer access code, it has been rewritten from the
ground up. The old logic had become rather a mess of special cases being
added whenever bugs were hit, and was still riddled with bugs. The new
logic was written to handle the "difficult" cases correctly, the most
notable of which is restructuring of a comptime-only array (for
instance, converting a `[3][2]comptime_int` to a `[2][3]comptime_int`.
Currently, the logic for loading and storing work somewhat differently,
but a future change will likely improve the loading logic to bring it
more in line with the store strategy. As far as I can tell, the rewrite
has fixed all bugs exposed by ziglang#19414.

As a part of this, the comptime bitcast logic has also been rewritten.
Previously, bitcasts simply worked by serializing the entire value into
an in-memory buffer, then deserializing it. This strategy has two key
weaknesses: pointers, and undefined values. Representations of these
values at comptime cannot be easily serialized/deserialized whilst
preserving data, which means many bitcasts would become runtime-known if
pointers were involved, or would turn `undefined` values into `0xAA`.
The new logic works by "flattening" the datastructure to be cast into a
sequence of bit-packed atomic values, and then "unflattening" it; using
serialization when necessary, but with special handling for `undefined`
values and for pointers which align in virtual memory. The resulting
code is definitely slower -- more on this later -- but it is correct.

The pointer access and bitcast logic required some helper functions and
types which are not generally useful elsewhere, so I opted to split them
into separate files `Sema/comptime_ptr_access.zig` and
`Sema/bitcast.zig`, with simple re-exports in `Sema.zig` for their small
public APIs.

Whilst working on this branch, I caught various unrelated bugs with
transitive Sema errors, and with the handling of `undefined` values.
These bugs have been fixed, and corresponding behavior test added.

In terms of performance, I do anticipate that this commit will regress
performance somewhat, because the new pointer access and bitcast logic
is necessarily more complex. I have not yet taken performance
measurements, but will do shortly, and post the results in this PR. If
the performance regression is severe, I will do work to to optimize the
new logic before merge.

Resolves: ziglang#19452
Resolves: ziglang#19460
  • Loading branch information
mlugg committed Apr 17, 2024
1 parent a0914e9 commit 01a2a5b
Show file tree
Hide file tree
Showing 14 changed files with 143 additions and 24 deletions.
31 changes: 31 additions & 0 deletions compile_errors/bad_usingnamespace_transitive_failure.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//! The full test name would be:
//! struct field type resolution marks transitive error from bad usingnamespace in @typeInfo call from non-initial field type
//!
//! This test is rather esoteric. It's ensuring that errors triggered by `@typeInfo` analyzing
//! a bad `usingnamespace` correctly trigger transitive errors when analyzed by struct field type
//! resolution, meaning we don't incorrectly analyze code past the uses of `S`.

const S = struct {
ok: u32,
bad: @typeInfo(T),
};

const T = struct {
pub usingnamespace @compileError("usingnamespace analyzed");
};

comptime {
const a: S = .{ .ok = 123, .bad = undefined };
_ = a;
@compileError("should not be reached");
}

comptime {
const b: S = .{ .ok = 123, .bad = undefined };
_ = b;
@compileError("should not be reached");
}

// error
//
// :14:24: error: usingnamespace analyzed
22 changes: 22 additions & 0 deletions compile_errors/bit_ptr_non_packed.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export fn entry1() void {
const S = extern struct { x: u32 };
_ = *align(1:2:8) S;
}

export fn entry2() void {
const S = struct { x: u32 };
_ = *align(1:2:@sizeOf(S) * 2) S;
}

export fn entry3() void {
const E = enum { implicit, backing, type };
_ = *align(1:2:8) E;
}

// error
//
// :3:23: error: bit-pointer cannot refer to value of type 'tmp.entry1.S'
// :3:23: note: only packed structs layout are allowed in packed types
// :8:36: error: bit-pointer cannot refer to value of type 'tmp.entry2.S'
// :8:36: note: only packed structs layout are allowed in packed types
// :13:23: error: bit-pointer cannot refer to value of type 'tmp.entry3.E'
20 changes: 20 additions & 0 deletions compile_errors/bitcast_undef.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export fn entry1() void {
const x: i32 = undefined;
const y: u32 = @bitCast(x);
@compileLog(y);
}

export fn entry2() void {
const x: packed struct { x: u16, y: u16 } = .{ .x = 123, .y = undefined };
const y: u32 = @bitCast(x);
@compileLog(y);
}

// error
//
// :4:5: error: found compile log statement
// :10:5: note: also here
//
// Compile Log Output:
// @as(u32, undefined)
// @as(u32, undefined)
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ export fn entry() void {
// :2:5: error: found compile log statement
//
// Compile Log Output:
// @as(*const anyopaque, &tmp.entry)
// @as(*const anyopaque, @as(*const anyopaque, @ptrCast(tmp.entry)))
13 changes: 0 additions & 13 deletions compile_errors/comptime_dereference_slice_of_struct.zig

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ comptime {

const payload_ptr = &opt_ptr.?;
opt_ptr = null;
_ = payload_ptr.*.*;
_ = payload_ptr.*.*; // TODO: this case was regressed by #19630
}
comptime {
var opt: ?u8 = 15;
Expand All @@ -28,6 +28,5 @@ comptime {
// backend=stage2
// target=native
//
// :9:20: error: attempt to use null value
// :16:20: error: attempt to use null value
// :24:20: error: attempt to unwrap error: Foo
3 changes: 2 additions & 1 deletion compile_errors/function_call_assigned_to_incorrect_type.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ fn concat() [16]f32 {
// target=native
//
// :3:17: error: expected type '[4]f32', found '[16]f32'
// :3:17: note: array of length 16 cannot cast into an array of length 4
// :3:17: note: destination has length 4
// :3:17: note: source has length 16
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,5 @@ export fn foo_slice_len_increment_beyond_bounds() void {
}

// error
// backend=stage2
// target=native
//
// :6:16: error: comptime store of index 8 out of bounds of array length 8
// :6:16: error: dereference of '*u8' exceeds bounds of containing decl of type '[8]u8'
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
comptime {
const a: @Vector(3, u8) = .{ 1, 200, undefined };
@compileLog(@addWithOverflow(a, a));
}

comptime {
const a: @Vector(3, u8) = .{ 1, 2, undefined };
const b: @Vector(3, u8) = .{ 0, 3, 10 };
@compileLog(@subWithOverflow(a, b));
}

comptime {
const a: @Vector(3, u8) = .{ 1, 200, undefined };
@compileLog(@mulWithOverflow(a, a));
}

// error
//
// :3:5: error: found compile log statement
// :9:5: note: also here
// :14:5: note: also here
//
// Compile Log Output:
// @as(struct{@Vector(3, u8), @Vector(3, u1)}, .{ .{ 2, 144, undefined }, .{ 0, 1, undefined } })
// @as(struct{@Vector(3, u8), @Vector(3, u1)}, .{ .{ 1, 255, undefined }, .{ 0, 1, undefined } })
// @as(struct{@Vector(3, u8), @Vector(3, u1)}, .{ .{ 1, 64, undefined }, .{ 0, 1, undefined } })
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export fn entry6() void {
}
export fn entry7() void {
_ = @sizeOf(packed struct {
x: enum { A, B },
x: enum(u1) { A, B },
});
}
export fn entry8() void {
Expand Down Expand Up @@ -70,6 +70,12 @@ export fn entry13() void {
x: *type,
});
}
export fn entry14() void {
const E = enum { implicit, backing, type };
_ = @sizeOf(packed struct {
x: E,
});
}

// error
// backend=llvm
Expand Down Expand Up @@ -97,3 +103,5 @@ export fn entry13() void {
// :70:12: error: packed structs cannot contain fields of type '*type'
// :70:12: note: comptime-only pointer has no guaranteed in-memory representation
// :70:12: note: types are not available at runtime
// :76:12: error: packed structs cannot contain fields of type 'tmp.entry14.E'
// :74:15: note: enum declared here
19 changes: 19 additions & 0 deletions compile_errors/pointer_exceeds_containing_value.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export fn entry1() void {
const x: u32 = 123;
const ptr: [*]const u32 = @ptrCast(&x);
_ = ptr - 1;
}

export fn entry2() void {
const S = extern struct { x: u32, y: u32 };
const y: u32 = 123;
const parent_ptr: *const S = @fieldParentPtr("y", &y);
_ = parent_ptr;
}

// error
//
// :4:13: error: pointer computation here causes undefined behavior
// :4:13: note: resulting pointer exceeds bounds of containing value which may trigger overflow
// :10:55: error: pointer computation here causes undefined behavior
// :10:55: note: resulting pointer exceeds bounds of containing value which may trigger overflow
8 changes: 8 additions & 0 deletions compile_errors/reading_past_end_of_pointer_casted_array.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,17 @@ comptime {
const deref = int_ptr.*;
_ = deref;
}
comptime {
const array: [4]u8 = "aoeu".*;
const sub_array = array[1..];
const int_ptr: *const u32 = @ptrCast(@alignCast(sub_array));
const deref = int_ptr.*;
_ = deref;
}

// error
// backend=stage2
// target=native
//
// :5:26: error: dereference of '*const u24' exceeds bounds of containing decl of type '[4]u8'
// :12:26: error: dereference of '*const u32' exceeds bounds of containing decl of type '[4]u8'
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ export fn foo() void {
// backend=stage2
// target=native
//
// :3:49: error: comptime dereference requires '[]const u8' to have a well-defined layout, but it does not.
// :3:49: error: comptime dereference requires '[]const u8' to have a well-defined layout
4 changes: 2 additions & 2 deletions comptime_aggregate_print.zig
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ pub fn main() !void {}
// :20:5: error: found compile log statement
//
// Compile Log Output:
// @as([]i32, &(comptime alloc).buf[0..2])
// @as([]i32, &(comptime alloc).buf[0..2])
// @as([]i32, @as([*]i32, @ptrCast(@as(tmp.UnionContainer, .{ .buf = .{ 1, 2 } }).buf[0]))[0..2])
// @as([]i32, @as([*]i32, @ptrCast(@as(tmp.StructContainer, .{ .buf = .{ 3, 4 } }).buf[0]))[0..2])

0 comments on commit 01a2a5b

Please sign in to comment.