开发者

OpenCL built-in function 'select'

It's not clear for me what is a purpose of built-in OpenCL function select. Can somebody, please, clarify?

开发者_开发知识库

From OpenCL specification:

function select(gentype a, gentype b, igentype c)

returns: for each component of a vector type, result[i] = if MSB of c[i] is set ? b[i] : a[i].

What is a MSB in this case? I know that MSB stands for most significant bit, but I have no idea how it's related to this case.


OpenCL select is to select elements from a pair of vectors (a, b), based on the truth value of a condition vector (c), returning a new vector composed of elements from the vectors a and b.

The MSB (most significant bit) is mentioned here, because the truth value of a vector element is defined to be -1 and the MSB should therefore be set (as the sign bit):

a = {1 , 2}  // Pseudocode for select operands
b = {3 , 4}
c = {0 ,-1}
r = {1 , 4}  // The result r contains some of a and b


This is a very useful operator which does the same job as what a conditional expression does in C. However, conditional expression often compiles to a conditional branch which cause warp/wavefront divergence. The 'select' usually generates a predicated expression - kind of like CMOV on x86 or blend_ps in SSE.


I have found 2 basic patterns of using select: scalar case and vector case. Scalar case is pretty straightforward:

if (a > 0.0f) b = 0.3f;

is equivalent to

b = select(b, 0.3f, isgreater(a, 0.0f));

If wanted to deal with vectors, i.e. obtain a vector result from select everything became a bit more complicated:

if (a > 0.0f) b = (float2)(0.3f, 0.4f);

is equivalent to

b = select(b, (float2)(0.3f, 0.4f), (int2)(isgreater(a, 0.0f) << 31));

That bit-wise shift needed to make LSB result of comparison operator to be MSB to conform select specification. Casting to int2 ensures that all components will take their positions in result.

Concluding remark is that using snippets above helps more to understand usage of select rather then thinking of equivalence with C ternary operator ?:.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜