5 ms·
Speaking as a professional compiler engineer, this is the biggest reason why signed overflow is treated as UB. It is incredibly useful to talk about a loop's t
by cokernel_hacker 10y ago
Speaking as a professional compiler engineer, this is the biggest reason why signed overflow is treated as UB.
It is incredibly useful to talk about a loop's trip count or the values an induction variable can have.
It turns out that taking advantage of signed overflow lets us do that in more places, a boon to all the programs which don't dynamically execute signed overflow.
The tradeoff, however, is that the programing model gets way more complicated. I have talked to the engineer who introduced this optimizing power to our compiler and he sorta regrets it.
IMO, we need better, higher level ways of talking about a loop's iteration space. Today, in C or C++, we are forced to represent the iteration space of a loop using the language's algebra. This is severely limiting when each operation on a signed type might introduce UB. With a higher level mechanism, we can separate the behavior that we want for loops from the behavior we want for everything else in a nice, clean way.
- pcwalton 10y ago> With a higher level mechanism, we can separate the behavior that we want for loops from the behavior we want for everything else in a nice, clean way. Yes! One decisive advantage that high-level iteration constructs have over for loops is that they're easier to optimize. One obvious example here is bounds checks: there's no need to have infrastructure to optimize out bounds checks over arrays during loops if you have a construct that eliminates the indexing entirely.
- btrask 10y agoGenuine question: what do you do when you want to implement your own loop mechanism, iterator, array type, or whatever?
- cokernel_hacker 10y agoIt is the job of the language to ensure that language primitives are reusable and composable. I think this would apply to whatever mechanism is designed to describe a loop's iteration space.
- Sean1708 10y agoMost languages use some sort of interface whereby if you implement certain methods for a type then that type can be iterated over using a for loop.