Friday, 12 July 2019

restrict keyword

Restrict keyword


  • restrict keyword is mainly used in pointer declarations as a type qualifier for pointers.
  • The compiler will optimize the code if restrict.
  • When we use restrict with a pointer ptr, it tells the compiler that ptr is the only way to access the object pointed by it and compiler doesn’t need to add any additional checks.
  • If a programmer uses restrict keyword and violate the above condition, result is undefined behavior.
  • GCC's and Clang's __restrict__,
  • restrict says that the pointer is the only thing that accesses the underlying object. It eliminates the potential for pointer aliasing, enabling better optimization by the compiler.

Note: I have checked __restrict__ is compiling in Gcc, but could not found difference between restrict & normal in assembly file.

In code somewhere found this below line:

/* Be friend of both C90 and C99 compilers */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    /* "inline" and "restrict" are keywords */
#else
#   define inline           /* inline */
#   define restrict         /* restrict */
#endif

Example:


int foo(int *a, int *b)
{
    *a = 5;
    *b = 6;
    return *a + *b;
}
 
int rfoo(int *restrict a, int *restrict b)
{
    *a = 5;
    *b = 6;
    return *a + *b;
}

Possible output:

# generated code on 64bit Intel platform:
foo:
    movl    $5, (%rdi)    # store 5 in *a
    movl    $6, (%rsi)    # store 6 in *b
    movl    (%rdi), %eax  # read back from *a in case previous store modified it
    addl    $6, %eax      # add 6 to the value read from *a
    ret
 
rfoo:
    movl      $11, %eax   # the result is 11, a compile-time constant
    movl      $5, (%rdi)  # store 5 in *a
    movl      $6, (%rsi)  # store 6 in *b
    ret 


Reference:
     https://www.geeksforgeeks.org/restrict-keyword-c/
     https://en.cppreference.com/w/c/language/restrict

No comments:

Post a Comment