]> git.sur5r.net Git - cc65/blob - src/cc65/function.c
Move the compiler stack pointer into its own module.
[cc65] / src / cc65 / function.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                function.c                                 */
4 /*                                                                           */
5 /*                      Parse function entry/body/exit                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2004 Ullrich von Bassewitz                                       */
10 /*               Römerstrasse 52                                             */
11 /*               D-70794 Filderstadt                                         */
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 "check.h"
38 #include "xmalloc.h"
39
40 /* cc65 */
41 #include "asmcode.h"
42 #include "asmlabel.h"
43 #include "codegen.h"
44 #include "error.h"
45 #include "funcdesc.h"
46 #include "global.h"
47 #include "litpool.h"
48 #include "locals.h"
49 #include "scanner.h"
50 #include "segments.h"
51 #include "stackptr.h"
52 #include "stmt.h"
53 #include "symtab.h"
54 #include "function.h"
55
56
57
58 /*****************************************************************************/
59 /*                                   Data                                    */
60 /*****************************************************************************/
61
62
63
64 /* Structure that holds all data needed for function activation */
65 struct Function {
66     struct SymEntry*    FuncEntry;      /* Symbol table entry */
67     type*               ReturnType;     /* Function return type */
68     struct FuncDesc*    Desc;           /* Function descriptor */
69     int                 Reserved;       /* Reserved local space */
70     unsigned            RetLab;         /* Return code label */
71     int                 TopLevelSP;     /* SP at function top level */
72     unsigned            RegOffs;        /* Register variable space offset */
73 };
74
75 /* Pointer to current function */
76 Function* CurrentFunc = 0;
77
78
79
80 /*****************************************************************************/
81 /*                 Subroutines working with struct Function                  */
82 /*****************************************************************************/
83
84
85
86 static Function* NewFunction (struct SymEntry* Sym)
87 /* Create a new function activation structure and return it */
88 {
89     /* Allocate a new structure */
90     Function* F = (Function*) xmalloc (sizeof (Function));
91
92     /* Initialize the fields */
93     F->FuncEntry  = Sym;
94     F->ReturnType = GetFuncReturn (Sym->Type);
95     F->Desc       = (FuncDesc*) DecodePtr (Sym->Type + 1);
96     F->Reserved   = 0;
97     F->RetLab     = GetLocalLabel ();
98     F->TopLevelSP = 0;
99     F->RegOffs    = RegisterSpace;
100
101     /* Return the new structure */
102     return F;
103 }
104
105
106
107 static void FreeFunction (Function* F)
108 /* Free a function activation structure */
109 {
110     xfree (F);
111 }
112
113
114
115 const char* F_GetFuncName (const Function* F)
116 /* Return the name of the current function */
117 {
118     return F->FuncEntry->Name;
119 }
120
121
122
123 unsigned F_GetParamCount (const Function* F)
124 /* Return the parameter count for the current function */
125 {
126     return F->Desc->ParamCount;
127 }
128
129
130
131 unsigned F_GetParamSize (const Function* F)
132 /* Return the parameter size for the current function */
133 {
134     return F->Desc->ParamSize;
135 }
136
137
138
139 type* F_GetReturnType (Function* F)
140 /* Get the return type for the function */
141 {
142     return F->ReturnType;
143 }
144
145
146
147 int F_HasVoidReturn (const Function* F)
148 /* Return true if the function does not have a return value */
149 {
150     return IsTypeVoid (F->ReturnType);
151 }
152
153
154
155 int F_IsVariadic (const Function* F)
156 /* Return true if this is a variadic function */
157 {
158     return (F->Desc->Flags & FD_VARIADIC) != 0;
159 }
160
161
162
163 int F_IsOldStyle (const Function* F)
164 /* Return true if this is an old style (K&R) function */
165 {
166     return (F->Desc->Flags & FD_OLDSTYLE) != 0;
167 }
168
169
170
171 int F_HasOldStyleIntRet (const Function* F)
172 /* Return true if this is an old style (K&R) function with an implicit int return */
173 {
174     return (F->Desc->Flags & FD_OLDSTYLE_INTRET) != 0;
175 }
176
177
178
179 unsigned F_GetRetLab (const Function* F)
180 /* Return the return jump label */
181 {
182     return F->RetLab;
183 }
184
185
186
187 int F_GetTopLevelSP (const Function* F)
188 /* Get the value of the stack pointer on function top level */
189 {
190     return F->TopLevelSP;
191 }
192
193
194
195 int F_ReserveLocalSpace (Function* F, unsigned Size)
196 /* Reserve (but don't allocate) the given local space and return the stack
197  * offset.
198  */
199 {
200     F->Reserved += Size;
201     return StackPtr - F->Reserved;
202 }
203
204
205
206 void F_AllocLocalSpace (Function* F)
207 /* Allocate any local space previously reserved. The function will do
208  * nothing if there is no reserved local space.
209  */
210 {
211     if (F->Reserved > 0) {
212
213         /* Create space on the stack */
214         g_space (F->Reserved);
215
216         /* Correct the stack pointer */
217         StackPtr -= F->Reserved;
218
219         /* Nothing more reserved */
220         F->Reserved = 0;
221     }
222 }
223
224
225
226 int F_AllocRegVar (Function* F, const type* Type)
227 /* Allocate a register variable for the given variable type. If the allocation
228  * was successful, return the offset of the register variable in the register
229  * bank (zero page storage). If there is no register space left, return -1.
230  */
231 {
232     /* Allow register variables only on top level and if enabled */
233     if (IS_Get (&EnableRegVars) && GetLexicalLevel () == LEX_LEVEL_FUNCTION) {
234
235         /* Get the size of the variable */
236         unsigned Size = CheckedSizeOf (Type);
237
238         /* Do we have space left? */
239         if (F->RegOffs >= Size) {
240             /* Space left. We allocate the variables from high to low addresses,
241              * so the adressing is compatible with the saved values on stack.
242              * This allows shorter code when saving/restoring the variables.
243              */
244             F->RegOffs -= Size;
245             return F->RegOffs;
246         }
247     }
248
249     /* No space left or no allocation */
250     return -1;
251 }
252
253
254
255 static void F_RestoreRegVars (Function* F)
256 /* Restore the register variables for the local function if there are any. */
257 {
258     const SymEntry* Sym;
259
260     /* If we don't have register variables in this function, bail out early */
261     if (F->RegOffs == RegisterSpace) {
262         return;
263     }
264
265     /* Save the accumulator if needed */
266     if (!F_HasVoidReturn (F)) {
267         g_save (CF_CHAR | CF_FORCECHAR);
268     }
269
270     /* Get the first symbol from the function symbol table */
271     Sym = F->FuncEntry->V.F.Func->SymTab->SymHead;
272
273     /* Walk through all symbols checking for register variables */
274     while (Sym) {
275         if (SymIsRegVar (Sym)) {
276
277             /* Check for more than one variable */
278             int Offs       = Sym->V.R.SaveOffs;
279             unsigned Bytes = CheckedSizeOf (Sym->Type);
280
281             while (1) {
282
283                 /* Find next register variable */
284                 const SymEntry* NextSym = Sym->NextSym;
285                 while (NextSym && !SymIsRegVar (NextSym)) {
286                     NextSym = NextSym->NextSym;
287                 }
288
289                 /* If we have a next one, compare the stack offsets */
290                 if (NextSym) {
291
292                     /* We have a following register variable. Get the size */
293                     int Size = CheckedSizeOf (NextSym->Type);
294
295                     /* Adjacent variable? */
296                     if (NextSym->V.R.SaveOffs + Size != Offs) {
297                         /* No */
298                         break;
299                     }
300
301                     /* Adjacent variable */
302                     Bytes += Size;
303                     Offs  -= Size;
304                     Sym   = NextSym;
305
306                 } else {
307                     break;
308                 }
309             }
310
311             /* Restore the memory range */
312             g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
313
314         }
315
316         /* Check next symbol */
317         Sym = Sym->NextSym;
318     }
319
320     /* Restore the accumulator if needed */
321     if (!F_HasVoidReturn (F)) {
322         g_restore (CF_CHAR | CF_FORCECHAR);
323     }
324 }
325
326
327
328 /*****************************************************************************/
329 /*                                   code                                    */
330 /*****************************************************************************/
331
332
333
334 void NewFunc (SymEntry* Func)
335 /* Parse argument declarations and function body. */
336 {
337     int HadReturn;
338     SymEntry* Param;
339
340     /* Get the function descriptor from the function entry */
341     FuncDesc* D = Func->V.F.Func;
342
343     /* Allocate the function activation record for the function */
344     CurrentFunc = NewFunction (Func);
345
346     /* Reenter the lexical level */
347     ReenterFunctionLevel (D);
348
349     /* Declare two special functions symbols: __fixargs__ and __argsize__.
350      * The latter is different depending on the type of the function (variadic
351      * or not).
352      */
353     AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize);
354     if (D->Flags & FD_VARIADIC) {
355         /* Variadic function. The variable must be const. */
356         static const type T [] = { T_UCHAR | T_QUAL_CONST, T_END };
357         AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0);
358     } else {
359         /* Non variadic */
360         AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
361     }
362
363     /* Function body now defined */
364     Func->Flags |= SC_DEF;
365
366     /* Allocate code and data segments for this function */
367     Func->V.F.Seg = PushSegments (Func);
368
369     /* Special handling for main() */
370     if (strcmp (Func->Name, "main") == 0) {
371         /* Main cannot be a fastcall function */
372         if (IsFastCallFunc (Func->Type)) {
373             Error ("`main' cannot be declared as __fastcall__");
374         }
375
376         /* If main() takes parameters, generate a forced import to a function
377          * that will setup these parameters. This way, programs that do not
378          * need the additional code will not get it.
379          */
380         if (D->ParamCount > 0 || (D->Flags & FD_VARIADIC) != 0) {
381             g_importmainargs ();
382         }
383     }
384
385     /* If this is a fastcall function, push the last parameter onto the stack */
386     if (IsFastCallFunc (Func->Type) && D->ParamCount > 0) {
387
388         unsigned Flags;
389
390         /* Fastcall functions may never have an ellipsis or the compiler is buggy */
391         CHECK ((D->Flags & FD_VARIADIC) == 0);
392
393         /* Generate the push */
394         if (IsTypeFunc (D->LastParam->Type)) {
395             /* Pointer to function */
396             Flags = CF_PTR;
397         } else {
398             Flags = TypeOf (D->LastParam->Type) | CF_FORCECHAR;
399         }
400         g_push (Flags, 0);
401     }
402
403     /* Generate function entry code if needed */
404     g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));
405
406     /* If stack checking code is requested, emit a call to the helper routine */
407     if (IS_Get (&CheckStack)) {
408         g_stackcheck ();
409     }
410
411     /* Setup the stack */
412     StackPtr = 0;
413
414     /* Walk through the parameter list and allocate register variable space
415      * for parameters declared as register. Generate code to swap the contents
416      * of the register bank with the save area on the stack.
417      */
418     Param = D->SymTab->SymHead;
419     while (Param && (Param->Flags & SC_PARAM) != 0) {
420
421         /* Check for a register variable */
422         if (SymIsRegVar (Param)) {
423
424             /* Allocate space */
425             int Reg = F_AllocRegVar (CurrentFunc, Param->Type);
426
427             /* Could we allocate a register? */
428             if (Reg < 0) {
429                 /* No register available: Convert parameter to auto */
430                 CvtRegVarToAuto (Param);
431             } else {
432                 /* Remember the register offset */
433                 Param->V.R.RegOffs = Reg;
434
435                 /* Generate swap code */
436                 g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type));
437
438             }
439         }
440
441         /* Next parameter */
442         Param = Param->NextSym;
443     }
444
445     /* Need a starting curly brace */
446     ConsumeLCurly ();
447
448     /* Parse local variable declarations if any */
449     DeclareLocals ();
450
451     /* Remember the current stack pointer. All variables allocated elsewhere
452      * must be dropped when doing a return from an inner block.
453      */
454     CurrentFunc->TopLevelSP = StackPtr;
455
456     /* Now process statements in this block */
457     HadReturn = 0;
458     while (CurTok.Tok != TOK_RCURLY) {
459         if (CurTok.Tok != TOK_CEOF) {
460             HadReturn = Statement (0);
461         } else {
462             break;
463         }
464     }
465
466     /* Output the function exit code label */
467     g_defcodelabel (F_GetRetLab (CurrentFunc));
468
469     /* Restore the register variables */
470     F_RestoreRegVars (CurrentFunc);
471
472     /* Generate the exit code */
473     g_leave ();
474
475     /* Emit references to imports/exports */
476     EmitExternals ();
477
478     /* Leave the lexical level */
479     LeaveFunctionLevel ();
480
481     /* Eat the closing brace */
482     ConsumeRCurly ();
483
484     /* Switch back to the old segments */
485     PopSegments ();
486
487     /* Reset the current function pointer */
488     FreeFunction (CurrentFunc);
489     CurrentFunc = 0;
490 }
491
492
493