The Restrict Keyword in C

My first patch is straightforward, simply adding function prototypes and defining a macro in the sys/signal.h header file in newlib/libc. If you are not familiar with Newlib, it is an open-source standard C library for use in embedded systems. Please see my colleague’s blog here for a great rundown on what Newlib is and how to build it.

For my patch, I took the function signatures straight from the new draft POSIX Standard which included a keyword I had never encountered: Restrict. The function signature was as follows:

int str2sig(const char *restrict, int *restrict);

Let’s look at the meaning of the Restrict keyword here.

Restrict has been a part of the standard since C99. It is used to signal to the compiler that a pointer reference can be optimized because the object to which it refers is only accessed in the function through that pointer. (p. 26, Stevens and Rago, Advanced Programming in the Unix Environment, 3rd Ed). What does this mean and why would we want it?

Let’s look at an excellent example and analysis from Markus Fasselt from the University of Hamburg. Suppose we have two functions (update and update_restrict) and a simple main function.

The results are the same. To see the real difference, let’s look at the assembly code for the two update functions generated from compiling “gcc -Wall -std=c99 update.c -O1 -S”, slightly simplified:

The second function has three main assembly instructions instead of four. The use of the Restrict keyword optimizes away the repeat loading of the contents of rdx into eax. This is done because Restrict assures the compiler that there will be no other variable pointing to that address in the function, potentially changing its value. Thus, it goes straight to adding the value that is still in eax to the value that is in rsi. Testing this difference on a very large n, Fasselt demonstrates a speed improvement of almost 3 times for the optimized assembly code using Restrict.

It is important to note that this potential performance enhancement must be used with caution. If a programmer illegally references the restricted pointer from elsewhere, unexpected behavior can ensue. Some go so far as to suggest that it is too risky to use at all, though this argument seems to ignore the real benefits it can bring when used properly. Please see the following discussion for many more examples of illegal (and the corresponding legal) uses of the Restrict keyword.