如何解决为什么在 C 中没有优化本地函数指针调用?
static int action1(void) { return 1; }
static int action2(void) { return 2; }
int test(int x) {
int (*const action)() = x > 5 ? action1 : action2;
return 1 + action();
}
// yielded :
action1():
mov eax,1
ret
action2():
mov eax,2
ret
test(int):
sub rsp,8
mov edx,OFFSET FLAT:action2()
cmp edi,5
mov eax,OFFSET FLAT:action1()
cmovle rax,rdx
call rax
add rsp,8
add eax,1
ret
然而:
int test2(void) { return test(6); }
// yields
test2: # @test2
mov eax,2
ret
建议动作调用的结果可以在编译时确定。
x86 gcc 10.2 和 clang 11.0 (-O2) 上的行为似乎相同。
Q1) 如果可以做到,有什么理由不可以吗?
Q2) 也许更重要的是,我如何写这样的东西,但让它内联 action1 和 action2 :
static int testHelper6(int x,int callback(int)) {
return 1 + callback(x);
}
int test6(int x) {
return testHelper6(x,x > 5 ? action1 : action2);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。