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