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 /* Pointer to current function */
65 Function* CurrentFunc = 0;
69 /*****************************************************************************/
70 /* Subroutines working with struct Function */
71 /*****************************************************************************/
75 static Function* NewFunction (struct SymEntry* Sym)
76 /* Create a new function activation structure and return it */
78 /* Allocate a new structure */
79 Function* F = (Function*) xmalloc (sizeof (Function));
81 /* Initialize the fields */
83 F->ReturnType = GetFuncReturn (Sym->Type);
84 F->Desc = GetFuncDesc (Sym->Type);
86 F->RetLab = GetLocalLabel ();
88 F->RegOffs = RegisterSpace;
89 F->Flags = IsTypeVoid (F->ReturnType) ? FF_VOID_RETURN : FF_NONE;
91 InitCollection (&F->LocalsBlockStack);
93 /* Return the new structure */
99 static void FreeFunction (Function* F)
100 /* Free a function activation structure */
102 DoneCollection (&F->LocalsBlockStack);
108 const char* F_GetFuncName (const Function* F)
109 /* Return the name of the current function */
111 return F->FuncEntry->Name;
116 unsigned F_GetParamCount (const Function* F)
117 /* Return the parameter count for the current function */
119 return F->Desc->ParamCount;
124 unsigned F_GetParamSize (const Function* F)
125 /* Return the parameter size for the current function */
127 return F->Desc->ParamSize;
132 Type* F_GetReturnType (Function* F)
133 /* Get the return type for the function */
135 return F->ReturnType;
140 int F_HasVoidReturn (const Function* F)
141 /* Return true if the function does not have a return value */
143 return (F->Flags & FF_VOID_RETURN) != 0;
148 void F_ReturnFound (Function* F)
149 /* Mark the function as having a return statement */
151 F->Flags |= FF_HAS_RETURN;
156 int F_HasReturn (const Function* F)
157 /* Return true if the function contains a return statement*/
159 return (F->Flags & FF_HAS_RETURN) != 0;
164 int F_IsMainFunc (const Function* F)
165 /* Return true if this is the main function */
167 return (F->Flags & FF_IS_MAIN) != 0;
172 int F_IsVariadic (const Function* F)
173 /* Return true if this is a variadic function */
175 return (F->Desc->Flags & FD_VARIADIC) != 0;
180 int F_IsOldStyle (const Function* F)
181 /* Return true if this is an old style (K&R) function */
183 return (F->Desc->Flags & FD_OLDSTYLE) != 0;
188 int F_HasOldStyleIntRet (const Function* F)
189 /* Return true if this is an old style (K&R) function with an implicit int return */
191 return (F->Desc->Flags & FD_OLDSTYLE_INTRET) != 0;
196 unsigned F_GetRetLab (const Function* F)
197 /* Return the return jump label */
204 int F_GetTopLevelSP (const Function* F)
205 /* Get the value of the stack pointer on function top level */
207 return F->TopLevelSP;
212 int F_ReserveLocalSpace (Function* F, unsigned Size)
213 /* Reserve (but don't allocate) the given local space and return the stack
218 return StackPtr - F->Reserved;
223 int F_GetStackPtr (const Function* F)
224 /* Return the current stack pointer including reserved (but not allocated)
225 ** space on the stack.
228 return StackPtr - F->Reserved;
233 void F_AllocLocalSpace (Function* F)
234 /* Allocate any local space previously reserved. The function will do
235 ** nothing if there is no reserved local space.
238 if (F->Reserved > 0) {
240 /* Create space on the stack */
241 g_space (F->Reserved);
243 /* Correct the stack pointer */
244 StackPtr -= F->Reserved;
246 /* Nothing more reserved */
253 int F_AllocRegVar (Function* F, const Type* Type)
254 /* Allocate a register variable for the given variable type. If the allocation
255 ** was successful, return the offset of the register variable in the register
256 ** bank (zero page storage). If there is no register space left, return -1.
259 /* Allow register variables only on top level and if enabled */
260 if (IS_Get (&EnableRegVars) && GetLexicalLevel () == LEX_LEVEL_FUNCTION) {
262 /* Get the size of the variable */
263 unsigned Size = CheckedSizeOf (Type);
265 /* Do we have space left? */
266 if (F->RegOffs >= Size) {
267 /* Space left. We allocate the variables from high to low addresses,
268 ** so the addressing is compatible with the saved values on stack.
269 ** This allows shorter code when saving/restoring the variables.
276 /* No space left or no allocation */
282 static void F_RestoreRegVars (Function* F)
283 /* Restore the register variables for the local function if there are any. */
287 /* If we don't have register variables in this function, bail out early */
288 if (F->RegOffs == RegisterSpace) {
292 /* Save the accumulator if needed */
293 if (!F_HasVoidReturn (F)) {
294 g_save (CF_CHAR | CF_FORCECHAR);
297 /* Get the first symbol from the function symbol table */
298 Sym = F->FuncEntry->V.F.Func->SymTab->SymHead;
300 /* Walk through all symbols checking for register variables */
302 if (SymIsRegVar (Sym)) {
304 /* Check for more than one variable */
305 int Offs = Sym->V.R.SaveOffs;
306 unsigned Bytes = CheckedSizeOf (Sym->Type);
310 /* Find next register variable */
311 const SymEntry* NextSym = Sym->NextSym;
312 while (NextSym && !SymIsRegVar (NextSym)) {
313 NextSym = NextSym->NextSym;
316 /* If we have a next one, compare the stack offsets */
319 /* We have a following register variable. Get the size */
320 int Size = CheckedSizeOf (NextSym->Type);
322 /* Adjacent variable? */
323 if (NextSym->V.R.SaveOffs + Size != Offs) {
328 /* Adjacent variable */
338 /* Restore the memory range */
339 g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
343 /* Check next symbol */
347 /* Restore the accumulator if needed */
348 if (!F_HasVoidReturn (F)) {
349 g_restore (CF_CHAR | CF_FORCECHAR);
355 static void F_EmitDebugInfo (void)
356 /* Emit debug infos for the current function */
359 /* Get the current function */
360 const SymEntry* Sym = CurrentFunc->FuncEntry;
362 /* Output info for the function itself */
363 AddTextLine ("\t.dbg\tfunc, \"%s\", \"00\", %s, \"%s\"",
365 (Sym->Flags & SC_EXTERN)? "extern" : "static",
372 /*****************************************************************************/
374 /*****************************************************************************/
378 void NewFunc (SymEntry* Func)
379 /* Parse argument declarations and function body. */
381 int C99MainFunc = 0;/* Flag for C99 main function returning int */
384 /* Get the function descriptor from the function entry */
385 FuncDesc* D = Func->V.F.Func;
387 /* Allocate the function activation record for the function */
388 CurrentFunc = NewFunction (Func);
390 /* Reenter the lexical level */
391 ReenterFunctionLevel (D);
393 /* Check if the function header contains unnamed parameters. These are
394 ** only allowed in cc65 mode.
396 if ((D->Flags & FD_UNNAMED_PARAMS) != 0 && (IS_Get (&Standard) != STD_CC65)) {
397 Error ("Parameter name omitted");
400 /* Declare two special functions symbols: __fixargs__ and __argsize__.
401 ** The latter is different depending on the type of the function (variadic
404 AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize);
405 if (D->Flags & FD_VARIADIC) {
406 /* Variadic function. The variable must be const. */
407 static const Type T[] = { TYPE(T_UCHAR | T_QUAL_CONST), TYPE(T_END) };
408 AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0);
411 AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
414 /* Function body now defined */
415 Func->Flags |= SC_DEF;
417 /* Special handling for main() */
418 if (strcmp (Func->Name, "main") == 0) {
420 /* Mark this as the main function */
421 CurrentFunc->Flags |= FF_IS_MAIN;
423 /* Main cannot be a fastcall function */
424 if (IsQualFastcall (Func->Type)) {
425 Error ("`main' cannot be declared as __fastcall__");
428 /* If cc65 extensions aren't enabled, don't allow a main function that
429 ** doesn't return an int.
431 if (IS_Get (&Standard) != STD_CC65 && CurrentFunc->ReturnType[0].C != T_INT) {
432 Error ("`main' must always return an int");
435 /* Add a forced import of a symbol that is contained in the startup
436 ** code. This will force the startup code to be linked in.
440 /* If main() takes parameters, generate a forced import to a function
441 ** that will setup these parameters. This way, programs that do not
442 ** need the additional code will not get it.
444 if (D->ParamCount > 0 || (D->Flags & FD_VARIADIC) != 0) {
447 /* The start-up code doesn't fast-call main(). */
448 Func->Type->C |= T_QUAL_CDECL;
451 /* Determine if this is a main function in a C99 environment that
454 if (IsTypeInt (F_GetReturnType (CurrentFunc)) &&
455 IS_Get (&Standard) == STD_C99) {
460 /* Allocate code and data segments for this function */
461 Func->V.F.Seg = PushSegments (Func);
463 /* Allocate a new literal pool */
464 PushLiteralPool (Func);
466 /* If this is a fastcall function, push the last parameter onto the stack */
467 if ((D->Flags & FD_VARIADIC) == 0 && D->ParamCount > 0 &&
469 IsQualFastcall (Func->Type) :
470 !IsQualCDecl (Func->Type))) {
473 /* Generate the push */
474 if (IsTypeFunc (D->LastParam->Type)) {
475 /* Pointer to function */
478 Flags = TypeOf (D->LastParam->Type) | CF_FORCECHAR;
483 /* Generate function entry code if needed */
484 g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));
486 /* If stack checking code is requested, emit a call to the helper routine */
487 if (IS_Get (&CheckStack)) {
491 /* Setup the stack */
494 /* Walk through the parameter list and allocate register variable space
495 ** for parameters declared as register. Generate code to swap the contents
496 ** of the register bank with the save area on the stack.
498 Param = D->SymTab->SymHead;
499 while (Param && (Param->Flags & SC_PARAM) != 0) {
501 /* Check for a register variable */
502 if (SymIsRegVar (Param)) {
505 int Reg = F_AllocRegVar (CurrentFunc, Param->Type);
507 /* Could we allocate a register? */
509 /* No register available: Convert parameter to auto */
510 CvtRegVarToAuto (Param);
512 /* Remember the register offset */
513 Param->V.R.RegOffs = Reg;
515 /* Generate swap code */
516 g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type));
521 Param = Param->NextSym;
524 /* Need a starting curly brace */
527 /* Make sure there is always something on the stack of local variable blocks */
528 CollAppend (&CurrentFunc->LocalsBlockStack, 0);
530 /* Parse local variable declarations if any */
533 /* Remember the current stack pointer. All variables allocated elsewhere
534 ** must be dropped when doing a return from an inner block.
536 CurrentFunc->TopLevelSP = StackPtr;
538 /* Now process statements in this block */
539 while (CurTok.Tok != TOK_RCURLY && CurTok.Tok != TOK_CEOF) {
543 /* If this is not a void function, and not the main function in a C99
544 ** environment returning int, output a warning if we didn't see a return
547 if (!F_HasVoidReturn (CurrentFunc) && !F_HasReturn (CurrentFunc) && !C99MainFunc) {
548 Warning ("Control reaches end of non-void function");
551 /* If this is the main function in a C99 environment returning an int, let
552 ** it always return zero. Note: Actual return statements jump to the return
553 ** label defined below.
554 ** The code is removed by the optimizer if unused.
557 g_getimmed (CF_INT | CF_CONST, 0, 0);
560 /* Output the function exit code label */
561 g_defcodelabel (F_GetRetLab (CurrentFunc));
563 /* Restore the register variables */
564 F_RestoreRegVars (CurrentFunc);
566 /* Generate the exit code */
569 /* Emit references to imports/exports */
572 /* Emit function debug info */
576 /* Leave the lexical level */
577 LeaveFunctionLevel ();
579 /* Eat the closing brace */
582 /* Restore the old literal pool, remembering the one for the function */
583 Func->V.F.LitPool = PopLiteralPool ();
585 /* Switch back to the old segments */
588 /* Reset the current function pointer */
589 FreeFunction (CurrentFunc);