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