How to declare the memory space for pointers stored in an extern __shared__ array?

If you declare an array of pointers, eg.

float * myArray[10];

there are 3 memory spaces in play:

  1. the memory containing the address of that myArray array. For this question we don’t care about this one.
  2. the memory containing the 10 pointers in the array, i.e. the memory that the myArray pointer value points at.
  3. the memory that myArray[0] points at.

Normally in C++, you do something like this:

volatile float *const myArray[10];

or

float volatile *const myArray[10];

In this example the const keyword is for the array (2) and the volatile keyword is for the floats (3).

So, now we want to store an array of pointers in CUDA shared memory. Those pointers each point somewhere else, let’s say, in device memory.

Analogous to the above that declaration would look like this:

extern __device__ float *__shared__ myArray[10];

except, this doesn’t work, and contra the usual spiral rule in C++, the line below declares an array that lives in shared memory.

extern __shared__ float * myArray[10];

This means those 10 pointers always point to generic memory and there is no way to declare pointers to a different memory space here. Is there a syntax to specify that those 10 pointers point to eg. device memory space?

One can use Address Space Predicate Functions 5.4. C/C++ Language Extensions — CUDA Programming Guide to tell the compiler that a pointer points to a specific memory type.

__shared__ float* myArray[10];
__builtin_assume(__isGlobal(myArray[0]));
__builtin_assume(__isGlobal(myArray[1]));
...
__builtin_assume(__isGlobal(myArray[9]));

Alternatively, you could use a cuda::annotated_ptr instead of a raw pointer. cuda::annotated_ptr — CUDA Core Compute Libraries

__shared__ cuda::annotated_ptr<int, cuda::access_property::global> myArray[10];

Side note: it is not valid to specify array bounds when using extern shared memory.

Thanks. I guess the values in the array would still be generic addresses right?

(and yes our actual declaration has unspecified bounds)