]> git.sur5r.net Git - cc65/blob - src/cc65/function.c
New/changed optimizations
[cc65] / src / cc65 / function.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                function.c                                 */
4 /*                                                                           */
5 /*                      Parse function entry/body/exit                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2001 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 "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 "stmt.h"
52 #include "symtab.h"
53 #include "function.h"
54
55
56
57 /*****************************************************************************/
58 /*                                   Data                                    */
59 /*****************************************************************************/
60
61
62
63 /* Structure that holds all data needed for function activation */
64 struct Function {
65     struct SymEntry*    FuncEntry;      /* Symbol table entry */
66     type*               ReturnType;     /* Function return type */
67     struct FuncDesc*    Desc;           /* Function descriptor */
68     int                 Reserved;       /* Reserved local space */
69     unsigned            RetLab;         /* Return code label */
70     int                 TopLevelSP;     /* SP at function top level */
71 };
72
73 /* Pointer to current function */
74 Function* CurrentFunc = 0;
75
76
77
78 /*****************************************************************************/
79 /*                 Subroutines working with struct Function                  */
80 /*****************************************************************************/
81
82
83
84 static Function* NewFunction (struct SymEntry* Sym)
85 /* Create a new function activation structure and return it */
86 {
87     /* Allocate a new structure */
88     Function* F = (Function*) xmalloc (sizeof (Function));
89
90     /* Initialize the fields */
91     F->FuncEntry  = Sym;
92     F->ReturnType = GetFuncReturn (Sym->Type);
93     F->Desc       = (FuncDesc*) DecodePtr (Sym->Type + 1);
94     F->Reserved   = 0;
95     F->RetLab     = GetLocalLabel ();
96     F->TopLevelSP = 0;
97
98     /* Return the new structure */
99     return F;
100 }
101
102
103
104 static void FreeFunction (Function* F)
105 /* Free a function activation structure */
106 {
107     xfree (F);
108 }
109
110
111
112 const char* F_GetFuncName (const Function* F)
113 /* Return the name of the current function */
114 {
115     return F->FuncEntry->Name;
116 }
117
118
119
120 unsigned F_GetParamCount (const Function* F)
121 /* Return the parameter count for the current function */
122 {
123     return F->Desc->ParamCount;
124 }
125
126
127
128 unsigned F_GetParamSize (const Function* F)
129 /* Return the parameter size for the current function */
130 {
131     return F->Desc->ParamSize;
132 }
133
134
135
136 type* F_GetReturnType (Function* F)
137 /* Get the return type for the function */
138 {
139     return F->ReturnType;
140 }
141
142
143
144 int F_HasVoidReturn (const Function* F)
145 /* Return true if the function does not have a return value */
146 {
147     return IsTypeVoid (F->ReturnType);
148 }
149
150
151
152 int F_IsVariadic (const Function* F)
153 /* Return true if this is a variadic function */
154 {
155     return (F->Desc->Flags & FD_VARIADIC) != 0;
156 }
157
158
159
160 int F_IsOldStyle (const Function* F)
161 /* Return true if this is an old style (K&R) function */
162 {
163     return (F->Desc->Flags & FD_OLDSTYLE) != 0;
164 }
165
166
167
168 int F_HasOldStyleIntRet (const Function* F)
169 /* Return true if this is an old style (K&R) function with an implicit int return */
170 {
171     return (F->Desc->Flags & FD_OLDSTYLE_INTRET) != 0;
172 }
173
174
175
176 unsigned F_GetRetLab (const Function* F)
177 /* Return the return jump label */
178 {
179     return F->RetLab;
180 }
181
182
183
184 int F_GetTopLevelSP (const Function* F)
185 /* Get the value of the stack pointer on function top level */
186 {
187     return F->TopLevelSP;
188 }
189
190
191
192 int F_ReserveLocalSpace (Function* F, unsigned Size)
193 /* Reserve (but don't allocate) the given local space and return the stack
194  * offset.
195  */
196 {
197     F->Reserved += Size;
198     return oursp - F->Reserved;
199 }
200
201
202
203 void F_AllocLocalSpace (Function* F)
204 /* Allocate any local space previously reserved. The function will do
205  * nothing if there is no reserved local space.
206  */
207 {
208     if (F->Reserved > 0) {
209
210         /* Create space on the stack */
211         g_space (F->Reserved);
212
213         /* Correct the stack pointer */
214         oursp -= F->Reserved;
215
216         /* Nothing more reserved */
217         F->Reserved = 0;
218     }
219 }
220
221
222
223 /*****************************************************************************/
224 /*                                   code                                    */
225 /*****************************************************************************/
226
227
228
229 void NewFunc (SymEntry* Func)
230 /* Parse argument declarations and function body. */
231 {
232     int HadReturn;
233     int IsVoidFunc;
234     SymEntry* LastParam;
235
236     /* Get the function descriptor from the function entry */
237     FuncDesc* D = Func->V.F.Func;
238
239     /* Allocate the function activation record for the function */
240     CurrentFunc = NewFunction (Func);
241
242     /* Reenter the lexical level */
243     ReenterFunctionLevel (D);
244
245     /* Before adding more symbols, remember the last parameter for later */
246     LastParam = D->SymTab->SymTail;
247
248     /* Declare two special functions symbols: __fixargs__ and __argsize__.
249      * The latter is different depending on the type of the function (variadic
250      * or not).
251      */
252     AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize);
253     if (D->Flags & FD_VARIADIC) {
254         /* Variadic function. The variable must be const. */
255         static const type T [] = { T_UCHAR | T_QUAL_CONST, T_END };
256         AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0);
257     } else {
258         /* Non variadic */
259         AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
260     }
261
262     /* Function body now defined */
263     Func->Flags |= SC_DEF;
264
265     /* Setup register variables */
266     InitRegVars ();
267
268     /* Allocate code and data segments for this function */
269     Func->V.F.Seg = PushSegments (Func);
270
271     /* If this is a fastcall function, push the last parameter onto the stack */
272     if (IsFastCallFunc (Func->Type) && D->ParamCount > 0) {
273
274         unsigned Flags;
275
276         /* Fastcall functions may never have an ellipsis or the compiler is buggy */
277         CHECK ((D->Flags & FD_VARIADIC) == 0);
278
279         /* Generate the push */
280         if (IsTypeFunc (LastParam->Type)) {
281             /* Pointer to function */
282             Flags = CF_PTR;
283         } else {
284             Flags = TypeOf (LastParam->Type) | CF_FORCECHAR;
285         }
286         g_push (Flags, 0);
287     }
288
289     /* If stack checking code is requested, emit a call to the helper routine */
290     if (CheckStack) {
291         g_stackcheck ();
292     }
293
294     /* Generate function entry code if needed */
295     g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));
296
297     /* Setup the stack */
298     oursp = 0;
299
300     /* Need a starting curly brace */
301     ConsumeLCurly ();
302
303     /* Parse local variable declarations if any */
304     DeclareLocals ();
305
306     /* Remember the current stack pointer. All variables allocated elsewhere
307      * must be dropped when doing a return from an inner block.
308      */
309     CurrentFunc->TopLevelSP = oursp;
310
311     /* Now process statements in this block */
312     HadReturn = 0;
313     while (CurTok.Tok != TOK_RCURLY) {
314         if (CurTok.Tok != TOK_CEOF) {
315             HadReturn = Statement (0);
316         } else {
317             break;
318         }
319     }
320
321     /* If the function has a return type but no return statement, flag
322      * a warning
323      */
324     IsVoidFunc = F_HasVoidReturn (CurrentFunc);
325 #if 0
326     /* Does not work reliably */
327     if (!F_IsVoidFunc && !HadReturn) {
328         Warning ("Function `%s' should return a value", Func->Name);
329     }
330 #endif
331
332     /* Output the function exit code label */
333     g_defcodelabel (F_GetRetLab (CurrentFunc));
334
335     /* Restore the register variables */
336     RestoreRegVars (!IsVoidFunc);
337
338     /* Generate the exit code */
339     g_leave ();
340
341     /* Eat the closing brace */
342     ConsumeRCurly ();
343
344     /* Emit references to imports/exports */
345     EmitExternals ();
346
347     /* Cleanup register variables */
348     DoneRegVars ();
349
350     /* Leave the lexical level */
351     LeaveFunctionLevel ();
352
353     /* Switch back to the old segments */
354     PopSegments ();
355
356     /* Reset the current function pointer */
357     FreeFunction (CurrentFunc);
358     CurrentFunc = 0;
359 }
360
361
362