On Thu, 11 Mar 2021 at 16:36, Jonathan Wakely <jwakely.gcc@xxxxxxxxx> wrote: > > On Thu, 11 Mar 2021 at 16:30, Hugo Musso Gualandi > <hgualandi@xxxxxxxxxxxxxx> 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) { > > The restrict qualifier says that no other function arguments alias > with that one, so it doesn't mean anything on a single argument. > > > 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... > > Did you try the access attribute? > https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html Or for older versions of GCC using the pure attribute seems to work as you want too.