Skip to content

struct field load through underaligned pointer has incorrect alignment #14904

Description

@andrewrk

Zig Version

0.11.0-dev.1969+d525ecb52

Steps to Reproduce and Observed Behavior

conststd=@import("std");
constexpect=std.testing.expect;
pubfnmain() !void {
varbuf: [9]u8align(4) = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
constptr=@ptrCast(*align(1) Header, buf[1..][0..8]);
constx=ptr.bytes_len;
std.debug.print("x=0x{x}\n", .{x});
}
constHeader=externstruct {
tag: u32,
bytes_len: u32,
};
$ stage3/bin/zig build-exe test3.zig -target mipsel-linux-musl
$ qemu-mipsel ./test3
Bus error (core dumped)

The problem is incorrect alignment in the LLVM IR:

conststd=@import("std");
pubfnpanic(msg: []constu8, st: ?*std.builtin.StackTrace, start: ?usize) noreturn {
_= .{ msg, st, start };
unreachable;
}
exportfnentry() bool {
doTheTest() catchreturnfalse;
returntrue;
}
fndoTheTest() !void {
varbuf: [9]u8align(4) = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
constptr: *align(1) Header=@ptrCast(buf[1..][0..8]);
constx=ptr.bytes_len;
foo(x);
}
externfnfoo(u32) void;
constHeader=externstruct {
tag: u32,
bytes_len: u32,
};
$ stage3/bin/zig build-obj test2.zig -target mipsel-linux-musl --verbose-llvm-ir -fstrip -OReleaseFast
defineinternalfastcci16@test2.doTheTest() unnamed_addr #0 {
Entry:
%0 = allocaptr, align4%1 = alloca [9 x i8], align4callvoid@llvm.memcpy.p0.p0.i32(ptralign4%1, ptralign1 @0, i329, i1false)
%2 = getelementptrinbounds [9 x i8], ptr%1, i320, i321storeptr%2, ptr%0, align4%3 = loadptr, ptr%0, align4%4 = getelementptrinbounds [8 x i8], ptr%3, i320, i320%5 = getelementptrinbounds%test2.Header, ptr%4, i320, i321%6 = loadi32, ptr%5, align4callvoid@foo(i32%6)
reti160
}

The problem is %6 = load i32, ptr %5, align 4 which has align 4 instead of align 1.

Side note: it is very annoying that the panic override above does not eliminate panicOutOfBounds from calling into std.debug.panicExtra and dragging in a whole lot of formatting code.

I have no evidence this is a regression, but I suspect it is.

Expected Behavior

I expect to see %6 = load i32, ptr %5, align 1 which would cause LLVM to generate machine code that did not cause a Bus Error.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backend-cThe C backend (CBE) outputs C source code.bugObserved behavior contradicts documented or intended behaviorfrontendTokenization, parsing, AstGen, Sema, and Liveness.miscompilationThe compiler reports success but produces semantically incorrect code.regressionIt worked in a previous version of Zig, but stopped working.

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions