LLVM 生成低效的 IR

LLVM generates unefficient IR

本文关键字:IR LLVM      更新时间:2023-10-16

我玩LLVM并尝试使用它编译简单的C++代码

#include <stdio.h>
#include <stdlib.h>
int main()
{
int test = rand();
if (test % 2)
test += 522;
else
test *= 333;
printf("test %dn", test);
}

特别是测试 LLVM 如何处理代码分支 我得到的结果很奇怪,它在执行时给出了有效的结果,但看起来效率低下

; Function Attrs: nounwind
define i32 @main() local_unnamed_addr #0 {
%1 = tail call i32 @rand() #3
%2 = and i32 %1, 1
%3 = icmp eq i32 %2, 0
%4 = add nsw i32 %1, 522
%5 = mul nsw i32 %1, 333
%6 = select i1 %3, i32 %5, i32 %4
%7 = tail call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @.str, i64 0, i64 0), i32 %6)
ret i32 0
}

看起来它以两种方式执行,即使只需要一个 我的问题是:在这种情况下,LLVM不应该生成标签吗,为什么? 谢谢

附言我正在使用 http://ellcc.org/demo/index.cgi 进行此测试

分支可能很昂贵,因此以一个不必要的addmul指令为代价生成没有分支的代码,在实践中通常会更快。

如果你把if的分支变长,你会发现它最终会成为一个合适的分支,而不是一个select

编译器往往对哪种情况下哪个选项更快有很好的了解,所以我会相信它,除非您有特定的基准测试显示select版本比分支版本慢。