This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
enforcing expression evaluation order
- To: egcs at egcs dot cygnus dot com
- Subject: enforcing expression evaluation order
- From: Per Bothner <bothner at cygnus dot com>
- Date: Tue, 02 Feb 1999 15:09:30 -0800
The topic of evaluation order in expressions has come up before.
Now I need advice on how best to enforce strict left-to-right
evaluation order for Java arithmetic.
Consider:
int x = 1; int y = x + ++x;
The Java Language Specification requires that y gets the value 3.
However, gcc will typically give it the value 4. This is because
calling expand_expr on the left operand `x' will just return the
rtx for the localation of x, then x is incremented. The addition
is done using the rtx we got for the first overand, which
refers to *location* of x, and so we use the updated value 2.
Changing the semantics of PLUS_EXPR etc to be strict is not an option,
nor is adding a new set of opcodes (such as STRICT_PLUS_EXPR);
either would require too many changes. One option is to call
save_expr on the operands to PLUS_EXPR. This should give the
correct semantics, but it seems at great cost. For example, I
don't think fold will do a good job on an expression full
of SAVE_EXPRs - though maybe that is not an issue, since
constants will not get wrapped in SAVE_EXPR anyway. But
I don't know Still, I can probably come up with something so
we only add SAVE_EXPRs if side effects are involved.
But I do wonder: How robust would such an approach be? If
the specification for PLUS_EXPR does not specify evaluation
order, then we risk expand_expr evaluating the operands in the
wrong order anyway. Perhaps the only robust solution is using
temporaries. I.e. replace (X + Y) by (int TMP = X; TMP + Y).
However, this seems even more expensive. When compiling without -O,
we might get a ton of useless temporary variables. Still, if
we use temporary variables only when side effects are involved,
it should not make much difference.
Any advice? Does anyone have a experience with a front-end
that requires strict evaluation order?
--Per Bothner
Cygnus Solutions bothner@cygnus.com http://www.cygnus.com/~bothner