| Issue |
243457
|
| Summary |
[AsmPrinter] `trunc` to a non-byte-sized type in a global initializer is emitted untruncated
|
| Labels |
llvm:codegen,
miscompilation
|
| Assignees |
|
| Reporter |
chfast
|
```llvm
@a = global [2 x i8] zeroinitializer
@b = global [2 x i8] zeroinitializer
@g = global i1 trunc (i64 sub (i64 ptrtoint (ptr @b to i64), i64 ptrtoint (ptr @a to i64)) to i1)
define i32 @load_g() {
%v = load i1, ptr @g
%z = zext i1 %v to i32
ret i32 %z
}
```
`llc -mtriple=x86_64-linux-gnu -O2`:
```asm
load_g:
movq g@GOTPCREL(%rip), %rax
movzbl (%rax), %eax
retq
...
g:
.byte b-a
```
`b - a` is 2. Truncated to i1 it is 0, but the byte holds 2. Codegen reads an `i1` as a zero-extended byte, so `load_g()` returns 2, which `zext i1` cannot produce. With this driver it prints `g byte = 2, load_g() = 2`:
```c
#include <stdio.h>
extern unsigned char g;
int load_g(void);
int main(void) {
printf("g byte = %d, load_g() = %d\n", g, load_g());
return 0;
}
```
`AsmPrinter::lowerConstant` handles `Instruction::Trunc` by emitting the operand _expression_ unchanged. The comment there says it relies on "the assembler to truncate the generated _expression_ properly". The assembler only truncates to the emitted size, one byte here, not to the bit width of the type.
So for a destination type that is not byte-sized, the truncation is lost. One option is to emit the _expression_ masked to the type width, `(b-a)&1`, which the assembler still folds for label differences (llvm-mc gives 0 for `.byte (b-a)&1` here). The other is to reject it.
LangRef has no sentence on the padding bits of global initializers. For stores and loads it says:
- **store:** a non-byte-sized store "behaves like a `zext` followed by a byte-sized store";
- **load:** a load treats a non-zero padding bit as poison.
So the initializer is expected to have zero padding.
This is with trunk e0b437836a21.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs