OpenCL built-in function 'select'

雨燕双飞 提交于 2019-12-23 15:05:59

问题


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.


回答1:


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



回答2:


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.




回答3:


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 ?:.



来源:https://stackoverflow.com/questions/7635706/opencl-built-in-function-select

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