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