仅限制函数的输出指针参数能否充分发挥restrict的作用?
问题:仅为输出指针添加restrict,能否让函数内所有读取操作获得优化收益?
假设我有一个函数,接收若干指针参数:部分非const指针用于写入,部分const指针仅用于读取,示例代码如下:
void f(int * a, int const *b);
同时该函数不会通过其他方式写入内存(即不使用全局变量、固定地址、将const指针强制转换为非const指针等手段)。
按照C语言标准,若仅为输出参数添加restrict限定符(即示例中的a,而非b),是否足以让函数f()内的所有读取操作获得restrict带来的优化收益?
测试验证
通过测试发现这种写法似乎可行,测试代码如下:
int f(int * restrict a, int const * b) { a[0] += b[0]; return a[0] + b[0]; } int all_restricted(int * restrict a, int const * restrict b) { a[0] += b[0]; return a[0] + b[0]; } int unrestricted(int * a, int const * b) { a[0] += b[0]; return a[0] + b[0]; }
生成的x86_64目标代码中,f与all_restricted的代码完全一致,而unrestricted的代码不同:
f: mov eax, DWORD PTR [rsi] mov edx, DWORD PTR [rdi] add edx, eax mov DWORD PTR [rdi], edx add eax, edx ret all_restricted: mov eax, DWORD PTR [rsi] mov edx, DWORD PTR [rdi] add edx, eax mov DWORD PTR [rdi], edx add eax, edx ret unrestricted: mov eax, DWORD PTR [rsi] add eax, DWORD PTR [rdi] mov DWORD PTR [rdi], eax add eax, DWORD PTR [rsi] ret
不过需要注意,这个测试结果并不构成通用保证。
内容的提问来源于stack exchange,提问作者einpoklum
相关产品推荐
相关产品推荐

