[comp.lang.misc] Query re optimising hcrs

jim@hcr.UUCP (Jim Sullivan) (07/28/88)

In article <24414@think.UUCP> barmar@kulla.think.com.UUCP (Barry Margolin) writes:
>
>This should not be confused with the common optimization where boolean
>expressions are short-circuited even when non-short-circuit operators
>are used.  This can be done when the expressions don't have
>side-effects (just like above).  However, since boolean expressions
>only have two possible values, true and false, it is quite common for
>hcr implementors to assume that each value will occur a
>significant fraction of the time.  Under this assumption, the
>transformation of
>
>     if <complex-expr> & <simple-expr>
>     then <result>
>
>into
>
>     if <simple-expr>
>     then if <complex-expr>
>	  then <result>
>
>is reasonable.
>

Actually, it isn't.  Only if the order that logical expressions is calculated
is undefined is this optimization reasonable.  Otherwise, you must follow the
defined order.  C is like this.  If I have a logical expression, the expression
is evaluated left to right, and the evaluation stops when the answer to the
expression is known.  For example,

	if( a && b ) 

is true only when a and b are true, so if a is false, then the expression is
false.  This protects me from many bad things, like:

	if( (p != NULL) && (*p == VALUE) )

where I check that the pointer is good and then check the value.  Reorganize
this and all hell will break loose.

Jim Sullivan

barmar@think.COM (Barry Margolin) (07/30/88)

In article <3678@hcr.UUCP> jim@hcr.UUCP (Jim Sullivan) writes:
]In article <24414@think.UUCP> barmar@kulla.think.com.UUCP (Barry Margolin) writes:
]>Under this assumption, the transformation of
]>     if <complex-expr> & <simple-expr>
]>     then <result>
]>into
]>     if <simple-expr>
]>     then if <complex-expr>
]>	  then <result>
]>is reasonable.
]Actually, it isn't....  For example,
]	if( a && b ) 

That is why MY example used "&", not "&&".  We should all know that
when the language semantics specify a particular order of evaluation
it is not reasonable for an optimizing compiler to change it.  The
discussion presupposed certain optimizations that are valid, and the
question was whether they are reasonable.


Barry Margolin
Thinking Machines Corp.

barmar@think.com
{uunet,harvard}!think!barmar

smryan@garth.UUCP (Steven Ryan) (07/31/88)

>                     Only if the order that logical expressions is calculated
>is undefined is this optimization reasonable.

That is why it is better to leave the order of evaluation undefined.
 
>	if( (p != NULL) && (*p == VALUE) )
>
>where I check that the pointer is good and then check the value.  Reorganize
>this and all hell will break loose.

C, Algol60, and Algol68 provide an alternate construct which safe, explicit,
and lets the operators be just operators:

         if ( p==nil ? false : *p==value )