Usage of CPU intrinsics in SPM projects

Hi everyone :wave:

I have a Swift Package that, when available, is using Intel SSE 4.2 instructions to accelerate the calculation of CRC32C checksums.

The parts for this are implemented in C using the Intel intrinsics in Clang.

Currently, clang requires the -msse4.2 flag to be passed as a compile option.

Is there a way in Swift Package Manager to pass the -msse4.2 flag as a compile option that doesn't involve unsafeFlags?

If not any suggestions other than restoring to inline assembly to use architecture-specific instructions.

Would it be worth considering to add support for intrinsics for ARM and Intel as "safe" compile options in Swift Package manager?

Instead of passing -msse4.2 (which is really too coarse-grained in general), put __attribute__((target("sse4.2"))) on your intel_crc function.

We still need a good solution for this problem in Swift code, but for C code target attributes are really a better option anyway and don't require an unsafe flag.

2 Likes

@scanon Thank you, I didn't consider annotating the function, which in hindsight is very obvious :flushed:

I think it's not currently possible to use Intel Intrinsic functions from Swift directly (maybe I am wrong).

A few weeks ago I've tried using _mm_crc32_u8 directly from Swift and it resulted in a compiler crash. (See Compiler crash when using intel intrinsics).

Thanks a lot,
Thomas

1 Like

It is possible, but the frontend isn't well set-up to deal with it yet, so it'll crash instead of issuing a diagnostic that you need to pass -msse4.2 (and passing that flag is a pain in Swift):

-Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +sse4.2

Needless to say, this is not a good option. What you have is good for now, and we should provide something like function attributes in Swift in the future.

1 Like

@scanon Good to know! I wasn't aware of that it needs to be passed as a +sse4.2 to the compiler :smile:.

Thank you.