我在玩LLVM并尝试使用它编译简单的C ++代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int test = rand();
if (test % 2)
test += 522;
else
test *= 333;
printf("test %d\n", 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是否不应该生成标签,为什么?谢谢
PS我正在使用http://ellcc.org/demo/index.cgi进行此测试
分支可能会很昂贵,因此生成一个没有分支的代码会以不必要的代价add
或一条mul
指令为代价,通常在实践中会更快。
如果您将分支的if
长度加长,则会看到它最终将成为适当的分支,而不是select
。
编译器倾向于对哪种情况下哪种选择更快有一个很好的了解,因此我相信它,除非您有特定的基准测试来显示该版本select
比分支的版本慢。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句