Earlier quoted context omitted.
OP here. Thanks for the great description of loop hoisting of invariant code, and it's awesome to hear from the guy who wrote it. However, what I wrote was not wrong. strlen is not marked as pure or const on OS X, and yet it is hoisted. glibc does happen to mark strlen as pure in string.h, but the optimization occurs even if you do not include that header - even if there is no declaration for strlen in scope at all!…
"So this optimization really does proceed because strlen is a builtin function, and does not depend on strlen being marked as pure or const." No. It's exactly the other way around. We could not give a crap whether it is a built in function, only whether it is pure or const. We do not special case built-in functions anywhere near this optimization. ~/sources/gcc/gcc (git)-[master]- :) $ grep BUILT_IN tree-ssa-sccvn.c…
That's what I meant when I wrote that "the compiler recognizes strlen, and optimizes it specially." It was not my intent to say that only builtins or all builtins may be hoisted in this way, although now I see how someone could interpret that. That was bad wording on my part.
The point I was trying to communicate is that gcc can do special optimizations on functions that it recognizes as builtins - for example, replacing printf() with fputs(). One illustration is how strlen is treated as pure, even if it is not marked as pure. As someone with far more gcc expertise than me, would you agree with that point?
"Basically, the compiler defines a function named "strlen" that is pure and nothrow behind your back, but you can override it by providing your own definition. This is unrelated to whether it is a builtin"
Well, the optimization is defeated by -fno-builtin, so I assumed that the underlying mechanism is that a call to strlen is replaced by a call to the builtin. Was this wrong?