1 /*****************************************************************************/
5 /* Symbol table management for the cc65 C compiler */
9 /* (C) 2000-2011, 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 /*****************************************************************************/
43 #include "debugflag.h"
63 /*****************************************************************************/
65 /*****************************************************************************/
69 /* An empty symbol table */
70 SymTable EmptySymTab = {
79 /* Symbol table sizes */
80 #define SYMTAB_SIZE_GLOBAL 211U
81 #define SYMTAB_SIZE_FUNCTION 29U
82 #define SYMTAB_SIZE_BLOCK 13U
83 #define SYMTAB_SIZE_STRUCT 19U
84 #define SYMTAB_SIZE_LABEL 7U
86 /* The current and root symbol tables */
87 static unsigned LexicalLevel = 0; /* For safety checks */
88 static SymTable* SymTab0 = 0;
89 static SymTable* SymTab = 0;
90 static SymTable* TagTab0 = 0;
91 static SymTable* TagTab = 0;
92 static SymTable* LabelTab = 0;
96 /*****************************************************************************/
98 /*****************************************************************************/
102 static SymTable* NewSymTable (unsigned Size)
103 /* Create and return a symbol table for the given lexical level */
107 /* Allocate memory for the table */
108 SymTable* S = xmalloc (sizeof (SymTable) + (Size-1) * sizeof (SymEntry*));
110 /* Initialize the symbol table structure */
116 for (I = 0; I < Size; ++I) {
120 /* Return the symbol table */
126 static void FreeSymTable (SymTable* S)
127 /* Free the given symbo table including all symbols */
129 /* Free all symbols */
130 SymEntry* Sym = S->SymHead;
132 SymEntry* NextSym = Sym->NextSym;
137 /* Free the table itself */
143 /*****************************************************************************/
144 /* Check symbols in a table */
145 /*****************************************************************************/
149 static void CheckSymTable (SymTable* Tab)
150 /* Check a symbol table for open references, unused symbols ... */
152 SymEntry* Entry = Tab->SymHead;
155 /* Get the storage flags for tne entry */
156 unsigned Flags = Entry->Flags;
158 /* Ignore typedef entries */
159 if (!SymIsTypeDef (Entry)) {
161 /* Check if the symbol is one with storage, and it if it was
162 * defined but not used.
164 if (((Flags & SC_AUTO) || (Flags & SC_STATIC)) && (Flags & SC_EXTERN) == 0) {
165 if (SymIsDef (Entry) && !SymIsRef (Entry) &&
166 !SymHasAttr (Entry, atUnused)) {
167 if (Flags & SC_PARAM) {
168 if (IS_Get (&WarnUnusedParam)) {
169 Warning ("Parameter `%s' is never used", Entry->Name);
172 if (IS_Get (&WarnUnusedVar)) {
173 Warning ("`%s' is defined but never used", Entry->Name);
179 /* If the entry is a label, check if it was defined in the function */
180 if (Flags & SC_LABEL) {
181 if (!SymIsDef (Entry)) {
182 /* Undefined label */
183 Error ("Undefined label: `%s'", Entry->Name);
184 } else if (!SymIsRef (Entry)) {
185 /* Defined but not used */
186 if (IS_Get (&WarnUnusedLabel)) {
187 Warning ("`%s' is defined but never used", Entry->Name);
195 Entry = Entry->NextSym;
201 /*****************************************************************************/
202 /* Handling of lexical levels */
203 /*****************************************************************************/
207 unsigned GetLexicalLevel (void)
208 /* Return the current lexical level */
215 void EnterGlobalLevel (void)
216 /* Enter the program global lexical level */
219 PRECONDITION (++LexicalLevel == LEX_LEVEL_GLOBAL);
221 /* Create and assign the symbol table */
222 SymTab0 = SymTab = NewSymTable (SYMTAB_SIZE_GLOBAL);
224 /* Create and assign the tag table */
225 TagTab0 = TagTab = NewSymTable (SYMTAB_SIZE_GLOBAL);
230 void LeaveGlobalLevel (void)
231 /* Leave the program global lexical level */
234 PRECONDITION (LexicalLevel-- == LEX_LEVEL_GLOBAL);
236 /* Check the tables */
237 CheckSymTable (SymTab0);
239 /* Dump the tables if requested */
241 PrintSymTable (SymTab0, stdout, "Global symbol table");
242 PrintSymTable (TagTab0, stdout, "Global tag table");
245 /* Don't delete the symbol and struct tables! */
252 void EnterFunctionLevel (void)
253 /* Enter function lexical level */
257 /* New lexical level */
260 /* Get a new symbol table and make it current */
261 S = NewSymTable (SYMTAB_SIZE_FUNCTION);
265 /* Get a new tag table and make it current */
266 S = NewSymTable (SYMTAB_SIZE_FUNCTION);
270 /* Create and assign a new label table */
271 LabelTab = NewSymTable (SYMTAB_SIZE_LABEL);
276 void RememberFunctionLevel (struct FuncDesc* F)
277 /* Remember the symbol tables for the level and leave the level without checks */
279 /* Leave the lexical level */
282 /* Remember the tables */
286 /* Don't delete the tables */
287 SymTab = SymTab->PrevTab;
288 TagTab = TagTab->PrevTab;
293 void ReenterFunctionLevel (struct FuncDesc* F)
294 /* Reenter the function lexical level using the existing tables from F */
296 /* New lexical level */
299 /* Make the tables current again */
300 F->SymTab->PrevTab = SymTab;
303 F->TagTab->PrevTab = TagTab;
306 /* Create and assign a new label table */
307 LabelTab = NewSymTable (SYMTAB_SIZE_LABEL);
312 void LeaveFunctionLevel (void)
313 /* Leave function lexical level */
315 /* Leave the lexical level */
318 /* Check the tables */
319 CheckSymTable (SymTab);
320 CheckSymTable (LabelTab);
322 /* Drop the label table if it is empty */
323 if (LabelTab->SymCount == 0) {
324 FreeSymTable (LabelTab);
327 /* Don't delete the tables */
328 SymTab = SymTab->PrevTab;
329 TagTab = TagTab->PrevTab;
335 void EnterBlockLevel (void)
336 /* Enter a nested block in a function */
340 /* New lexical level */
343 /* Get a new symbol table and make it current */
344 S = NewSymTable (SYMTAB_SIZE_BLOCK);
348 /* Get a new tag table and make it current */
349 S = NewSymTable (SYMTAB_SIZE_BLOCK);
356 void LeaveBlockLevel (void)
357 /* Leave a nested block in a function */
359 /* Leave the lexical level */
362 /* Check the tables */
363 CheckSymTable (SymTab);
365 /* Don't delete the tables */
366 SymTab = SymTab->PrevTab;
367 TagTab = TagTab->PrevTab;
372 void EnterStructLevel (void)
373 /* Enter a nested block for a struct definition */
377 /* Get a new symbol table and make it current. Note: Structs and enums
378 * nested in struct scope are NOT local to the struct but visible in the
379 * outside scope. So we will NOT create a new struct or enum table.
381 S = NewSymTable (SYMTAB_SIZE_BLOCK);
388 void LeaveStructLevel (void)
389 /* Leave a nested block for a struct definition */
391 /* Don't delete the table */
392 SymTab = SymTab->PrevTab;
397 /*****************************************************************************/
399 /*****************************************************************************/
403 static SymEntry* FindSymInTable (const SymTable* T, const char* Name, unsigned Hash)
404 /* Search for an entry in one table */
406 /* Get the start of the hash chain */
407 SymEntry* E = T->Tab [Hash % T->Size];
409 /* Compare the name */
410 if (strcmp (E->Name, Name) == 0) {
414 /* Not found, next entry in hash chain */
424 static SymEntry* FindSymInTree (const SymTable* Tab, const char* Name)
425 /* Find the symbol with the given name in the table tree that starts with T */
427 /* Get the hash over the name */
428 unsigned Hash = HashStr (Name);
430 /* Check all symbol tables for the symbol */
432 /* Try to find the symbol in this table */
433 SymEntry* E = FindSymInTable (Tab, Name, Hash);
435 /* Bail out if we found it */
440 /* Repeat the search in the next higher lexical level */
450 SymEntry* FindSym (const char* Name)
451 /* Find the symbol with the given name */
453 return FindSymInTree (SymTab, Name);
458 SymEntry* FindGlobalSym (const char* Name)
459 /* Find the symbol with the given name in the global symbol table only */
461 return FindSymInTable (SymTab0, Name, HashStr (Name));
466 SymEntry* FindLocalSym (const char* Name)
467 /* Find the symbol with the given name in the current symbol table only */
469 return FindSymInTable (SymTab, Name, HashStr (Name));
474 SymEntry* FindTagSym (const char* Name)
475 /* Find the symbol with the given name in the tag table */
477 return FindSymInTree (TagTab, Name);
482 SymEntry* FindStructField (const Type* T, const char* Name)
483 /* Find a struct field in the fields list */
487 /* The given type may actually be a pointer to struct */
492 /* Non-structs do not have any struct fields... */
493 if (IsClassStruct (T)) {
495 /* Get a pointer to the struct/union type */
496 const SymEntry* Struct = GetSymEntry (T);
499 /* Now search in the struct symbol table. Beware: The table may not
502 if (Struct->V.S.SymTab) {
503 Field = FindSymInTable (Struct->V.S.SymTab, Name, HashStr (Name));
512 /*****************************************************************************/
513 /* Add stuff to the symbol table */
514 /*****************************************************************************/
518 static void AddSymEntry (SymTable* T, SymEntry* S)
519 /* Add a symbol to a symbol table */
521 /* Get the hash value for the name */
522 unsigned Hash = HashStr (S->Name) % T->Size;
524 /* Insert the symbol into the list of all symbols in this level */
526 T->SymTail->NextSym = S;
528 S->PrevSym = T->SymTail;
530 if (T->SymHead == 0) {
536 /* Insert the symbol into the hash chain */
537 S->NextHash = T->Tab[Hash];
540 /* Tell the symbol in which table it is */
546 SymEntry* AddStructSym (const char* Name, unsigned Size, SymTable* Tab)
547 /* Add a struct/union entry and return it */
549 /* Do we have an entry with this name already? */
550 SymEntry* Entry = FindSymInTable (TagTab, Name, HashStr (Name));
553 /* We do have an entry. This may be a forward, so check it. */
554 if ((Entry->Flags & SC_STRUCT) == 0) {
555 /* Existing symbol is not a struct */
556 Error ("Symbol `%s' is already different kind", Name);
557 } else if (Size > 0 && Entry->V.S.Size > 0) {
558 /* Both structs are definitions. */
559 Error ("Multiple definition for `%s'", Name);
561 /* Define the struct size if it is given */
563 Entry->V.S.SymTab = Tab;
564 Entry->V.S.Size = Size;
570 /* Create a new entry */
571 Entry = NewSymEntry (Name, SC_STRUCT);
573 /* Set the struct data */
574 Entry->V.S.SymTab = Tab;
575 Entry->V.S.Size = Size;
577 /* Add it to the current table */
578 AddSymEntry (TagTab, Entry);
581 /* Return the entry */
587 SymEntry* AddBitField (const char* Name, unsigned Offs, unsigned BitOffs, unsigned Width)
588 /* Add a bit field to the local symbol table and return the symbol entry */
590 /* Do we have an entry with this name already? */
591 SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
594 /* We have a symbol with this name already */
595 Error ("Multiple definition for `%s'", Name);
599 /* Create a new entry */
600 Entry = NewSymEntry (Name, SC_BITFIELD);
602 /* Set the symbol attributes. Bit-fields are always of type unsigned */
603 Entry->Type = type_uint;
604 Entry->V.B.Offs = Offs;
605 Entry->V.B.BitOffs = BitOffs;
606 Entry->V.B.BitWidth = Width;
608 /* Add the entry to the symbol table */
609 AddSymEntry (SymTab, Entry);
613 /* Return the entry */
619 SymEntry* AddConstSym (const char* Name, const Type* T, unsigned Flags, long Val)
620 /* Add an constant symbol to the symbol table and return it */
622 /* Enums must be inserted in the global symbol table */
623 SymTable* Tab = ((Flags & SC_ENUM) == SC_ENUM)? SymTab0 : SymTab;
625 /* Do we have an entry with this name already? */
626 SymEntry* Entry = FindSymInTable (Tab, Name, HashStr (Name));
628 if ((Entry->Flags & SC_CONST) != SC_CONST) {
629 Error ("Symbol `%s' is already different kind", Name);
631 Error ("Multiple definition for `%s'", Name);
636 /* Create a new entry */
637 Entry = NewSymEntry (Name, Flags);
639 /* Enum values are ints */
640 Entry->Type = TypeDup (T);
642 /* Set the enum data */
643 Entry->V.ConstVal = Val;
645 /* Add the entry to the symbol table */
646 AddSymEntry (Tab, Entry);
648 /* Return the entry */
654 SymEntry* AddLabelSym (const char* Name, unsigned Flags)
655 /* Add a goto label to the label table */
657 /* Do we have an entry with this name already? */
658 SymEntry* Entry = FindSymInTable (LabelTab, Name, HashStr (Name));
661 if (SymIsDef (Entry) && (Flags & SC_DEF) != 0) {
662 /* Trying to define the label more than once */
663 Error ("Label `%s' is defined more than once", Name);
665 Entry->Flags |= Flags;
669 /* Create a new entry */
670 Entry = NewSymEntry (Name, SC_LABEL | Flags);
672 /* Set a new label number */
673 Entry->V.Label = GetLocalLabel ();
675 /* Generate the assembler name of the label */
676 Entry->AsmName = xstrdup (LocalLabelName (Entry->V.Label));
678 /* Add the entry to the label table */
679 AddSymEntry (LabelTab, Entry);
683 /* Return the entry */
689 SymEntry* AddLocalSym (const char* Name, const Type* T, unsigned Flags, int Offs)
690 /* Add a local symbol and return the symbol entry */
692 /* Do we have an entry with this name already? */
693 SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
696 /* We have a symbol with this name already */
697 Error ("Multiple definition for `%s'", Name);
701 /* Create a new entry */
702 Entry = NewSymEntry (Name, Flags);
704 /* Set the symbol attributes */
705 Entry->Type = TypeDup (T);
706 if ((Flags & SC_AUTO) == SC_AUTO) {
707 Entry->V.Offs = Offs;
708 } else if ((Flags & SC_REGISTER) == SC_REGISTER) {
709 Entry->V.R.RegOffs = Offs;
710 Entry->V.R.SaveOffs = StackPtr;
711 } else if ((Flags & SC_EXTERN) == SC_EXTERN) {
712 Entry->V.Label = Offs;
713 } else if ((Flags & SC_STATIC) == SC_STATIC) {
714 /* Generate the assembler name from the label number */
715 Entry->V.Label = Offs;
716 Entry->AsmName = xstrdup (LocalLabelName (Entry->V.Label));
717 } else if ((Flags & SC_STRUCTFIELD) == SC_STRUCTFIELD) {
718 Entry->V.Offs = Offs;
720 Internal ("Invalid flags in AddLocalSym: %04X", Flags);
723 /* Add the entry to the symbol table */
724 AddSymEntry (SymTab, Entry);
728 /* Return the entry */
734 SymEntry* AddGlobalSym (const char* Name, const Type* T, unsigned Flags)
735 /* Add an external or global symbol to the symbol table and return the entry */
737 /* There is some special handling for functions, so check if it is one */
738 int IsFunc = IsTypeFunc (T);
740 /* Functions must be inserted in the global symbol table */
741 SymTable* Tab = IsFunc? SymTab0 : SymTab;
743 /* Do we have an entry with this name already? */
744 SymEntry* Entry = FindSymInTable (Tab, Name, HashStr (Name));
749 /* We have a symbol with this name already */
750 if (Entry->Flags & SC_TYPE) {
751 Error ("Multiple definition for `%s'", Name);
755 /* Get the type string of the existing symbol */
758 /* If we are handling arrays, the old entry or the new entry may be an
759 * incomplete declaration. Accept this, and if the exsting entry is
760 * incomplete, complete it.
762 if (IsTypeArray (T) && IsTypeArray (EType)) {
764 /* Get the array sizes */
765 long Size = GetElementCount (T);
766 long ESize = GetElementCount (EType);
768 if ((Size != UNSPECIFIED && ESize != UNSPECIFIED && Size != ESize) ||
769 TypeCmp (T + 1, EType + 1) < TC_EQUAL) {
770 /* Types not identical: Conflicting types */
771 Error ("Conflicting types for `%s'", Name);
774 /* Check if we have a size in the existing definition */
775 if (ESize == UNSPECIFIED) {
776 /* Existing, size not given, use size from new def */
777 SetElementCount (EType, Size);
782 /* New type must be identical */
783 if (TypeCmp (EType, T) < TC_EQUAL) {
784 Error ("Conflicting types for `%s'", Name);
788 /* In case of a function, use the new type descriptor, since it
789 * contains pointers to the new symbol tables that are needed if
790 * an actual function definition follows. Be sure not to use the
791 * new descriptor if it contains a function declaration with an
792 * empty parameter list.
795 /* Get the function descriptor from the new type */
796 FuncDesc* F = GetFuncDesc (T);
797 /* Use this new function descriptor if it doesn't contain
798 * an empty parameter list.
800 if ((F->Flags & FD_EMPTY) == 0) {
802 SetFuncDesc (EType, F);
807 /* Add the new flags */
808 Entry->Flags |= Flags;
814 /* Create a new entry */
815 Entry = NewSymEntry (Name, Flags);
817 /* Set the symbol attributes */
818 Entry->Type = TypeDup (T);
820 /* If this is a function, set the function descriptor and clear
824 Entry->V.F.Func = GetFuncDesc (Entry->Type);
828 /* Add the assembler name of the symbol */
830 Entry->AsmName = xmalloc (Len + 2);
831 Entry->AsmName[0] = '_';
832 memcpy (Entry->AsmName+1, Name, Len+1);
834 /* Add the entry to the symbol table */
835 AddSymEntry (Tab, Entry);
838 /* Return the entry */
844 /*****************************************************************************/
846 /*****************************************************************************/
850 SymTable* GetSymTab (void)
851 /* Return the current symbol table */
858 SymTable* GetGlobalSymTab (void)
859 /* Return the global symbol table */
866 int SymIsLocal (SymEntry* Sym)
867 /* Return true if the symbol is defined in the highest lexical level */
869 return (Sym->Owner == SymTab || Sym->Owner == TagTab);
874 void MakeZPSym (const char* Name)
875 /* Mark the given symbol as zero page symbol */
877 /* Get the symbol table entry */
878 SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
880 /* Mark the symbol as zeropage */
882 Entry->Flags |= SC_ZEROPAGE;
884 Error ("Undefined symbol: `%s'", Name);
890 void PrintSymTable (const SymTable* Tab, FILE* F, const char* Header, ...)
891 /* Write the symbol table to the given file */
894 const SymEntry* Entry;
896 /* Print the header */
898 va_start (ap, Header);
900 Len = vfprintf (F, Header, ap);
904 /* Underline the header */
911 Entry = Tab->SymHead;
913 fprintf (F, "(empty)\n");
916 DumpSymEntry (F, Entry);
917 Entry = Entry->NextSym;
920 fprintf (F, "\n\n\n");
925 void EmitExternals (void)
926 /* Write import/export statements for external symbols */
930 Entry = SymTab->SymHead;
932 unsigned Flags = Entry->Flags;
933 if (Flags & SC_EXTERN) {
934 /* Only defined or referenced externs */
935 if (SymIsRef (Entry) && !SymIsDef (Entry)) {
937 g_defimport (Entry->Name, Flags & SC_ZEROPAGE);
938 } else if (SymIsDef (Entry)) {
940 g_defexport (Entry->Name, Flags & SC_ZEROPAGE);
943 Entry = Entry->NextSym;
949 void EmitDebugInfo (void)
950 /* Emit debug infos for the locals of the current scope */
955 /* Output info for locals if enabled */
957 /* For cosmetic reasons in the output file, we will insert two tabs
958 * on global level and just one on local level.
960 if (LexicalLevel == LEX_LEVEL_GLOBAL) {
961 Head = "\t.dbg\t\tsym";
963 Head = "\t.dbg\tsym";
965 Sym = SymTab->SymHead;
967 if ((Sym->Flags & (SC_CONST|SC_TYPE)) == 0) {
968 if (Sym->Flags & SC_AUTO) {
969 AddTextLine ("%s, \"%s\", \"00\", auto, %d",
970 Head, Sym->Name, Sym->V.Offs);
971 } else if (Sym->Flags & SC_REGISTER) {
972 AddTextLine ("%s, \"%s\", \"00\", register, \"regbank\", %d",
973 Head, Sym->Name, Sym->V.R.RegOffs);
975 } else if (SymIsRef (Sym) && !SymIsDef (Sym)) {
976 AddTextLine ("%s, \"%s\", \"00\", %s, \"%s\"",
978 (Sym->Flags & SC_EXTERN)? "extern" : "static",