Skip to content

Instantly share code, notes, and snippets.

@NocturnDragon
Last active October 15, 2023 01:20
Show Gist options
  • Save NocturnDragon/ea699328cd5c73d5cfdb49e54395598c to your computer and use it in GitHub Desktop.
Save NocturnDragon/ea699328cd5c73d5cfdb49e54395598c to your computer and use it in GitHub Desktop.
Swizzles in Clang, GCC, and Visual c++
#include <stdio.h>
// #define CLANG_EXTENSION
// Clang compile with -O3
#define VS_EXTENSION
// https://godbolt.org/z/sVWrF4
// Clang compile with -O3 -fms-compatibility
// VS2017 compile with /O3
#if defined(CLANG_EXTENSION)
typedef float float2 __attribute__((ext_vector_type(2)));
#elif defined(VS_EXTENSION)
struct float2
{
float x, y;
// xy
__declspec(property(get = get_xy, put = put_xy)) float2 xy;
inline float2 get_xy() const { return {x, y}; }
inline void put_xy(float2 v){ *this = v.xy; }
// yx
__declspec(property(get = get_yx, put = put_yx)) float2 yx;
inline float2 get_yx() const { return {y, x}; }
inline void put_yx(float2 v){ *this = v.yx; }
};
#else
#error
#endif
int main()
{
float2 v1{1.0f, 2.0f};
float2 v2 = v1.xy;
printf("v = {x:%f, y:%f, }\n", v2.x, v2.y);
v2.yx = v1.xy;
printf("v = {x:%f, y:%f, }\n", v2.x, v2.y);
return 0;
}
/*
GENERATED ASSEMBLY FOR BOTH VERSIONS IN CLANG 3.9.0 -O3
.LCPI0_0:
.quad 4607182418800017408 # double 1
.LCPI0_1:
.quad 4611686018427387904 # double 2
main: # @main
push rax
movsd xmm0, qword ptr [rip + .LCPI0_0] # xmm0 = mem[0],zero
movsd xmm1, qword ptr [rip + .LCPI0_1] # xmm1 = mem[0],zero
mov edi, .L.str
mov al, 2
call printf
mov edi, .L.str
mov al, 2
movsd xmm0, qword ptr [rip + .LCPI0_1] # xmm0 = mem[0],zero
movsd xmm1, qword ptr [rip + .LCPI0_0] # xmm1 = mem[0],zero
call printf
xor eax, eax
pop rcx
ret
.L.str:
.asciz "v = {x:%f, y:%f, }\n"
*/
@lukakostic
Copy link

What about .xx or .yy ? Is there a way to automatically generate all combinations? In shader coding you can do .rgb or .rrr or any combination of 'r' 'g' 'b' 'a' or 'x' 'y' 'z' 'w' to swizzle any vector like type (or color)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment