r/Compilers • u/fernando_quintao • 15d ago
Question about LLVM's Constraint Elimination Pass
Hi redditors, I am trying to understand how clang eliminates the dead code below:
#include <stdio.h>
#include <stdlib.h>
void foo(int M, int N, int P) {
if (P > N)
if (N > M)
if (M > P)
printf("%x\n", 0xDEADC0DE);
}
When I compile it with clang 20.1.0, I get this assembly:
foo:
ret
If I compile it with clang 19.1.0 -O2 (-O3 makes no difference), then I get:
foo:
cmp edi, edx
jle .LBB0_3
cmp esi, edi
jle .LBB0_3
cmp edx, esi
jle .LBB0_3
lea rdi, [rip + .L.str]
mov esi, -559038242
xor eax, eax
jmp printf@PLT
.LBB0_3:
ret
.L.str:
.asciz "%x\n"
When I do:
clang-20 -O2 -S -emit-llvm -mllvm -print-after-all -o /dev/null foo.c 2>&1
I can see that ConstraintEliminationPass is likely the one that proves that the branch is dead. However, this pass was already present in clang 19. I was wondering if some redditor that followed that implementation could explain how they improved the pass to make it able to solve that case.
Ps.: Notice that the same program would be fully optimized by gcc, already in version 7.1 -O2 (however, not in gcc 6.5, and not in gcc 7.1 -O1), using VRP.
8
u/PudgeNikita 15d ago edited 14d ago
After about 4 hours (i have an i5-9400f) of trying to get it to compile in the first place (because of stuff like HAS_LOGF128 and stdint.h missing somewhere because of transitive header include changes) and then git bisecting llvm's opt to spit out
falseon the IR fromwhich is
with
i think its this commit https://github.com/llvm/llvm-project/commit/0f0c0c36e3e90b4cb04004ed9c930f3863a36422
closing this https://github.com/llvm/llvm-project/issues/117107 issue
3
u/regehr 15d ago
I don't know what changed to make this possible, but one nice thing about constraint elimination is that it can tell you what it's thinking, try this with your input:
clang -O2 -S -emit-llvm -o /dev/null foo.c -mllvm -debug-only=constraint-elimination,constraint-system
(this works with an LLVM I built yesterday, possibly won't work with earlier versions)
constraint elimination is one of my favorite LLVM passes-- it does a single thing well, and since it was introduced relatively recently, its code is quite clean and easy to understand.
2
u/dumael 15d ago
Have you tried running adding -llvm -debug to the command line? It may show the some of the internal workings of the pass. It may require an asserts build or debug build of LLVM.
1
u/ha9unaka 15d ago
u/RemindMeBot 1 day
-1
u/KingOfZero 15d ago
Ask in the LLVM Discourse channels and the actual engineers will respond