1 /*****************************************************************************/
5 /* Parse function entry/body/exit */
9 /* (C) 2000-2004 Ullrich von Bassewitz */
10 /* Römerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
58 /*****************************************************************************/
60 /*****************************************************************************/
64 /* Structure that holds all data needed for function activation */
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 */
75 /* Pointer to current function */
76 Function* CurrentFunc = 0;
80 /*****************************************************************************/
81 /* Subroutines working with struct Function */
82 /*****************************************************************************/
86 static Function* NewFunction (struct SymEntry* Sym)
87 /* Create a new function activation structure and return it */
89 /* Allocate a new structure */
90 Function* F = (Function*) xmalloc (sizeof (Function));
92 /* Initialize the fields */
94 F->ReturnType = GetFuncReturn (Sym->Type);
95 F->Desc = (FuncDesc*) DecodePtr (Sym->Type + 1);
97 F->RetLab = GetLocalLabel ();
99 F->RegOffs = RegisterSpace;
101 /* Return the new structure */
107 static void FreeFunction (Function* F)
108 /* Free a function activation structure */
115 const char* F_GetFuncName (const Function* F)
116 /* Return the name of the current function */
118 return F->FuncEntry->Name;
123 unsigned F_GetParamCount (const Function* F)
124 /* Return the parameter count for the current function */
126 return F->Desc->ParamCount;
131 unsigned F_GetParamSize (const Function* F)
132 /* Return the parameter size for the current function */
134 return F->Desc->ParamSize;
139 type* F_GetReturnType (Function* F)
140 /* Get the return type for the function */
142 return F->ReturnType;
147 int F_HasVoidReturn (const Function* F)
148 /* Return true if the function does not have a return value */
150 return IsTypeVoid (F->ReturnType);
155 int F_IsVariadic (const Function* F)
156 /* Return true if this is a variadic function */
158 return (F->Desc->Flags & FD_VARIADIC) != 0;
163 int F_IsOldStyle (const Function* F)
164 /* Return true if this is an old style (K&R) function */
166 return (F->Desc->Flags & FD_OLDSTYLE) != 0;
171 int F_HasOldStyleIntRet (const Function* F)
172 /* Return true if this is an old style (K&R) function with an implicit int return */
174 return (F->Desc->Flags & FD_OLDSTYLE_INTRET) != 0;
179 unsigned F_GetRetLab (const Function* F)
180 /* Return the return jump label */
187 int F_GetTopLevelSP (const Function* F)
188 /* Get the value of the stack pointer on function top level */
190 return F->TopLevelSP;
195 int F_ReserveLocalSpace (Function* F, unsigned Size)
196 /* Reserve (but don't allocate) the given local space and return the stack
201 return StackPtr - F->Reserved;
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.
211 if (F->Reserved > 0) {
213 /* Create space on the stack */
214 g_space (F->Reserved);
216 /* Correct the stack pointer */
217 StackPtr -= F->Reserved;
219 /* Nothing more reserved */
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.
232 /* Allow register variables only on top level and if enabled */
233 if (IS_Get (&EnableRegVars) && GetLexicalLevel () == LEX_LEVEL_FUNCTION) {
235 /* Get the size of the variable */
236 unsigned Size = CheckedSizeOf (Type);
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.
249 /* No space left or no allocation */
255 static void F_RestoreRegVars (Function* F)
256 /* Restore the register variables for the local function if there are any. */
260 /* If we don't have register variables in this function, bail out early */
261 if (F->RegOffs == RegisterSpace) {
265 /* Save the accumulator if needed */
266 if (!F_HasVoidReturn (F)) {
267 g_save (CF_CHAR | CF_FORCECHAR);
270 /* Get the first symbol from the function symbol table */
271 Sym = F->FuncEntry->V.F.Func->SymTab->SymHead;
273 /* Walk through all symbols checking for register variables */
275 if (SymIsRegVar (Sym)) {
277 /* Check for more than one variable */
278 int Offs = Sym->V.R.SaveOffs;
279 unsigned Bytes = CheckedSizeOf (Sym->Type);
283 /* Find next register variable */
284 const SymEntry* NextSym = Sym->NextSym;
285 while (NextSym && !SymIsRegVar (NextSym)) {
286 NextSym = NextSym->NextSym;
289 /* If we have a next one, compare the stack offsets */
292 /* We have a following register variable. Get the size */
293 int Size = CheckedSizeOf (NextSym->Type);
295 /* Adjacent variable? */
296 if (NextSym->V.R.SaveOffs + Size != Offs) {
301 /* Adjacent variable */
311 /* Restore the memory range */
312 g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
316 /* Check next symbol */
320 /* Restore the accumulator if needed */
321 if (!F_HasVoidReturn (F)) {
322 g_restore (CF_CHAR | CF_FORCECHAR);
328 /*****************************************************************************/
330 /*****************************************************************************/
334 void NewFunc (SymEntry* Func)
335 /* Parse argument declarations and function body. */
340 /* Get the function descriptor from the function entry */
341 FuncDesc* D = Func->V.F.Func;
343 /* Allocate the function activation record for the function */
344 CurrentFunc = NewFunction (Func);
346 /* Reenter the lexical level */
347 ReenterFunctionLevel (D);
349 /* Declare two special functions symbols: __fixargs__ and __argsize__.
350 * The latter is different depending on the type of the function (variadic
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);
360 AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
363 /* Function body now defined */
364 Func->Flags |= SC_DEF;
366 /* Allocate code and data segments for this function */
367 Func->V.F.Seg = PushSegments (Func);
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__");
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.
380 if (D->ParamCount > 0 || (D->Flags & FD_VARIADIC) != 0) {
385 /* If this is a fastcall function, push the last parameter onto the stack */
386 if (IsFastCallFunc (Func->Type) && D->ParamCount > 0) {
390 /* Fastcall functions may never have an ellipsis or the compiler is buggy */
391 CHECK ((D->Flags & FD_VARIADIC) == 0);
393 /* Generate the push */
394 if (IsTypeFunc (D->LastParam->Type)) {
395 /* Pointer to function */
398 Flags = TypeOf (D->LastParam->Type) | CF_FORCECHAR;
403 /* Generate function entry code if needed */
404 g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));
406 /* If stack checking code is requested, emit a call to the helper routine */
407 if (IS_Get (&CheckStack)) {
411 /* Setup the stack */
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.
418 Param = D->SymTab->SymHead;
419 while (Param && (Param->Flags & SC_PARAM) != 0) {
421 /* Check for a register variable */
422 if (SymIsRegVar (Param)) {
425 int Reg = F_AllocRegVar (CurrentFunc, Param->Type);
427 /* Could we allocate a register? */
429 /* No register available: Convert parameter to auto */
430 CvtRegVarToAuto (Param);
432 /* Remember the register offset */
433 Param->V.R.RegOffs = Reg;
435 /* Generate swap code */
436 g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type));
442 Param = Param->NextSym;
445 /* Need a starting curly brace */
448 /* Parse local variable declarations if any */
451 /* Remember the current stack pointer. All variables allocated elsewhere
452 * must be dropped when doing a return from an inner block.
454 CurrentFunc->TopLevelSP = StackPtr;
456 /* Now process statements in this block */
458 while (CurTok.Tok != TOK_RCURLY) {
459 if (CurTok.Tok != TOK_CEOF) {
460 HadReturn = Statement (0);
466 /* Output the function exit code label */
467 g_defcodelabel (F_GetRetLab (CurrentFunc));
469 /* Restore the register variables */
470 F_RestoreRegVars (CurrentFunc);
472 /* Generate the exit code */
475 /* Emit references to imports/exports */
478 /* Leave the lexical level */
479 LeaveFunctionLevel ();
481 /* Eat the closing brace */
484 /* Switch back to the old segments */
487 /* Reset the current function pointer */
488 FreeFunction (CurrentFunc);