authorgravatar for david@vortan.devDavid Rubin <david@vortan.dev> 2024-05-22 08:51:16-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-05-22 10:51:16-05:00
loga7de02e05216db9a04e438703ddf1b6b12f3fbef
treebf70046bbcf24c00bf201c0638f2f90543a62df5
parented75f62568f64c0d3859aab35aaf5289c3f07026
signaturebadge-check Signed by PGP key B5690EEEBB952194

implement `@expect` builtin (#19658)

* implement `@expect` * add docs * add a second arg for expected bool * fix typo * move `expect` to use BinOp * update to newer langref format

25 files changed, 202 insertions(+), 1 deletions(-)

doc/langref.html.in+8
......@@ -4799,6 +4799,14 @@ fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_val
47994799 {#see_also|@export#}
48004800 {#header_close#}
48014801
4802 {#header_open|@expect#}
4803 <pre>{#syntax#}@expect(operand: bool, expected: bool) bool{#endsyntax#}</pre>
4804 <p>
4805 Informs the optimizer that {#syntax#}operand{#endsyntax#} will likely be {#syntax#}expected{#endsyntax#}, which influences branch compilation to prefer generating the true branch first.
4806 </p>
4807 {#code|expect_if.zig#}
4808 {#header_close#}
4809
48024810 {#header_open|@fence#}
48034811 <pre>{#syntax#}@fence(order: AtomicOrder) void{#endsyntax#}</pre>
48044812 <p>
doc/langref/expect_if.zig created+15
......@@ -0,0 +1,15 @@
1pub fn a(x: u32) void {
2 if (@expect(x == 0, false)) {
3 // condition check falls through at code generation
4 return;
5 } else {
6 // condition is branched to at code generation
7 return;
8 }
9}
10
11test "expect" {
12 a(10);
13}
14
15// test
lib/std/zig/AstGen.zig+9-1
......@@ -2823,6 +2823,7 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As
28232823 .set_float_mode,
28242824 .set_align_stack,
28252825 .set_cold,
2826 .expect,
28262827 => break :b true,
28272828 else => break :b false,
28282829 },
......@@ -9292,7 +9293,14 @@ fn builtinCall(
92929293 });
92939294 return rvalue(gz, ri, .void_value, node);
92949295 },
9295
9296 .expect => {
9297 const val = try gz.addExtendedPayload(.expect, Zir.Inst.BinNode{
9298 .node = gz.nodeIndexToRelative(node),
9299 .lhs = try expr(gz, scope, .{ .rl = .{ .ty = .bool_type } }, params[0]),
9300 .rhs = try expr(gz, scope, .{ .rl = .{ .ty = .bool_type } }, params[1]),
9301 });
9302 return rvalue(gz, ri, val, node);
9303 },
92969304 .src => {
92979305 const token_starts = tree.tokens.items(.start);
92989306 const node_start = token_starts[tree.firstToken(node)];
lib/std/zig/AstRlAnnotate.zig+5
......@@ -1100,5 +1100,10 @@ fn builtinCall(astrl: *AstRlAnnotate, block: ?*Block, ri: ResultInfo, node: Ast.
11001100 _ = try astrl.expr(args[4], block, ResultInfo.type_only);
11011101 return false;
11021102 },
1103 .expect => {
1104 _ = try astrl.expr(args[0], block, ResultInfo.none);
1105 _ = try astrl.expr(args[1], block, ResultInfo.none);
1106 return false;
1107 },
11031108 }
11041109}
lib/std/zig/BuiltinFn.zig+8
......@@ -82,6 +82,7 @@ pub const Tag = enum {
8282 select,
8383 set_align_stack,
8484 set_cold,
85 expect,
8586 set_eval_branch_quota,
8687 set_float_mode,
8788 set_runtime_safety,
......@@ -743,6 +744,13 @@ pub const list = list: {
743744 .illegal_outside_function = true,
744745 },
745746 },
747 .{
748 "@expect",
749 .{
750 .tag = .expect,
751 .param_count = 2,
752 },
753 },
746754 .{
747755 "@setEvalBranchQuota",
748756 .{
lib/std/zig/Zir.zig+3
......@@ -2060,6 +2060,9 @@ pub const Inst = struct {
20602060 /// Guaranteed to not have the `ptr_cast` flag.
20612061 /// Uses the `pl_node` union field with payload `FieldParentPtr`.
20622062 field_parent_ptr,
2063 /// Implements the `@expect` builtin.
2064 /// `operand` is BinOp
2065 expect,
20632066
20642067 pub const InstData = struct {
20652068 opcode: Extended,
lib/zig.h+6
......@@ -318,6 +318,12 @@ typedef char bool;
318318#define zig_noreturn
319319#endif
320320
321#if defined(__GNUC__) || defined(__clang__)
322#define zig_expect(op, exp) __builtin_expect(op, exp)
323#else
324#define zig_expect(op, exp) (op)
325#endif
326
321327#define zig_bitSizeOf(T) (CHAR_BIT * sizeof(T))
322328
323329#define zig_compiler_rt_abbrev_uint32_t si
src/Air.zig+7
......@@ -848,6 +848,10 @@ pub const Inst = struct {
848848 /// Operand is unused and set to Ref.none
849849 work_group_id,
850850
851 /// Implements @expect builtin.
852 /// Uses the `bin_op` field.
853 expect,
854
851855 pub fn fromCmpOp(op: std.math.CompareOperator, optimized: bool) Tag {
852856 switch (op) {
853857 .lt => return if (optimized) .cmp_lt_optimized else .cmp_lt,
......@@ -1517,6 +1521,8 @@ pub fn typeOfIndex(air: *const Air, inst: Air.Inst.Index, ip: *const InternPool)
15171521 .work_group_id,
15181522 => return Type.u32,
15191523
1524 .expect => return Type.bool,
1525
15201526 .inferred_alloc => unreachable,
15211527 .inferred_alloc_comptime => unreachable,
15221528 }
......@@ -1634,6 +1640,7 @@ pub fn mustLower(air: Air, inst: Air.Inst.Index, ip: *const InternPool) bool {
16341640 .add_safe,
16351641 .sub_safe,
16361642 .mul_safe,
1643 .expect,
16371644 => true,
16381645
16391646 .add,
src/Liveness.zig+2
......@@ -286,6 +286,7 @@ pub fn categorizeOperand(
286286 .cmp_gte_optimized,
287287 .cmp_gt_optimized,
288288 .cmp_neq_optimized,
289 .expect,
289290 => {
290291 const o = air_datas[@intFromEnum(inst)].bin_op;
291292 if (o.lhs == operand_ref) return matchOperandSmallIndex(l, inst, 0, .none);
......@@ -955,6 +956,7 @@ fn analyzeInst(
955956 .memset,
956957 .memset_safe,
957958 .memcpy,
959 .expect,
958960 => {
959961 const o = inst_datas[@intFromEnum(inst)].bin_op;
960962 return analyzeOperands(a, pass, data, inst, .{ o.lhs, o.rhs, .none });
src/Liveness/Verify.zig+1
......@@ -257,6 +257,7 @@ fn verifyBody(self: *Verify, body: []const Air.Inst.Index) Error!void {
257257 .memset,
258258 .memset_safe,
259259 .memcpy,
260 .expect,
260261 => {
261262 const bin_op = data[@intFromEnum(inst)].bin_op;
262263 try self.verifyInstOperands(inst, .{ bin_op.lhs, bin_op.rhs, .none });
src/Module.zig+1
......@@ -5546,6 +5546,7 @@ pub const Feature = enum {
55465546 /// to generate better machine code in the backends. All backends should migrate to
55475547 /// enabling this feature.
55485548 safety_checked_instructions,
5549 can_expect,
55495550};
55505551
55515552pub fn backendSupportsFeature(zcu: Module, feature: Feature) bool {
src/Sema.zig+29
......@@ -1258,6 +1258,7 @@ fn analyzeBodyInner(
12581258 .work_group_size => try sema.zirWorkItem( block, extended, extended.opcode),
12591259 .work_group_id => try sema.zirWorkItem( block, extended, extended.opcode),
12601260 .in_comptime => try sema.zirInComptime( block),
1261 .expect => try sema.zirExpect( block, extended),
12611262 .closure_get => try sema.zirClosureGet( block, extended),
12621263 // zig fmt: on
12631264
......@@ -17553,6 +17554,34 @@ fn zirThis(
1755317554 return sema.analyzeDeclVal(block, src, this_decl_index);
1755417555}
1755517556
17557fn zirExpect(sema: *Sema, block: *Block, inst: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
17558 const bin_op = sema.code.extraData(Zir.Inst.BinNode, inst.operand).data;
17559 const operand = try sema.resolveInst(bin_op.lhs);
17560 const expected = try sema.resolveInst(bin_op.rhs);
17561
17562 const expected_src = LazySrcLoc{ .node_offset_builtin_call_arg1 = bin_op.node };
17563
17564 if (!try sema.isComptimeKnown(expected)) {
17565 return sema.fail(block, expected_src, "@expect 'expected' must be comptime-known", .{});
17566 }
17567
17568 if (try sema.resolveValue(operand)) |op| {
17569 return Air.internedToRef(op.toIntern());
17570 }
17571
17572 if (sema.mod.backendSupportsFeature(.can_expect) and sema.mod.optimizeMode() != .Debug) {
17573 return try block.addInst(.{
17574 .tag = .expect,
17575 .data = .{ .bin_op = .{
17576 .lhs = operand,
17577 .rhs = expected,
17578 } },
17579 });
17580 } else {
17581 return operand;
17582 }
17583}
17584
1755617585fn zirClosureGet(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
1755717586 const mod = sema.mod;
1755817587 const ip = &mod.intern_pool;
src/arch/aarch64/CodeGen.zig+2
......@@ -803,6 +803,8 @@ fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
803803 .@"try" => try self.airTry(inst),
804804 .try_ptr => try self.airTryPtr(inst),
805805
806 .expect => unreachable,
807
806808 .dbg_stmt => try self.airDbgStmt(inst),
807809 .dbg_inline_block => try self.airDbgInlineBlock(inst),
808810 .dbg_var_ptr,
src/arch/arm/CodeGen.zig+2
......@@ -844,6 +844,8 @@ fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
844844 .wrap_errunion_payload => try self.airWrapErrUnionPayload(inst),
845845 .wrap_errunion_err => try self.airWrapErrUnionErr(inst),
846846
847 .expect => unreachable,
848
847849 .add_optimized,
848850 .sub_optimized,
849851 .mul_optimized,
src/arch/riscv64/CodeGen.zig+2
......@@ -1200,6 +1200,8 @@ fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
12001200 .@"try" => try self.airTry(inst),
12011201 .try_ptr => return self.fail("TODO: try_ptr", .{}),
12021202
1203 .expect => unreachable,
1204
12031205 .dbg_var_ptr,
12041206 .dbg_var_val,
12051207 => try self.airDbgVar(inst),
src/arch/sparc64/CodeGen.zig+2
......@@ -636,6 +636,8 @@ fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
636636 .@"try" => try self.airTry(inst),
637637 .try_ptr => @panic("TODO try self.airTryPtr(inst)"),
638638
639 .expect => unreachable,
640
639641 .dbg_stmt => try self.airDbgStmt(inst),
640642 .dbg_inline_block => try self.airDbgInlineBlock(inst),
641643 .dbg_var_ptr,
src/arch/wasm/CodeGen.zig+2
......@@ -2016,6 +2016,8 @@ fn genInst(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
20162016 .c_va_start,
20172017 => |tag| return func.fail("TODO: Implement wasm inst: {s}", .{@tagName(tag)}),
20182018
2019 .expect => unreachable,
2020
20192021 .atomic_load => func.airAtomicLoad(inst),
20202022 .atomic_store_unordered,
20212023 .atomic_store_monotonic,
src/arch/x86_64/CodeGen.zig+2
......@@ -2014,6 +2014,8 @@ fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
20142014
20152015 .abs => try self.airAbs(inst),
20162016
2017 .expect => unreachable,
2018
20172019 .add_with_overflow => try self.airAddSubWithOverflow(inst),
20182020 .sub_with_overflow => try self.airAddSubWithOverflow(inst),
20192021 .mul_with_overflow => try self.airMulWithOverflow(inst),
src/codegen/c.zig+23
......@@ -3343,6 +3343,8 @@ fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail,
33433343
33443344 .@"try" => try airTry(f, inst),
33453345 .try_ptr => try airTryPtr(f, inst),
3346
3347 .expect => try airExpect(f, inst),
33463348
33473349 .dbg_stmt => try airDbgStmt(f, inst),
33483350 .dbg_inline_block => try airDbgInlineBlock(f, inst),
......@@ -4704,6 +4706,27 @@ fn airTryPtr(f: *Function, inst: Air.Inst.Index) !CValue {
47044706 return lowerTry(f, inst, extra.data.ptr, body, err_union_ty, true);
47054707}
47064708
4709fn airExpect(f: *Function, inst: Air.Inst.Index) !CValue {
4710 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
4711 const operand = try f.resolveInst(bin_op.lhs);
4712 const expected = try f.resolveInst(bin_op.rhs);
4713
4714 const writer = f.object.writer();
4715 const local = try f.allocLocal(inst, Type.bool);
4716 const a = try Assignment.start(f, writer, CType.bool);
4717 try f.writeCValue(writer, local, .Other);
4718 try a.assign(f, writer);
4719
4720 try writer.writeAll("zig_expect(");
4721 try f.writeCValue(writer, operand, .FunctionArgument);
4722 try writer.writeAll(", ");
4723 try f.writeCValue(writer, expected, .FunctionArgument);
4724 try writer.writeAll(")");
4725
4726 try a.end(f, writer);
4727 return local;
4728}
4729
47074730fn lowerTry(
47084731 f: *Function,
47094732 inst: Air.Inst.Index,
src/codegen/llvm.zig+22
......@@ -5038,6 +5038,8 @@ pub const FuncGen = struct {
50385038 .slice_ptr => try self.airSliceField(inst, 0),
50395039 .slice_len => try self.airSliceField(inst, 1),
50405040
5041 .expect => try self.airExpect(inst),
5042
50415043 .call => try self.airCall(inst, .auto),
50425044 .call_always_tail => try self.airCall(inst, .always_tail),
50435045 .call_never_tail => try self.airCall(inst, .never_tail),
......@@ -6365,6 +6367,26 @@ pub const FuncGen = struct {
63656367 return result;
63666368 }
63676369
6370 // Note that the LowerExpectPass only runs in Release modes
6371 fn airExpect(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
6372 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
6373
6374 const operand = try self.resolveInst(bin_op.lhs);
6375 const expected = try self.resolveInst(bin_op.rhs);
6376
6377 return try self.wip.callIntrinsic(
6378 .normal,
6379 .none,
6380 .expect,
6381 &.{operand.typeOfWip(&self.wip)},
6382 &.{
6383 operand,
6384 expected,
6385 },
6386 "",
6387 );
6388 }
6389
63686390 fn sliceOrArrayPtr(fg: *FuncGen, ptr: Builder.Value, ty: Type) Allocator.Error!Builder.Value {
63696391 const o = fg.dg.object;
63706392 const mod = o.module;
src/print_air.zig+1
......@@ -162,6 +162,7 @@ const Writer = struct {
162162 .memcpy,
163163 .memset,
164164 .memset_safe,
165 .expect,
165166 => try w.writeBinOp(s, inst),
166167
167168 .is_null,
src/print_zir.zig+1
......@@ -591,6 +591,7 @@ const Writer = struct {
591591 .wasm_memory_grow,
592592 .prefetch,
593593 .c_va_arg,
594 .expect,
594595 => {
595596 const inst_data = self.code.extraData(Zir.Inst.BinNode, extended.operand).data;
596597 const src = LazySrcLoc.nodeOffset(inst_data.node);
src/target.zig+1
......@@ -535,5 +535,6 @@ pub fn backendSupportsFeature(
535535 .error_set_has_value => use_llvm or cpu_arch.isWasm(),
536536 .field_reordering => ofmt == .c or use_llvm,
537537 .safety_checked_instructions => use_llvm,
538 .can_expect => use_llvm or ofmt == .c,
538539 };
539540}
test/behavior/expect.zig created+37
......@@ -0,0 +1,37 @@
1const std = @import("std");
2const expect = std.testing.expect;
3
4test "@expect if-statement" {
5 const x: u32 = 10;
6 _ = &x;
7 if (@expect(x == 20, true)) {}
8}
9
10test "@expect runtime if-statement" {
11 var x: u32 = 10;
12 var y: u32 = 20;
13 _ = &x;
14 _ = &y;
15 if (@expect(x != y, false)) {}
16}
17
18test "@expect bool input/output" {
19 const b: bool = true;
20 try expect(@TypeOf(@expect(b, false)) == bool);
21}
22
23test "@expect bool is transitive" {
24 const a: bool = true;
25 const b = @expect(a, false);
26
27 const c = @intFromBool(!b);
28 std.mem.doNotOptimizeAway(c);
29
30 try expect(c == 0);
31 try expect(@expect(c != 0, false) == false);
32}
33
34test "@expect at comptime" {
35 const a: bool = true;
36 comptime try expect(@expect(a, true) == true);
37}
test/cases/compile_errors/@expect_non_bool.zig created+11
......@@ -0,0 +1,11 @@
1export fn a() void {
2 var x: u32 = 10;
3 _ = &x;
4 _ = @expect(x, true);
5}
6
7// error
8// backend=stage2
9// target=native
10//
11// :4:17: error: expected type 'bool', found 'u32'