Suppose we have linked list and code like this:
void play_with_list(struct int_list *list) {
while (list != NULL) {
__builtin_prefetch(list->next);
do_something(list->n);
list = list->next;
}
}
On the last iteration, __builtin_prefetch will be called with nullptr, because list->next is nullptr.
Is that safe?
Second part of the question - suppose list data is pointer to C string (char *) allocated on the heap. Will it be beneficial if I prefetch it too?
As @RichardCritten wrote in the comment above - by definition, it will not generate a fault. That much is guaranteed by the ISA. However, that doesn't meant it's entirely safe: there was a known performance penalty on Intel CPUs for prefetching address 0.
Intl optimization guide itself states:
Prefetching to addresses that are not mapped to physical pages can experience non-deterministic performance penalty. For example specifying a NULL pointer (0L) as address for a prefetch can cause long delays.
(taken from here, chapter 9.3)
However, you are probably a little bit safer as of Skylake since at least some of the penalty was fixed. Section 2.6.3 states that one of the changes there was:
Reduced performance penalty for a software prefetch that specifies a NULL pointer.