chris@mimsy.UUCP (Chris Torek) (11/29/87)
In article <10572@brl-adm.ARPA> I1090801%DBSTU1.BITNET@CUNYVM.CUNY.EDU writes: >I think there is a good reason for a C-compiler to allocate >space for all local variables at the beginning of a function. I agree, but not for the first reason you give: >int f() >{ > if (...) > { int a; > ... > goto label2; > label1: ... /* do someting with a */ > } > else > { int b; > ... > goto label1; > label2: ... /* do something with b */ > } >} >In this case it is not possible to allocate the same space >for the variables a and b. Not so. Indeed, a and b are likely to use the exact same slot in this example, which would mean no stack manipulation would be required after all. >If you allocate space for a at the start of the then-block there >is no space allocated for variable b after you do the jump into >the else-part (at least not until the compiler does some very >tricky code generation). It is not even particularly tricky: All the compiler need do is this: For each jump out of a block, generate the `exit block' code just before the jump; for each label within a block, generate the `enter block' code, with a branch around it to keep linear execution from re-running the enter-block code. The `goto label2' becomes add #4,sp jmp Llabel2 while label2 looks like this: jmp L27 Llabel2: sub #4,sp L27: (The tricky part comes in where the code generator/optimiser figures out that the `sub' balances the `add' and deletes both of them.) Remember also that there is no requirement that the compiler use the stack; a and b might be in registers. They might even be dynamically allocated on a heap! (But I would hope not.) > Another reason for allocating space at the beginning of >a function is the gain in code-space and runtime (but perhaps >with a loss of data-space, which may only become a problem in >recursive calls). Agreed. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris