Null references redux

Rainer Deyke rainerd at eldwood.com
Sun Sep 27 11:50:48 PDT 2009


Walter Bright wrote:
>>   void bar(bool foo) {
>>     int a = void;
>>     if (foo) {
>>       a = 1;
>>     } else {
>>       a = 2; // Reuse variable.
>>     }
>>     int c = 3;
>>   }
>>
>> You now only have two variables, but both of them coexist at the end of
>> the function.  Unless the compiler applies a clever optimization, the
>> compiler is now forced to allocate space for two variables on the stack.
> 
> Not necessarily. The optimizer uses a technique called "live range
> analysis" to determine if two variables have non-overlapping ranges. It
> uses this for register assignment, but it could just as well be used for
> minimizing stack usage.

That's the optimization I was referring to.  It works for ints, but not
for RAII types.  It also doesn't (necessarily) work if you reorder the
function:

   void bar(bool foo) {
     int a = void;
     int c = 3;
     if (foo) {
       a = 1;
     } else {
       a = 2; // Reuse variable.
     }
   }

Of course, a good optimizer can still reorder the declarations in this
case, or even eliminate the whole function body (since it doesn't do
anything).


-- 
Rainer Deyke - rainerd at eldwood.com



More information about the Digitalmars-d mailing list