<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/93096>93096</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
nuw/nsw should not be added to trunc instruction when there are undef bits in the source value
</td>
</tr>
<tr>
<th>Labels</th>
<td>
llvm:optimizations
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
weiguozhi
</td>
</tr>
</table>
<pre>
Run ipsccp on the code
```
; opt -passes=ipsccp -S test.ll
define void @foo(i1 %cond1, i32 %p1) {
entry:
br label %loop
loop:
%phi1 = phi i64 [undef, %entry], [%phi2, %latch]
br i1 %cond1, label %then2, label %else2
then2:
%and = and i64 %phi1, -1095216660481 ; 0xFFFFFF00FFFFFFFF
br label %latch
else2:
%ext = zext i32 %p1 to i64
%or = or i64 %ext, 4294967296 ; 0x100000000
br label %latch
latch:
%phi2 = phi i64 [%and, %then2], [%or, %else2]
%shr = lshr i64 %phi2, 32
%res = trunc i64 %shr to i8
%cond2 = call i1 @bar(i8 %res)
br i1 %cond2, label %loop, label %exit
exit:
ret void
}
declare i1 @bar(i8)
```
LLVM adds nuw/nsw flags to the trunc instruction
```
%res = trunc nuw nsw i64 %shr to i8
```
It means all high bits of %shr are 0.
But %phi1 may be undef, bits [32..39] of %and are cleared, bits[40..63] can still be undef, and later it is moved to bits[8..31] of %shr, so not all high bits of %shr are 0.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVV2PrCgQ_TX4UhmDiLY--HB7O51scvdlN9l31LJlQ4MBnJ6ZX78B7M-dZC-ZjCL1cerUqUY4J08asSPVnlSHTKx-Nra7oDyt5muWWW_Gz-7PVYNc3DAsYDT4GWEwIxJ6IPQHqen2l7blHszi4W0RzqEj5WFzfPsLPDqfK7UZxv8jTlIjvBs5AuF0MoawRhZAWDUYPRaE_QayZGG_FIS1QHb75Ina209SbnEAegtK9KiCqTJmecwS93fTEGwOSco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