1 /*****************************************************************************/
5 /* Parse function entry/body/exit */
9 /* (C) 2000-2008 Ullrich von Bassewitz */
10 /* Roemerstrasse 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 /*****************************************************************************/
59 /*****************************************************************************/
61 /*****************************************************************************/
65 /* Structure that holds all data needed for function activation */
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 */
76 /* Pointer to current function */
77 Function* CurrentFunc = 0;
81 /*****************************************************************************/
82 /* Subroutines working with struct Function */
83 /*****************************************************************************/
87 static Function* NewFunction (struct SymEntry* Sym)
88 /* Create a new function activation structure and return it */
90 /* Allocate a new structure */
91 Function* F = (Function*) xmalloc (sizeof (Function));
93 /* Initialize the fields */
95 F->ReturnType = GetFuncReturn (Sym->Type);
96 F->Desc = GetFuncDesc (Sym->Type);
98 F->RetLab = GetLocalLabel ();
100 F->RegOffs = RegisterSpace;
102 /* Return the new structure */
108 static void FreeFunction (Function* F)
109 /* Free a function activation structure */
116 const char* F_GetFuncName (const Function* F)
117 /* Return the name of the current function */
119 return F->FuncEntry->Name;
124 unsigned F_GetParamCount (const Function* F)
125 /* Return the parameter count for the current function */
127 return F->Desc->ParamCount;
132 unsigned F_GetParamSize (const Function* F)
133 /* Return the parameter size for the current function */
135 return F->Desc->ParamSize;
140 Type* F_GetReturnType (Function* F)
141 /* Get the return type for the function */
143 return F->ReturnType;
148 int F_HasVoidReturn (const Function* F)
149 /* Return true if the function does not have a return value */
151 return IsTypeVoid (F->ReturnType);
156 int F_IsVariadic (const Function* F)
157 /* Return true if this is a variadic function */
159 return (F->Desc->Flags & FD_VARIADIC) != 0;
164 int F_IsOldStyle (const Function* F)
165 /* Return true if this is an old style (K&R) function */
167 return (F->Desc->Flags & FD_OLDSTYLE) != 0;
172 int F_HasOldStyleIntRet (const Function* F)
173 /* Return true if this is an old style (K&R) function with an implicit int return */
175 return (F->Desc->Flags & FD_OLDSTYLE_INTRET) != 0;
180 unsigned F_GetRetLab (const Function* F)
181 /* Return the return jump label */
188 int F_GetTopLevelSP (const Function* F)
189 /* Get the value of the stack pointer on function top level */
191 return F->TopLevelSP;
196 int F_ReserveLocalSpace (Function* F, unsigned Size)
197 /* Reserve (but don't allocate) the given local space and return the stack
202 return StackPtr - F->Reserved;
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.
212 if (F->Reserved > 0) {
214 /* Create space on the stack */
215 g_space (F->Reserved);
217 /* Correct the stack pointer */
218 StackPtr -= F->Reserved;
220 /* Nothing more reserved */
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.
233 /* Allow register variables only on top level and if enabled */
234 if (IS_Get (&EnableRegVars) && GetLexicalLevel () == LEX_LEVEL_FUNCTION) {
236 /* Get the size of the variable */
237 unsigned Size = CheckedSizeOf (Type);
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.
250 /* No space left or no allocation */
256 static void F_RestoreRegVars (Function* F)
257 /* Restore the register variables for the local function if there are any. */
261 /* If we don't have register variables in this function, bail out early */
262 if (F->RegOffs == RegisterSpace) {
266 /* Save the accumulator if needed */
267 if (!F_HasVoidReturn (F)) {
268 g_save (CF_CHAR | CF_FORCECHAR);
271 /* Get the first symbol from the function symbol table */
272 Sym = F->FuncEntry->V.F.Func->SymTab->SymHead;
274 /* Walk through all symbols checking for register variables */
276 if (SymIsRegVar (Sym)) {
278 /* Check for more than one variable */
279 int Offs = Sym->V.R.SaveOffs;
280 unsigned Bytes = CheckedSizeOf (Sym->Type);
284 /* Find next register variable */
285 const SymEntry* NextSym = Sym->NextSym;
286 while (NextSym && !SymIsRegVar (NextSym)) {
287 NextSym = NextSym->NextSym;
290 /* If we have a next one, compare the stack offsets */
293 /* We have a following register variable. Get the size */
294 int Size = CheckedSizeOf (NextSym->Type);
296 /* Adjacent variable? */
297 if (NextSym->V.R.SaveOffs + Size != Offs) {
302 /* Adjacent variable */
312 /* Restore the memory range */
313 g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
317 /* Check next symbol */
321 /* Restore the accumulator if needed */
322 if (!F_HasVoidReturn (F)) {
323 g_restore (CF_CHAR | CF_FORCECHAR);
329 /*****************************************************************************/
331 /*****************************************************************************/
335 void NewFunc (SymEntry* Func)
336 /* Parse argument declarations and function body. */
341 /* Get the function descriptor from the function entry */
342 FuncDesc* D = Func->V.F.Func;
344 /* Allocate the function activation record for the function */
345 CurrentFunc = NewFunction (Func);
347 /* Reenter the lexical level */
348 ReenterFunctionLevel (D);
350 /* Declare two special functions symbols: __fixargs__ and __argsize__.
351 * The latter is different depending on the type of the function (variadic
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);
361 AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
364 /* Function body now defined */
365 Func->Flags |= SC_DEF;
367 /* Special handling for main() */
368 if (strcmp (Func->Name, "main") == 0) {
369 /* Main cannot be a fastcall function */
370 if (IsQualFastcall (Func->Type)) {
371 Error ("`main' cannot be declared as __fastcall__");
374 /* If cc65 extensions aren't enabled, don't allow a main function that
375 * doesn't return an int.
377 if (IS_Get (&Standard) != STD_CC65 && CurrentFunc->ReturnType[0].C != T_INT) {
378 Error ("`main' must always return an int");
381 /* Add a forced import of a symbol that is contained in the startup
382 * code. This will force the startup code to be linked in.
386 /* If main() takes parameters, generate a forced import to a function
387 * that will setup these parameters. This way, programs that do not
388 * need the additional code will not get it.
390 if (D->ParamCount > 0 || (D->Flags & FD_VARIADIC) != 0) {
395 /* Allocate code and data segments for this function */
396 Func->V.F.Seg = PushSegments (Func);
398 /* If this is a fastcall function, push the last parameter onto the stack */
399 if (IsQualFastcall (Func->Type) && D->ParamCount > 0) {
403 /* Fastcall functions may never have an ellipsis or the compiler is buggy */
404 CHECK ((D->Flags & FD_VARIADIC) == 0);
406 /* Generate the push */
407 if (IsTypeFunc (D->LastParam->Type)) {
408 /* Pointer to function */
411 Flags = TypeOf (D->LastParam->Type) | CF_FORCECHAR;
416 /* Generate function entry code if needed */
417 g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));
419 /* If stack checking code is requested, emit a call to the helper routine */
420 if (IS_Get (&CheckStack)) {
424 /* Setup the stack */
427 /* Walk through the parameter list and allocate register variable space
428 * for parameters declared as register. Generate code to swap the contents
429 * of the register bank with the save area on the stack.
431 Param = D->SymTab->SymHead;
432 while (Param && (Param->Flags & SC_PARAM) != 0) {
434 /* Check for a register variable */
435 if (SymIsRegVar (Param)) {
438 int Reg = F_AllocRegVar (CurrentFunc, Param->Type);
440 /* Could we allocate a register? */
442 /* No register available: Convert parameter to auto */
443 CvtRegVarToAuto (Param);
445 /* Remember the register offset */
446 Param->V.R.RegOffs = Reg;
448 /* Generate swap code */
449 g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type));
455 Param = Param->NextSym;
458 /* Need a starting curly brace */
461 /* Parse local variable declarations if any */
464 /* Remember the current stack pointer. All variables allocated elsewhere
465 * must be dropped when doing a return from an inner block.
467 CurrentFunc->TopLevelSP = StackPtr;
469 /* Now process statements in this block */
471 while (CurTok.Tok != TOK_RCURLY) {
472 if (CurTok.Tok != TOK_CEOF) {
473 HadReturn = Statement (0);
479 /* Output the function exit code label */
480 g_defcodelabel (F_GetRetLab (CurrentFunc));
482 /* Restore the register variables */
483 F_RestoreRegVars (CurrentFunc);
485 /* Generate the exit code */
488 /* Emit references to imports/exports */
491 /* Leave the lexical level */
492 LeaveFunctionLevel ();
494 /* Eat the closing brace */
497 /* Switch back to the old segments */
500 /* Reset the current function pointer */
501 FreeFunction (CurrentFunc);