a question about const and pure functions.
Roger Sayle
roger@eyesopen.com
Thu Nov 11 17:45:00 GMT 2004
On Thu, 11 Nov 2004, Geert Bosch wrote:
> I find the definition in the Ada standard (ISO/IEC 8652:1995)
> very useful in practice.
> ...
> _Implementation Permissions_
>
> 18. If a library unit is declared pure, then the implementation is
> permitted to omit a call on a library-level subprogram of the
> library unit if the results are not needed after the call...
> This permission applies even if the subprogram
> produces other side effects when called.
The critical distinction is between whether the attributes of a function
are determined by the compiler, or are asserted by the programmer. GCC
already makes use of Ada's implementation permission #18 above.
Consider:
int foo() __attribute__(const)
{
printf("Hello world!\n");
global++;
return 0;
}
here the programmer is *declaring* (note the wording in the Ada standard)
that this function may be considered const, and therefore optimized away
if the return value is not used, or CSE'd blah, blah, blah! Of course,
Ada's implementation permission #18, doesn't apply if the definition of
foo isn't explicitly *declared* foo. Instead the remaining implementation
permissions described what constitutes a "safe code transformation" based
upon observable behaviour.
The other implementation permissions allow that calls to
int foo()
{
return 0;
}
may be eliminated if the result isn't used, but for example prohibit
the compiler eliminating calls to
int foo()
{
printf("hello world!\n");
return 0;
}
where foo has not been explicitly declared "pure". Hence pragmatically
Ada's notion of pure is actually derived from the aspects of the remaining
implementation permissions that allow a function to be eliminated under
the same conditions as being explicitly declared "pure".
Note it is the distinction between "declared" behaviour and "actual"
behaviour that allows us to optimize away calls to "sqrt" with -ffast-math
even though sqrt(-1.0) has observable side-effects. Some language
front-ends are required to check whether the "const" and/or "pure"
attribute are actually honored by the code, others don't. In GCC's
middle-end, however, these definitions are honored as always "true".
Roger
--
More information about the Gcc
mailing list