* src/pic16/gen.c: fixed bug #1106975,
[fw/sdcc] / src / SDCCsymt.c
1 /*-------------------------------------------------------------------------
2   SDCCsymt.c - Code file for Symbols table related structures and MACRO's.
3         Written By -  Sandeep Dutta . sandeep.dutta@usa.net (1998)
4
5    This program is free software; you can redistribute it and/or modify it
6    under the terms of the GNU General Public License as published by the
7    Free Software Foundation; either version 2, or (at your option) any
8    later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18
19    In other words, you are welcome to use, share and improve this program.
20    You are forbidden to forbid anyone else to use, share and improve
21    what you give them.   Help stamp out software-hoarding!
22 -------------------------------------------------------------------------*/
23
24 #include "common.h"
25 #include "newalloc.h"
26
27 #include "SDCCsymt.h"
28
29 value *aggregateToPointer (value *val);
30 void printTypeChainRaw (sym_link * start, FILE * of);
31
32 void printFromToType(sym_link *from, sym_link *to) {
33   fprintf (stderr, "from type '");
34   printTypeChain (from, stderr);
35   fprintf (stderr, "'\nto type '");
36   printTypeChain (to, stderr);
37   fprintf (stderr, "'\n");
38 }
39
40 /* noun strings */
41 char *nounName(sym_link *sl) {
42   switch (SPEC_NOUN(sl)) 
43     {
44     case V_INT: {
45       if (SPEC_LONG(sl)) return "long";
46       if (sl->select.s._short) return "short";
47       return "int";
48     }
49     case V_FLOAT: return "float";
50     case V_CHAR: return "char";
51     case V_VOID: return "void";
52     case V_STRUCT: return "struct";
53     case V_LABEL: return "label";
54     case V_BITFIELD: return "bitfield";
55     case V_BIT: return "bit";
56     case V_SBIT: return "sbit";
57     case V_DOUBLE: return "double";
58     }
59   return "unknown";
60 };
61
62 bucket *SymbolTab[256];         /* the symbol    table  */
63 bucket *StructTab[256];         /* the structure table  */
64 bucket *TypedefTab[256];        /* the typedef   table  */
65 bucket *LabelTab[256];          /* the Label     table  */
66 bucket *enumTab[256];           /* enumerated    table  */
67
68 /*------------------------------------------------------------------*/
69 /* initSymt () - initialises symbol table related stuff             */
70 /*------------------------------------------------------------------*/
71 void 
72 initSymt ()
73 {
74   int i = 0;
75
76   for (i = 0; i < 256; i++)
77     SymbolTab[i] = StructTab[i] = (void *) NULL;
78
79
80 }
81 /*-----------------------------------------------------------------*/
82 /* newBucket - allocates & returns a new bucket        */
83 /*-----------------------------------------------------------------*/
84 bucket *
85 newBucket ()
86 {
87   bucket *bp;
88
89   bp = Safe_alloc ( sizeof (bucket));
90
91   return bp;
92 }
93
94 /*-----------------------------------------------------------------*/
95 /* hashKey - computes the hashkey given a symbol name              */
96 /*-----------------------------------------------------------------*/
97 int 
98 hashKey (const char *s)
99 {
100   unsigned long key = 0;
101
102   while (*s)
103     key += *s++;
104   return key % 256;
105 }
106
107 /*-----------------------------------------------------------------*/
108 /* addSym - adds a symbol to the hash Table                        */
109 /*-----------------------------------------------------------------*/
110 void 
111 addSym (bucket ** stab,
112         void *sym,
113         char *sname,
114         int level,
115         int block,
116         int checkType)
117 {
118   int i;                        /* index into the hash Table */
119   bucket *bp;                   /* temp bucket    *         */
120
121   if (checkType) {
122     symbol *csym = (symbol *)sym;
123
124     if (getenv("DEBUG_SANITY")) {
125       fprintf (stderr, "addSym: %s ", sname);
126     }
127     /* make sure the type is complete and sane */
128     checkTypeSanity(csym->etype, csym->name);
129   }
130
131   /* prevent overflow of the (r)name buffers */
132   if (strlen(sname)>SDCC_SYMNAME_MAX) {
133     werror (W_SYMBOL_NAME_TOO_LONG, SDCC_SYMNAME_MAX);
134     sname[SDCC_SYMNAME_MAX]='\0';
135   }
136
137   /* the symbols are always added at the head of the list  */
138   i = hashKey (sname);
139   /* get a free entry */
140   bp = Safe_alloc ( sizeof (bucket));
141
142   bp->sym = sym;                /* update the symbol pointer  */
143   bp->level = level;            /* update the nest level      */
144   bp->block = block;
145   strncpyz (bp->name, sname, sizeof(bp->name)); /* copy the name into place */
146
147   /* if this is the first entry */
148   if (stab[i] == NULL)
149     {
150       bp->prev = bp->next = (void *) NULL;      /* point to nothing */
151       stab[i] = bp;
152     }
153   /* not first entry then add @ head of list */
154   else
155     {
156       bp->prev = NULL;
157       stab[i]->prev = bp;
158       bp->next = stab[i];
159       stab[i] = bp;
160     }
161 }
162
163 /*-----------------------------------------------------------------*/
164 /* deleteSym - deletes a symbol from the hash Table  entry     */
165 /*-----------------------------------------------------------------*/
166 void 
167 deleteSym (bucket ** stab, void *sym, char *sname)
168 {
169   int i = 0;
170   bucket *bp;
171
172   i = hashKey (sname);
173
174   bp = stab[i];
175   /* find the symbol */
176   while (bp)
177     {
178       if (bp->sym == sym)       /* found it then break out */
179         break;                  /* of the loop       */
180       bp = bp->next;
181     }
182
183   if (!bp)                      /* did not find it */
184     return;
185   /* if this is the first one in the chain */
186   if (!bp->prev)
187     {
188       stab[i] = bp->next;
189       if (stab[i])              /* if chain ! empty */
190         stab[i]->prev = (void *) NULL;
191     }
192   /* middle || end of chain */
193   else
194     {
195       if (bp->next)             /* if not end of chain */
196         bp->next->prev = bp->prev;
197
198       bp->prev->next = bp->next;
199     }
200
201 }
202
203 /*-----------------------------------------------------------------*/
204 /* findSym - finds a symbol in a table           */
205 /*-----------------------------------------------------------------*/
206 void *
207 findSym (bucket ** stab, void *sym, const char *sname)
208 {
209   bucket *bp;
210
211   bp = stab[hashKey (sname)];
212   while (bp)
213     {
214       if (bp->sym == sym || strcmp (bp->name, sname) == 0)
215         break;
216       bp = bp->next;
217     }
218
219   return (bp ? bp->sym : (void *) NULL);
220 }
221
222 /*-----------------------------------------------------------------*/
223 /* findSymWithLevel - finds a symbol with a name & level           */
224 /*-----------------------------------------------------------------*/
225 void *
226 findSymWithLevel (bucket ** stab, symbol * sym)
227 {
228   bucket *bp;
229
230   bp = stab[hashKey (sym->name)];
231
232   /**
233    **  do the search from the head of the list since the
234    **  elements are added at the head it is ensured that
235    ** we will find the deeper definitions before we find
236    ** the global ones. we need to check for symbols with
237    ** level <= to the level given, if levels match then block
238    ** numbers need to match as well
239    **/
240   while (bp)
241     {
242       if (strcmp (bp->name, sym->name) == 0 && bp->level <= sym->level)
243         {
244           /* if this is parameter then nothing else need to be checked */
245           if (((symbol *) (bp->sym))->_isparm)
246             return (bp->sym);
247           /* if levels match then block numbers should also match */
248           if (bp->level && bp->level == sym->level && bp->block == sym->block)
249             return (bp->sym);
250           /* if levels don't match then we are okay */
251           if (bp->level && bp->level != sym->level && bp->block <= sym->block)
252             return (bp->sym);
253           /* if this is a global variable then we are ok too */
254           if (bp->level == 0)
255             return (bp->sym);
256         }
257
258       bp = bp->next;
259     }
260
261   return (void *) NULL;
262 }
263
264 /*-----------------------------------------------------------------*/
265 /* findSymWithBlock - finds a symbol with name in with a block     */
266 /*-----------------------------------------------------------------*/
267 void *
268 findSymWithBlock (bucket ** stab, symbol * sym, int block)
269 {
270   bucket *bp;
271
272   bp = stab[hashKey (sym->name)];
273   while (bp)
274     {
275       if (strcmp (bp->name, sym->name) == 0 &&
276           bp->block <= block)
277         break;
278       bp = bp->next;
279     }
280
281   return (bp ? bp->sym : (void *) NULL);
282 }
283
284 /*------------------------------------------------------------------*/
285 /* newSymbol () - returns a new pointer to a symbol                 */
286 /*------------------------------------------------------------------*/
287 symbol *
288 newSymbol (char *name, int scope)
289 {
290   symbol *sym;
291
292   sym = Safe_alloc ( sizeof (symbol));
293
294   strncpyz (sym->name, name, sizeof(sym->name));        /* copy the name */
295   sym->level = scope;           /* set the level    */
296   sym->block = currBlockno;
297   sym->lineDef = mylineno;      /* set the line number */
298   sym->fileDef = currFname;
299   return sym;
300 }
301
302 /*------------------------------------------------------------------*/
303 /* newLink - creates a new link (declarator,specifier)              */
304 /*------------------------------------------------------------------*/
305 sym_link *
306 newLink (SYM_LINK_CLASS select)
307 {
308   sym_link *p;
309
310   p = Safe_alloc ( sizeof (sym_link));
311   p->class=select;
312
313   return p;
314 }
315
316 /*------------------------------------------------------------------*/
317 /* newStruct - creats a new structdef from the free list            */
318 /*------------------------------------------------------------------*/
319 structdef *
320 newStruct (char *tag)
321 {
322   structdef *s;
323
324   s = Safe_alloc ( sizeof (structdef));
325
326   strncpyz (s->tag, tag, sizeof(s->tag));               /* copy the tag */
327   return s;
328 }
329   
330 /*------------------------------------------------------------------*/
331 /* sclsFromPtr - Return the storage class a pointer points into.    */
332 /*               S_FIXED is returned for generic pointers or other  */
333 /*               unexpected cases                                   */
334 /*------------------------------------------------------------------*/
335 STORAGE_CLASS
336 sclsFromPtr(sym_link *ptr)
337 {
338   switch (DCL_TYPE (ptr))
339     {
340     case POINTER:
341       return S_DATA;
342     case GPOINTER:
343       return S_FIXED;
344     case FPOINTER:
345       return S_XDATA;
346     case CPOINTER:
347       return S_CODE;
348     case IPOINTER:
349       return S_IDATA;
350     case PPOINTER:
351       return S_PDATA;
352     case EEPPOINTER:
353       return S_EEPROM;
354     case FUNCTION:
355       return S_CODE;
356     default:
357       return S_FIXED;
358     }
359 }
360
361 /*------------------------------------------------------------------*/
362 /* pointerTypes - do the computation for the pointer types          */
363 /*------------------------------------------------------------------*/
364 void 
365 pointerTypes (sym_link * ptr, sym_link * type)
366 {
367   if (IS_SPEC (ptr))
368     return;
369
370   /* find the first pointer type */
371   while (ptr && !IS_PTR (ptr))
372     ptr = ptr->next;
373
374   /* could not find it */
375   if (!ptr || IS_SPEC (ptr))
376     return;
377   
378   if (IS_PTR(ptr) && DCL_TYPE(ptr)!=UPOINTER) {
379     pointerTypes (ptr->next, type);
380     return;
381   }
382
383   /* change the pointer type depending on the
384      storage class of the type */
385   if (IS_SPEC (type))
386     {
387       switch (SPEC_SCLS (type))
388         {
389         case S_XDATA:
390           DCL_TYPE (ptr) = FPOINTER;
391           break;
392         case S_IDATA:
393           DCL_TYPE (ptr) = IPOINTER;
394           break;
395         case S_PDATA:
396           DCL_TYPE (ptr) = PPOINTER;
397           break;
398         case S_DATA:
399           DCL_TYPE (ptr) = POINTER;
400           break;
401         case S_CODE:
402           DCL_TYPE (ptr) = CPOINTER;
403           break;
404         case S_EEPROM:
405           DCL_TYPE (ptr) = EEPPOINTER;
406           break;
407         default:
408           DCL_TYPE (ptr) = port->unqualified_pointer;
409           break;
410         }
411       /* the storage class of type ends here */
412       SPEC_SCLS (type) = 0;
413     }
414
415   /* now change all the remaining unknown pointers
416      to generic pointers */
417   while (ptr)
418     {
419       if (!IS_SPEC (ptr) && DCL_TYPE (ptr) == UPOINTER)
420         DCL_TYPE (ptr) = port->unqualified_pointer;
421       ptr = ptr->next;
422     }
423
424   /* same for the type although it is highly unlikely that
425      type will have a pointer */
426   while (type)
427     {
428       if (!IS_SPEC (type) && DCL_TYPE (type) == UPOINTER)
429         DCL_TYPE (type) = port->unqualified_pointer;
430       type = type->next;
431     }
432 }
433
434 /*------------------------------------------------------------------*/
435 /* addDecl - adds a declarator @ the end of a chain                 */
436 /*------------------------------------------------------------------*/
437 void 
438 addDecl (symbol * sym, int type, sym_link * p)
439 {
440   sym_link *head;
441   sym_link *tail;
442   sym_link *t;
443
444   if (getenv("SDCC_DEBUG_FUNCTION_POINTERS"))
445     fprintf (stderr, "SDCCsymt.c:addDecl(%s,%d,%p)\n", sym->name, type, p);
446
447   /* if we are passed a link then set head & tail */
448   if (p)
449     {
450       tail = head = p;
451       while (tail->next)
452         tail = tail->next;
453     }
454   else
455     {
456       head = tail = newLink (DECLARATOR);
457       DCL_TYPE (head) = type;
458     }
459
460   /* if this is the first entry   */
461   if (!sym->type)
462     {
463       sym->type = head;
464       sym->etype = tail;
465     }
466   else
467     {
468       if (IS_SPEC (sym->etype) && IS_SPEC (head) && head == tail)
469         {
470           sym->etype = mergeSpec (sym->etype, head, sym->name);
471         }
472       else
473         {
474           if (IS_SPEC (sym->etype) && !IS_SPEC (head) && head == tail)
475             {
476               t = sym->type;
477               while (t->next != sym->etype)
478                 t = t->next;
479               t->next = head;
480               tail->next = sym->etype;
481             }
482           else
483             {
484               sym->etype->next = head;
485               sym->etype = tail;
486             }
487         }
488     }
489
490   /* if the type is an unknown pointer and has
491      a tspec then take the storage class const & volatile
492      attribute from the tspec & make it those of this
493      symbol */
494   if (p &&
495       !IS_SPEC (p) &&
496       //DCL_TYPE (p) == UPOINTER &&
497       DCL_TSPEC (p))
498     {
499       if (!IS_SPEC (sym->etype))
500         {
501           sym->etype = sym->etype->next = newLink (SPECIFIER);
502         }
503       SPEC_SCLS (sym->etype) = SPEC_SCLS (DCL_TSPEC (p));
504       DCL_TSPEC (p) = NULL;
505     }
506
507   // if there is a function in this type chain
508   if (p && funcInChain(sym->type)) {
509     processFuncArgs (sym);
510   }
511
512   return;
513 }
514
515 /*------------------------------------------------------------------
516   checkTypeSanity: prevent the user from doing e.g.:
517   unsigned float uf;
518   ------------------------------------------------------------------*/
519 void checkTypeSanity(sym_link *etype, char *name) {
520   char *noun;
521
522   if (!etype) {
523     if (getenv("DEBUG_SANITY")) {
524       fprintf (stderr, "sanity check skipped for %s (etype==0)\n", name);
525     }
526     return;
527   }
528
529   if (!IS_SPEC(etype)) {
530     if (getenv("DEBUG_SANITY")) {
531       fprintf (stderr, "sanity check skipped for %s (!IS_SPEC)\n", name);
532     }
533     return;
534   }
535
536   noun=nounName(etype);
537
538   if (getenv("DEBUG_SANITY")) {
539     fprintf (stderr, "checking sanity for %s %p\n", name, etype);
540   }
541
542   if ((SPEC_NOUN(etype)==V_CHAR || 
543        SPEC_NOUN(etype)==V_FLOAT || 
544        SPEC_NOUN(etype)==V_DOUBLE || 
545        SPEC_NOUN(etype)==V_VOID) &&
546       (etype->select.s._short || SPEC_LONG(etype))) {
547     // long or short for char float double or void
548     werror (E_LONG_OR_SHORT_INVALID, noun, name);
549   }
550   if ((SPEC_NOUN(etype)==V_FLOAT || 
551        SPEC_NOUN(etype)==V_DOUBLE || 
552        SPEC_NOUN(etype)==V_VOID) && 
553       (etype->select.s._signed || SPEC_USIGN(etype))) {
554     // signed or unsigned for float double or void
555     werror (E_SIGNED_OR_UNSIGNED_INVALID, noun, name);
556   }
557
558   // special case for "short"
559   if (etype->select.s._short) {
560     SPEC_NOUN(etype) = options.shortis8bits ? V_CHAR : V_INT;
561     etype->select.s._short = 0;
562   }
563
564   /* if no noun e.g. 
565      "const a;" or "data b;" or "signed s" or "long l"
566      assume an int */
567   if (!SPEC_NOUN(etype)) {
568     SPEC_NOUN(etype)=V_INT;
569   }
570
571   /* ISO/IEC 9899 J.3.9 implementation defined behaviour: */
572   /* a "plain" int bitfield is unsigned */
573   if (SPEC_NOUN(etype)==V_BIT ||
574       SPEC_NOUN(etype)==V_SBIT) {
575     if (!etype->select.s._signed)
576       SPEC_USIGN(etype) = 1;
577   }
578
579   if (etype->select.s._signed && SPEC_USIGN(etype)) {
580     // signed AND unsigned 
581     werror (E_SIGNED_AND_UNSIGNED_INVALID, noun, name);
582   }
583   if (etype->select.s._short && SPEC_LONG(etype)) {
584     // short AND long
585     werror (E_LONG_AND_SHORT_INVALID, noun, name);
586   }
587
588 }
589
590 /*------------------------------------------------------------------*/
591 /* mergeSpec - merges two specifiers and returns the new one        */
592 /*------------------------------------------------------------------*/
593 sym_link *
594 mergeSpec (sym_link * dest, sym_link * src, char *name)
595 {
596   if (!IS_SPEC(dest) || !IS_SPEC(src)) {
597 #if 0
598     werror (E_INTERNAL_ERROR, __FILE__, __LINE__, "cannot merge declarator");
599     exit (1);
600 #else
601     werror (E_SYNTAX_ERROR, yytext);
602     // the show must go on
603     return newIntLink();
604 #endif
605   }
606
607   if (SPEC_NOUN(src)) {
608     if (!SPEC_NOUN(dest)) {
609       SPEC_NOUN(dest)=SPEC_NOUN(src);
610     } else {
611       /* we shouldn't redeclare the type */
612       if (getenv("DEBUG_SANITY")) {
613         fprintf (stderr, "mergeSpec: ");
614       }
615       werror(E_TWO_OR_MORE_DATA_TYPES, name);
616     }
617   }
618   
619   if (SPEC_SCLS(src)) {
620     /* if destination has no storage class */
621     if (!SPEC_SCLS (dest) || SPEC_SCLS(dest)==S_REGISTER) {
622       SPEC_SCLS (dest) = SPEC_SCLS (src);
623     } else {
624       if (getenv("DEBUG_SANITY")) {
625         fprintf (stderr, "mergeSpec: ");
626       }
627       werror(E_TWO_OR_MORE_STORAGE_CLASSES, name);
628     }
629   }
630
631   /* copy all the specifications  */
632
633   // we really should do: 
634 #if 0
635   if (SPEC_what(src)) {
636     if (SPEC_what(dest)) {
637       werror(W_DUPLICATE_SPEC, "what");
638     }
639     SPEC_what(dst)|=SPEC_what(src);
640   }
641 #endif
642   // but there are more important thing right now
643
644   SPEC_LONG (dest) |= SPEC_LONG (src);
645   dest->select.s._short|=src->select.s._short;
646   SPEC_USIGN (dest) |= SPEC_USIGN (src);
647   dest->select.s._signed|=src->select.s._signed;
648   SPEC_STAT (dest) |= SPEC_STAT (src);
649   SPEC_EXTR (dest) |= SPEC_EXTR (src);
650   SPEC_CONST(dest) |= SPEC_CONST (src);
651   SPEC_ABSA (dest) |= SPEC_ABSA (src);
652   SPEC_VOLATILE (dest) |= SPEC_VOLATILE (src);
653   SPEC_ADDR (dest) |= SPEC_ADDR (src);
654   SPEC_OCLS (dest) = SPEC_OCLS (src);
655   SPEC_BLEN (dest) |= SPEC_BLEN (src);
656   SPEC_BSTR (dest) |= SPEC_BSTR (src);
657   SPEC_TYPEDEF (dest) |= SPEC_TYPEDEF (src);
658   SPEC_ENUM (dest) |= SPEC_ENUM (src);
659   if (SPEC_ARGREG(src) && !SPEC_ARGREG(dest))
660       SPEC_ARGREG(dest) = SPEC_ARGREG(src);
661   
662   if (IS_STRUCT (dest) && SPEC_STRUCT (dest) == NULL)
663     SPEC_STRUCT (dest) = SPEC_STRUCT (src);
664
665   /* these are the only function attributes that will be set 
666      in a specifier while parsing */
667   FUNC_NONBANKED(dest) |= FUNC_NONBANKED(src);
668   FUNC_BANKED(dest) |= FUNC_BANKED(src);
669   FUNC_ISCRITICAL(dest) |= FUNC_ISCRITICAL(src);
670   FUNC_ISREENT(dest) |= FUNC_ISREENT(src);
671   FUNC_ISNAKED(dest) |= FUNC_ISNAKED(src);
672   FUNC_ISISR(dest) |= FUNC_ISISR(src);
673   FUNC_ISJAVANATIVE(dest) |= FUNC_ISJAVANATIVE(src);
674   FUNC_ISBUILTIN(dest) |= FUNC_ISBUILTIN(src);
675   FUNC_ISOVERLAY(dest) |= FUNC_ISOVERLAY(src);
676   FUNC_INTNO(dest) |= FUNC_INTNO(src);
677   FUNC_REGBANK(dest) |= FUNC_REGBANK(src);
678
679   return dest;
680 }
681
682 /*------------------------------------------------------------------*/
683 /* genSymName - generates and returns a name used for anonymous vars */
684 /*------------------------------------------------------------------*/
685 char *
686 genSymName (int level)
687 {
688   static int gCount = 0;
689   static char gname[SDCC_NAME_MAX + 1];
690
691   SNPRINTF (gname, sizeof(gname), "__%04d%04d", level, gCount++);
692   return gname;
693 }
694
695 /*------------------------------------------------------------------*/
696 /* getSpec - returns the specifier part from a declaration chain    */
697 /*------------------------------------------------------------------*/
698 sym_link *
699 getSpec (sym_link * p)
700 {
701   sym_link *loop;
702
703   loop = p;
704   while (p && !(IS_SPEC (p)))
705     p = p->next;
706
707   return p;
708 }
709
710 /*------------------------------------------------------------------*/
711 /* newCharLink() - creates an char type                             */
712 /*------------------------------------------------------------------*/
713 sym_link *
714 newCharLink ()
715 {
716   sym_link *p;
717
718   p = newLink (SPECIFIER);
719   SPEC_NOUN (p) = V_CHAR;
720
721   return p;
722 }
723
724 /*------------------------------------------------------------------*/
725 /* newFloatLink - a new Float type                                  */
726 /*------------------------------------------------------------------*/
727 sym_link *
728 newFloatLink ()
729 {
730   sym_link *p;
731
732   p = newLink (SPECIFIER);
733   SPEC_NOUN (p) = V_FLOAT;
734
735   return p;
736 }
737
738 /*------------------------------------------------------------------*/
739 /* newLongLink() - new long type                                    */
740 /*------------------------------------------------------------------*/
741 sym_link *
742 newLongLink ()
743 {
744   sym_link *p;
745
746   p = newLink (SPECIFIER);
747   SPEC_NOUN (p) = V_INT;
748   SPEC_LONG (p) = 1;
749
750   return p;
751 }
752
753 /*------------------------------------------------------------------*/
754 /* newIntLink() - creates an int type                               */
755 /*------------------------------------------------------------------*/
756 sym_link *
757 newIntLink ()
758 {
759   sym_link *p;
760
761   p = newLink (SPECIFIER);
762   SPEC_NOUN (p) = V_INT;
763
764   return p;
765 }
766
767 /*------------------------------------------------------------------*/
768 /* getSize - returns size of a type chain in bits                   */
769 /*------------------------------------------------------------------*/
770 unsigned int 
771 getSize (sym_link * p)
772 {
773   /* if nothing return 0 */
774   if (!p)
775     return 0;
776   if (IS_SPEC (p))
777     {                           /* if this is the specifier then */
778       switch (SPEC_NOUN (p))
779         {                       /* depending on the specifier type */
780         case V_INT:
781           return (IS_LONG (p) ? LONGSIZE : INTSIZE);
782         case V_FLOAT:
783           return FLOATSIZE;
784         case V_CHAR:
785           return CHARSIZE;
786         case V_VOID:
787           return 0;
788         case V_STRUCT:
789           return SPEC_STRUCT (p)->size;
790         case V_LABEL:
791           return 0;
792         case V_SBIT:
793         case V_BIT:
794           return BITSIZE;
795         case V_BITFIELD:
796           return ((SPEC_BLEN (p) / 8) + (SPEC_BLEN (p) % 8 ? 1 : 0));
797         default:
798           return 0;
799         }
800     }
801
802   /* this is a declarator */
803   switch (DCL_TYPE (p))
804     {
805     case ARRAY:
806       if (DCL_ELEM(p)) {
807         return DCL_ELEM (p) * getSize (p->next);
808       } else {
809           //    werror (E_INTERNAL_ERROR, __FILE__, __LINE__, 
810           //    "can not tell the size of an array[]");
811         return 0;
812       }
813     case IPOINTER:
814     case PPOINTER:
815     case POINTER:
816       return (PTRSIZE);
817     case EEPPOINTER:
818     case FPOINTER:
819     case CPOINTER:
820     case FUNCTION:
821       return (FPTRSIZE);
822     case GPOINTER:
823       return (GPTRSIZE);
824
825     default:
826       return 0;
827     }
828 }
829
830 /*---------------------------------------------------------------------*/
831 /* getAllocSize - returns size of a type chain in bytes for allocation */
832 /*---------------------------------------------------------------------*/
833 unsigned int
834 getAllocSize (sym_link *p)
835 {
836   if (IS_STRUCT (p) && SPEC_STRUCT (p)->type == STRUCT)
837     {
838       /* if this is a struct specifier then  */
839       /* calculate the size as it could end  */
840       /* with an array of unspecified length */
841       symbol *sflds = SPEC_STRUCT (p)->fields;
842
843       while (sflds && sflds->next)
844         sflds = sflds->next;
845
846       if (sflds && !IS_BITFIELD (sflds->type))
847         return sflds->offset + getAllocSize (sflds->type);
848       else
849         return SPEC_STRUCT (p)->size;
850     }
851   else
852     return getSize (p);
853 }
854
855 /*------------------------------------------------------------------*/
856 /* bitsForType - returns # of bits required to store this type      */
857 /*------------------------------------------------------------------*/
858 unsigned int 
859 bitsForType (sym_link * p)
860 {
861   /* if nothing return 0 */
862   if (!p)
863     return 0;
864
865   if (IS_SPEC (p))
866     {                           /* if this is the specifier then */
867
868       switch (SPEC_NOUN (p))
869         {                       /* depending on the specifier type */
870         case V_INT:
871           return (IS_LONG (p) ? LONGSIZE * 8 : INTSIZE * 8);
872         case V_FLOAT:
873           return FLOATSIZE * 8;
874         case V_CHAR:
875           return CHARSIZE * 8;
876         case V_VOID:
877           return 0;
878         case V_STRUCT:
879           return SPEC_STRUCT (p)->size * 8;
880         case V_LABEL:
881           return 0;
882         case V_SBIT:
883         case V_BIT:
884           return 1;
885         case V_BITFIELD:
886           return SPEC_BLEN (p);
887         default:
888           return 0;
889         }
890     }
891
892   /* this is a specifier  */
893   switch (DCL_TYPE (p))
894     {
895     case ARRAY:
896       return DCL_ELEM (p) * getSize (p->next) * 8;
897     case IPOINTER:
898     case PPOINTER:
899     case POINTER:
900       return (PTRSIZE * 8);
901     case EEPPOINTER:
902     case FPOINTER:
903     case CPOINTER:
904     case FUNCTION:
905       return (FPTRSIZE * 8);
906     case GPOINTER:
907       return (GPTRSIZE * 8);
908
909     default:
910       return 0;
911     }
912 }
913
914 /*------------------------------------------------------------------*/
915 /* copySymbolChain - copies a symbol chain                          */
916 /*------------------------------------------------------------------*/
917 symbol *
918 copySymbolChain (symbol * src)
919 {
920   symbol *dest;
921
922   if (!src)
923     return NULL;
924
925   dest = copySymbol (src);
926   dest->next = copySymbolChain (src->next);
927   return dest;
928 }
929
930 /*------------------------------------------------------------------*/
931 /* copySymbol - makes a copy of a symbol                            */
932 /*------------------------------------------------------------------*/
933 symbol *
934 copySymbol (symbol * src)
935 {
936   symbol *dest;
937
938   if (!src)
939     return NULL;
940
941   dest = newSymbol (src->name, src->level);
942   memcpy (dest, src, sizeof (symbol));
943   dest->level = src->level;
944   dest->block = src->block;
945   dest->ival = copyIlist (src->ival);
946   dest->type = copyLinkChain (src->type);
947   dest->etype = getSpec (dest->type);
948   dest->next = NULL;
949   dest->key = src->key;
950   dest->allocreq = src->allocreq;
951   return dest;
952 }
953
954 /*------------------------------------------------------------------*/
955 /* reverseSyms - reverses the links for a symbol chain      */
956 /*------------------------------------------------------------------*/
957 symbol *
958 reverseSyms (symbol * sym)
959 {
960   symbol *prev, *curr, *next;
961
962   if (!sym)
963     return NULL;
964
965   prev = sym;
966   curr = sym->next;
967
968   while (curr)
969     {
970       next = curr->next;
971       curr->next = prev;
972       prev = curr;
973       curr = next;
974     }
975   sym->next = (void *) NULL;
976   return prev;
977 }
978
979 /*------------------------------------------------------------------*/
980 /* reverseLink - reverses the links for a type chain        */
981 /*------------------------------------------------------------------*/
982 sym_link *
983 reverseLink (sym_link * type)
984 {
985   sym_link *prev, *curr, *next;
986
987   if (!type)
988     return NULL;
989
990   prev = type;
991   curr = type->next;
992
993   while (curr)
994     {
995       next = curr->next;
996       curr->next = prev;
997       prev = curr;
998       curr = next;
999     }
1000   type->next = (void *) NULL;
1001   return prev;
1002 }
1003
1004 /*------------------------------------------------------------------*/
1005 /* addSymChain - adds a symbol chain to the symboltable             */
1006 /*------------------------------------------------------------------*/
1007 void 
1008 addSymChain (symbol * symHead)
1009 {
1010   symbol *sym = symHead;
1011   symbol *csym = NULL;
1012   int error = 0;
1013
1014   for (; sym != NULL; sym = sym->next)
1015     {
1016       changePointer(sym->type);
1017       checkTypeSanity(sym->etype, sym->name);
1018
1019       if (!sym->level && !(IS_SPEC(sym->etype) && IS_TYPEDEF(sym->etype)))
1020         checkDecl (sym, 0);
1021       
1022       /* if already exists in the symbol table then check if
1023          one of them is an extern definition if yes then
1024          then check if the type match, if the types match then
1025          delete the current entry and add the new entry      */
1026       if ((csym = findSymWithLevel (SymbolTab, sym)) &&
1027           csym->level == sym->level) {
1028
1029         /* If the previous definition was for an array with incomplete */
1030         /* type, and the new definition has completed the type, update */
1031         /* the original type to match */
1032         if (IS_DECL(csym->type) && DCL_TYPE(csym->type)==ARRAY
1033             && IS_DECL(sym->type) && DCL_TYPE(sym->type)==ARRAY)
1034           {
1035             if (!DCL_ELEM(csym->type) && DCL_ELEM(sym->type))
1036               DCL_ELEM(csym->type) = DCL_ELEM(sym->type);
1037           }
1038
1039         #if 0
1040         /* If only one of the definitions used the "at" keyword, copy */
1041         /* the address to the other. */
1042         if (IS_SPEC(csym->etype) && SPEC_ABSA(csym->etype)
1043             && IS_SPEC(sym->etype) && !SPEC_ABSA(sym->etype))
1044           {
1045             SPEC_ABSA (sym->etype) = 1;
1046             SPEC_ADDR (sym->etype) = SPEC_ADDR (csym->etype);
1047           }
1048         if (IS_SPEC(csym->etype) && !SPEC_ABSA(csym->etype)
1049             && IS_SPEC(sym->etype) && SPEC_ABSA(sym->etype))
1050           {
1051             SPEC_ABSA (csym->etype) = 1;
1052             SPEC_ADDR (csym->etype) = SPEC_ADDR (sym->etype);
1053           }
1054         #endif
1055   
1056         error = 0;        
1057         if (csym->ival && sym->ival)
1058           error = 1;
1059         if (compareTypeExact (csym->type, sym->type, sym->level) != 1)
1060           error = 1;
1061         
1062         if (error) {
1063           /* one definition extern ? */
1064           if (IS_EXTERN (csym->etype) || IS_EXTERN (sym->etype))
1065             werror (E_EXTERN_MISMATCH, sym->name);
1066           else
1067             werror (E_DUPLICATE, sym->name);
1068           werrorfl (csym->fileDef, csym->lineDef, E_PREVIOUS_DEF);
1069           #if 0
1070           fprintf (stderr, "from type '");
1071           printTypeChain (csym->type, stderr);
1072           if (IS_SPEC (csym->etype) && SPEC_ABSA (csym->etype))
1073             fprintf(stderr, " at 0x%x", SPEC_ADDR (csym->etype));
1074           fprintf (stderr, "'\nto type '");
1075           printTypeChain (sym->type, stderr);
1076           if (IS_SPEC (sym->etype) && SPEC_ABSA (sym->etype))
1077             fprintf(stderr, " at 0x%x", SPEC_ADDR (sym->etype));
1078           fprintf (stderr, "'\n");
1079           #endif
1080           continue;
1081         }
1082
1083         if (csym->ival && !sym->ival)
1084           sym->ival = csym->ival;
1085
1086         /* delete current entry */
1087         deleteSym (SymbolTab, csym, csym->name);
1088         deleteFromSeg(csym);
1089       }
1090       
1091       /* add new entry */
1092       addSym (SymbolTab, sym, sym->name, sym->level, sym->block, 1);
1093     }
1094 }
1095
1096
1097 /*------------------------------------------------------------------*/
1098 /* funcInChain - DCL Type 'FUNCTION' found in type chain            */
1099 /*------------------------------------------------------------------*/
1100 int 
1101 funcInChain (sym_link * lnk)
1102 {
1103   while (lnk)
1104     {
1105       if (IS_FUNC (lnk))
1106         return 1;
1107       lnk = lnk->next;
1108     }
1109   return 0;
1110 }
1111
1112 /*------------------------------------------------------------------*/
1113 /* structElemType - returns the type info of a struct member        */
1114 /*------------------------------------------------------------------*/
1115 sym_link *
1116 structElemType (sym_link * stype, value * id)
1117 {
1118   symbol *fields = (SPEC_STRUCT (stype) ? SPEC_STRUCT (stype)->fields : NULL);
1119   sym_link *type, *etype;
1120   sym_link *petype = getSpec (stype);
1121
1122   if (fields && id) {
1123     
1124     /* look for the id */
1125     while (fields)
1126       {
1127         if (strcmp (fields->rname, id->name) == 0)
1128           {
1129             type = copyLinkChain (fields->type);
1130             etype = getSpec (type);
1131             SPEC_SCLS (etype) = (SPEC_SCLS (petype) == S_REGISTER ?
1132                                  SPEC_SCLS (etype) : SPEC_SCLS (petype));
1133             if (IS_SPEC (type))
1134               SPEC_CONST (type) |= SPEC_CONST (stype);
1135             else
1136               DCL_PTR_CONST (type) |= SPEC_CONST (stype);
1137             return type;
1138           }
1139         fields = fields->next;
1140       }
1141   }
1142
1143   werror (E_NOT_MEMBER, id->name);
1144     
1145   // the show must go on
1146   return newIntLink();
1147 }
1148
1149 /*------------------------------------------------------------------*/
1150 /* getStructElement - returns element of a tructure definition      */
1151 /*------------------------------------------------------------------*/
1152 symbol *
1153 getStructElement (structdef * sdef, symbol * sym)
1154 {
1155   symbol *field;
1156
1157   for (field = sdef->fields; field; field = field->next)
1158     if (strcmp (field->name, sym->name) == 0)
1159       return field;
1160
1161   werror (E_NOT_MEMBER, sym->name);
1162
1163   return sdef->fields;
1164 }
1165
1166 /*------------------------------------------------------------------*/
1167 /* compStructSize - computes the size of a structure                */
1168 /*------------------------------------------------------------------*/
1169 int 
1170 compStructSize (int su, structdef * sdef)
1171 {
1172     int sum = 0, usum = 0;
1173     int bitOffset = 0;
1174     symbol *loop;
1175
1176     /* for the identifiers  */
1177     loop = sdef->fields;
1178     while (loop) {
1179
1180         /* create the internal name for this variable */
1181         SNPRINTF (loop->rname, sizeof(loop->rname), "_%s", loop->name);
1182         if (su == UNION) {
1183             sum = 0;
1184             bitOffset = 0;
1185         }
1186         SPEC_VOLATILE (loop->etype) |= (su == UNION ? 1 : 0);
1187
1188         /* if this is a bit field  */
1189         if (loop->bitVar) {
1190
1191             /* change it to a unsigned bit */
1192             SPEC_NOUN (loop->etype) = V_BITFIELD;
1193             SPEC_USIGN (loop->etype) = 1;
1194             SPEC_BLEN (loop->etype) = loop->bitVar;
1195
1196             if (loop->bitVar == BITVAR_PAD) {
1197                 /* A zero length bitfield forces padding */
1198                 SPEC_BSTR (loop->etype) = bitOffset;
1199                 SPEC_BLEN (loop->etype) = 0;
1200                 bitOffset = 8;
1201                 loop->offset = sum;
1202             }
1203             else {
1204                 if (bitOffset == 8) {
1205                     bitOffset = 0;
1206                     sum++;
1207                 }
1208                 /* check if this fit into the remaining   */
1209                 /* bits of this byte else align it to the */
1210                 /* next byte boundary                     */
1211                 if (loop->bitVar <= (8 - bitOffset)) {
1212                     /* fits into current byte */
1213                     loop->offset = sum;
1214                     SPEC_BSTR (loop->etype) = bitOffset;
1215                     bitOffset += loop->bitVar;
1216                 }
1217                 else if (!bitOffset) {
1218                     /* does not fit, but is already byte aligned */
1219                     loop->offset = sum;
1220                     SPEC_BSTR (loop->etype) = bitOffset;
1221                     bitOffset += loop->bitVar;
1222                 } 
1223                 else {
1224                     /* does not fit; need to realign first */
1225                     sum++;
1226                     loop->offset = (su == UNION ? sum = 0 : sum);
1227                     bitOffset = 0;
1228                     SPEC_BSTR (loop->etype) = bitOffset;
1229                     bitOffset += loop->bitVar;
1230                 }
1231                 while (bitOffset>8) {
1232                     bitOffset -= 8;
1233                     sum++;
1234                 } 
1235             }
1236         }
1237         else {
1238             /* This is a non-bit field. Make sure we are */
1239             /* byte aligned first */
1240             if (bitOffset) {
1241                 sum++;
1242                 loop->offset = (su == UNION ? sum = 0 : sum);
1243                 bitOffset = 0;
1244             }
1245             loop->offset = sum;
1246             checkDecl (loop, 1);
1247             sum += getSize (loop->type);
1248         }
1249
1250         loop = loop->next;
1251
1252         /* if union then size = sizeof largest field */
1253         if (su == UNION) {
1254             /* For UNION, round up after each field */
1255             sum += ((bitOffset+7)/8);
1256             usum = max (usum, sum);
1257         }
1258
1259     }
1260     
1261     /* For STRUCT, round up after all fields processed */
1262     if (su != UNION)
1263         sum += ((bitOffset+7)/8);
1264
1265     return (su == UNION ? usum : sum);
1266 }
1267
1268 /*-------------------------------------------------------------------*/
1269 /* promoteAnonStructs - promote anonymous struct/union's fields into */
1270 /*                      an enclosing struct/union                    */
1271 /*-------------------------------------------------------------------*/
1272 void
1273 promoteAnonStructs (int su, structdef * sdef)
1274 {
1275   symbol *field;
1276   symbol *subfield;
1277   symbol **tofield;
1278   symbol *nextfield;
1279   symbol *dupfield;
1280   int base;
1281
1282   tofield = &sdef->fields;
1283   field = sdef->fields;
1284   while (field)
1285     {
1286       nextfield = field->next;
1287       if (!*field->name && IS_STRUCT (field->type))
1288         {
1289           /* Found an anonymous struct/union. Replace it */
1290           /* with the fields it contains and adjust all  */
1291           /* the offsets */
1292           
1293           base = field->offset;
1294           subfield = copySymbolChain (SPEC_STRUCT (field->type)->fields);
1295           if (!subfield)
1296             continue;           /* just in case it's empty */
1297           
1298           *tofield = subfield;
1299           for (;;)
1300             {
1301               /* check for field name conflicts resulting from promotion */
1302               dupfield = sdef->fields;
1303               while (dupfield && dupfield != subfield)
1304                 {
1305                   if (*subfield->name && !strcmp (dupfield->name, subfield->name))
1306                     {
1307                       werrorfl (subfield->fileDef, subfield->lineDef,
1308                                 E_DUPLICATE_MEMBER,
1309                                 su==STRUCT ? "struct" : "union",
1310                                 subfield->name);
1311                       werrorfl (dupfield->fileDef, dupfield->lineDef,
1312                                 E_PREVIOUS_DEF);
1313                     }
1314                   dupfield = dupfield->next;
1315                 }
1316               
1317               subfield->offset += base;
1318               if (subfield->next)
1319                 subfield = subfield->next;
1320               else
1321                 break;
1322             }
1323           subfield->next = nextfield;
1324           tofield = &subfield->next;
1325         }
1326       else
1327         tofield = &field->next;
1328       field = nextfield;
1329     }
1330 }
1331
1332
1333 /*------------------------------------------------------------------*/
1334 /* checkSClass - check the storage class specification              */
1335 /*------------------------------------------------------------------*/
1336 static void 
1337 checkSClass (symbol * sym, int isProto)
1338 {
1339   sym_link *t;
1340   
1341   if (getenv("DEBUG_SANITY")) {
1342     fprintf (stderr, "checkSClass: %s \n", sym->name);
1343   }
1344   
1345   /* type is literal can happen for enums change
1346      to auto */
1347   if (SPEC_SCLS (sym->etype) == S_LITERAL && !SPEC_ENUM (sym->etype))
1348     SPEC_SCLS (sym->etype) = S_AUTO;
1349   
1350   /* if sfr or sbit then must also be volatile */
1351   if (SPEC_SCLS (sym->etype) == S_SBIT ||
1352       SPEC_SCLS (sym->etype) == S_SFR)
1353     {
1354       SPEC_VOLATILE (sym->etype) = 1;
1355     }
1356   
1357   /* if absolute address given then it mark it as
1358      volatile -- except in the PIC port */
1359
1360 #if !OPT_DISABLE_PIC || !OPT_DISABLE_PIC16
1361   /* The PIC port uses a different peep hole optimizer based on "pCode" */
1362   if (!TARGET_IS_PIC && !TARGET_IS_PIC16)
1363 #endif
1364
1365     if (IS_ABSOLUTE (sym->etype))
1366       SPEC_VOLATILE (sym->etype) = 1;
1367   
1368   /* If code memory is read only, then pointers to code memory */
1369   /* implicitly point to constants -- make this explicit       */
1370   t = sym->type;
1371   while (t && t->next) {
1372     if (IS_CODEPTR(t) && port->mem.code_ro) {
1373       if (IS_SPEC(t->next)) {
1374         SPEC_CONST (t->next) = 1;
1375       } else {
1376         DCL_PTR_CONST (t->next) = 1;
1377       }
1378     }
1379     t = t->next;
1380   }
1381
1382   /* global variables declared const put into code */
1383   /* if no other storage class specified */
1384   if (sym->level == 0 &&
1385       SPEC_SCLS(sym->etype) == S_FIXED &&
1386       !IS_FUNC(sym->type)) {
1387     /* find the first non-array link */
1388     t = sym->type;
1389     while (IS_ARRAY(t))
1390       t = t->next;
1391     if (IS_CONSTANT (t)) {
1392       SPEC_SCLS (sym->etype) = S_CODE;
1393     }
1394   }
1395
1396   /* global variable in code space is a constant */
1397   if (sym->level == 0 &&
1398       SPEC_SCLS (sym->etype) == S_CODE &&
1399       port->mem.code_ro) {
1400     /* find the first non-array link */
1401     t = sym->type;
1402     while (IS_ARRAY(t))
1403       t = t->next;
1404     if (IS_SPEC(t)) {
1405       SPEC_CONST (t) = 1;
1406     } else {
1407       DCL_PTR_CONST (t) = 1;
1408     }
1409   }
1410
1411   /* if bit variable then no storage class can be */
1412   /* specified since bit is already a storage */
1413   if (IS_BITVAR (sym->etype) &&
1414       (SPEC_SCLS (sym->etype) != S_FIXED &&
1415        SPEC_SCLS (sym->etype) != S_SBIT &&
1416        SPEC_SCLS (sym->etype) != S_BIT)
1417     )
1418     {
1419       werror (E_BITVAR_STORAGE, sym->name);
1420       SPEC_SCLS (sym->etype) = S_FIXED;
1421     }
1422
1423   /* extern variables cannot be initialized */
1424   if (IS_EXTERN (sym->etype) && sym->ival)
1425     {
1426       werror (E_EXTERN_INIT, sym->name);
1427       sym->ival = NULL;
1428     }
1429
1430   /* if this is an automatic symbol */
1431   if (sym->level && (options.stackAuto || reentrant)) {
1432     if ((SPEC_SCLS (sym->etype) == S_AUTO ||
1433          SPEC_SCLS (sym->etype) == S_FIXED ||
1434          SPEC_SCLS (sym->etype) == S_REGISTER ||
1435          SPEC_SCLS (sym->etype) == S_STACK ||
1436          SPEC_SCLS (sym->etype) == S_XSTACK)) {
1437       SPEC_SCLS (sym->etype) = S_AUTO;
1438     } else {
1439       /* storage class may only be specified for statics */
1440       if (!IS_STATIC(sym->etype)) {
1441         werror (E_AUTO_ASSUMED, sym->name);
1442       }
1443     }
1444   }
1445
1446   /* automatic symbols cannot be given   */
1447   /* an absolute address ignore it      */
1448   if (sym->level &&
1449       SPEC_ABSA (sym->etype) &&
1450       (options.stackAuto || reentrant))
1451     {
1452       werror (E_AUTO_ABSA, sym->name);
1453       SPEC_ABSA (sym->etype) = 0;
1454     }
1455
1456   /* arrays & pointers cannot be defined for bits   */
1457   /* SBITS or SFRs or BIT                           */
1458   if ((IS_ARRAY (sym->type) || IS_PTR (sym->type)) &&
1459       (SPEC_NOUN (sym->etype) == V_BIT ||
1460        SPEC_NOUN (sym->etype) == V_SBIT ||
1461        SPEC_NOUN (sym->etype) == V_BITFIELD ||
1462        SPEC_SCLS (sym->etype) == S_SFR))
1463     werror (E_BIT_ARRAY, sym->name);
1464
1465   /* if this is a bit|sbit then set length & start  */
1466   if (SPEC_NOUN (sym->etype) == V_BIT ||
1467       SPEC_NOUN (sym->etype) == V_SBIT)
1468     {
1469       SPEC_BLEN (sym->etype) = 1;
1470       SPEC_BSTR (sym->etype) = 0;
1471     }
1472
1473   if (!isProto) {
1474     /* variables declared in CODE space must have */
1475     /* initializers if not an extern */
1476     if (SPEC_SCLS (sym->etype) == S_CODE &&
1477         sym->ival == NULL &&
1478         !sym->_isparm &&
1479         //!sym->level &&
1480         port->mem.code_ro &&
1481         !IS_EXTERN (sym->etype) &&
1482         !funcInChain (sym->type))
1483       werror (E_CODE_NO_INIT, sym->name);
1484   }
1485
1486   /* if parameter or local variable then change */
1487   /* the storage class to reflect where the var will go */
1488   if (sym->level && SPEC_SCLS (sym->etype) == S_FIXED
1489    && !IS_STATIC(sym->etype)
1490       )
1491     {
1492       if (options.stackAuto || (currFunc && IFFUNC_ISREENT (currFunc->type)))
1493         {
1494           SPEC_SCLS (sym->etype) = (options.useXstack ?
1495                                     S_XSTACK : S_STACK);
1496         }
1497       else
1498         {
1499           /* hack-o-matic! I see no reason why the useXstack option should ever
1500            * control this allocation, but the code was originally that way, and
1501            * changing it for non-390 ports breaks the compiler badly.
1502            */
1503           bool useXdata = (TARGET_IS_DS390 || TARGET_IS_DS400) ? 
1504                 1 : options.useXstack;
1505           SPEC_SCLS (sym->etype) = (useXdata ?
1506                                     S_XDATA : S_FIXED);
1507         }
1508     }
1509 }
1510
1511 /*------------------------------------------------------------------*/
1512 /* changePointer - change pointer to functions                      */
1513 /*------------------------------------------------------------------*/
1514 void 
1515 changePointer (sym_link * p)
1516 {
1517
1518   /* go thru the chain of declarations   */
1519   /* if we find a pointer to a function  */
1520   /* unconditionally change it to a ptr  */
1521   /* to code area                        */
1522   for (; p; p = p->next)
1523     {
1524       if (!IS_SPEC (p) && DCL_TYPE (p) == UPOINTER)
1525         DCL_TYPE (p) = port->unqualified_pointer;
1526       if (IS_PTR (p) && IS_FUNC (p->next))
1527         DCL_TYPE (p) = CPOINTER;
1528     }
1529 }
1530
1531 /*------------------------------------------------------------------*/
1532 /* checkDecl - does semantic validation of a declaration                   */
1533 /*------------------------------------------------------------------*/
1534 int 
1535 checkDecl (symbol * sym, int isProto)
1536 {
1537
1538   checkSClass (sym, isProto);           /* check the storage class      */
1539   changePointer (sym->type);          /* change pointers if required */
1540
1541   /* if this is an array without any dimension
1542      then update the dimension from the initial value */
1543   if (IS_ARRAY (sym->type) && !DCL_ELEM (sym->type))
1544     DCL_ELEM (sym->type) = getNelements (sym->type, sym->ival);
1545
1546   return 0;
1547 }
1548
1549 /*------------------------------------------------------------------*/
1550 /* copyLinkChain - makes a copy of the link chain & rets ptr 2 head */
1551 /*------------------------------------------------------------------*/
1552 sym_link *
1553 copyLinkChain (sym_link * p)
1554 {
1555   sym_link *head, *curr, *loop;
1556
1557   curr = p;
1558   head = loop = (curr ? newLink (p->class) : (void *) NULL);
1559   while (curr)
1560     {
1561       memcpy (loop, curr, sizeof (sym_link));   /* copy it */
1562       loop->next = (curr->next ? newLink (curr->next->class) : (void *) NULL);
1563       loop = loop->next;
1564       curr = curr->next;
1565     }
1566
1567   return head;
1568 }
1569
1570 /*------------------------------------------------------------------*/
1571 /* cleanUpBlock - cleansup the symbol table specified for all the   */
1572 /*                symbols in the given block                        */
1573 /*------------------------------------------------------------------*/
1574 void 
1575 cleanUpBlock (bucket ** table, int block)
1576 {
1577   int i;
1578   bucket *chain;
1579
1580   /* go thru the entire  table  */
1581   for (i = 0; i < 256; i++)
1582     {
1583       for (chain = table[i]; chain; chain = chain->next)
1584         {
1585           if (chain->block >= block)
1586             {
1587               deleteSym (table, chain->sym, chain->name);
1588             }
1589         }
1590     }
1591 }
1592
1593 /*------------------------------------------------------------------*/
1594 /* cleanUpLevel - cleansup the symbol table specified for all the   */
1595 /*                symbols in the given level                        */
1596 /*------------------------------------------------------------------*/
1597 void 
1598 cleanUpLevel (bucket ** table, int level)
1599 {
1600   int i;
1601   bucket *chain;
1602
1603   /* go thru the entire  table  */
1604   for (i = 0; i < 256; i++)
1605     {
1606       for (chain = table[i]; chain; chain = chain->next)
1607         {
1608           if (chain->level >= level)
1609             {
1610               deleteSym (table, chain->sym, chain->name);
1611             }
1612         }
1613     }
1614 }
1615
1616 /*------------------------------------------------------------------*/
1617 /* computeTypeOr - computes the resultant type from two types       */
1618 /*------------------------------------------------------------------*/
1619 static sym_link *
1620 computeTypeOr (sym_link * etype1, sym_link * etype2, sym_link * reType)
1621 {
1622   /* sanity check */
1623   assert (   (IS_CHAR (etype1) || IS_BIT (etype1))
1624           && (IS_CHAR (etype2) || IS_BIT (etype2)));
1625
1626   if (SPEC_USIGN (etype1) == SPEC_USIGN (etype2))
1627     {
1628       SPEC_USIGN (reType) = SPEC_USIGN (etype1);
1629       return reType;
1630     }
1631   
1632   if (SPEC_USIGN (etype1))
1633     {
1634       if (   IS_LITERAL (etype2)
1635           && floatFromVal (valFromType (etype2)) >= 0)
1636         SPEC_USIGN (reType) = 1;
1637       else
1638         {
1639           /* promote to int */
1640           SPEC_USIGN (reType) = 0;
1641           SPEC_NOUN (reType) = V_INT;
1642         }
1643     }
1644   else /* etype1 signed */
1645     {
1646       if (   IS_LITERAL (etype2)
1647           && floatFromVal (valFromType (etype2)) <= 127)
1648         SPEC_USIGN (reType) = 0;
1649       else
1650         {
1651           /* promote to int */
1652           SPEC_USIGN (reType) = 0;
1653           SPEC_NOUN (reType) = V_INT;
1654         }
1655     }
1656
1657   if (SPEC_USIGN (etype2))
1658     {
1659       if (   IS_LITERAL (etype1)
1660           && floatFromVal (valFromType (etype1)) >= 0)
1661         SPEC_USIGN (reType) = 1;
1662       else
1663         {
1664           /* promote to int */
1665           SPEC_USIGN (reType) = 0;
1666           SPEC_NOUN (reType) = V_INT;
1667         }
1668     }
1669   else /* etype2 signed */
1670     {
1671       if (   IS_LITERAL (etype1)
1672           && floatFromVal (valFromType (etype1)) <= 127)
1673         SPEC_USIGN (reType) = 0;
1674       else
1675         {
1676           /* promote to int */
1677           SPEC_USIGN (reType) = 0;
1678           SPEC_NOUN (reType) = V_INT;
1679         }
1680     }
1681   return reType;
1682 }
1683
1684 /*------------------------------------------------------------------*/
1685 /* computeType - computes the resultant type from two types         */
1686 /*------------------------------------------------------------------*/
1687 sym_link *
1688 computeType (sym_link * type1, sym_link * type2,
1689              RESULT_TYPE resultType, int op)
1690 {
1691   sym_link *rType;
1692   sym_link *reType;
1693   sym_link *etype1 = getSpec (type1);
1694   sym_link *etype2;
1695
1696   etype2 = type2 ? getSpec (type2) : type1;
1697
1698   /* if one of them is a float then result is a float */
1699   /* here we assume that the types passed are okay */
1700   /* and can be cast to one another                */
1701   /* which ever is greater in size */
1702   if (IS_FLOAT (etype1) || IS_FLOAT (etype2))
1703     rType = newFloatLink ();
1704   else
1705     /* if both are bitvars choose the larger one */
1706   if (IS_BITVAR (etype1) && IS_BITVAR (etype2))
1707     {
1708       rType = SPEC_BLEN (etype1) >= SPEC_BLEN (etype2) ?
1709                 copyLinkChain (type1) : copyLinkChain (type1);
1710     }
1711     /* if only one of them is a bit variable
1712        then the other one prevails */
1713   else if (IS_BITVAR (etype1) && !IS_BITVAR (etype2))
1714     {
1715       rType = copyLinkChain (type2);
1716       /* bitfield can have up to 16 bits */
1717       if (getSize (etype1) > 1)
1718         SPEC_NOUN (getSpec (rType)) = V_INT;
1719     }
1720   else if (IS_BITVAR (etype2) && !IS_BITVAR (etype1))
1721     {
1722       rType = copyLinkChain (type1);
1723       /* bitfield can have up to 16 bits */
1724       if (getSize (etype2) > 1)
1725         SPEC_NOUN (getSpec (rType)) = V_INT;
1726     }
1727   else
1728     /* if one of them is a pointer or array then that
1729        prevails */
1730   if (IS_PTR (type1) || IS_ARRAY (type1))
1731     rType = copyLinkChain (type1);
1732   else if (IS_PTR (type2) || IS_ARRAY (type2))
1733     rType = copyLinkChain (type2);
1734   else if (getSize (type1) > getSize (type2))
1735     rType = copyLinkChain (type1);
1736   else
1737     rType = copyLinkChain (type2);
1738
1739   reType = getSpec (rType);
1740
1741   /* avoid conflicting types */
1742   reType->select.s._signed = 0;
1743
1744   /* if result is a literal then make not so */
1745   if (IS_LITERAL (reType))
1746     SPEC_SCLS (reType) = S_REGISTER;
1747
1748   switch (resultType)
1749     {
1750       case RESULT_TYPE_CHAR:
1751         if (IS_BITVAR (reType))
1752           {
1753             SPEC_NOUN (reType) = V_CHAR;
1754             SPEC_SCLS (reType) = 0;
1755             SPEC_USIGN (reType) = 0;
1756             return rType;
1757           }
1758         break;
1759       case RESULT_TYPE_INT:
1760       case RESULT_TYPE_NONE:
1761       case RESULT_TYPE_OTHER:
1762         if (IS_BIT (reType))
1763           {
1764             SPEC_NOUN (reType) = V_CHAR;
1765             SPEC_SCLS (reType) = 0;
1766             SPEC_USIGN (reType) = 0;
1767             return rType;
1768           }
1769         else if (IS_BITFIELD (reType))
1770           {
1771             /* could be smarter, but it depends on the op */
1772             /* this is for the worst case: a multiplication of 4 * 4 bit */
1773             SPEC_NOUN (reType) = SPEC_BLEN (reType) <= 4 ? V_CHAR : V_INT;
1774             SPEC_SCLS (reType) = 0;
1775             SPEC_USIGN (reType) = 0;
1776             return rType;
1777           }
1778         else if (IS_CHAR (reType))
1779           {
1780             if (op == '|' || op == '^')
1781               return computeTypeOr (etype1, etype2, reType);
1782             else if (   op == '&'
1783                      && SPEC_USIGN (etype1) != SPEC_USIGN (etype2))
1784               {
1785                 SPEC_USIGN (reType) = 1;
1786                 return rType;
1787               }
1788             else if (op == '*')
1789               {
1790                 SPEC_NOUN (reType) = V_INT;
1791                 SPEC_USIGN (reType) = 0;
1792                 return rType;
1793               }
1794             /* TODO: should be in SDCCast.c */
1795             else if (   op == '/'
1796                      && (   !SPEC_USIGN (etype1)
1797                          || !SPEC_USIGN (etype2)))
1798               {
1799                 SPEC_NOUN (reType) = V_INT;
1800                 SPEC_USIGN (reType) = 0;
1801                 return rType;
1802               }
1803           }
1804         break;
1805       default:
1806         break;
1807     }
1808
1809   /* SDCC's sign promotion:
1810      - if one or both operands are unsigned, the resultant type will be unsigned
1811        (except char, see below)
1812      - if an operand is promoted to a larger type (char -> int, int -> long),
1813        the larger type will be signed
1814
1815      SDCC tries hard to avoid promotion to int and does 8 bit calculation as
1816      much as possible. We're leaving ISO IEC 9899 here and have to extrapolate
1817      the standard. The standard demands, that the result has to be the same
1818      "as if" the promotion would have been performed:
1819
1820      - if the result of an operation with two char's is promoted to a
1821        larger type, the result will be signed.
1822
1823      More sophisticated are these:
1824      - if the result of an operation with two char's is a char again,
1825        the result will only then be unsigned, if both operands are
1826        unsigned. In all other cases the result will be signed.
1827
1828        This seems to be contradictionary to the first two rules, but it makes
1829        real sense (all types are char's):
1830
1831         A signed char can be negative; this must be preserved in the result
1832                 -1 * 100 = -100;
1833
1834         Only if both operands are unsigned it's safe to make the result
1835         unsigned; this helps to avoid overflow:
1836                 2 * 100 =  200;
1837
1838      - ToDo: document '|', '^' and '&'
1839      
1840      Homework: - why is (200 * 200 < 0) true?
1841                - why is { char l = 200, r = 200; (r * l > 0) } true?
1842   */
1843
1844   if (!IS_FLOAT (reType)
1845       && (   (SPEC_USIGN (etype1)
1846               /* if this operand is promoted to a larger type,
1847                  then it will be promoted to a signed type */
1848               && !(getSize (etype1) < getSize (reType))
1849               /* char require special handling */
1850               && !IS_CHAR (etype1))
1851           || /* same for 2nd operand */  
1852              (SPEC_USIGN (etype2)
1853               && !(getSize (etype2) < getSize (reType))
1854               && !IS_CHAR (etype2))
1855           || /* if both are 'unsigned char' and not promoted
1856                 let the result be unsigned too */
1857              (   SPEC_USIGN (etype1)
1858               && SPEC_USIGN (etype2)
1859               && IS_CHAR (etype1)
1860               && IS_CHAR (etype2)
1861               && IS_CHAR (reType))))
1862     SPEC_USIGN (reType) = 1;
1863   else
1864     SPEC_USIGN (reType) = 0;
1865
1866   return rType;
1867 }
1868
1869 /*--------------------------------------------------------------------*/
1870 /* compareType - will do type check return 1 if match, -1 if castable */
1871 /*--------------------------------------------------------------------*/
1872 int
1873 compareType (sym_link * dest, sym_link * src)
1874 {
1875   if (!dest && !src)
1876     return 1;
1877
1878   if (dest && !src)
1879     return 0;
1880
1881   if (src && !dest)
1882     return 0;
1883
1884   /* if dest is a declarator then */
1885   if (IS_DECL (dest))
1886     {
1887       if (IS_DECL (src))
1888         {
1889           if (DCL_TYPE (src) == DCL_TYPE (dest)) {
1890             if (IS_FUNC(src)) {
1891               //checkFunction(src,dest);
1892             }
1893             return compareType (dest->next, src->next);
1894           }
1895           if (IS_PTR (dest) && IS_GENPTR (src) && IS_VOID(src->next)) {
1896             return -1;
1897           }
1898           if (IS_PTR (src) && 
1899               (IS_GENPTR (dest) ||
1900                ((DCL_TYPE(src) == POINTER) && (DCL_TYPE(dest) == IPOINTER))
1901              ))
1902             return -1;
1903           if (IS_PTR (dest) && IS_ARRAY (src)) {
1904             value *val=aggregateToPointer (valFromType(src));
1905             int res=compareType (dest, val->type);
1906             Safe_free(val->type);
1907             Safe_free(val);
1908             return res;
1909           }
1910           if (IS_PTR (dest) && IS_FUNC (dest->next) && IS_FUNC (src))
1911             return compareType (dest->next, src);
1912           return 0;
1913         }
1914       else if (IS_PTR (dest) && IS_INTEGRAL (src))
1915         return -1;
1916       else
1917         return 0;
1918     }
1919
1920   /* if one is a specifier and the other is not */
1921   if ((IS_SPEC (src) && !IS_SPEC (dest)) ||
1922       (IS_SPEC (dest) && !IS_SPEC (src)))
1923     return 0;
1924
1925   /* if one of them is a void then ok */
1926   if (SPEC_NOUN (dest) == V_VOID &&
1927       SPEC_NOUN (src) != V_VOID)
1928     return -1;
1929
1930   if (SPEC_NOUN (dest) != V_VOID &&
1931       SPEC_NOUN (src) == V_VOID)
1932     return -1;
1933
1934   /* if they are both bitfields then if the lengths
1935      and starts don't match */
1936   if (IS_BITFIELD (dest) && IS_BITFIELD (src) &&
1937       (SPEC_BLEN (dest) != SPEC_BLEN (src) ||
1938        SPEC_BSTR (dest) != SPEC_BSTR (src)))
1939     return -1;
1940
1941   /* it is a specifier */
1942   if (SPEC_NOUN (dest) != SPEC_NOUN (src))
1943     {
1944       if (SPEC_USIGN (dest) == SPEC_USIGN (src) &&
1945           IS_INTEGRAL (dest) && IS_INTEGRAL (src) &&
1946           /* I would prefer
1947           bitsForType (dest) == bitsForType (src))
1948              instead of the next two lines, but the regression tests fail with
1949              them; I guess it's a problem with replaceCheaperOp  */
1950           getSize (dest) == getSize (src) &&
1951           !(!IS_BIT (dest) && IS_BIT (src)))
1952         return 1;
1953       else if (IS_ARITHMETIC (dest) && IS_ARITHMETIC (src))
1954         return -1;
1955       else
1956         return 0;
1957     }
1958   else if (IS_STRUCT (dest))
1959     {
1960       if (SPEC_STRUCT (dest) != SPEC_STRUCT (src))
1961         return 0;
1962       else
1963         return 1;
1964     }
1965   if (SPEC_LONG (dest) != SPEC_LONG (src))
1966     return -1;
1967
1968   if (SPEC_USIGN (dest) != SPEC_USIGN (src))
1969     return -1;
1970
1971   return 1;
1972 }
1973
1974 /*--------------------------------------------------------------------*/
1975 /* compareTypeExact - will do type check return 1 if match exactly    */
1976 /*--------------------------------------------------------------------*/
1977 int
1978 compareTypeExact (sym_link * dest, sym_link * src, int level)
1979 {
1980   STORAGE_CLASS srcScls, destScls;
1981   
1982   if (!dest && !src)
1983     return 1;
1984
1985   if (dest && !src)
1986     return 0;
1987
1988   if (src && !dest)
1989     return 0;
1990
1991   /* if dest is a declarator then */
1992   if (IS_DECL (dest))
1993     {
1994       if (IS_DECL (src))
1995         {
1996           if (DCL_TYPE (src) == DCL_TYPE (dest)) {
1997             if ((DCL_TYPE (src) == ARRAY) && (DCL_ELEM (src) != DCL_ELEM (dest)))
1998               return 0;
1999             if (DCL_PTR_CONST (src) != DCL_PTR_CONST (dest))
2000               return 0;
2001             if (DCL_PTR_VOLATILE (src) != DCL_PTR_VOLATILE (dest))
2002               return 0;
2003             if (IS_FUNC(src))
2004               {
2005                 value *exargs, *acargs, *checkValue;
2006
2007                 /* verify function return type */
2008                 if (!compareTypeExact (dest->next, src->next, -1))
2009                   return 0;
2010                 if (FUNC_ISISR (dest) != FUNC_ISISR (src))
2011                   return 0;
2012                 if (FUNC_REGBANK (dest) != FUNC_REGBANK (src))
2013                   return 0;
2014                 if (IFFUNC_ISNAKED (dest) != IFFUNC_ISNAKED (src))
2015                   return 0;
2016                 #if 0
2017                 if (IFFUNC_ISREENT (dest) != IFFUNC_ISREENT (src) && argCnt>1)
2018                   return 0;
2019                 #endif
2020
2021                 /* compare expected args with actual args */
2022                 exargs = FUNC_ARGS(dest);
2023                 acargs = FUNC_ARGS(src);
2024
2025                 /* for all the expected args do */
2026                 for (; exargs && acargs; exargs = exargs->next, acargs = acargs->next)
2027                   {
2028                     //checkTypeSanity(acargs->etype, acargs->name);
2029
2030                     if (IS_AGGREGATE (acargs->type))
2031                       {
2032                         checkValue = copyValue (acargs);
2033                         aggregateToPointer (checkValue);
2034                       }
2035                     else
2036                       checkValue = acargs;
2037
2038                     #if 0
2039                     if (!compareTypeExact (exargs->type, checkValue->type, -1))
2040                       return 0;
2041                     #endif
2042                   }
2043
2044                   /* if one them ended we have a problem */
2045                   if ((exargs && !acargs && !IS_VOID (exargs->type)) ||
2046                       (!exargs && acargs && !IS_VOID (acargs->type)))
2047                     return 0;                  
2048                   return 1;
2049               }
2050             return compareTypeExact (dest->next, src->next, level);
2051           }
2052           return 0;
2053         }
2054       return 0;
2055     }
2056
2057   /* if one is a specifier and the other is not */
2058   if ((IS_SPEC (src) && !IS_SPEC (dest)) ||
2059       (IS_SPEC (dest) && !IS_SPEC (src)))
2060     return 0;
2061
2062   /* if one of them is a void then ok */
2063   if (SPEC_NOUN (dest) != SPEC_NOUN (src))
2064     return 0;
2065
2066   /* if they are both bitfields then if the lengths
2067      and starts don't match */
2068   if (IS_BITFIELD (dest) && IS_BITFIELD (src) &&
2069       (SPEC_BLEN (dest) != SPEC_BLEN (src) ||
2070        SPEC_BSTR (dest) != SPEC_BSTR (src)))
2071     return 0;
2072
2073   if (IS_INTEGRAL (dest))
2074     {
2075       /* signedness must match */
2076       if (SPEC_USIGN (dest) != SPEC_USIGN (src))
2077         return 0;
2078       /* size must match */
2079       if (SPEC_LONG (dest) != SPEC_LONG (src))
2080         return 0;
2081       if (SPEC_SHORT (dest) != SPEC_SHORT (src))
2082         return 0;
2083     }
2084   
2085   if (IS_STRUCT (dest))
2086     {
2087       if (SPEC_STRUCT (dest) != SPEC_STRUCT (src))
2088         return 0;
2089     }
2090
2091   if (SPEC_CONST (dest) != SPEC_CONST (src))
2092     return 0;
2093   if (SPEC_VOLATILE (dest) != SPEC_VOLATILE (src))
2094     return 0;
2095   if (SPEC_STAT (dest) != SPEC_STAT (src))
2096     return 0;
2097   if (SPEC_ABSA (dest) != SPEC_ABSA (src))
2098     return 0;
2099   if (SPEC_ABSA (dest) && SPEC_ADDR (dest) != SPEC_ADDR (src))
2100     return 0;
2101       
2102   destScls = SPEC_SCLS (dest);
2103   srcScls = SPEC_SCLS (src);
2104   
2105   /* Compensate for const to const code change in checkSClass() */
2106   if (!level & port->mem.code_ro && SPEC_CONST (dest))
2107     {
2108       if (srcScls == S_CODE && destScls == S_FIXED)
2109         destScls = S_CODE;
2110       if (destScls == S_CODE && srcScls == S_FIXED)
2111         srcScls = S_CODE;
2112     }
2113
2114   /* compensate for allocGlobal() */  
2115   if ((srcScls == S_FIXED || srcScls == S_AUTO)
2116       && port->mem.default_globl_map == xdata
2117       && !level)
2118     srcScls = S_XDATA;
2119   
2120   if (level>0 && !SPEC_STAT (dest))
2121     {
2122       /* Compensate for hack-o-matic in checkSClass() */
2123       if (options.stackAuto || (currFunc && IFFUNC_ISREENT (currFunc->type)))
2124         {
2125           if (destScls == S_FIXED)
2126             destScls = (options.useXstack ? S_XSTACK : S_STACK);
2127           if (srcScls == S_FIXED)
2128             srcScls = (options.useXstack ? S_XSTACK : S_STACK);
2129         }
2130       else if (TARGET_IS_DS390 || TARGET_IS_DS400 || options.useXstack)
2131         {
2132           if (destScls == S_FIXED)
2133             destScls = S_XDATA;
2134           if (srcScls == S_FIXED)
2135             srcScls = S_XDATA;
2136         }
2137     }
2138
2139   if (srcScls != destScls)
2140     {
2141       #if 0
2142       printf ("level = %d\n", level);
2143       printf ("SPEC_SCLS (src) = %d, SPEC_SCLS (dest) = %d\n",
2144                 SPEC_SCLS (src), SPEC_SCLS (dest));
2145       printf ("srcScls = %d, destScls = %d\n",srcScls, destScls);
2146       #endif
2147       return 0;
2148     }
2149   
2150   return 1;
2151 }
2152
2153 /*------------------------------------------------------------------*/
2154 /* inCalleeSaveList - return 1 if found in callee save list          */
2155 /*------------------------------------------------------------------*/
2156 static int
2157 calleeCmp(void *p1, void *p2)
2158 {
2159   return (strcmp((char *)p1, (char *)(p2)) == 0);
2160 }
2161
2162 bool
2163 inCalleeSaveList(char *s)
2164 {
2165   if (options.all_callee_saves)
2166     return 1;
2167   return isinSetWith(options.calleeSavesSet, s, calleeCmp);
2168 }
2169
2170 /*-----------------------------------------------------------------*/
2171 /* aggregateToPointer:  change an agggregate type function      */
2172 /*         argument to a pointer to that type.     */
2173 /*-----------------------------------------------------------------*/
2174 value *
2175 aggregateToPointer (value * val)
2176 {
2177   if (IS_AGGREGATE (val->type))
2178     {
2179       /* if this is a structure */
2180       /* then we need to add a new link */
2181       if (IS_STRUCT (val->type))
2182         {
2183           /* first lets add DECLARATOR type */
2184           sym_link *p = val->type;
2185
2186           werror (W_STRUCT_AS_ARG, val->name);
2187           val->type = newLink (DECLARATOR);
2188           val->type->next = p;
2189         }
2190
2191       /* change to a pointer depending on the */
2192       /* storage class specified        */
2193       switch (SPEC_SCLS (val->etype))
2194         {
2195         case S_IDATA:
2196           DCL_TYPE (val->type) = IPOINTER;
2197           break;
2198         case S_PDATA:
2199           DCL_TYPE (val->type) = PPOINTER;
2200           break;
2201         case S_FIXED:
2202           if (SPEC_OCLS(val->etype)) {
2203             DCL_TYPE(val->type)=PTR_TYPE(SPEC_OCLS(val->etype));
2204           } else {
2205             // this happens for (external) function parameters
2206             DCL_TYPE (val->type) = port->unqualified_pointer;
2207           }
2208           break;
2209         case S_AUTO:
2210         case S_DATA:
2211         case S_REGISTER:
2212           DCL_TYPE (val->type) = POINTER;
2213           break;
2214         case S_CODE:
2215           DCL_TYPE (val->type) = CPOINTER;
2216           break;
2217         case S_XDATA:
2218           DCL_TYPE (val->type) = FPOINTER;
2219           break;
2220         case S_EEPROM:
2221           DCL_TYPE (val->type) = EEPPOINTER;
2222           break;
2223         default:
2224           DCL_TYPE (val->type) = port->unqualified_pointer;
2225         }
2226       
2227       /* is there is a symbol associated then */
2228       /* change the type of the symbol as well */
2229       if (val->sym)
2230         {
2231           val->sym->type = copyLinkChain (val->type);
2232           val->sym->etype = getSpec (val->sym->type);
2233         }
2234     }
2235   return val;
2236 }
2237 /*------------------------------------------------------------------*/
2238 /* checkFunction - does all kinds of check on a function            */
2239 /*------------------------------------------------------------------*/
2240 int 
2241 checkFunction (symbol * sym, symbol *csym)
2242 {
2243   value *exargs, *acargs;
2244   value *checkValue;
2245   int argCnt = 0;
2246
2247   if (getenv("DEBUG_SANITY")) {
2248     fprintf (stderr, "checkFunction: %s ", sym->name);
2249   }
2250
2251   if (!IS_DECL(sym->type) || DCL_TYPE(sym->type)!=FUNCTION)
2252     {
2253       werror(E_SYNTAX_ERROR, sym->name);
2254       return 0;
2255     }
2256     
2257   /* make sure the type is complete and sane */
2258   checkTypeSanity(((symbol *)sym)->etype, ((symbol *)sym)->name);
2259
2260   /* if not type then some kind of error */
2261   if (!sym->type)
2262     return 0;
2263
2264   /* if the function has no type then make it return int */
2265   if (!sym->type->next)
2266     sym->type->next = sym->etype = newIntLink ();
2267
2268   /* function cannot return aggregate */
2269   if (IS_AGGREGATE (sym->type->next))
2270     {
2271       werror (E_FUNC_AGGR, sym->name);
2272       return 0;
2273     }
2274
2275   /* function cannot return bit */
2276   if (IS_BITVAR (sym->type->next))
2277     {
2278       werror (E_FUNC_BIT, sym->name);
2279       return 0;
2280     }
2281
2282   /* check if this function is defined as calleeSaves
2283      then mark it as such */
2284   FUNC_CALLEESAVES(sym->type) = inCalleeSaveList (sym->name);
2285
2286   /* if interrupt service routine  */
2287   /* then it cannot have arguments */
2288   if (IFFUNC_ARGS(sym->type) && FUNC_ISISR (sym->type))
2289     {
2290       if (!IS_VOID(FUNC_ARGS(sym->type)->type)) {
2291         werror (E_INT_ARGS, sym->name);
2292         FUNC_ARGS(sym->type)=NULL;
2293       }
2294     }
2295
2296   if (IFFUNC_ISSHADOWREGS(sym->type) && !FUNC_ISISR (sym->type))
2297     {
2298       werror (E_SHADOWREGS_NO_ISR, sym->name);
2299     }
2300
2301
2302   for (argCnt=1, acargs = FUNC_ARGS(sym->type); 
2303        acargs; 
2304        acargs=acargs->next, argCnt++) {
2305     if (!acargs->sym) { 
2306       // this can happen for reentrant functions
2307       werror(E_PARAM_NAME_OMITTED, sym->name, argCnt);
2308       // the show must go on: synthesize a name and symbol
2309       SNPRINTF (acargs->name, sizeof(acargs->name), "_%s_PARM_%d", sym->name, argCnt);
2310       acargs->sym = newSymbol (acargs->name, 1);
2311       SPEC_OCLS (acargs->etype) = istack;
2312       acargs->sym->type = copyLinkChain (acargs->type);
2313       acargs->sym->etype = getSpec (acargs->sym->type);
2314       acargs->sym->_isparm = 1;
2315       strncpyz (acargs->sym->rname, acargs->name, sizeof(acargs->sym->rname));
2316     } else if (strcmp(acargs->sym->name, acargs->sym->rname)==0) { 
2317       // synthesized name
2318       werror(E_PARAM_NAME_OMITTED, sym->name, argCnt);
2319     }
2320   }
2321   argCnt--;
2322
2323   if (!csym && !(csym = findSym (SymbolTab, sym, sym->name)))
2324     return 1;                   /* not defined nothing more to check  */
2325
2326   /* check if body already present */
2327   if (csym && IFFUNC_HASBODY(csym->type))
2328     {
2329       werror (E_FUNC_BODY, sym->name);
2330       return 0;
2331     }
2332
2333   /* check the return value type   */
2334   if (compareType (csym->type, sym->type) <= 0)
2335     {
2336       werror (E_PREV_DEF_CONFLICT, csym->name, "type");
2337       printFromToType(csym->type, sym->type);
2338       return 0;
2339     }
2340
2341   if (FUNC_ISISR (csym->type) != FUNC_ISISR (sym->type))
2342     {
2343       werror (E_PREV_DEF_CONFLICT, csym->name, "interrupt");
2344     }
2345
2346   /* I don't think this is necessary for interrupts. An isr is a  */
2347   /* root in the calling tree.                                    */
2348   if ((FUNC_REGBANK (csym->type) != FUNC_REGBANK (sym->type)) &&
2349       (!FUNC_ISISR (sym->type)))
2350     {
2351       werror (E_PREV_DEF_CONFLICT, csym->name, "using");
2352     }
2353
2354   if (IFFUNC_ISNAKED (csym->type) != IFFUNC_ISNAKED (sym->type))
2355     {
2356       werror (E_PREV_DEF_CONFLICT, csym->name, "_naked");
2357     }
2358
2359   /* Really, reentrant should match regardless of argCnt, but     */
2360   /* this breaks some existing code (the fp lib functions). If    */
2361   /* the first argument is always passed the same way, this       */
2362   /* lax checking is ok (but may not be true for in future ports) */
2363   if (IFFUNC_ISREENT (csym->type) != IFFUNC_ISREENT (sym->type)
2364       && argCnt>1)
2365     {
2366       //printf("argCnt = %d\n",argCnt);
2367       werror (E_PREV_DEF_CONFLICT, csym->name, "reentrant");
2368     }
2369
2370   if (IFFUNC_ISWPARAM (csym->type) != IFFUNC_ISWPARAM (sym->type))
2371     {
2372       werror (E_PREV_DEF_CONFLICT, csym->name, "wparam");
2373     }
2374
2375   if (IFFUNC_ISSHADOWREGS (csym->type) != IFFUNC_ISSHADOWREGS (sym->type))
2376     {
2377       werror (E_PREV_DEF_CONFLICT, csym->name, "shadowregs");
2378     }
2379   
2380
2381   /* compare expected args with actual args */
2382   exargs = FUNC_ARGS(csym->type);
2383   acargs = FUNC_ARGS(sym->type);
2384
2385   /* for all the expected args do */
2386   for (argCnt = 1;
2387        exargs && acargs;
2388        exargs = exargs->next, acargs = acargs->next, argCnt++)
2389     {
2390       if (getenv("DEBUG_SANITY")) {
2391         fprintf (stderr, "checkFunction: %s ", exargs->name);
2392       }
2393       /* make sure the type is complete and sane */
2394       checkTypeSanity(exargs->etype, exargs->name);
2395
2396       /* If the actual argument is an array, any prototype
2397        * will have modified it to a pointer. Duplicate that
2398        * change here.
2399        */
2400       if (IS_AGGREGATE (acargs->type))
2401         {
2402           checkValue = copyValue (acargs);
2403           aggregateToPointer (checkValue);
2404         }
2405       else
2406         {
2407           checkValue = acargs;
2408         }
2409
2410       if (compareType (exargs->type, checkValue->type) <= 0)
2411         {
2412           werror (E_ARG_TYPE, argCnt);
2413           printFromToType(exargs->type, checkValue->type);
2414           return 0;
2415         }
2416     }
2417
2418   /* if one them ended we have a problem */
2419   if ((exargs && !acargs && !IS_VOID (exargs->type)) ||
2420       (!exargs && acargs && !IS_VOID (acargs->type)))
2421     werror (E_ARG_COUNT);
2422
2423   /* replace with this defition */
2424   sym->cdef = csym->cdef;
2425   deleteSym (SymbolTab, csym, csym->name);
2426   deleteFromSeg(csym);
2427   addSym (SymbolTab, sym, sym->name, sym->level, sym->block, 1);
2428   if (IS_EXTERN (csym->etype) && !
2429       IS_EXTERN (sym->etype))
2430     {
2431       addSet (&publics, sym);
2432     }
2433   return 1;
2434 }
2435
2436 /*------------------------------------------------------------------*/
2437 /* cdbStructBlock - calls struct printing for a blcks               */
2438 /*------------------------------------------------------------------*/
2439 void cdbStructBlock (int block)
2440 {
2441   int i;
2442   bucket **table = StructTab;
2443   bucket *chain;
2444
2445   /* go thru the entire  table  */
2446   for (i = 0; i < 256; i++)
2447     {
2448       for (chain = table[i]; chain; chain = chain->next)
2449         {
2450           if (chain->block >= block)
2451             {
2452               if(debugFile)
2453                 debugFile->writeType((structdef *)chain->sym, chain->block, 0, NULL);
2454             }
2455         }
2456     }
2457 }
2458
2459 /*-----------------------------------------------------------------*/
2460 /* processFuncArgs - does some processing with function args       */
2461 /*-----------------------------------------------------------------*/
2462 void 
2463 processFuncArgs (symbol * func)
2464 {
2465   value *val;
2466   int pNum = 1;
2467   sym_link *funcType=func->type;
2468
2469   if (getenv("SDCC_DEBUG_FUNCTION_POINTERS"))
2470     fprintf (stderr, "SDCCsymt.c:processFuncArgs(%s)\n", func->name);
2471
2472   /* find the function declaration within the type */
2473   while (funcType && !IS_FUNC(funcType))
2474     funcType=funcType->next;
2475
2476   /* if this function has variable argument list */
2477   /* then make the function a reentrant one    */
2478   if (IFFUNC_HASVARARGS(funcType) || (options.stackAuto && !func->cdef))
2479     FUNC_ISREENT(funcType)=1;
2480
2481   /* check if this function is defined as calleeSaves
2482      then mark it as such */
2483   FUNC_CALLEESAVES(funcType) = inCalleeSaveList (func->name);
2484
2485   /* loop thru all the arguments   */
2486   val = FUNC_ARGS(funcType);
2487
2488   /* if it is void then remove parameters */
2489   if (val && IS_VOID (val->type))
2490     {
2491       FUNC_ARGS(funcType) = NULL;
2492       return;
2493     }
2494
2495   /* reset regparm for the port */
2496   (*port->reset_regparms) ();
2497
2498   /* if any of the arguments is an aggregate */
2499   /* change it to pointer to the same type */
2500   while (val)
2501     {
2502       int argreg = 0;
2503       char buffer[SDCC_NAME_MAX+1];
2504       
2505       SNPRINTF (buffer, sizeof(buffer), "%s parameter %d", func->name, pNum);
2506       checkTypeSanity (val->etype, buffer);
2507       
2508       /* mark it as a register parameter if
2509          the function does not have VA_ARG
2510          and as port dictates */
2511       if (!IFFUNC_HASVARARGS(funcType) &&
2512           (argreg = (*port->reg_parm) (val->type)))
2513         {
2514           SPEC_REGPARM (val->etype) = 1;
2515           SPEC_ARGREG(val->etype) = argreg;
2516         } else if (IFFUNC_ISREENT(funcType)) {
2517             FUNC_HASSTACKPARM(funcType) = 1;
2518         }
2519
2520       if (IS_AGGREGATE (val->type))
2521         {
2522           aggregateToPointer (val);
2523         }
2524
2525       val = val->next;
2526       pNum++;
2527     }
2528
2529   /* if this is an internal generated function call */
2530   if (func->cdef) {
2531     /* ignore --stack-auto for this one, we don't know how it is compiled */
2532     /* simply trust on --int-long-reent or --float-reent */
2533     if (IFFUNC_ISREENT(funcType)) {
2534       return;
2535     }
2536   } else {
2537     /* if this function is reentrant or */
2538     /* automatics r 2b stacked then nothing */
2539     if (IFFUNC_ISREENT (funcType) || options.stackAuto)
2540       return;
2541   }
2542
2543   val = FUNC_ARGS(funcType);
2544   pNum = 1;
2545   while (val)
2546     {
2547
2548       /* if a symbolname is not given  */
2549       /* synthesize a variable name */
2550       if (!val->sym)
2551         {
2552           SNPRINTF (val->name, sizeof(val->name), 
2553                     "_%s_PARM_%d", func->name, pNum++);
2554           val->sym = newSymbol (val->name, 1);
2555           if (SPEC_SCLS(val->etype) == S_BIT)
2556             SPEC_OCLS (val->etype) = bit;
2557           else
2558             SPEC_OCLS (val->etype) = port->mem.default_local_map;
2559           val->sym->type = copyLinkChain (val->type);
2560           val->sym->etype = getSpec (val->sym->type);
2561           val->sym->_isparm = 1;
2562           strncpyz (val->sym->rname, val->name, sizeof(val->sym->rname));
2563           #if 0
2564           /* ?? static functions shouldn't imply static parameters - EEP */
2565           if (IS_SPEC(func->etype)) {
2566             SPEC_STAT (val->etype) = SPEC_STAT (val->sym->etype) =
2567               SPEC_STAT (func->etype);
2568           }
2569           #endif
2570           addSymChain (val->sym);
2571
2572         }
2573       else                      /* symbol name given create synth name */
2574         {
2575
2576           SNPRINTF (val->name, sizeof(val->name), "_%s_PARM_%d", func->name, pNum++);
2577           strncpyz (val->sym->rname, val->name, sizeof(val->sym->rname));
2578           val->sym->_isparm = 1;
2579           if (SPEC_SCLS(val->etype) == S_BIT)
2580             SPEC_OCLS (val->etype) = SPEC_OCLS (val->sym->etype) = bit;
2581           else
2582             SPEC_OCLS (val->etype) = SPEC_OCLS (val->sym->etype) =
2583               (options.model != MODEL_SMALL ? xdata : data);
2584           
2585           #if 0
2586           /* ?? static functions shouldn't imply static parameters - EEP */
2587           if (IS_SPEC(func->etype)) {
2588             SPEC_STAT (val->etype) = SPEC_STAT (val->sym->etype) =
2589               SPEC_STAT (func->etype);
2590           }
2591           #endif
2592         }
2593       if (!isinSet(operKeyReset, val->sym)) {
2594         addSet (&operKeyReset, val->sym);
2595         applyToSet (operKeyReset, resetParmKey);
2596       }
2597       val = val->next;
2598     }
2599 }
2600
2601 /*-----------------------------------------------------------------*/
2602 /* isSymbolEqual - compares two symbols return 1 if they match     */
2603 /*-----------------------------------------------------------------*/
2604 int 
2605 isSymbolEqual (symbol * dest, symbol * src)
2606 {
2607   /* if pointers match then equal */
2608   if (dest == src)
2609     return 1;
2610
2611   /* if one of them is null then don't match */
2612   if (!dest || !src)
2613     return 0;
2614
2615   /* if both of them have rname match on rname */
2616   if (dest->rname[0] && src->rname[0])
2617     return (!strcmp (dest->rname, src->rname));
2618
2619   /* otherwise match on name */
2620   return (!strcmp (dest->name, src->name));
2621 }
2622
2623 void PT(sym_link *type)
2624 {
2625         printTypeChain(type,0);
2626 }
2627 /*-----------------------------------------------------------------*/
2628 /* printTypeChain - prints the type chain in human readable form   */
2629 /*-----------------------------------------------------------------*/
2630 void
2631 printTypeChain (sym_link * start, FILE * of)
2632 {
2633   int nlr = 0;
2634   value *args;
2635   sym_link * type, * search;
2636   STORAGE_CLASS scls;
2637
2638   if (!of)
2639     {
2640       of = stdout;
2641       nlr = 1;
2642     }
2643
2644   if (start==NULL) {
2645     fprintf (of, "void");
2646     return;
2647   }
2648
2649   /* Print the chain as it is written in the source: */
2650   /* start with the last entry.                      */
2651   /* However, the storage class at the end of the    */
2652   /* chain reall applies to the first in the chain!  */
2653
2654   for (type = start; type && type->next; type = type->next)
2655     ;
2656   if (IS_SPEC (type))
2657     scls=SPEC_SCLS(type);
2658   else
2659     scls=0;
2660   while (type)
2661     {
2662       if (type==start) {
2663         switch (scls) 
2664           {
2665           case S_DATA: fprintf (of, "data-"); break;
2666           case S_XDATA: fprintf (of, "xdata-"); break;
2667           case S_SFR: fprintf (of, "sfr-"); break;
2668           case S_SBIT: fprintf (of, "sbit-"); break;
2669           case S_CODE: fprintf (of, "code-"); break;
2670           case S_IDATA: fprintf (of, "idata-"); break;
2671           case S_PDATA: fprintf (of, "pdata-"); break;
2672           case S_LITERAL: fprintf (of, "literal-"); break;
2673           case S_STACK: fprintf (of, "stack-"); break;
2674           case S_XSTACK: fprintf (of, "xstack-"); break;
2675           case S_BIT: fprintf (of, "bit-"); break;
2676           case S_EEPROM: fprintf (of, "eeprom-"); break;
2677           default: break;
2678           }
2679       }
2680
2681       if (IS_DECL (type))
2682         {
2683           if (!IS_FUNC(type)) {
2684             if (DCL_PTR_VOLATILE (type)) {
2685               fprintf (of, "volatile-");
2686             }
2687             if (DCL_PTR_CONST (type)) {
2688               fprintf (of, "const-");
2689             }
2690           }
2691           switch (DCL_TYPE (type))
2692             {
2693             case FUNCTION:
2694               fprintf (of, "function %s %s", 
2695                        (IFFUNC_ISBUILTIN(type) ? "__builtin__" : " "),
2696                        (IFFUNC_ISJAVANATIVE(type) ? "_JavaNative" : " "));
2697               fprintf (of, "( ");
2698               for (args = FUNC_ARGS(type); 
2699                    args; 
2700                    args=args->next) {
2701                 printTypeChain(args->type, of);
2702                 if (args->next)
2703                   fprintf(of, ", ");
2704               }
2705               fprintf (of, ") ");
2706               break;
2707             case GPOINTER:
2708               fprintf (of, "generic* ");
2709               break;
2710             case CPOINTER:
2711               fprintf (of, "code* ");
2712               break;
2713             case FPOINTER:
2714               fprintf (of, "xdata* ");
2715               break;
2716             case EEPPOINTER:
2717               fprintf (of, "eeprom* ");
2718               break;
2719             case POINTER:
2720               fprintf (of, "near* ");
2721               break;
2722             case IPOINTER:
2723               fprintf (of, "idata* ");
2724               break;
2725             case PPOINTER:
2726               fprintf (of, "pdata* ");
2727               break;
2728             case UPOINTER:
2729               fprintf (of, "unknown* ");
2730               break;
2731             case ARRAY:
2732               if (DCL_ELEM(type)) {
2733                 fprintf (of, "[%d] ", DCL_ELEM(type));
2734               } else {
2735                 fprintf (of, "[] ");
2736               }
2737               break;
2738             }
2739         }
2740       else
2741         {
2742           if (SPEC_VOLATILE (type))
2743             fprintf (of, "volatile-");
2744           if (SPEC_CONST (type))
2745             fprintf (of, "const-");
2746           if (SPEC_USIGN (type))
2747             fprintf (of, "unsigned-");
2748           switch (SPEC_NOUN (type))
2749             {
2750             case V_INT:
2751               if (IS_LONG (type))
2752                 fprintf (of, "long-");
2753               fprintf (of, "int");
2754               break;
2755
2756             case V_CHAR:
2757               fprintf (of, "char");
2758               break;
2759
2760             case V_VOID:
2761               fprintf (of, "void");
2762               break;
2763
2764             case V_FLOAT:
2765               fprintf (of, "float");
2766               break;
2767
2768             case V_STRUCT:
2769               fprintf (of, "struct %s", SPEC_STRUCT (type)->tag);
2770               break;
2771
2772             case V_SBIT:
2773               fprintf (of, "sbit");
2774               break;
2775
2776             case V_BIT:
2777               fprintf (of, "bit");
2778               break;
2779
2780             case V_BITFIELD:
2781               fprintf (of, "bitfield {%d,%d}", SPEC_BSTR (type), SPEC_BLEN (type));
2782               break;
2783
2784             case V_DOUBLE:
2785               fprintf (of, "double");
2786               break;
2787
2788             default:
2789               fprintf (of, "unknown type");
2790               break;
2791             }
2792         }
2793       /* search entry in list before "type" */
2794       for (search = start; search && search->next != type;)
2795         search = search->next;
2796       type = search;
2797       if (type)
2798         fputc (' ', of);
2799     }
2800   if (nlr)
2801     fprintf (of, "\n");
2802 }
2803
2804 /*--------------------------------------------------------------------*/
2805 /* printTypeChainRaw - prints the type chain in human readable form   */
2806 /*                     in the raw data structure ordering             */
2807 /*--------------------------------------------------------------------*/
2808 void
2809 printTypeChainRaw (sym_link * start, FILE * of)
2810 {
2811   int nlr = 0;
2812   value *args;
2813   sym_link * type;
2814
2815   if (!of)
2816     {
2817       of = stdout;
2818       nlr = 1;
2819     }
2820
2821   if (start==NULL) {
2822     fprintf (of, "void");
2823     return;
2824   }
2825
2826   type = start;
2827   
2828   while (type)
2829     {
2830       if (IS_DECL (type))
2831         {
2832           if (!IS_FUNC(type)) {
2833             if (DCL_PTR_VOLATILE (type)) {
2834               fprintf (of, "volatile-");
2835             }
2836             if (DCL_PTR_CONST (type)) {
2837               fprintf (of, "const-");
2838             }
2839           }
2840           switch (DCL_TYPE (type))
2841             {
2842             case FUNCTION:
2843               fprintf (of, "function %s %s", 
2844                        (IFFUNC_ISBUILTIN(type) ? "__builtin__" : " "),
2845                        (IFFUNC_ISJAVANATIVE(type) ? "_JavaNative" : " "));
2846               fprintf (of, "( ");
2847               for (args = FUNC_ARGS(type); 
2848                    args; 
2849                    args=args->next) {
2850                 printTypeChain(args->type, of);
2851                 if (args->next)
2852                   fprintf(of, ", ");
2853               }
2854               fprintf (of, ") ");
2855               break;
2856             case GPOINTER:
2857               fprintf (of, "generic* ");
2858               break;
2859             case CPOINTER:
2860               fprintf (of, "code* ");
2861               break;
2862             case FPOINTER:
2863               fprintf (of, "xdata* ");
2864               break;
2865             case EEPPOINTER:
2866               fprintf (of, "eeprom* ");
2867               break;
2868             case POINTER:
2869               fprintf (of, "near* ");
2870               break;
2871             case IPOINTER:
2872               fprintf (of, "idata* ");
2873               break;
2874             case PPOINTER:
2875               fprintf (of, "pdata* ");
2876               break;
2877             case UPOINTER:
2878               fprintf (of, "unknown* ");
2879               break;
2880             case ARRAY:
2881               if (DCL_ELEM(type)) {
2882                 fprintf (of, "[%d] ", DCL_ELEM(type));
2883               } else {
2884                 fprintf (of, "[] ");
2885               }
2886               break;
2887             }
2888           if (DCL_TSPEC(type))
2889             {
2890               fprintf (of, "{");
2891               printTypeChainRaw(DCL_TSPEC(type), of);
2892               fprintf (of, "}");
2893             }
2894         }
2895       else if (IS_SPEC (type))
2896         {
2897         switch (SPEC_SCLS (type)) 
2898           {
2899           case S_DATA: fprintf (of, "data-"); break;
2900           case S_XDATA: fprintf (of, "xdata-"); break;
2901           case S_SFR: fprintf (of, "sfr-"); break;
2902           case S_SBIT: fprintf (of, "sbit-"); break;
2903           case S_CODE: fprintf (of, "code-"); break;
2904           case S_IDATA: fprintf (of, "idata-"); break;
2905           case S_PDATA: fprintf (of, "pdata-"); break;
2906           case S_LITERAL: fprintf (of, "literal-"); break;
2907           case S_STACK: fprintf (of, "stack-"); break;
2908           case S_XSTACK: fprintf (of, "xstack-"); break;
2909           case S_BIT: fprintf (of, "bit-"); break;
2910           case S_EEPROM: fprintf (of, "eeprom-"); break;
2911           default: break;
2912           }
2913           if (SPEC_VOLATILE (type))
2914             fprintf (of, "volatile-");
2915           if (SPEC_CONST (type))
2916             fprintf (of, "const-");
2917           if (SPEC_USIGN (type))
2918             fprintf (of, "unsigned-");
2919           switch (SPEC_NOUN (type))
2920             {
2921             case V_INT:
2922               if (IS_LONG (type))
2923                 fprintf (of, "long-");
2924               fprintf (of, "int");
2925               break;
2926
2927             case V_CHAR:
2928               fprintf (of, "char");
2929               break;
2930
2931             case V_VOID:
2932               fprintf (of, "void");
2933               break;
2934
2935             case V_FLOAT:
2936               fprintf (of, "float");
2937               break;
2938
2939             case V_STRUCT:
2940               fprintf (of, "struct %s", SPEC_STRUCT (type)->tag);
2941               break;
2942
2943             case V_SBIT:
2944               fprintf (of, "sbit");
2945               break;
2946
2947             case V_BIT:
2948               fprintf (of, "bit");
2949               break;
2950
2951             case V_BITFIELD:
2952               fprintf (of, "bitfield {%d,%d}", SPEC_BSTR (type), SPEC_BLEN (type));
2953               break;
2954
2955             case V_DOUBLE:
2956               fprintf (of, "double");
2957               break;
2958
2959             default:
2960               fprintf (of, "unknown type");
2961               break;
2962             }
2963         }
2964       else
2965         fprintf (of, "NOT_SPEC_OR_DECL");
2966       type = type->next;
2967       if (type)
2968         fputc (' ', of);
2969     }
2970   if (nlr)
2971     fprintf (of, "\n");
2972 }
2973
2974
2975 /*-----------------------------------------------------------------*/
2976 /* powof2 - returns power of two for the number if number is pow 2 */
2977 /*-----------------------------------------------------------------*/
2978 int
2979 powof2 (TYPE_UDWORD num)
2980 {
2981   int nshifts = 0;
2982   int n1s = 0;
2983
2984   while (num)
2985     {
2986       if (num & 1)
2987         n1s++;
2988       num >>= 1;
2989       nshifts++;
2990     }
2991
2992   if (n1s > 1 || nshifts == 0)
2993     return 0;
2994   return nshifts - 1;
2995 }
2996
2997 symbol *__fsadd;
2998 symbol *__fssub;
2999 symbol *__fsmul;
3000 symbol *__fsdiv;
3001 symbol *__fseq;
3002 symbol *__fsneq;
3003 symbol *__fslt;
3004 symbol *__fslteq;
3005 symbol *__fsgt;
3006 symbol *__fsgteq;
3007
3008 /* Dims: mul/div/mod, BYTE/WORD/DWORD, SIGNED/UNSIGNED */
3009 symbol *__muldiv[3][3][2];
3010 /* Dims: BYTE/WORD/DWORD SIGNED/UNSIGNED */
3011 sym_link *__multypes[3][2];
3012 /* Dims: to/from float, BYTE/WORD/DWORD, SIGNED/USIGNED */
3013 symbol *__conv[2][3][2];
3014 /* Dims: shift left/shift right, BYTE/WORD/DWORD, SIGNED/UNSIGNED */
3015 symbol *__rlrr[2][3][2];
3016
3017 sym_link *floatType;
3018
3019 static char *
3020 _mangleFunctionName(char *in)
3021 {
3022   if (port->getMangledFunctionName)
3023     {
3024       return port->getMangledFunctionName(in);
3025     }
3026   else
3027     {
3028       return in;
3029     }
3030 }
3031
3032 /*-----------------------------------------------------------------*/
3033 /* typeFromStr - create a typechain from an encoded string         */
3034 /* basic types -        'c' - char                                 */
3035 /*                      's' - short                                */
3036 /*                      'i' - int                                  */
3037 /*                      'l' - long                                 */
3038 /*                      'f' - float                                */
3039 /*                      'v' - void                                 */
3040 /*                      '*' - pointer - default (GPOINTER)         */
3041 /* modifiers -          'u' - unsigned                             */
3042 /* pointer modifiers -  'g' - generic                              */
3043 /*                      'x' - xdata                                */
3044 /*                      'p' - code                                 */
3045 /*                      'd' - data                                 */                     
3046 /*                      'F' - function                             */                     
3047 /* examples : "ig*" - generic int *                                */
3048 /*            "cx*" - char xdata *                                 */
3049 /*            "ui" -  unsigned int                                 */
3050 /*-----------------------------------------------------------------*/
3051 sym_link *typeFromStr (char *s)
3052 {
3053     sym_link *r = newLink(DECLARATOR);
3054     int usign = 0;
3055
3056     do {
3057         sym_link *nr;
3058         switch (*s) {
3059         case 'u' : 
3060             usign = 1;
3061             s++;
3062             continue ;
3063             break ;
3064         case 'c':
3065             r->class = SPECIFIER;
3066             SPEC_NOUN(r) = V_CHAR;
3067             break;
3068         case 's':
3069         case 'i':
3070             r->class = SPECIFIER;
3071             SPEC_NOUN(r) = V_INT;
3072             break;
3073         case 'l':
3074             r->class = SPECIFIER;
3075             SPEC_NOUN(r) = V_INT;
3076             SPEC_LONG(r) = 1;
3077             break;
3078         case 'f':
3079             r->class = SPECIFIER;
3080             SPEC_NOUN(r) = V_FLOAT;
3081             break;
3082         case 'v':
3083             r->class = SPECIFIER;
3084             SPEC_NOUN(r) = V_VOID;
3085             break;
3086         case '*':
3087             DCL_TYPE(r) = port->unqualified_pointer;
3088             break;
3089         case 'g':
3090         case 'x':
3091         case 'p':
3092         case 'd':
3093         case 'F':
3094             assert(*(s+1)=='*');
3095             nr = newLink(DECLARATOR);
3096             nr->next = r;
3097             r = nr;
3098             switch (*s) {
3099             case 'g':
3100                 DCL_TYPE(r) = GPOINTER;
3101                 break;
3102             case 'x':
3103                 DCL_TYPE(r) = FPOINTER;
3104                 break;
3105             case 'p':
3106                 DCL_TYPE(r) = CPOINTER;
3107                 break;
3108             case 'd':
3109                 DCL_TYPE(r) = POINTER;
3110                 break;
3111             case 'F':
3112                 DCL_TYPE(r) = FUNCTION;
3113                 nr = newLink(DECLARATOR);
3114                 nr->next = r;
3115                 r = nr;
3116                 DCL_TYPE(r) = CPOINTER;
3117                 break;
3118             }
3119             s++;
3120             break;
3121         default:
3122             werror(E_INTERNAL_ERROR, __FILE__, __LINE__, 
3123                    "typeFromStr: unknown type");
3124             break;
3125         }
3126         if (IS_SPEC(r) && usign) {
3127             SPEC_USIGN(r) = 1;
3128             usign = 0;
3129         }
3130         s++;
3131     } while (*s);
3132     return r;
3133 }
3134
3135 /*-----------------------------------------------------------------*/
3136 /* initCSupport - create functions for C support routines          */
3137 /*-----------------------------------------------------------------*/
3138 void 
3139 initCSupport ()
3140 {
3141   const char *smuldivmod[] =
3142   {
3143     "mul", "div", "mod"
3144   };
3145   const char *sbwd[] =
3146   {
3147     "char", "int", "long"
3148   };
3149   const char *ssu[] =
3150   {
3151     "s", "u"
3152   };
3153   const char *srlrr[] =
3154   {
3155     "rl", "rr"
3156   };
3157
3158   int bwd, su, muldivmod, tofrom, rlrr;
3159
3160   if (getenv("SDCC_NO_C_SUPPORT")) {
3161     /* for debugging only */
3162     return;
3163   }
3164
3165   floatType = newFloatLink ();
3166
3167   for (bwd = 0; bwd < 3; bwd++)
3168     {
3169       sym_link *l = NULL;
3170       switch (bwd)
3171         {
3172         case 0:
3173           l = newCharLink ();
3174           break;
3175         case 1:
3176           l = newIntLink ();
3177           break;
3178         case 2:
3179           l = newLongLink ();
3180           break;
3181         default:
3182           assert (0);
3183         }
3184       __multypes[bwd][0] = l;
3185       __multypes[bwd][1] = copyLinkChain (l);
3186       SPEC_USIGN (__multypes[bwd][1]) = 1;
3187     }
3188
3189   __fsadd = funcOfType ("__fsadd", floatType, floatType, 2, options.float_rent);
3190   __fssub = funcOfType ("__fssub", floatType, floatType, 2, options.float_rent);
3191   __fsmul = funcOfType ("__fsmul", floatType, floatType, 2, options.float_rent);
3192   __fsdiv = funcOfType ("__fsdiv", floatType, floatType, 2, options.float_rent);
3193   __fseq = funcOfType ("__fseq", CHARTYPE, floatType, 2, options.float_rent);
3194   __fsneq = funcOfType ("__fsneq", CHARTYPE, floatType, 2, options.float_rent);
3195   __fslt = funcOfType ("__fslt", CHARTYPE, floatType, 2, options.float_rent);
3196   __fslteq = funcOfType ("__fslteq", CHARTYPE, floatType, 2, options.float_rent);
3197   __fsgt = funcOfType ("__fsgt", CHARTYPE, floatType, 2, options.float_rent);
3198   __fsgteq = funcOfType ("__fsgteq", CHARTYPE, floatType, 2, options.float_rent);
3199
3200   for (tofrom = 0; tofrom < 2; tofrom++)
3201     {
3202       for (bwd = 0; bwd < 3; bwd++)
3203         {
3204           for (su = 0; su < 2; su++)
3205             {
3206               if (tofrom)
3207                 {
3208                   SNPRINTF (buffer, sizeof(buffer), "__fs2%s%s", ssu[su], sbwd[bwd]);
3209                   __conv[tofrom][bwd][su] = funcOfType (buffer, __multypes[bwd][su], floatType, 1, options.float_rent);
3210                 }
3211               else
3212                 {
3213                   SNPRINTF (buffer, sizeof(buffer), "__%s%s2fs", ssu[su], sbwd[bwd]);
3214                   __conv[tofrom][bwd][su] = funcOfType (buffer, floatType, __multypes[bwd][su], 1, options.float_rent);
3215                 }
3216             }
3217         }
3218     }
3219
3220 /*
3221   for (muldivmod = 0; muldivmod < 3; muldivmod++)
3222     {
3223       for (bwd = 0; bwd < 3; bwd++)
3224         {
3225           for (su = 0; su < 2; su++)
3226             {
3227               SNPRINTF (buffer, sizeof(buffer),
3228                         "_%s%s%s",
3229                        smuldivmod[muldivmod],
3230                        ssu[su],
3231                        sbwd[bwd]);
3232               __muldiv[muldivmod][bwd][su] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[bwd][su], 2, options.intlong_rent);
3233               FUNC_NONBANKED (__muldiv[muldivmod][bwd][su]->type) = 1;
3234             }
3235         }
3236     }
3237
3238   muluint() and mulsint() resp. mululong() and mulslong() return the same result.
3239   Therefore they've been merged into mulint() and mullong().
3240 */
3241
3242   for (bwd = 0; bwd < 3; bwd++)
3243     {
3244       for (su = 0; su < 2; su++)
3245         {
3246           for (muldivmod = 1; muldivmod < 3; muldivmod++)
3247             {
3248               /* div and mod */
3249               SNPRINTF (buffer, sizeof(buffer),
3250                         "_%s%s%s",
3251                        smuldivmod[muldivmod],
3252                        ssu[su],
3253                        sbwd[bwd]);
3254               __muldiv[muldivmod][bwd][su] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[bwd][su], 2, options.intlong_rent);
3255               FUNC_NONBANKED (__muldiv[muldivmod][bwd][su]->type) = 1;
3256             }
3257         }
3258     }
3259   /* mul only */
3260   muldivmod = 0;
3261   /* byte */
3262   bwd = 0;
3263   for (su = 0; su < 2; su++)
3264     {
3265       /* muluchar and mulschar are still separate functions, because e.g. the z80
3266          port is sign/zero-extending to int before calling mulint() */
3267       SNPRINTF (buffer, sizeof(buffer),
3268                 "_%s%s%s",
3269                 smuldivmod[muldivmod],
3270                 ssu[su],
3271                 sbwd[bwd]);
3272       __muldiv[muldivmod][bwd][su] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[bwd][su], 2, options.intlong_rent);
3273       FUNC_NONBANKED (__muldiv[muldivmod][bwd][su]->type) = 1;
3274     }
3275   /* signed only */
3276   su = 0;
3277   /* word and doubleword */
3278   for (bwd = 1; bwd < 3; bwd++)
3279     {
3280       /* mul, int/long */
3281       SNPRINTF (buffer, sizeof(buffer),
3282                 "_%s%s",
3283                 smuldivmod[muldivmod],
3284                 sbwd[bwd]);
3285       __muldiv[muldivmod][bwd][0] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[bwd][su], 2, options.intlong_rent);
3286       FUNC_NONBANKED (__muldiv[muldivmod][bwd][0]->type) = 1;
3287       /* signed = unsigned */
3288       __muldiv[muldivmod][bwd][1] = __muldiv[muldivmod][bwd][0];
3289     }
3290
3291   for (rlrr = 0; rlrr < 2; rlrr++)
3292     {
3293       for (bwd = 0; bwd < 3; bwd++)
3294         {
3295           for (su = 0; su < 2; su++)
3296             {
3297               SNPRINTF (buffer, sizeof(buffer),
3298                         "_%s%s%s",
3299                        srlrr[rlrr],
3300                        ssu[su],
3301                        sbwd[bwd]);
3302               __rlrr[rlrr][bwd][su] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[0][0], 2, options.intlong_rent);
3303               FUNC_NONBANKED (__rlrr[rlrr][bwd][su]->type) = 1;
3304             }
3305         }
3306     }
3307 }
3308
3309 /*-----------------------------------------------------------------*/
3310 /* initBuiltIns - create prototypes for builtin functions          */
3311 /*-----------------------------------------------------------------*/
3312 void initBuiltIns()
3313 {
3314     int i;
3315     symbol *sym;
3316
3317     if (!port->builtintable) return ;
3318
3319     for (i = 0 ; port->builtintable[i].name ; i++) {
3320         sym = funcOfTypeVarg(port->builtintable[i].name,port->builtintable[i].rtype,
3321                              port->builtintable[i].nParms,port->builtintable[i].parm_types);
3322         FUNC_ISBUILTIN(sym->type) = 1;
3323         FUNC_ISREENT(sym->type) = 0;    /* can never be reentrant */
3324     }
3325 }
3326
3327 sym_link *validateLink(sym_link         *l, 
3328                         const char      *macro,
3329                         const char      *args,
3330                         const char      select,
3331                         const char      *file, 
3332                         unsigned        line)
3333 {    
3334   if (l && l->class==select)
3335     {
3336         return l;
3337     }
3338     fprintf(stderr, 
3339             "Internal error: validateLink failed in %s(%s) @ %s:%u:"
3340             " expected %s, got %s\n",
3341             macro, args, file, line, 
3342             DECLSPEC2TXT(select), l ? DECLSPEC2TXT(l->class) : "null-link");
3343     exit(-1);
3344     return l; // never reached, makes compiler happy.
3345 }
3346
3347 /*--------------------------------------------------------------------*/
3348 /* newEnumType - create an integer type compatible with enumerations  */
3349 /*--------------------------------------------------------------------*/
3350 sym_link *
3351 newEnumType (symbol *enumlist)
3352 {
3353   int min, max, v;
3354   symbol *sym;
3355   sym_link *type;
3356
3357   if (!enumlist)
3358     {
3359       type = newLink (SPECIFIER);
3360       SPEC_NOUN (type) = V_INT;
3361       return type;
3362     }
3363       
3364   /* Determine the range of the enumerated values */
3365   sym = enumlist;
3366   min = max = (int) floatFromVal (valFromType (sym->type));
3367   for (sym = sym->next; sym; sym = sym->next)
3368     {
3369       v = (int) floatFromVal (valFromType (sym->type));
3370       if (v<min)
3371         min = v;
3372       if (v>max)
3373         max = v;
3374     }
3375
3376   /* Determine the smallest integer type that is compatible with this range */
3377   type = newLink (SPECIFIER);
3378   if (min>=0 && max<=255)
3379     {
3380       SPEC_NOUN (type) = V_CHAR;
3381       SPEC_USIGN (type) = 1;
3382     }
3383   else if (min>=-128 && max<=127)
3384     {
3385       SPEC_NOUN (type) = V_CHAR;
3386     }
3387   else if (min>=0 && max<=65535)
3388     {
3389       SPEC_NOUN (type) = V_INT;
3390       SPEC_USIGN (type) = 1;
3391     }
3392   else if (min>=-32768 && max<=32767)
3393     {
3394       SPEC_NOUN (type) = V_INT;
3395     }
3396   else
3397     {
3398       SPEC_NOUN (type) = V_INT;
3399       SPEC_LONG (type) = 1;
3400       if (min>=0)
3401         SPEC_USIGN (type) = 1;
3402     }
3403   
3404   return type;    
3405 }