
On Tue, Dec 9, 2008 at 1:23 PM, Thorsten Ottosen <thorsten.ottosen@dezide.com> wrote:
Kim Barrett skrev:
At 2:23 PM +0100 12/6/08, Robert Kawulak wrote:
... maybe the problem could be somehow solved if we have a function float exact(float) that, given a floating point value (that may have greater precision because of caching in a register), returns a value that is truncated (has exactly the precision of float, not greater).
I think that something along the lines of the following will likely work:
inline double exact(double x) { struct { volatile double x; } xx = { x }; return xx.x; }
Please no. Not only it might prevent other optimizations, but is also completely thread unsafe.
The idea is to force the value to make a round trip through a memory location of the "correct" size. The use of volatile should prevent the compiler from optimizing away the trip through memory.
If worried about whether a compiler will really do what's needed here, then I think the only other option is inline assembler to produce the equivalent behavior. Looking through the x86 instruction set, I don't see any other way to cause the desired rounding.
For some ABIs I think using class instead of struct will have the desired effect of passing the value on the stack. So maybe something like
AFAIK usually is the presence of a constructor that is the discriminant between passing by via stack or via register, not the struct/class keyword itself...
template< class T > class rounder { ... };
template< class T > inline T exact( rounder<T> r ) { return r.val(); }
... and if the call itself is inlined, I doubt that the object is actually forced to the stack. -- gpd