]> git.sur5r.net Git - cc65/blob - src/cc65/locals.c
Reenable register variables
[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 type* Type)
105 /* Allocate a register variable for the given variable type. If the allocation
106  * was successful, return the offset of the register variable in the register
107  * bank (zero page storage). If there is no register space left, return -1.
108  */
109 {
110     /* Maybe register variables are disabled... */
111     if (EnableRegVars) {
112
113         /* Get the size of the variable */
114         unsigned Size = CheckedSizeOf (Type);
115
116         /* Do we have space left? */
117         if (RegOffs >= Size) {
118             /* Space left. We allocate the variables from high to low addresses,
119              * so the adressing is compatible with the saved values on stack.
120              * This allows shorter code when saving/restoring the variables.
121              */
122             RegOffs -= Size;
123             return RegOffs;
124         }
125     }
126
127     /* No space left or no allocation */
128     return -1;
129 }
130
131
132
133 static void RememberRegVar (const SymEntry* Sym)
134 /* Remember the given register variable */
135 {
136     RegSyms[RegSymCount++] = Sym;
137 }
138
139
140
141 static unsigned ParseRegisterDecl (Declaration* Decl, unsigned* SC, int Reg)
142 /* Parse the declaration of a register variable. The function returns the
143  * symbol data, which is the offset of the variable in the register bank.
144  */
145 {
146     unsigned Flags;
147     unsigned InitLabel;
148
149     /* Determine if this is a compound variable */
150     int IsCompound = IsClassStruct (Decl->Type) || IsTypeArray (Decl->Type);
151
152     /* Get the size of the variable */
153     unsigned Size = SizeOf (Decl->Type);
154
155     /* Save the current contents of the register variable on stack */
156     F_AllocLocalSpace (CurrentFunc);
157     g_save_regvars (Reg, Size);
158
159     /* Check for an optional initialization */
160     if (CurTok.Tok == TOK_ASSIGN) {
161
162         ExprDesc lval;
163
164         /* Skip the '=' */
165         NextToken ();
166
167         /* Special handling for compound types */
168         if (IsCompound) {
169
170             /* Switch to read only data */
171             g_userodata ();
172
173             /* Define a label for the initialization data */
174             InitLabel = GetLocalLabel ();
175             g_defdatalabel (InitLabel);
176
177             /* Parse the initialization generating a memory image of the
178              * data in the RODATA segment.
179              */
180             ParseInit (Decl->Type);
181
182             /* Generate code to copy this data into the variable space */
183             g_initregister (InitLabel, Reg, Size);
184
185         } else {
186
187             /* Setup the type flags for the assignment */
188             Flags = CF_REGVAR;
189             if (Size == SIZEOF_CHAR) {
190                 Flags |= CF_FORCECHAR;
191             }
192
193             /* Get the expression into the primary */
194             if (evalexpr (Flags, hie1, &lval) == 0) {
195                 /* Constant expression. Adjust the types */
196                 assignadjust (Decl->Type, &lval);
197                 Flags |= CF_CONST;
198             } else {
199                 /* Expression is not constant and in the primary */
200                 assignadjust (Decl->Type, &lval);
201             }
202
203             /* Store the value into the variable */
204             g_putstatic (Flags | TypeOf (Decl->Type), Reg, 0);
205
206         }
207
208         /* Mark the variable as referenced */
209         *SC |= SC_REF;
210     }
211
212     /* Cannot allocate a variable of zero size */
213     if (Size == 0) {
214         Error ("Variable `%s' has unknown size", Decl->Ident);
215     }
216
217     /* Return the symbol data */
218     return Reg;
219 }
220
221
222
223 static unsigned ParseAutoDecl (Declaration* Decl, unsigned* SC)
224 /* Parse the declaration of an auto variable. The function returns the symbol
225  * data, which is the offset for variables on the stack, and the label for
226  * static variables.
227  */
228 {
229     unsigned Flags;
230     unsigned SymData;
231     unsigned InitLabel;
232
233     /* Determine if this is a compound variable */
234     int IsCompound = IsClassStruct (Decl->Type) || IsTypeArray (Decl->Type);
235
236     /* Get the size of the variable */
237     unsigned Size = SizeOf (Decl->Type);
238
239     /* Check if this is a variable on the stack or in static memory */
240     if (StaticLocals == 0) {
241
242         /* Check for an optional initialization */
243         if (CurTok.Tok == TOK_ASSIGN) {
244
245             ExprDesc lval;
246
247             /* Skip the '=' */
248             NextToken ();
249
250             /* Special handling for compound types */
251             if (IsCompound) {
252
253                 /* First reserve space for the variable */
254                 SymData = F_ReserveLocalSpace (CurrentFunc, Size);
255
256                 /* Next, allocate the space on the stack. This means that the
257                  * variable is now located at offset 0 from the current sp.
258                  */
259                 F_AllocLocalSpace (CurrentFunc);
260
261                 /* Switch to read only data */
262                 g_userodata ();
263
264                 /* Define a label for the initialization data */
265                 InitLabel = GetLocalLabel ();
266                 g_defdatalabel (InitLabel);
267
268                 /* Parse the initialization generating a memory image of the
269                  * data in the RODATA segment.
270                  */
271                 ParseInit (Decl->Type);
272
273                 /* Generate code to copy this data into the variable space */
274                 g_initauto (InitLabel, Size);
275
276             } else {
277
278                 /* Allocate previously reserved local space */
279                 F_AllocLocalSpace (CurrentFunc);
280
281                 /* Setup the type flags for the assignment */
282                 Flags = (Size == SIZEOF_CHAR)? CF_FORCECHAR : CF_NONE;
283
284                 /* Get the expression into the primary */
285                 if (evalexpr (Flags, hie1, &lval) == 0) {
286                     /* Constant expression. Adjust the types */
287                     assignadjust (Decl->Type, &lval);
288                     Flags |= CF_CONST;
289                 } else {
290                     /* Expression is not constant and in the primary */
291                     assignadjust (Decl->Type, &lval);
292                 }
293
294                 /* Push the value */
295                 g_push (Flags | TypeOf (Decl->Type), lval.ConstVal);
296
297             }
298
299             /* Mark the variable as referenced */
300             *SC |= SC_REF;
301
302             /* Variable is located at the current SP */
303             SymData = oursp;
304
305         } else {
306             /* Non-initialized local variable. Just keep track of
307              * the space needed.
308              */
309             SymData = F_ReserveLocalSpace (CurrentFunc, Size);
310         }
311
312     } else {
313
314         /* Static local variables. */
315         *SC = (*SC & ~SC_AUTO) | SC_STATIC;
316
317         /* Put them into the BSS */
318         g_usebss ();
319
320         /* Define the variable label */
321         SymData = GetLocalLabel ();
322         g_defdatalabel (SymData);
323
324         /* Reserve space for the data */
325         g_res (Size);
326
327         /* Allow assignments */
328         if (CurTok.Tok == TOK_ASSIGN) {
329
330             ExprDesc lval;
331
332             /* Skip the '=' */
333             NextToken ();
334
335             if (IsCompound) {
336
337                 /* Switch to read only data */
338                 g_userodata ();
339
340                 /* Define a label for the initialization data */
341                 InitLabel = GetLocalLabel ();
342                 g_defdatalabel (InitLabel);
343
344                 /* Parse the initialization generating a memory image of the
345                  * data in the RODATA segment.
346                  */
347                 ParseInit (Decl->Type);
348
349                 /* Generate code to copy this data into the variable space */
350                 g_initstatic (InitLabel, SymData, Size);
351
352             } else {
353
354                 /* Setup the type flags for the assignment */
355                 Flags = (Size == SIZEOF_CHAR)? CF_FORCECHAR : CF_NONE;
356
357                 /* Get the expression into the primary */
358                 if (evalexpr (Flags, hie1, &lval) == 0) {
359                     /* Constant expression. Adjust the types */
360                     assignadjust (Decl->Type, &lval);
361                     Flags |= CF_CONST;
362                     /* Load it into the primary */
363                     exprhs (Flags, 0, &lval);
364                 } else {
365                     /* Expression is not constant and in the primary */
366                     assignadjust (Decl->Type, &lval);
367                 }
368
369                 /* Store the value into the variable */
370                 g_putstatic (Flags | TypeOf (Decl->Type), SymData, 0);
371
372             }
373
374             /* Mark the variable as referenced */
375             *SC |= SC_REF;
376         }
377     }
378
379     /* Cannot allocate a variable of zero size */
380     if (Size == 0) {
381         Error ("Variable `%s' has unknown size", Decl->Ident);
382     }
383
384     /* Return the symbol data */
385     return SymData;
386 }
387
388
389
390 static unsigned ParseStaticDecl (Declaration* Decl, unsigned* SC)
391 /* Parse the declaration of a static variable. The function returns the symbol
392  * data, which is the asm label of the variable.
393  */
394 {
395     unsigned SymData;
396
397     /* Get the size of the variable */
398     unsigned Size = SizeOf (Decl->Type);
399
400     /* Static data */
401     if (CurTok.Tok == TOK_ASSIGN) {
402
403         /* Initialization ahead, switch to data segment */
404         if (IsQualConst (Decl->Type)) {
405             g_userodata ();
406         } else {
407             g_usedata ();
408         }
409
410         /* Define the variable label */
411         SymData = GetLocalLabel ();
412         g_defdatalabel (SymData);
413
414         /* Skip the '=' */
415         NextToken ();
416
417         /* Allow initialization of static vars */
418         ParseInit (Decl->Type);
419
420         /* If the previous size has been unknown, it must be known now */
421         if (Size == 0) {
422             Size = SizeOf (Decl->Type);
423         }
424
425         /* Mark the variable as referenced */
426         *SC |= SC_REF;
427
428     } else {
429
430         /* Uninitialized data, use BSS segment */
431         g_usebss ();
432
433         /* Define the variable label */
434         SymData = GetLocalLabel ();
435         g_defdatalabel (SymData);
436
437         /* Reserve space for the data */
438         g_res (Size);
439
440     }
441
442     /* Cannot allocate a variable of zero size */
443     if (Size == 0) {
444         Error ("Variable `%s' has unknown size", Decl->Ident);
445     }
446
447     /* Return the symbol data */
448     return SymData;
449 }
450
451
452
453 static void ParseOneDecl (const DeclSpec* Spec)
454 /* Parse one variable declaration */
455 {
456     unsigned    SC;             /* Storage class for symbol */
457     unsigned    SymData = 0;    /* Symbol data (offset, label name, ...) */
458     Declaration Decl;           /* Declaration data structure */
459     SymEntry*   Sym;            /* Symbol declared */
460
461
462     /* Remember the storage class for the new symbol */
463     SC = Spec->StorageClass;
464
465     /* Read the declaration */
466     ParseDecl (Spec, &Decl, DM_NEED_IDENT);
467
468     /* Set the correct storage class for functions */
469     if (IsTypeFunc (Decl.Type)) {
470         /* Function prototypes are always external */
471         if ((SC & SC_EXTERN) == 0) {
472             Warning ("Function must be extern");
473         }
474         SC |= SC_FUNC | SC_EXTERN;
475
476     }
477
478     /* If we don't have a name, this was flagged as an error earlier.
479      * To avoid problems later, use an anonymous name here.
480      */
481     if (Decl.Ident[0] == '\0') {
482         AnonName (Decl.Ident, "param");
483     }
484
485     /* Handle anything that needs storage (no functions, no typdefs) */
486     if ((SC & SC_FUNC) != SC_FUNC && (SC & SC_TYPEDEF) != SC_TYPEDEF) {
487
488         /* If we have a register variable, try to allocate a register and
489          * convert the declaration to "auto" if this is not possible.
490          */
491         int Reg = 0;    /* Initialize to avoid gcc complains */
492         if ((SC & SC_REGISTER) != 0 && (Reg = AllocRegVar (Decl.Type)) < 0) {
493             /* No space for this register variable, convert to auto */
494             SC = (SC & ~SC_REGISTER) | SC_AUTO;
495         }
496
497         /* Check the variable type */
498         if (SC & SC_REGISTER) {
499             /* Register variable */
500             SymData = ParseRegisterDecl (&Decl, &SC, Reg);
501         } else if (SC & SC_AUTO) {
502             /* Auto variable */
503             SymData = ParseAutoDecl (&Decl, &SC);
504         } else if (SC & SC_STATIC) {
505             /* Static variable */
506             SymData = ParseStaticDecl (&Decl, &SC);
507         } else {
508             Internal ("Invalid storage class in ParseOneDecl: %04X", SC);
509         }
510     }
511
512     /* If the symbol is not marked as external, it will be defined now */
513     if ((SC & SC_EXTERN) == 0) {
514         SC |= SC_DEF;
515     }
516
517     /* Add the symbol to the symbol table */
518     Sym = AddLocalSym (Decl.Ident, Decl.Type, SC, SymData);
519
520     /* If we had declared a register variable, remember it now */
521     if (SC & SC_REGISTER) {
522         RememberRegVar (Sym);
523     }
524 }
525
526
527
528 void DeclareLocals (void)
529 /* Declare local variables and types. */
530 {
531     /* Remember the current stack pointer */
532     int InitialStack = oursp;
533
534     /* Loop until we don't find any more variables */
535     while (1) {
536
537         /* Check variable declarations. We need to distinguish between a
538          * default int type and the end of variable declarations. So we
539          * will do the following: If there is no explicit storage class
540          * specifier *and* no explicit type given, it is assume that we
541          * have reached the end of declarations.
542          */
543         DeclSpec Spec;
544         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
545         if ((Spec.Flags & DS_DEF_STORAGE) != 0 && (Spec.Flags & DS_DEF_TYPE) != 0) {
546             break;
547         }
548
549         /* Accept type only declarations */
550         if (CurTok.Tok == TOK_SEMI) {
551             /* Type declaration only */
552             CheckEmptyDecl (&Spec);
553             NextToken ();
554             continue;
555         }
556
557         /* Parse a comma separated variable list */
558         while (1) {
559
560             /* Parse one declaration */
561             ParseOneDecl (&Spec);
562
563             /* Check if there is more */
564             if (CurTok.Tok == TOK_COMMA) {
565                 /* More to come */
566                 NextToken ();
567             } else {
568                 /* Done */
569                 break;
570             }
571         }
572
573         /* A semicolon must follow */
574         ConsumeSemi ();
575     }
576
577     /* Be sure to allocate any reserved space for locals */
578     F_AllocLocalSpace (CurrentFunc);
579
580     /* In case we've allocated local variables in this block, emit a call to
581      * the stack checking routine if stack checks are enabled.
582      */
583     if (CheckStack && InitialStack != oursp) {
584         g_cstackcheck ();
585     }
586 }
587
588
589
590 void RestoreRegVars (int HaveResult)
591 /* Restore the register variables for the local function if there are any.
592  * The parameter tells us if there is a return value in ax, in that case,
593  * the accumulator must be saved across the restore.
594  */
595 {
596     unsigned I, J;
597     int Bytes, Offs;
598
599     /* If we don't have register variables in this function, bail out early */
600     if (RegSymCount == 0) {
601         return;
602     }
603
604     /* Save the accumulator if needed */
605     if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
606         g_save (CF_CHAR | CF_FORCECHAR);
607     }
608
609     /* Walk through all variables. If there are several variables in a row
610      * (that is, with increasing stack offset), restore them in one chunk.
611      */
612     I = 0;
613     while (I < RegSymCount) {
614
615         /* Check for more than one variable */
616         const SymEntry* Sym = RegSyms[I];    
617         Offs  = Sym->V.R.SaveOffs;
618         Bytes = CheckedSizeOf (Sym->Type);
619         J = I+1;
620
621         while (J < RegSymCount) {
622
623             /* Get the next symbol */
624             const SymEntry* NextSym = RegSyms [J];
625
626             /* Get the size */
627             int Size = CheckedSizeOf (NextSym->Type);
628
629             /* Adjacent variable? */
630             if (NextSym->V.R.SaveOffs + Size != Offs) {
631                 /* No */
632                 break;
633             }
634
635             /* Adjacent variable */
636             Bytes += Size;
637             Offs  -= Size;
638             Sym   = NextSym;
639             ++J;
640         }
641
642         /* Restore the memory range */
643         g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
644
645         /* Next round */
646         I = J;
647     }
648
649     /* Restore the accumulator if needed */
650     if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
651         g_restore (CF_CHAR | CF_FORCECHAR);
652     }
653 }
654
655
656