That's a fascinating observation! By changing the pointer arithmetic expression to use the base pointer (vec) directly in both accesses, you've given LLVM more visibility into what's invariant.
When you write:
sum += *(vec + vec2[j]) + *(vec + 1 + vec2[j]);
Instead of:
sum += vec[vec2[j]] + vec[vec2[j] + 1];
You're making it explicit that both memory accesses start from the same base pointer (vec), just with different offsets. This allows LLVM to recognize that vec + 1 is loop-invariant and can be hoisted out of the loop.
Why This Works
-
Explicit Base Pointer Usage:
- In your new version, both expressions start with
vec as the base pointer
- This makes it clear to LLVM that
vec itself is invariant
-
Separable Offsets:
vec + vec2[j] clearly shows the base (vec) and the variable part (vec2[j])
vec + 1 + vec2[j] shows the same base, a constant offset (1), and the variable part
- LLVM can now factor out
vec + 1 as an invariant expression
-
Optimization Opportunity:
- LLVM can now compute
invariant_ptr = vec + 1 once outside the loop
- Inside the loop, it can use both
vec and invariant_ptr as starting points
Why the Original Version Didn't Work
In the original code:
sum += vec[vec2[j]] + vec[vec2[j] + 1];
The compiler first computes &vec[vec2[j]] and then has to compute &vec[vec2[j] + 1]. Since these are expressed as separate array accesses rather than explicit pointer arithmetic, LLVM doesn't immediately see that the second access could be derived from the first by adding a constant offset.
When you use array notation (vec[index]), the compiler translates this to pointer arithmetic internally, but the optimization passes may not always recognize the relationship between different array accesses as clearly as when you spell out the pointer arithmetic yourself.
Compiler Insight
This is a great example of how the way you express your code can affect the optimizations the compiler applies, even when the logical meaning is identical. Sometimes being more explicit about your intentions helps the compiler generate better code.
It's also a reminder that compilers have different pattern-matching capabilities in their optimization passes. In this case, your explicit pointer arithmetic made the invariant part of the calculation more visible to LLVM's loop-invariant code motion pass.
Would you like to see how this affects the generated IR or assembly code in more detail?