Telling the C optimizer that a pointer's contents won't be modified

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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...

-- Hugo





[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux