On 3/11/21 8:29 AM, Hugo Musso Gualandi wrote:
Hi everyone,
Does anyone know if there is a way to tell the C compiler that a
pointer's contents won't change after a function call? For example, if I
compile the following code with -O2 then GCC 10 can optimize away the
second pointer dereference in "f" but not in "g".
https://godbolt.org/z/5P3rxn
void reader(const int *p);
int f(int *p) {
int x = *p;
int y = *p;
return x + y;
}
int g(int *p) {
int x = *p;
reader(p);
int y = *p;
return x + y;
}
Note how there is a single "movl" in the first case but two in the second:
f:
movl (%rdi), %eax
addl %eax, %eax
ret
g:
pushq %rbp
pushq %rbx
movq %rdi, %rbx
subq $8, %rsp
movl (%rdi), %ebp
call reader
movl (%rbx), %eax
addq $8, %rsp
popq %rbx
addl %ebp, %eax
popq %rbp
ret
I also tried using restrict but the result was still the same.
// The generated ASM was still the same even with restrict.
int g(int * restrict p) {
Is there a way to tell the optimizer that the "reader" function won't
modify the contents of "p"? The context of this is that I'm working with
a compiler that uses C as a compilation target. We can rely on GCC to
optimize most things I can't figure out how help it optimize this one...
Declaring the pointer restrict and what it points to const implies
that the pointer isn't used to modify the object:
int g (const int * restrict p);
Unfortunately, GCC doesn't do anything with it. See:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81009
Martin