1 /*****************************************************************************/
5 /* Parse function entry/body/exit */
9 /* (C) 2000-2015, 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 /*****************************************************************************/
58 /*****************************************************************************/
60 /*****************************************************************************/
64 /* Enumeration for function flags */
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 */
72 /* Structure that holds all data needed for function activation */
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 */
84 /* Pointer to current function */
85 Function* CurrentFunc = 0;
89 /*****************************************************************************/
90 /* Subroutines working with struct Function */
91 /*****************************************************************************/
95 static Function* NewFunction (struct SymEntry* Sym)
96 /* Create a new function activation structure and return it */
98 /* Allocate a new structure */
99 Function* F = (Function*) xmalloc (sizeof (Function));
101 /* Initialize the fields */
103 F->ReturnType = GetFuncReturn (Sym->Type);
104 F->Desc = GetFuncDesc (Sym->Type);
106 F->RetLab = GetLocalLabel ();
108 F->RegOffs = RegisterSpace;
109 F->Flags = IsTypeVoid (F->ReturnType) ? FF_VOID_RETURN : FF_NONE;
111 /* Return the new structure */
117 static void FreeFunction (Function* F)
118 /* Free a function activation structure */
125 const char* F_GetFuncName (const Function* F)
126 /* Return the name of the current function */
128 return F->FuncEntry->Name;
133 unsigned F_GetParamCount (const Function* F)
134 /* Return the parameter count for the current function */
136 return F->Desc->ParamCount;
141 unsigned F_GetParamSize (const Function* F)
142 /* Return the parameter size for the current function */
144 return F->Desc->ParamSize;
149 Type* F_GetReturnType (Function* F)
150 /* Get the return type for the function */
152 return F->ReturnType;
157 int F_HasVoidReturn (const Function* F)
158 /* Return true if the function does not have a return value */
160 return (F->Flags & FF_VOID_RETURN) != 0;
165 void F_ReturnFound (Function* F)
166 /* Mark the function as having a return statement */
168 F->Flags |= FF_HAS_RETURN;
173 int F_HasReturn (const Function* F)
174 /* Return true if the function contains a return statement*/
176 return (F->Flags & FF_HAS_RETURN) != 0;
181 int F_IsMainFunc (const Function* F)
182 /* Return true if this is the main function */
184 return (F->Flags & FF_IS_MAIN) != 0;
189 int F_IsVariadic (const Function* F)
190 /* Return true if this is a variadic function */
192 return (F->Desc->Flags & FD_VARIADIC) != 0;
197 int F_IsOldStyle (const Function* F)
198 /* Return true if this is an old style (K&R) function */
200 return (F->Desc->Flags & FD_OLDSTYLE) != 0;
205 int F_HasOldStyleIntRet (const Function* F)
206 /* Return true if this is an old style (K&R) function with an implicit int return */
208 return (F->Desc->Flags & FD_OLDSTYLE_INTRET) != 0;
213 unsigned F_GetRetLab (const Function* F)
214 /* Return the return jump label */
221 int F_GetTopLevelSP (const Function* F)
222 /* Get the value of the stack pointer on function top level */
224 return F->TopLevelSP;
229 int F_ReserveLocalSpace (Function* F, unsigned Size)
230 /* Reserve (but don't allocate) the given local space and return the stack
235 return StackPtr - F->Reserved;
240 int F_GetStackPtr (const Function* F)
241 /* Return the current stack pointer including reserved (but not allocated)
242 ** space on the stack.
245 return StackPtr - F->Reserved;
250 void F_AllocLocalSpace (Function* F)
251 /* Allocate any local space previously reserved. The function will do
252 ** nothing if there is no reserved local space.
255 if (F->Reserved > 0) {
257 /* Create space on the stack */
258 g_space (F->Reserved);
260 /* Correct the stack pointer */
261 StackPtr -= F->Reserved;
263 /* Nothing more reserved */
270 int F_AllocRegVar (Function* F, const Type* Type)
271 /* Allocate a register variable for the given variable type. If the allocation
272 ** was successful, return the offset of the register variable in the register
273 ** bank (zero page storage). If there is no register space left, return -1.
276 /* Allow register variables only on top level and if enabled */
277 if (IS_Get (&EnableRegVars) && GetLexicalLevel () == LEX_LEVEL_FUNCTION) {
279 /* Get the size of the variable */
280 unsigned Size = CheckedSizeOf (Type);
282 /* Do we have space left? */
283 if (F->RegOffs >= Size) {
284 /* Space left. We allocate the variables from high to low addresses,
285 ** so the addressing is compatible with the saved values on stack.
286 ** This allows shorter code when saving/restoring the variables.
293 /* No space left or no allocation */
299 static void F_RestoreRegVars (Function* F)
300 /* Restore the register variables for the local function if there are any. */
304 /* If we don't have register variables in this function, bail out early */
305 if (F->RegOffs == RegisterSpace) {
309 /* Save the accumulator if needed */
310 if (!F_HasVoidReturn (F)) {
311 g_save (CF_CHAR | CF_FORCECHAR);
314 /* Get the first symbol from the function symbol table */
315 Sym = F->FuncEntry->V.F.Func->SymTab->SymHead;
317 /* Walk through all symbols checking for register variables */
319 if (SymIsRegVar (Sym)) {
321 /* Check for more than one variable */
322 int Offs = Sym->V.R.SaveOffs;
323 unsigned Bytes = CheckedSizeOf (Sym->Type);
327 /* Find next register variable */
328 const SymEntry* NextSym = Sym->NextSym;
329 while (NextSym && !SymIsRegVar (NextSym)) {
330 NextSym = NextSym->NextSym;
333 /* If we have a next one, compare the stack offsets */
336 /* We have a following register variable. Get the size */
337 int Size = CheckedSizeOf (NextSym->Type);
339 /* Adjacent variable? */
340 if (NextSym->V.R.SaveOffs + Size != Offs) {
345 /* Adjacent variable */
355 /* Restore the memory range */
356 g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
360 /* Check next symbol */
364 /* Restore the accumulator if needed */
365 if (!F_HasVoidReturn (F)) {
366 g_restore (CF_CHAR | CF_FORCECHAR);
372 static void F_EmitDebugInfo (void)
373 /* Emit debug infos for the current function */
376 /* Get the current function */
377 const SymEntry* Sym = CurrentFunc->FuncEntry;
379 /* Output info for the function itself */
380 AddTextLine ("\t.dbg\tfunc, \"%s\", \"00\", %s, \"%s\"",
382 (Sym->Flags & SC_EXTERN)? "extern" : "static",
389 /*****************************************************************************/
391 /*****************************************************************************/
395 void NewFunc (SymEntry* Func)
396 /* Parse argument declarations and function body. */
398 int C99MainFunc = 0;/* Flag for C99 main function returning int */
401 /* Get the function descriptor from the function entry */
402 FuncDesc* D = Func->V.F.Func;
404 /* Allocate the function activation record for the function */
405 CurrentFunc = NewFunction (Func);
407 /* Reenter the lexical level */
408 ReenterFunctionLevel (D);
410 /* Check if the function header contains unnamed parameters. These are
411 ** only allowed in cc65 mode.
413 if ((D->Flags & FD_UNNAMED_PARAMS) != 0 && (IS_Get (&Standard) != STD_CC65)) {
414 Error ("Parameter name omitted");
417 /* Declare two special functions symbols: __fixargs__ and __argsize__.
418 ** The latter is different depending on the type of the function (variadic
421 AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize);
422 if (D->Flags & FD_VARIADIC) {
423 /* Variadic function. The variable must be const. */
424 static const Type T[] = { TYPE(T_UCHAR | T_QUAL_CONST), TYPE(T_END) };
425 AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0);
428 AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
431 /* Function body now defined */
432 Func->Flags |= SC_DEF;
434 /* Special handling for main() */
435 if (strcmp (Func->Name, "main") == 0) {
437 /* Mark this as the main function */
438 CurrentFunc->Flags |= FF_IS_MAIN;
440 /* Main cannot be a fastcall function */
441 if (IsQualFastcall (Func->Type)) {
442 Error ("`main' cannot be declared as __fastcall__");
445 /* If cc65 extensions aren't enabled, don't allow a main function that
446 ** doesn't return an int.
448 if (IS_Get (&Standard) != STD_CC65 && CurrentFunc->ReturnType[0].C != T_INT) {
449 Error ("`main' must always return an int");
452 /* Add a forced import of a symbol that is contained in the startup
453 ** code. This will force the startup code to be linked in.
457 /* If main() takes parameters, generate a forced import to a function
458 ** that will setup these parameters. This way, programs that do not
459 ** need the additional code will not get it.
461 if (D->ParamCount > 0 || (D->Flags & FD_VARIADIC) != 0) {
464 /* The start-up code doesn't fast-call main(). */
465 Func->Type->C |= T_QUAL_CDECL;
468 /* Determine if this is a main function in a C99 environment that
471 if (IsTypeInt (F_GetReturnType (CurrentFunc)) &&
472 IS_Get (&Standard) == STD_C99) {
477 /* Allocate code and data segments for this function */
478 Func->V.F.Seg = PushSegments (Func);
480 /* Allocate a new literal pool */
481 PushLiteralPool (Func);
483 /* If this is a fastcall function, push the last parameter onto the stack */
484 if ((D->Flags & FD_VARIADIC) == 0 && D->ParamCount > 0 &&
486 IsQualFastcall (Func->Type) :
487 !IsQualCDecl (Func->Type))) {
490 /* Generate the push */
491 if (IsTypeFunc (D->LastParam->Type)) {
492 /* Pointer to function */
495 Flags = TypeOf (D->LastParam->Type) | CF_FORCECHAR;
500 /* Generate function entry code if needed */
501 g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));
503 /* If stack checking code is requested, emit a call to the helper routine */
504 if (IS_Get (&CheckStack)) {
508 /* Setup the stack */
511 /* Walk through the parameter list and allocate register variable space
512 ** for parameters declared as register. Generate code to swap the contents
513 ** of the register bank with the save area on the stack.
515 Param = D->SymTab->SymHead;
516 while (Param && (Param->Flags & SC_PARAM) != 0) {
518 /* Check for a register variable */
519 if (SymIsRegVar (Param)) {
522 int Reg = F_AllocRegVar (CurrentFunc, Param->Type);
524 /* Could we allocate a register? */
526 /* No register available: Convert parameter to auto */
527 CvtRegVarToAuto (Param);
529 /* Remember the register offset */
530 Param->V.R.RegOffs = Reg;
532 /* Generate swap code */
533 g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type));
538 Param = Param->NextSym;
541 /* Need a starting curly brace */
544 /* Parse local variable declarations if any */
547 /* Remember the current stack pointer. All variables allocated elsewhere
548 ** must be dropped when doing a return from an inner block.
550 CurrentFunc->TopLevelSP = StackPtr;
552 /* Now process statements in this block */
553 while (CurTok.Tok != TOK_RCURLY && CurTok.Tok != TOK_CEOF) {
557 /* If this is not a void function, and not the main function in a C99
558 ** environment returning int, output a warning if we didn't see a return
561 if (!F_HasVoidReturn (CurrentFunc) && !F_HasReturn (CurrentFunc) && !C99MainFunc) {
562 Warning ("Control reaches end of non-void function");
565 /* If this is the main function in a C99 environment returning an int, let
566 ** it always return zero. Note: Actual return statements jump to the return
567 ** label defined below.
568 ** The code is removed by the optimizer if unused.
571 g_getimmed (CF_INT | CF_CONST, 0, 0);
574 /* Output the function exit code label */
575 g_defcodelabel (F_GetRetLab (CurrentFunc));
577 /* Restore the register variables */
578 F_RestoreRegVars (CurrentFunc);
580 /* Generate the exit code */
583 /* Emit references to imports/exports */
586 /* Emit function debug info */
590 /* Leave the lexical level */
591 LeaveFunctionLevel ();
593 /* Eat the closing brace */
596 /* Restore the old literal pool, remembering the one for the function */
597 Func->V.F.LitPool = PopLiteralPool ();
599 /* Switch back to the old segments */
602 /* Reset the current function pointer */
603 FreeFunction (CurrentFunc);