4 ms·
You can easily write a for loop that optimizes to memset without relying on undefined behavior. The only potential problem is that the loop bound evaluation cou
by cwzwarich 11y ago
You can easily write a for loop that optimizes to memset without relying on undefined behavior. The only potential problem is that the loop bound evaluation could require a memory access, but this is simple to work around.
- pcwalton 11y agoWell, not if the compiler can't prove that the stores don't alias the induction variable. TBAA is the easiest and most reliable way to prove that, which is UB exploitation.
- cwzwarich 11y agoNo, that is not the most reliable way to prove that property. The most reliable way is to ensure that the loop bound and induction variable are local variables that have not had their address taken.
- pcwalton 11y agoWell, yes, in the trivial case, but not if the induction variable and/or loop bound come in as references (as in templated code, etc). There's also the issue of the store changing the array base, as in Chris Lattner's example on "What Every C Programmer Should Know".
- cwzwarich 11y agoYou can always make the induction variable and loop bound local variables, and the induction variable is almost always a local variable anyways. It was the WebKit coding style for years to use local variables for loop bounds for this reason. This is the example you're talking about in "What Every C Programmer Should Know": float *P; void zero_array() { int i; for (i = 0; i < 10000; ++i) P[i] = 0.0f; } If you make the global variable static, then it gets converted to a memset with -fno-strict-aliasing, because the 'P' variable never has its address taken. If you used LTO with sufficient linkage information, the same thing would happen. Similarly, if you pass the array as an argument then the loop gets converted to a bzero call just fine without -fno-strict-aliasing: float *P; void zero_array_impl(float* a) { int i; for (i = 0; i < 10000; ++i) a[i] = 0.0f; } void zero_array() { zero_array_impl(P); } I don't think this is a very good example for these reasons.