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