]> git.sur5r.net Git - cc65/blob - src/cc65/locals.c
Renamed the functions working with "struct Function".
[cc65] / src / cc65 / locals.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 locals.c                                  */
4 /*                                                                           */
5 /*              Local variable handling for the cc65 C compiler              */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2002 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 /* common */
37 #include "xmalloc.h"
38 #include "xsprintf.h"
39
40 /* cc65 */
41 #include "anonname.h"
42 #include "asmlabel.h"
43 #include "codegen.h"
44 #include "declare.h"
45 #include "error.h"
46 #include "expr.h"
47 #include "function.h"
48 #include "global.h"
49 #include "symtab.h"
50 #include "locals.h"
51
52
53
54 /*****************************************************************************/
55 /*                                   Data                                    */
56 /*****************************************************************************/
57
58
59
60 /* Register variable management */
61 unsigned MaxRegSpace            = 6;    /* Maximum space available */
62 static unsigned RegOffs         = 0;    /* Offset into register space */
63 static const SymEntry** RegSyms = 0;    /* The register variables */
64 static unsigned RegSymCount     = 0;    /* Number of register variables */
65
66
67
68 /*****************************************************************************/
69 /*                                   Code                                    */
70 /*****************************************************************************/
71
72
73
74 void InitRegVars (void)
75 /* Initialize register variable control data */
76 {
77     /* If the register space is zero, bail out */
78     if (MaxRegSpace == 0) {
79         return;
80     }
81
82     /* The maximum number of register variables is equal to the register
83      * variable space available. So allocate one pointer per byte. This
84      * will usually waste some space but we don't need to dynamically
85      * grow the array.
86      */
87     RegSyms = (const SymEntry**) xmalloc (MaxRegSpace * sizeof (RegSyms[0]));
88     RegOffs = MaxRegSpace;
89 }
90
91
92
93 void DoneRegVars (void)
94 /* Free the register variables */
95 {
96     xfree (RegSyms);
97     RegSyms = 0;
98     RegOffs = MaxRegSpace;
99     RegSymCount = 0;
100 }
101
102
103
104 static int AllocRegVar (const SymEntry* Sym, const type* tarray)
105 /* Allocate a register variable with the given amount of storage. If the
106  * allocation was successful, return the offset of the register variable in
107  * the register bank (zero page storage). If there is no register space left,
108  * return -1.
109  */
110 {
111     /* Maybe register variables are disabled... */
112     if (EnableRegVars) {
113
114         /* Get the size of the variable */
115         unsigned Size = CheckedSizeOf (tarray);
116
117         /* Do we have space left? */
118         if (RegOffs >= Size) {
119
120             /* Space left. We allocate the variables from high to low addresses,
121              * so the adressing is compatible with the saved values on stack.
122              * This allows shorter code when saving/restoring the variables.
123              */
124             RegOffs -= Size;
125             RegSyms [RegSymCount++] = Sym;
126             return RegOffs;
127         }
128     }
129
130     /* No space left or no allocation */
131     return -1;
132 }
133
134
135
136 static void ParseOneDecl (const DeclSpec* Spec)
137 /* Parse one variable declaration */
138 {
139     int         Size;           /* Size of an auto variable */
140     int         SC;             /* Storage class for symbol */
141     int         SymData = 0;    /* Symbol data (offset, label name, ...) */
142     unsigned    flags = 0;      /* Code generator flags */
143     Declaration Decl;           /* Declaration data structure */
144
145     /* Remember the storage class for the new symbol */
146     SC = Spec->StorageClass;
147
148     /* Read the declaration */
149     ParseDecl (Spec, &Decl, DM_NEED_IDENT);
150
151     /* Set the correct storage class for functions */
152     if (IsTypeFunc (Decl.Type)) {
153         /* Function prototypes are always external */
154         if ((SC & SC_EXTERN) == 0) {
155             Warning ("Function must be extern");
156         }
157         SC |= SC_FUNC | SC_EXTERN;
158
159     }
160
161     /* If we don't have a name, this was flagged as an error earlier.
162      * To avoid problems later, use an anonymous name here.
163      */
164     if (Decl.Ident[0] == '\0') {
165         AnonName (Decl.Ident, "param");
166     }
167
168     /* Handle anything that needs storage (no functions, no typdefs) */
169     if ((SC & SC_FUNC) != SC_FUNC && (SC & SC_TYPEDEF) != SC_TYPEDEF) {
170
171         /* Get the size of the variable */
172         Size = SizeOf (Decl.Type);
173
174         /* */
175         if (SC & (SC_AUTO | SC_REGISTER)) {
176
177             /* Auto variable */
178             if (StaticLocals == 0) {
179
180                 /* Change SC in case it was register */
181                 SC = (SC & ~SC_REGISTER) | SC_AUTO;
182                 if (CurTok.Tok == TOK_ASSIGN) {
183
184                     ExprDesc lval;
185
186                     /* Allocate previously reserved local space */
187                     F_AllocLocalSpace (CurrentFunc);
188
189                     /* Skip the '=' */
190                     NextToken ();
191
192                     /* Setup the type flags for the assignment */
193                     flags = Size == 1? CF_FORCECHAR : CF_NONE;
194
195                     /* Get the expression into the primary */
196                     if (evalexpr (flags, hie1, &lval) == 0) {
197                         /* Constant expression. Adjust the types */
198                         assignadjust (Decl.Type, &lval);
199                         flags |= CF_CONST;
200                     } else {
201                         /* Expression is not constant and in the primary */
202                         assignadjust (Decl.Type, &lval);
203                     }
204
205                     /* Push the value */
206                     g_push (flags | TypeOf (Decl.Type), lval.ConstVal);
207
208                     /* Mark the variable as referenced */
209                     SC |= SC_REF;
210
211                     /* Variable is located at the current SP */
212                     SymData = oursp;
213
214                 } else {
215                     /* Non-initialized local variable. Just keep track of
216                      * the space needed.
217                      */
218                     SymData = F_ReserveLocalSpace (CurrentFunc, Size);
219                 }
220
221             } else {
222
223                 /* Static local variables. */
224                 SC = (SC & ~(SC_REGISTER | SC_AUTO)) | SC_STATIC;
225
226                 /* Put them into the BSS */
227                 g_usebss ();
228
229                 /* Define the variable label */
230                 SymData = GetLocalLabel ();
231                 g_defdatalabel (SymData);
232
233                 /* Reserve space for the data */
234                 g_res (Size);
235
236                 /* Allow assignments */
237                 if (CurTok.Tok == TOK_ASSIGN) {
238
239                     ExprDesc lval;
240
241                     /* Skip the '=' */
242                     NextToken ();
243
244                     /* Setup the type flags for the assignment */
245                     flags = Size == 1? CF_FORCECHAR : CF_NONE;
246
247                     /* Get the expression into the primary */
248                     if (evalexpr (flags, hie1, &lval) == 0) {
249                         /* Constant expression. Adjust the types */
250                         assignadjust (Decl.Type, &lval);
251                         flags |= CF_CONST;
252                         /* Load it into the primary */
253                         exprhs (flags, 0, &lval);
254                     } else {
255                         /* Expression is not constant and in the primary */
256                         assignadjust (Decl.Type, &lval);
257                     }
258
259                     /* Store the value into the variable */
260                     g_putstatic (flags | TypeOf (Decl.Type), SymData, 0);
261
262                     /* Mark the variable as referenced */
263                     SC |= SC_REF;
264                 }
265             }
266
267         } else if ((SC & SC_STATIC) == SC_STATIC) {
268
269             /* Static data */
270             if (CurTok.Tok == TOK_ASSIGN) {
271
272                 /* Initialization ahead, switch to data segment */
273                 if (IsQualConst (Decl.Type)) {
274                     g_userodata ();
275                 } else {
276                     g_usedata ();
277                 }
278
279                 /* Define the variable label */
280                 SymData = GetLocalLabel ();
281                 g_defdatalabel (SymData);
282
283                 /* Skip the '=' */
284                 NextToken ();
285
286                 /* Allow initialization of static vars */
287                 ParseInit (Decl.Type);
288
289                 /* If the previous size has been unknown, it must be known now */
290                 if (Size == 0) {
291                     Size = SizeOf (Decl.Type);
292                 }
293
294                 /* Mark the variable as referenced */
295                 SC |= SC_REF;
296
297             } else {
298
299                 /* Uninitialized data, use BSS segment */
300                 g_usebss ();
301
302                 /* Define the variable label */
303                 SymData = GetLocalLabel ();
304                 g_defdatalabel (SymData);
305
306                 /* Reserve space for the data */
307                 g_res (Size);
308
309             }
310         }
311
312         /* Cannot allocate a variable of zero size */
313         if (Size == 0) {
314             Error ("Variable `%s' has unknown size", Decl.Ident);
315             return;
316         }
317     }
318
319     /* If the symbol is not marked as external, it will be defined */
320     if ((SC & SC_EXTERN) == 0) {
321         SC |= SC_DEF;
322     }
323
324     /* Add the symbol to the symbol table */
325     AddLocalSym (Decl.Ident, Decl.Type, SC, SymData);
326 }
327
328
329
330 void DeclareLocals (void)
331 /* Declare local variables and types. */
332 {
333     /* Remember the current stack pointer */
334     int InitialStack = oursp;
335
336     /* Loop until we don't find any more variables */
337     while (1) {
338
339         /* Check variable declarations. We need to distinguish between a
340          * default int type and the end of variable declarations. So we
341          * will do the following: If there is no explicit storage class
342          * specifier *and* no explicit type given, it is assume that we
343          * have reached the end of declarations.
344          */
345         DeclSpec Spec;
346         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
347         if ((Spec.Flags & DS_DEF_STORAGE) != 0 && (Spec.Flags & DS_DEF_TYPE) != 0) {
348             break;
349         }
350
351         /* Accept type only declarations */
352         if (CurTok.Tok == TOK_SEMI) {
353             /* Type declaration only */
354             CheckEmptyDecl (&Spec);
355             NextToken ();
356             continue;
357         }
358
359         /* Parse a comma separated variable list */
360         while (1) {
361
362             /* Parse one declaration */
363             ParseOneDecl (&Spec);
364
365             /* Check if there is more */
366             if (CurTok.Tok == TOK_COMMA) {
367                 /* More to come */
368                 NextToken ();
369             } else {
370                 /* Done */
371                 break;
372             }
373         }
374
375         /* A semicolon must follow */
376         ConsumeSemi ();
377     }
378
379     /* Be sure to allocate any reserved space for locals */
380     F_AllocLocalSpace (CurrentFunc);
381
382     /* In case we've allocated local variables in this block, emit a call to
383      * the stack checking routine if stack checks are enabled.
384      */
385     if (CheckStack && InitialStack != oursp) {
386         g_cstackcheck ();
387     }
388 }
389
390
391
392 void RestoreRegVars (int HaveResult)
393 /* Restore the register variables for the local function if there are any.
394  * The parameter tells us if there is a return value in ax, in that case,
395  * the accumulator must be saved across the restore.
396  */
397 {
398     unsigned I, J;
399     int Bytes, Offs;
400
401     /* If we don't have register variables in this function, bail out early */
402     if (RegSymCount == 0) {
403         return;
404     }
405
406     /* Save the accumulator if needed */
407     if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
408         g_save (CF_CHAR | CF_FORCECHAR);
409     }
410
411     /* Walk through all variables. If there are several variables in a row
412      * (that is, with increasing stack offset), restore them in one chunk.
413      */
414     I = 0;
415     while (I < RegSymCount) {
416
417         /* Check for more than one variable */
418         const SymEntry* Sym = RegSyms[I];
419         Offs  = Sym->V.Offs;
420         Bytes = CheckedSizeOf (Sym->Type);
421         J = I+1;
422
423         while (J < RegSymCount) {
424
425             /* Get the next symbol */
426             const SymEntry* NextSym = RegSyms [J];
427
428             /* Get the size */
429             int Size = CheckedSizeOf (NextSym->Type);
430
431             /* Adjacent variable? */
432             if (NextSym->V.Offs + Size != Offs) {
433                 /* No */
434                 break;
435             }
436
437             /* Adjacent variable */
438             Bytes += Size;
439             Offs  -= Size;
440             Sym   = NextSym;
441             ++J;
442         }
443
444         /* Restore the memory range */
445         g_restore_regvars (Offs, Sym->V.Offs, Bytes);
446
447         /* Next round */
448         I = J;
449     }
450
451     /* Restore the accumulator if needed */
452     if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
453         g_restore (CF_CHAR | CF_FORCECHAR);
454     }
455 }
456
457
458