How to set the right alignment for an OpenCL array of structs?

拥有回忆 提交于 2019-12-21 20:55:26

问题


I have the following structure:

C++:

struct ss{
    cl_float3 pos;
    cl_float value;
    cl_bool moved;
    cl_bool nextMoved;
    cl_int movePriority;
    cl_int nextMovePriority;
    cl_float value2;
    cl_float value3;
    cl_int neighbors[6];
    cl_float3 offsets[6];
    cl_float off1[6];
    cl_float off2[6];
};

OpenCL:

typedef struct{
    float3 nextPos;
    float value;
    bool moved;
    bool nextMoved;
    int movePriority;
    int nextMovePriority;
    float value2;
    float value3;
    int neighbors[6];
    float3 offsets[6];
    float off1[6];
    float off2[6];
} ss;

I have an array of these, and I pass them to an opencl Buffer, but when I operate with them in a kernel, the data gets corrupted.

I believe this is because of the alignment, I have read other posts about it

I need help understanding data alignment in OpenCL's buffers

Aligning for Memory Accesses in OpenCL/CUDA

But still, I don't fully get the idea of how to properly set the alignment to my struct. Also, I dont fully understand the attribute aligned and packed qualifiers.

So:

Q1. Could you show me how to align my struct to work properly?

Q2. Could you explain me or give me some link to understand all the alignment problem and the qualifiers?

Thanx.


回答1:


I recommend declaring your structure from the widest types first down to the narrowest types. First, this avoids wasted unused spaces due to alignment. Second, this often avoids any headaches with different alignments on different devices.

So,

struct ss{
    cl_float3 pos;
    cl_float3 offsets[6];
    cl_float value;
    cl_float value2;
    cl_float value3;
    cl_float off1[6];
    cl_float off2[6];
    cl_int movePriority;
    cl_int nextMovePriority;
    cl_int neighbors[6];
    cl_bool moved;
    cl_bool nextMoved;
};

Also, beware of the float3 type; it is often a float4 on the GPU and if the host-side layout doesn't also do that, then your alignment will be off. You could switch to float4 to avoid this.



来源:https://stackoverflow.com/questions/17361274/how-to-set-the-right-alignment-for-an-opencl-array-of-structs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!