r/C_Programming • u/Future_Pace_5290 • Sep 02 '26
How to force compiler to fuse loops?
I'm writing an ML library in C.
My current plan is this.
Have a Linear layer , that does w.x + b
Have a separate activation layer(ReLU, GeLU, sigmoid, etc).
This is very modular and allows for custom activation functions.
However, this does 2 passes over memory(one loop for adding the bias, one loop for applying the activation function), whereas you could do it in a single loop(e.g y[i] = ReLU(y[i] + b[i]);)
Is there a way to make the compiler fuse the loops automatically?(My functions are all inline).
Without automatic fusion, I'd either have to use function pointers(which slows things down, also prevents inlining usually), make the entire function a macro(kind of ugly), or have one layer be y = w.x the other y=f(y + b) which is really weird.
The other option is merging the 2 into one(Linear_ReLU). I'd have to write multiple functions for the common activation functions, or make a macro that creates those activation functions.
All of these are unelegant compared to the first design.
3
u/yuehuang Sep 02 '26
LLVM support loop fusion, but like anything optimizer, it is hard to ensure consistency.
5
u/glasket_ Sep 03 '26
Depends on exactly how your code is structured. If the pointers are traceable and GCC knows (or is almost certain with speculative inlining) that the pointer is to a specific function it will still typically inline it. The only time it really becomes a problem is if the function pointer value can't be determined statically, if the pointer value comes from outside the TU (LTO can solve this one), or if the pointer may have any of several values (technically still possible to end up inlined, but it usually won't be due to the cost heuristics related to devirtualization and inlining).
2
u/jugglist Sep 03 '26
You should look at https://ispc.github.io/ instead of straight-C for this kind of thing.
Purpose-built to do a lot of math.
There's also C++ templates, which are honestly really good for this kind of substitute-a-kernel thing.
2
u/duane11583 Sep 03 '26
be careful inline things.
sometimes the compiler just vomits and gives up on the optimization…
sometimes its better to look at that key function and work on it.
1
u/[deleted] 18d ago
Just get LLVM support
1
u/DawnOnTheEdge Sep 03 '26
You may be able to use OpenMP loop-transformation constructs, such as
fuse.-1
u/dstroy0 Sep 03 '26
The alternative to loop fusion for this problem in gcc is SIMD (SIMD within a register) which is portable to all compilers natively, and is the most universal parallelizer.