a5a81b6f5ea89be39ad0e04be127424ea6cb7e3e
[fw/sdcc] / src / pic16 / main.c
1 /*-------------------------------------------------------------------------
2
3   main.c - pic16 specific general functions.
4
5    Written by - Scott Dattalo scott@dattalo.com
6    Ported to PIC16 by - Martin Dubuc m.debuc@rogers.com
7     
8    Note that mlh prepended _pic16_ on the static functions.  Makes
9    it easier to set a breakpoint using the debugger.
10
11
12    This program is free software; you can redistribute it and/or modify it
13    under the terms of the GNU General Public License as published by the
14    Free Software Foundation; either version 2, or (at your option) any
15    later version.
16    
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21    
22    You should have received a copy of the GNU General Public License
23    along with this program; if not, write to the Free Software
24    Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 -------------------------------------------------------------------------*/
26
27 #include "common.h"
28 #include "main.h"
29 #include "ralloc.h"
30 #include "device.h"
31 #include "SDCCutil.h"
32 #include "glue.h"
33 #include "pcode.h"
34
35
36 static char _defaultRules[] =
37 {
38 #include "peeph.rul"
39 };
40
41 /* list of key words used by pic16 */
42 static char *_pic16_keywords[] =
43 {
44   "at",
45   "code",
46   "critical",
47   "register",
48   "data",
49   "far",
50   "interrupt",
51   "near",
52   "pdata",
53   "reentrant",
54   "sfr",
55   "sfr16",
56   "using",
57   "_data",
58   "_code",
59   "_generic",
60   "_near",
61   "_pdata",
62   "_naked",
63   "shadowregs",
64   "wparam",
65   "prodlp",
66   "prodhp",
67   "fsr0lp",
68   "fixed16x16",
69   
70 //  "bit",
71 //  "idata",
72 //  "sbit",
73 //  "xdata",
74 //  "_xdata",
75 //  "_idata",
76   NULL
77 };
78
79
80 pic16_sectioninfo_t pic16_sectioninfo;
81
82 int xinst=0;
83
84
85 extern char *pic16_processor_base_name(void);
86
87 void  pic16_pCodeInitRegisters(void);
88
89 void pic16_assignRegisters (ebbIndex *);
90
91 static int regParmFlg = 0;      /* determine if we can register a parameter */
92
93 pic16_options_t pic16_options;
94
95 extern set *includeDirsSet;
96 extern set *dataDirsSet;
97 extern set *libFilesSet;
98
99 /* Also defined in gen.h, but the #include is commented out */
100 /* for an unknowned reason. - EEP */
101 void pic16_emitDebuggerSymbol (char *);
102  
103 extern void pic16_emitConfigRegs(FILE *of);
104 extern void pic16_emitIDRegs(FILE *of);
105
106
107
108 static void
109 _pic16_init (void)
110 {
111   asm_addTree (&asm_asxxxx_mapping);
112   pic16_pCodeInitRegisters();
113   maxInterrupts = 2;
114 }
115
116 static void
117 _pic16_reset_regparm (void)
118 {
119   regParmFlg = 0;
120 }
121
122 static int
123 _pic16_regparm (sym_link * l, bool reentrant)
124 {
125   /* force all parameters via SEND/RECEIVE */
126   if(0 /*pic16_options.ip_stack*/) {
127     /* for this processor it is simple
128      * can pass only the first parameter in a register */
129     if(regParmFlg)return 0;
130       regParmFlg++;
131       return 1; //regParmFlg;
132   } else {
133     /* otherwise pass all arguments in registers via SEND/RECEIVE */
134     regParmFlg++;// = 1;
135     return regParmFlg;
136   }
137 }
138
139
140 int initsfpnt=0;                /* set to 1 if source provides a pragma for stack
141                                  * so glue() later emits code to initialize stack/frame pointers */
142 set *absSymSet;
143
144 set *sectNames=NULL;                    /* list of section listed in pragma directives */
145 set *sectSyms=NULL;                     /* list of symbols set in a specific section */
146 set *wparamList=NULL;
147
148 #if 0
149 /* This is an experimental code for #pragma inline
150    and is temporarily disabled for 2.5.0 release */
151 set *asmInlineMap=NULL;
152 #endif  /* 0 */
153
154 struct {
155   unsigned ignore: 1;
156   unsigned want_libc: 1;
157   unsigned want_libm: 1;
158   unsigned want_libio: 1;
159   unsigned want_libdebug: 1;
160 } libflags = { 0, 0, 0, 0, 0 };
161   
162
163 enum {
164   P_MAXRAM = 1,
165   P_STACK,
166   P_CODE,
167   P_UDATA,
168   P_LIBRARY
169 };
170
171 static int
172 do_pragma(int id, const char *name, const char *cp)
173 {
174   struct pragma_token_s token;
175   int err = 0;
176   int processed = 1;
177
178   init_pragma_token(&token);
179
180   switch (id)
181     {
182     /* #pragma maxram [maxram] */
183     case P_MAXRAM:
184       {
185         int max_ram;
186
187         cp = get_pragma_token(cp, &token);
188         if (TOKEN_INT == token.type)
189           max_ram = token.val.int_val;
190         else
191           {
192             err = 1;
193             break;
194           }
195
196         cp = get_pragma_token(cp, &token);
197         if (TOKEN_EOL != token.type)
198           {
199             err = 1;
200             break;
201           }
202
203         pic16_setMaxRAM(max_ram);
204       }
205       break;
206
207     /* #pragma stack [stack-position] [stack-len] */
208     case  P_STACK:
209       {
210         unsigned int stackPos, stackLen;
211         regs *reg;
212         symbol *sym;
213
214         cp = get_pragma_token(cp, &token);
215         if (TOKEN_INT != token.type)
216           {
217             err = 1;
218             break;
219           }
220         stackPos = token.val.int_val;
221
222         cp = get_pragma_token(cp, &token);
223         if (TOKEN_INT != token.type)
224           {
225             err = 1;
226             break;
227           }
228         stackLen = token.val.int_val;
229
230         cp = get_pragma_token(cp, &token);
231         if (TOKEN_EOL != token.type)
232           {
233             err = 1;
234             break;
235           }
236
237         if (stackLen < 1) {
238           stackLen = 64;
239           fprintf(stderr, "%s:%d: warning: setting stack to default size %d (0x%04x)\n",
240                   filename, lineno, stackLen, stackLen);
241         }
242
243         /* check sanity of stack */
244         if ((stackPos >> 8) != ((stackPos + stackLen - 1) >> 8)) {
245           fprintf (stderr, "%s:%u: warning: stack [0x%03X,0x%03X] crosses memory bank boundaries (not fully tested)\n",
246                   filename, lineno, stackPos, stackPos + stackLen - 1);
247         }
248
249         if (pic16) {
250           if (stackPos < pic16->acsSplitOfs) {
251             fprintf (stderr, "%s:%u: warning: stack [0x%03X, 0x%03X] intersects with the access bank [0x000,0x%03x] -- this is highly discouraged!\n",
252                   filename, lineno, stackPos, stackPos + stackLen - 1, pic16->acsSplitOfs);
253           }
254
255           if (stackPos+stackLen > 0xF00 + pic16->acsSplitOfs) {
256             fprintf (stderr, "%s:%u: warning: stack [0x%03X,0x%03X] intersects with special function registers [0x%03X,0xFFF]-- this is highly discouraged!\n",
257                    filename, lineno, stackPos, stackPos + stackLen - 1, 0xF00 + pic16->acsSplitOfs);
258           }
259
260           if (stackPos+stackLen > pic16->RAMsize) {
261             fprintf (stderr, "%s:%u: error: stack [0x%03X,0x%03X] is placed outside available memory [0x000,0x%03X]!\n",
262                   filename, lineno, stackPos, stackPos + stackLen - 1, pic16->RAMsize-1);
263             err = 1;
264             break;
265           }
266         }
267
268         reg = newReg(REG_SFR, PO_SFR_REGISTER, stackPos, "_stack", stackLen-1, 0, NULL);
269         addSet(&pic16_fix_udata, reg);
270
271         reg = newReg(REG_SFR, PO_SFR_REGISTER, stackPos + stackLen-1, "_stack_end", 1, 0, NULL);
272         addSet(&pic16_fix_udata, reg);
273
274         sym = newSymbol("stack", 0);
275         sprintf(sym->rname, "_%s", sym->name);
276         addSet(&publics, sym);
277
278         sym = newSymbol("stack_end", 0);
279         sprintf(sym->rname, "_%s", sym->name);
280         addSet(&publics, sym);
281     
282         initsfpnt = 1;    // force glue() to initialize stack/frame pointers */
283       }
284       break;
285
286     /* #pragma code [symbol] [location] */
287     case P_CODE:
288       {
289         absSym *absS;
290
291         cp = get_pragma_token(cp, &token);
292         if (TOKEN_STR != token.type)
293           goto code_err;
294
295         absS = Safe_calloc(1, sizeof(absSym));
296         sprintf(absS->name, "_%s", get_pragma_string(&token));
297
298         cp = get_pragma_token(cp, &token);
299         if (TOKEN_INT != token.type)
300           {
301           code_err:
302             //fprintf (stderr, "%s:%d: #pragma code [symbol] [location] -- symbol or location missing\n", filename, lineno);
303             err = 1;
304             break;
305           }
306         absS->address = token.val.int_val;
307
308         cp = get_pragma_token(cp, &token);
309         if (TOKEN_EOL != token.type)
310           {
311             err = 1;
312             break;
313           }
314
315         if ((absS->address % 2) != 0) {
316           absS->address--;
317           fprintf(stderr, "%s:%d: warning: code memory locations should be word aligned, will locate to 0x%06x instead\n",
318                   filename, lineno, absS->address);
319         }
320
321         addSet(&absSymSet, absS);
322 //      fprintf(stderr, "%s:%d symbol %s will be placed in location 0x%06x in code memory\n",
323 //        __FILE__, __LINE__, symname, absS->address);
324       }
325       break;
326
327     /* #pragma udata [section-name] [symbol] */
328     case P_UDATA:
329       {
330         char *sectname;
331         const char *symname;
332         symbol *nsym;
333         sectSym *ssym;
334         sectName *snam;
335         int found = 0;
336
337         cp = get_pragma_token(cp, &token);
338         if (TOKEN_STR == token.type)
339           sectname = Safe_strdup(get_pragma_string(&token));
340         else
341           {
342             err = 1;
343             break;
344           }
345
346         cp = get_pragma_token(cp, &token);
347         if (TOKEN_STR == token.type)
348           symname = get_pragma_string(&token);
349         else
350           {
351             //fprintf (stderr, "%s:%d: #pragma udata [section-name] [symbol] -- section-name or symbol missing!\n", filename, lineno);
352             err = 1;
353             symname = NULL;
354           }
355
356         while (symname)
357           {
358             ssym = Safe_calloc(1, sizeof(sectSym));
359             ssym->name = Safe_calloc(1, strlen(symname) + 2);
360             sprintf(ssym->name, "%s%s", port->fun_prefix, symname);
361             ssym->reg = NULL;
362
363             addSet(&sectSyms, ssym);
364
365             nsym = newSymbol((char *)symname, 0);
366             strcpy(nsym->rname, ssym->name);
367
368 #if 0
369             checkAddSym(&publics, nsym);
370 #endif
371
372             found = 0;
373             for (snam = setFirstItem(sectNames);snam;snam=setNextItem(sectNames))
374               {
375                 if (!strcmp(sectname, snam->name))
376                   {
377                     found=1;
378                     break;
379                   }
380               }
381
382             if(!found)
383               {
384                 snam = Safe_calloc(1, sizeof(sectName));
385                 snam->name = Safe_strdup(sectname);
386                 snam->regsSet = NULL;
387
388                 addSet(&sectNames, snam);
389               }
390
391             ssym->section = snam;
392
393 #if 0
394             fprintf(stderr, "%s:%d placing symbol %s at section %s (%p)\n", __FILE__, __LINE__,
395                ssym->name, snam->name, snam);
396 #endif
397
398             cp = get_pragma_token(cp, &token);
399             if (TOKEN_STR == token.type)
400               symname = get_pragma_string(&token);
401             else if (TOKEN_EOL == token.type)
402               symname = NULL;
403             else
404               {
405                 err = 1;
406                 symname = NULL;
407               }
408           }
409
410           Safe_free(sectname);
411       }
412       break;
413
414     /* #pragma library library_module */
415     case P_LIBRARY:
416       {
417         const char *lmodule;
418
419         cp = get_pragma_token(cp, &token);
420         if (TOKEN_EOL != token.type)
421           {
422             lmodule = get_pragma_string(&token);
423
424             /* lmodule can be:
425              * c        link the C library
426              * math     link the math library
427              * io       link the IO library
428              * debug    link the debug libary
429              * anything else, will link as-is */
430      
431             if(!strcmp(lmodule, "c"))
432               libflags.want_libc = 1;
433             else if(!strcmp(lmodule, "math"))
434               libflags.want_libm = 1;
435             else if(!strcmp(lmodule, "io"))
436               libflags.want_libio = 1;
437             else if(!strcmp(lmodule, "debug"))
438               libflags.want_libdebug = 1;
439             else if(!strcmp(lmodule, "ignore"))
440               libflags.ignore = 1;
441             else
442               {
443                 if(!libflags.ignore)
444                   {
445                     fprintf(stderr, "link library %s\n", lmodule);
446                     addSetHead(&libFilesSet, (char *)lmodule);
447                   }
448               }
449           }
450         else
451           {
452             err = 1;
453             break;
454           }
455
456         cp = get_pragma_token(cp, &token);
457         if (TOKEN_EOL != token.type)
458           {
459             err = 1;
460             break;
461           }
462       }
463       break;
464
465 #if 0
466   /* This is an experimental code for #pragma inline
467      and is temporarily disabled for 2.5.0 release */
468     case P_INLINE:
469       {
470         char *tmp = strtok((char *)NULL, WHITECOMMA);
471
472         while(tmp) {
473           addSet(&asmInlineMap, Safe_strdup( tmp ));
474           tmp = strtok((char *)NULL, WHITECOMMA);
475         }
476
477         {
478           char *s;
479           
480           for(s = setFirstItem(asmInlineMap); s ; s = setNextItem(asmInlineMap)) {
481             debugf("inline asm: `%s'\n", s);
482           }
483         }
484       }
485       break;
486 #endif  /* 0 */
487
488     default:
489       processed = 0;
490       break;
491   }
492
493   get_pragma_token(cp, &token);
494
495   if (1 == err)
496     werror(W_BAD_PRAGMA_ARGUMENTS, name);
497
498   free_pragma_token(&token);
499   return processed;
500 }
501
502 static struct pragma_s pragma_tbl[] = {
503   { "maxram",  P_MAXRAM,  0, do_pragma },
504   { "stack",   P_STACK,   0, do_pragma },
505   { "code",    P_CODE,    0, do_pragma },
506   { "udata",   P_UDATA,   0, do_pragma },
507   { "library", P_LIBRARY, 0, do_pragma },
508 /*{ "inline",  P_INLINE,  0, do_pragma }, */
509   { NULL,      0,         0, NULL },
510   };
511
512 static int
513 _process_pragma(const char *s)
514 {
515   return process_pragma_tbl(pragma_tbl, s);
516 }
517
518 #define REP_UDATA       "--preplace-udata-with="
519
520 #define STACK_MODEL     "--pstack-model="
521 #define OPT_BANKSEL     "--obanksel="
522
523 #define ALT_ASM         "--asm="
524 #define ALT_LINK        "--link="
525
526 #define IVT_LOC         "--ivt-loc="
527 #define NO_DEFLIBS      "--nodefaultlibs"
528 #define MPLAB_COMPAT    "--mplab-comp"
529
530 #define NL_OPT          "--nl="
531 #define USE_CRT         "--use-crt="
532
533 #define OFMSG_LRSUPPORT "--flr-support"
534
535 #define OPTIMIZE_GOTO   "--optimize-goto"
536 #define OPTIMIZE_CMP    "--optimize-cmp"
537 #define OPTIMIZE_DF     "--optimize-df"
538
539 char *alt_asm=NULL;
540 char *alt_link=NULL;
541
542 int pic16_mplab_comp=0;
543 extern int pic16_debug_verbose;
544 extern int pic16_ralloc_debug;
545 extern int pic16_pcode_verbose;
546
547 int pic16_fstack=0;
548 int pic16_enable_peeps=0;
549 int pic16_nl=0;                 /* 0 for LF, 1 for CRLF */
550
551 OPTION pic16_optionsTable[]= {
552         { 0,    NO_DEFLIBS,             &pic16_options.nodefaultlibs,   "do not link default libraries when linking"},
553         { 0,    "--pno-banksel",        &pic16_options.no_banksel,      "do not generate BANKSEL assembler directives"},
554         { 0,    OPT_BANKSEL,            NULL,                           "set banksel optimization level (default=0 no)"},
555 //      { 0,    "--pomit-config-words", &pic16_options.omit_configw,    "omit the generation of configuration words"},
556 //      { 0,    "--pomit-ivt",          &pic16_options.omit_ivt,        "omit the generation of the Interrupt Vector Table"},
557 //      { 0,    "--pleave-reset-vector",&pic16_options.leave_reset,     "when omitting IVT leave RESET vector"},
558         { 0,    STACK_MODEL,            NULL,                           "use stack model 'small' (default) or 'large'"},
559
560         { 0,    "--debug-xtra",         &pic16_debug_verbose,   "show more debug info in assembly output"},
561         { 0,    "--debug-ralloc",       &pic16_ralloc_debug,    "dump register allocator debug file *.d"},
562         { 0,    "--pcode-verbose",      &pic16_pcode_verbose,   "dump pcode related info"},
563                 
564         { 0,    REP_UDATA,      NULL,   "Place udata variables at another section: udata_acs, udata_ovr, udata_shr"},
565
566         { 0,    ALT_ASM,        NULL,   "Use alternative assembler"},
567         { 0,    ALT_LINK,       NULL,   "Use alternative linker"},
568
569         { 0,    "--denable-peeps",      &pic16_enable_peeps,    "explicit enable of peepholes"},
570         { 0,    IVT_LOC,        NULL,   "<nnnn> interrupt vector table location"},
571         { 0,    "--calltree",           &pic16_options.dumpcalltree,    "dump call tree in .calltree file"},
572         { 0,    MPLAB_COMPAT,           &pic16_mplab_comp,      "enable compatibility mode for MPLAB utilities (MPASM/MPLINK)"},
573         { 0,    "--fstack",             &pic16_fstack,          "enable stack optimizations"},
574         { 0,    NL_OPT,         NULL,                           "new line, \"lf\" or \"crlf\""},
575         { 0,    USE_CRT,        NULL,   "use <crt-o> run-time initialization module"},
576         { 0,    "--no-crt",     &pic16_options.no_crt,  "do not link any default run-time initialization module"},
577         { 0,    "--gstack",     &pic16_options.gstack,  "trace stack pointer push/pop to overflow"},
578         { 0,    OPTIMIZE_GOTO,  NULL,                   "try to use (conditional) BRA instead of GOTO"},
579         { 0,    OPTIMIZE_CMP,   NULL,                   "try to optimize some compares"},
580         { 0,    OPTIMIZE_DF,    NULL,                   "thoroughly analyze data flow (memory and time intensive!)"},
581         { 0,    "--num-func-alloc-regs", &pic16_options.CATregs, "dump number of temporary registers allocated for each function"},
582 #if XINST
583         { 'y',  "--extended",   &xinst, "enable Extended Instruction Set/Literal Offset Addressing mode"},
584 #endif
585         { 0,    NULL,           NULL,   NULL}
586         };
587
588
589 #define ISOPT(str)      !strncmp(argv[ *i ], str, strlen(str) )
590
591 extern char *getStringArg(const char *,  char **, int *, int);
592 extern int getIntArg(const char *, char **, int *, int);
593
594 static bool
595 _pic16_parseOptions (int *pargc, char **argv, int *i)
596 {
597   int j=0;
598   char *stkmodel;
599   
600   /* TODO: allow port-specific command line options to specify
601    * segment names here.
602    */
603   
604     /* check for arguments that have associated an integer variable */
605     while(pic16_optionsTable[j].pparameter) {
606       if(ISOPT( pic16_optionsTable[j].longOpt )) {
607         (*pic16_optionsTable[j].pparameter)++;
608         return TRUE;
609       }
610       j++;
611     }
612
613     if(ISOPT(STACK_MODEL)) {
614       stkmodel = getStringArg(STACK_MODEL, argv, i, *pargc);
615       if(!STRCASECMP(stkmodel, "small"))pic16_options.stack_model = 0;
616       else if(!STRCASECMP(stkmodel, "large"))pic16_options.stack_model = 1;
617       else {
618         fprintf(stderr, "Unknown stack model: %s", stkmodel);
619         exit(EXIT_FAILURE);
620       }
621       return TRUE;
622     }
623
624     if(ISOPT(OPT_BANKSEL)) {
625       pic16_options.opt_banksel = getIntArg(OPT_BANKSEL, argv, i, *pargc);
626       return TRUE;
627     }
628
629     if(ISOPT(REP_UDATA)) {
630       pic16_sectioninfo.at_udata = Safe_strdup(getStringArg(REP_UDATA, argv, i, *pargc));
631       return TRUE;
632     }
633         
634     if(ISOPT(ALT_ASM)) {
635       alt_asm = Safe_strdup(getStringArg(ALT_ASM, argv, i, *pargc));
636       return TRUE;
637     }
638         
639     if(ISOPT(ALT_LINK)) {
640       alt_link = Safe_strdup(getStringArg(ALT_LINK, argv, i, *pargc));
641       return TRUE;
642     }
643
644     if(ISOPT(IVT_LOC)) {
645       pic16_options.ivt_loc = getIntArg(IVT_LOC, argv, i, *pargc);
646       fprintf(stderr, "%s:%d setting interrupt vector addresses 0x%x\n", __FILE__, __LINE__, pic16_options.ivt_loc);
647       return TRUE;
648     }
649         
650     if(ISOPT(NL_OPT)) {
651       char *tmp;
652             
653         tmp = Safe_strdup( getStringArg(NL_OPT, argv, i, *pargc) );
654         if(!STRCASECMP(tmp, "lf"))pic16_nl = 0;
655         else if(!STRCASECMP(tmp, "crlf"))pic16_nl = 1;
656         else {
657           fprintf(stderr, "invalid termination character id\n");
658           exit(EXIT_FAILURE);
659         }
660         return TRUE;
661     }
662
663     if(ISOPT(USE_CRT)) {
664       pic16_options.no_crt = 0;
665       pic16_options.crt_name = Safe_strdup( getStringArg(USE_CRT, argv, i, *pargc) );
666
667       return TRUE;
668     }
669
670 #if 0
671     if(ISOPT(OFMSG_LRSUPPORT)) {
672       pic16_options.opt_flags |= OF_LR_SUPPORT;
673       return TRUE;
674     }
675 #endif
676
677     if (ISOPT(OPTIMIZE_GOTO)) {
678       pic16_options.opt_flags |= OF_OPTIMIZE_GOTO;
679       return TRUE;
680     }
681
682     if(ISOPT(OPTIMIZE_CMP)) {
683       pic16_options.opt_flags |= OF_OPTIMIZE_CMP;
684       return TRUE;
685     }
686
687     if (ISOPT(OPTIMIZE_DF)) {
688       pic16_options.opt_flags |= OF_OPTIMIZE_DF;
689       return TRUE;
690     }
691     
692
693   return FALSE;
694 }
695
696 extern set *userIncDirsSet;
697
698 static void _pic16_initPaths(void)
699 {
700   char pic16incDir[512];
701   char pic16libDir[512];
702   set *pic16incDirsSet=NULL;
703   set *pic16libDirsSet=NULL;
704   char devlib[512];
705
706     setMainValue("mcu", pic16->name[2] );
707     addSet(&preArgvSet, Safe_strdup("-D{mcu}"));
708
709     setMainValue("mcu1", pic16->name[1] );
710     addSet(&preArgvSet, Safe_strdup("-D__{mcu1}"));
711
712     sprintf(pic16incDir, "%s%cpic16", INCLUDE_DIR_SUFFIX, DIR_SEPARATOR_CHAR);
713     sprintf(pic16libDir, "%s%cpic16", LIB_DIR_SUFFIX, DIR_SEPARATOR_CHAR);
714
715
716     if(!options.nostdinc) {
717       /* setup pic16 include directory */
718       pic16incDirsSet = appendStrSet(dataDirsSet, NULL, pic16incDir);
719       includeDirsSet = pic16incDirsSet;
720 //      mergeSets(&includeDirsSet, pic16incDirsSet);
721     }
722     /* pic16 port should not search to the SDCC standard include directories,
723      * so add here the deleted include dirs that user has issued in command line */
724     mergeSets(&pic16incDirsSet, userIncDirsSet);
725
726     if(!options.nostdlib) {
727       /* setup pic16 library directory */
728       pic16libDirsSet = appendStrSet(dataDirsSet, NULL, pic16libDir);
729       libDirsSet = pic16libDirsSet;
730 //      mergeSets(&libDirsSet, pic16libDirsSet);
731     }
732
733     if(!pic16_options.nodefaultlibs) {
734       /* now add the library for the device */
735       sprintf(devlib, "%s.lib", pic16->name[2]);
736       addSet(&libFilesSet, Safe_strdup(devlib));
737
738       /* add the internal SDCC library */
739       addSet(&libFilesSet, Safe_strdup( "libsdcc.lib" ));
740     }
741 }
742
743 extern set *linkOptionsSet;
744 char *msprintf(hTab *pvals, const char *pformat, ...);
745 int my_system(const char *cmd);
746
747 /* forward declarations */   
748 extern const char *pic16_linkCmd[];
749 extern const char *pic16_asmCmd[];
750 extern set *asmOptionsSet;
751   
752 /* custom function to link objects */
753 static void _pic16_linkEdit(void)
754 {
755   hTab *linkValues=NULL;
756   char lfrm[1024];
757   char *lcmd;
758   char temp[1024];
759   set *tSet=NULL;
760   int ret;
761   
762         /*
763          * link command format:
764          * {linker} {incdirs} {lflags} -o {outfile} {spec_ofiles} {ofiles} {libs}
765          *
766          */
767         sprintf(lfrm, "{linker} {incdirs} {lflags} -w -r -o {outfile} {user_ofile} {ofiles} {spec_ofiles} {libs}");
768
769         shash_add(&linkValues, "linker", pic16_linkCmd[0]);
770
771         mergeSets(&tSet, libDirsSet);
772         mergeSets(&tSet, libPathsSet);
773         
774         shash_add(&linkValues, "incdirs", joinStrSet( appendStrSet(tSet, "-I\"", "\"")));
775         shash_add(&linkValues, "lflags", joinStrSet(linkOptionsSet));
776   
777         shash_add(&linkValues, "outfile", fullDstFileName ? fullDstFileName : dstFileName);
778
779         if(fullSrcFileName) {
780                 sprintf(temp, "%s.o", fullDstFileName ? fullDstFileName : dstFileName);
781 //              addSetHead(&relFilesSet, Safe_strdup(temp));
782                 shash_add(&linkValues, "user_ofile", temp);
783         }
784
785         if(!pic16_options.no_crt)
786           shash_add(&linkValues, "spec_ofiles", pic16_options.crt_name);
787
788         shash_add(&linkValues, "ofiles", joinStrSet(relFilesSet));
789
790         if(!libflags.ignore) {
791           if(libflags.want_libc)
792             addSet(&libFilesSet, Safe_strdup("libc18f.lib"));
793         
794           if(libflags.want_libm)
795             addSet(&libFilesSet, Safe_strdup("libm18f.lib"));
796         
797           if(libflags.want_libio) {
798             sprintf(temp, "libio%s.lib", pic16->name[1]);       /* build libio18f452.lib name */
799             addSet(&libFilesSet, Safe_strdup(temp));
800           }
801         
802           if(libflags.want_libdebug)
803             addSet(&libFilesSet, Safe_strdup("libdebug.lib"));
804         }
805
806         shash_add(&linkValues, "libs", joinStrSet(libFilesSet));
807         
808         lcmd = msprintf(linkValues, lfrm);
809          
810         ret = my_system( lcmd );
811          
812         Safe_free( lcmd );
813          
814         if(ret)
815                 exit(1);
816 }
817
818
819 static void
820 _pic16_finaliseOptions (void)
821 {
822     port->mem.default_local_map = data;
823     port->mem.default_globl_map = data;
824
825     /* peepholes are disabled for the time being */
826     options.nopeep = 1;
827
828     /* explicit enable peepholes for testing */
829     if(pic16_enable_peeps)
830       options.nopeep = 0;
831
832     options.all_callee_saves = 1;               // always callee saves
833
834 #if 0
835     options.float_rent = 1;
836     options.intlong_rent = 1;
837 #endif
838         
839
840     if(alt_asm && strlen(alt_asm))
841       pic16_asmCmd[0] = alt_asm;
842         
843     if(alt_link && strlen(alt_link))
844       pic16_linkCmd[0] = alt_link;
845         
846     if(!pic16_options.no_crt) {
847       pic16_options.omit_ivt = 1;
848       pic16_options.leave_reset = 0;
849     }
850     
851     if(options.model == MODEL_SMALL)
852       addSet(&asmOptionsSet, Safe_strdup("-DSDCC_MODEL_SMALL"));
853     else
854     if(options.model == MODEL_LARGE)
855       addSet(&asmOptionsSet, Safe_strdup("-DSDCC_MODEL_LARGE"));
856     
857     {
858       char buf[128];
859
860         sprintf(buf, "-D%s -D__%s", pic16->name[2], pic16->name[1]);
861         *(strrchr(buf, 'f')) = 'F';
862         addSet(&asmOptionsSet, Safe_strdup( buf ));
863     }
864     
865     if(STACK_MODEL_LARGE) {
866       addSet(&preArgvSet, Safe_strdup("-DSTACK_MODEL_LARGE"));
867       addSet(&asmOptionsSet, Safe_strdup("-DSTACK_MODEL_LARGE"));
868     } else {
869       addSet(&preArgvSet, Safe_strdup("-DSTACK_MODEL_SMALL"));
870       addSet(&asmOptionsSet, Safe_strdup("-DSTACK_MODEL_SMALL"));
871     }
872 }
873
874
875 #if 0
876   if (options.model == MODEL_LARGE)
877     {
878       port->mem.default_local_map = xdata;
879       port->mem.default_globl_map = xdata;
880     }
881   else
882     {
883       port->mem.default_local_map = data;
884       port->mem.default_globl_map = data;
885     }
886
887   if (options.stack10bit)
888     {
889       if (options.model != MODEL_FLAT24)
890         {
891           fprintf (stderr,
892                    "*** warning: 10 bit stack mode is only supported in flat24 model.\n");
893           fprintf (stderr, "\t10 bit stack mode disabled.\n");
894           options.stack10bit = 0;
895         }
896       else
897         {
898           /* Fixup the memory map for the stack; it is now in
899            * far space and requires a FPOINTER to access it.
900            */
901           istack->fmap = 1;
902           istack->ptrType = FPOINTER;
903         }
904     }
905 #endif
906
907
908 static void
909 _pic16_setDefaultOptions (void)
910 {
911   options.stackAuto = 0;                /* implicit declaration */
912   /* port is not capable yet to allocate separate registers 
913    * dedicated for passing certain parameters */
914   
915   /* initialize to defaults section locations, names and addresses */
916   pic16_sectioninfo.at_udata    = "udata";
917
918   /* set pic16 port options to defaults */
919   pic16_options.no_banksel = 0;
920   pic16_options.opt_banksel = 0;
921   pic16_options.omit_configw = 0;
922   pic16_options.omit_ivt = 0;
923   pic16_options.leave_reset = 0;
924   pic16_options.stack_model = 0;                        /* 0 for 'small', 1 for 'large' */
925   pic16_options.ivt_loc = 0x000000;
926   pic16_options.nodefaultlibs = 0;
927   pic16_options.dumpcalltree = 0;
928   pic16_options.crt_name = "crt0i.o";           /* the default crt to link */
929   pic16_options.no_crt = 0;                     /* use crt by default */
930   pic16_options.ip_stack = 1;           /* set to 1 to enable ipop/ipush for stack */
931   pic16_options.gstack = 0;
932   pic16_options.debgen = 0;
933   pic16_options.CATregs = 0;
934 }
935
936 static const char *
937 _pic16_getRegName (struct regs *reg)
938 {
939   if (reg)
940     return reg->name;
941   return "err";
942 }
943
944
945 #if 1
946 static  char *_pic16_mangleFunctionName(char *sz)
947 {
948 //      fprintf(stderr, "mangled function name: %s\n", sz);
949
950   return sz;
951 }
952 #endif
953
954
955 static void
956 _pic16_genAssemblerPreamble (FILE * of)
957 {
958   char *name = pic16_processor_base_name();
959
960         if(!name) {
961                 name = "p18f452";
962                 fprintf(stderr,"WARNING: No Pic has been selected, defaulting to %s\n",name);
963         }
964
965         fprintf (of, "\tlist\tp=%s\n",&name[1]);
966         if (pic16_mplab_comp) {
967           // provide ACCESS macro used during SFR accesses
968           fprintf (of, "\tinclude <p%s.inc>\n", &name[1]);
969         }
970
971         if(!pic16_options.omit_configw) {
972                 pic16_emitConfigRegs(of);
973                 fprintf(of, "\n");
974                 pic16_emitIDRegs(of);
975         }
976         
977   fprintf (of, "\tradix dec\n");
978 }
979
980 /* Generate interrupt vector table. */
981 static int
982 _pic16_genIVT (FILE * of, symbol ** interrupts, int maxInterrupts)
983 {
984 #if 1
985         /* PIC18F family has only two interrupts, the high and the low
986          * priority interrupts, which reside at 0x0008 and 0x0018 respectively - VR */
987
988         if((!pic16_options.omit_ivt) || (pic16_options.omit_ivt && pic16_options.leave_reset)) {
989                 fprintf(of, "; RESET vector\n");
990                 fprintf(of, "\tgoto\t__sdcc_gsinit_startup\n");
991         }
992         
993         if(!pic16_options.omit_ivt) {
994                 fprintf(of, "\tres 4\n");
995
996
997                 fprintf(of, "; High priority interrupt vector 0x0008\n");
998                 if(interrupts[1]) {
999                         fprintf(of, "\tgoto\t%s\n", interrupts[1]->rname);
1000                         fprintf(of, "\tres\t12\n"); 
1001                 } else {
1002                         fprintf(of, "\tretfie\n");
1003                         fprintf(of, "\tres\t14\n");
1004                 }
1005
1006                 fprintf(of, "; Low priority interrupt vector 0x0018\n");
1007                 if(interrupts[2]) {
1008                         fprintf(of, "\tgoto\t%s\n", interrupts[2]->rname);
1009                 } else {
1010                         fprintf(of, "\tretfie\n");
1011                 }
1012         }
1013 #endif
1014   return TRUE;
1015 }
1016
1017 /* return True if the port can handle the type,
1018  * False to convert it to function call */
1019 static bool _hasNativeMulFor (iCode *ic, sym_link *left, sym_link *right)
1020 {
1021   //fprintf(stderr,"checking for native mult for %c (size: %d)\n", ic->op, getSize(OP_SYMBOL(IC_RESULT(ic))->type));
1022   int symL, symR, symRes, sizeL = 0, sizeR = 0, sizeRes = 0;
1023
1024   /* left/right are symbols? */
1025   symL = IS_SYMOP(IC_LEFT(ic));
1026   symR = IS_SYMOP(IC_RIGHT(ic));
1027   symRes = IS_SYMOP(IC_RESULT(ic));
1028
1029   /* --> then determine their sizes */
1030   sizeL = symL ? getSize(OP_SYM_TYPE(IC_LEFT(ic))) : 4;
1031   sizeR = symR ? getSize(OP_SYM_TYPE(IC_RIGHT(ic))) : 4;
1032   sizeRes = symRes ? getSize(OP_SYM_TYPE(IC_RESULT(ic))) : 4;
1033
1034   /* Checks to enable native multiplication.
1035    * PICs do not offer native division at all...
1036    *
1037    * Ideas:
1038    * (  i) if result is just one byte, use native MUL
1039    *       (regardless of the operands)
1040    * ( ii) if left and right are unsigned 8-bit operands,
1041    *       use native MUL
1042    * (iii) if left or right is a literal in the range of [-128..256)
1043    *       and the other is an unsigned byte, use native MUL
1044    */
1045   if (ic->op == '*')
1046   {
1047     /* use native mult for `*: <?> x <?> --> {u8_t, s8_t}' */
1048     if (sizeRes == 1) { return TRUE; }
1049
1050     /* use native mult for `u8_t x u8_t --> { u16_t, s16_t }' */
1051     if (sizeL == 1 && symL /*&& SPEC_USIGN(OP_SYM_TYPE(IC_LEFT(ic)))*/) {
1052       sizeL = 1;
1053     } else {
1054       //printf( "%s: left too large (%u) / signed (%u)\n", __FUNCTION__, sizeL, symL && !SPEC_USIGN(OP_SYM_TYPE(IC_LEFT(ic))));
1055       sizeL = 4;
1056     }
1057     if (sizeR == 1 && symR /*&& SPEC_USIGN(OP_SYM_TYPE(IC_RIGHT(ic)))*/) {
1058       sizeR = 1;
1059     } else {
1060       //printf( "%s: right too large (%u) / signed (%u)\n", __FUNCTION__, sizeR, symR && !SPEC_USIGN(OP_SYM_TYPE(IC_RIGHT(ic))));
1061       sizeR = 4;
1062     }
1063
1064     /* also allow literals [-128..256) for left/right operands */
1065     if (IS_VALOP(IC_LEFT(ic)))
1066     {
1067       long l = (long)floatFromVal( OP_VALUE( IC_LEFT(ic) ) );
1068       sizeL = 4;
1069       //printf( "%s: val(left) = %ld\n", __FUNCTION__, l );
1070       if (l >= -128 && l < 256)
1071       {
1072         sizeL = 1;
1073       } else {
1074         //printf( "%s: left value %ld outside [-128..256)\n", __FUNCTION__, l );
1075       }
1076     }
1077     if (IS_VALOP( IC_RIGHT(ic) ))
1078     {
1079       long l = (long)floatFromVal( OP_VALUE( IC_RIGHT(ic) ) );
1080       sizeR = 4;
1081       //printf( "%s: val(right) = %ld\n", __FUNCTION__, l );
1082       if (l >= -128 && l < 256)
1083       {
1084         sizeR = 1;
1085       } else {
1086         //printf( "%s: right value %ld outside [-128..256)\n", __FUNCTION__, l );
1087       }
1088     }
1089
1090     /* use native mult iff left and right are (unsigned) 8-bit operands */
1091     if (sizeL == 1 && sizeR == 1) { return TRUE; }
1092   }
1093
1094   if (ic->op == '/' || ic->op == '%')
1095   {
1096     /* We must catch /: {u8_t,s8_t} x {u8_t,s8_t} --> {u8_t,s8_t},
1097      * because SDCC will call 'divuchar' even for u8_t / s8_t.
1098      * Example: 128 / -2 becomes 128 / 254 = 0 != -64... */
1099     if (sizeL == 1 && sizeR == 1) return TRUE;
1100
1101     /* What about literals? */
1102     if (IS_VALOP( IC_LEFT(ic) ))
1103     {
1104       long l = (long)floatFromVal( OP_VALUE( IC_LEFT(ic) ) );
1105       sizeL = 4;
1106       //printf( "%s: val(left) = %ld\n", __FUNCTION__, l );
1107       if (l >= -128 && l < 256)
1108       {
1109         sizeL = 1;
1110       } else {
1111         //printf( "%s: left value %ld outside [-128..256)\n", __FUNCTION__, l );
1112       }
1113     }
1114     if (IS_VALOP( IC_RIGHT(ic) ))
1115     {
1116       long l = (long)floatFromVal( OP_VALUE( IC_RIGHT(ic) ) );
1117       sizeR = 4;
1118       //printf( "%s: val(right) = %ld\n", __FUNCTION__, l );
1119       if (l >= -128 && l < 256)
1120       {
1121         sizeR = 1;
1122       } else {
1123         //printf( "%s: right value %ld outside [-128..256)\n", __FUNCTION__, l );
1124       }
1125     }
1126     if (sizeL == 1 && sizeR == 1) { return TRUE; }
1127   }
1128
1129   return FALSE;
1130 }
1131
1132
1133 #if 0
1134 /* Do CSE estimation */
1135 static bool cseCostEstimation (iCode *ic, iCode *pdic)
1136 {
1137 //    operand *result = IC_RESULT(ic);
1138 //    sym_link *result_type = operandType(result);
1139
1140
1141         /* VR -- this is an adhoc. Put here after conversation
1142          * with Erik Epetrich */
1143
1144         if(ic->op == '<'
1145                 || ic->op == '>'
1146                 || ic->op == EQ_OP) {
1147
1148                 fprintf(stderr, "%d %s\n", __LINE__, __FUNCTION__);
1149           return 0;
1150         }
1151
1152 #if 0
1153     /* if it is a pointer then return ok for now */
1154     if (IC_RESULT(ic) && IS_PTR(result_type)) return 1;
1155
1156     /* if bitwise | add & subtract then no since mcs51 is pretty good at it
1157        so we will cse only if they are local (i.e. both ic & pdic belong to
1158        the same basic block */
1159     if (IS_BITWISE_OP(ic) || ic->op == '+' || ic->op == '-') {
1160         /* then if they are the same Basic block then ok */
1161         if (ic->eBBlockNum == pdic->eBBlockNum) return 1;
1162         else return 0;
1163     }
1164 #endif
1165
1166     /* for others it is cheaper to do the cse */
1167     return 1;
1168 }
1169 #endif
1170
1171
1172 /* Indicate which extended bit operations this port supports */
1173 static bool
1174 hasExtBitOp (int op, int size)
1175 {
1176   if (op == RRC
1177       || op == RLC
1178       /* || op == GETHBIT */ /* GETHBIT doesn't look complete for PIC */
1179      )
1180     return TRUE;
1181   else
1182     return FALSE;
1183 }
1184
1185 /* Indicate the expense of an access to an output storage class */
1186 static int
1187 oclsExpense (struct memmap *oclass)
1188 {
1189   /* The IN_FARSPACE test is compatible with historical behaviour, */
1190   /* but I don't think it is applicable to PIC. If so, please feel */
1191   /* free to remove this test -- EEP */
1192   if (IN_FARSPACE(oclass))
1193     return 1;
1194     
1195   return 0;
1196 }
1197
1198 /** $1 is the input object file (PIC16 specific)        // >>always the basename<<.
1199     $2 is always the output file.
1200     $3 -L path and -l libraries
1201     $l is the list of extra options that should be there somewhere...
1202     MUST be terminated with a NULL.
1203 */
1204 const char *pic16_linkCmd[] =
1205 {
1206   "gplink", "$l", "-w", "-r", "-o \"$2\"", "\"$1\"","$3", NULL
1207 };
1208
1209
1210
1211 /** $1 is always the basename.
1212     $2 is always the output file.
1213     $3 varies (nothing currently)
1214     $l is the list of extra options that should be there somewhere...
1215     MUST be terminated with a NULL.
1216 */
1217 const char *pic16_asmCmd[] =
1218 {
1219   "gpasm", "$l", "$3", "-c", "\"$1.asm\"", "-o \"$2\"", NULL
1220
1221 };
1222
1223 /* Globals */
1224 PORT pic16_port =
1225 {
1226   TARGET_ID_PIC16,
1227   "pic16",
1228   "MCU PIC16",                  /* Target name */
1229   "p18f452",                    /* Processor */
1230   {
1231     pic16glue,
1232     TRUE,                       /* Emit glue around main */
1233     MODEL_SMALL | MODEL_LARGE | MODEL_FLAT24,
1234     MODEL_SMALL
1235   },
1236   {
1237     pic16_asmCmd,               /* assembler command and arguments */
1238     NULL,                       /* alternate macro based form */
1239     "-g",                       /* arguments for debug mode */
1240     NULL,                       /* arguments for normal mode */
1241     0,                          /* print externs as global */
1242     ".asm",                     /* assembler file extension */
1243     NULL                        /* no do_assemble function */
1244   },
1245   {
1246     NULL,                       //    pic16_linkCmd,            /* linker command and arguments */
1247     NULL,                       /* alternate macro based form */
1248     _pic16_linkEdit,            //NULL,                 /* no do_link function */
1249     ".o",                       /* extension for object files */
1250     0                           /* no need for linker file */
1251   },
1252   {
1253     _defaultRules
1254   },
1255   {
1256         /* Sizes */
1257     1,          /* char */
1258     2,          /* short */
1259     2,          /* int */
1260     4,          /* long */
1261     2,          /* ptr */
1262     3,          /* fptr, far pointers (see Microchip) */
1263     3,          /* gptr */
1264     1,          /* bit */
1265     4,          /* float */
1266     4           /* max */
1267   },
1268
1269     /* generic pointer tags */
1270   {
1271     0x00,       /* far */
1272     0x80,       /* near */
1273     0x00,       /* xstack */
1274     0x00        /* code */
1275   },
1276   
1277   {
1278     "XSEG    (XDATA)",          // xstack
1279     "STACK   (DATA)",           // istack
1280     "CSEG    (CODE)",           // code
1281     "DSEG    (DATA)",           // data
1282     "ISEG    (DATA)",           // idata
1283     "PSEG    (DATA)",           // pdata
1284     "XSEG    (XDATA)",          // xdata
1285     "BSEG    (BIT)",            // bit
1286     "RSEG    (DATA)",           // reg
1287     "GSINIT  (CODE)",           // static
1288     "OSEG    (OVR,DATA)",       // overlay
1289     "GSFINAL (CODE)",           // post static
1290     "HOME    (CODE)",   // home
1291     NULL,                       // xidata
1292     NULL,                       // xinit
1293     "CONST   (CODE)",           // const_name - const data (code or not)
1294     "CABS    (ABS,CODE)",       // cabs_name - const absolute data (code or not)
1295     "XABS    (ABS,XDATA)",      // xabs_name - absolute xdata
1296     "IABS    (ABS,DATA)",       // iabs_name - absolute data
1297     NULL,                       // default location for auto vars
1298     NULL,                       // default location for global vars
1299     1                           // code is read only 1=yes
1300   },
1301   {
1302     NULL,               /* genExtraAreaDeclaration */
1303     NULL                /* genExatrAreaLinkOptions */
1304   },
1305   {
1306         /* stack related information */
1307     -1,                 /* -1 stack grows downwards, +1 upwards */
1308     1,                  /* extra overhead when calling between banks */
1309     4,                  /* extra overhead when the function is an ISR */
1310     1,                  /* extra overhead for a function call */
1311     1,                  /* re-entrant space */
1312     0                   /* 'banked' call overhead, mild overlap with bank_overhead */
1313   },
1314     /* pic16 has an 8 bit mul */
1315   {
1316      0, -1
1317   },
1318   {
1319     pic16_emitDebuggerSymbol
1320   },
1321   {
1322     255/3,      /* maxCount */
1323     3,          /* sizeofElement */
1324     /* The rest of these costs are bogus. They approximate */
1325     /* the behavior of src/SDCCicode.c 1.207 and earlier.  */
1326     {4,4,4},    /* sizeofMatchJump[] */
1327     {0,0,0},    /* sizeofRangeCompare[] */
1328     0,          /* sizeofSubtract */
1329     3,          /* sizeofDispatch */
1330   },
1331   "_",
1332   _pic16_init,
1333   _pic16_parseOptions,
1334   pic16_optionsTable,
1335   _pic16_initPaths,
1336   _pic16_finaliseOptions,
1337   _pic16_setDefaultOptions,
1338   pic16_assignRegisters,
1339   _pic16_getRegName,
1340   _pic16_keywords,
1341   _pic16_genAssemblerPreamble,
1342   NULL,                         /* no genAssemblerEnd */
1343   _pic16_genIVT,
1344   NULL, // _pic16_genXINIT
1345   NULL,                         /* genInitStartup */
1346   _pic16_reset_regparm,
1347   _pic16_regparm,
1348   _process_pragma,                              /* process a pragma */
1349   _pic16_mangleFunctionName,                            /* mangles function name */
1350   _hasNativeMulFor,
1351   hasExtBitOp,                  /* hasExtBitOp */
1352   oclsExpense,                  /* oclsExpense */
1353   FALSE,                        
1354   TRUE,                         /* little endian */
1355   0,                            /* leave lt */
1356   0,                            /* leave gt */
1357   1,                            /* transform <= to ! > */
1358   1,                            /* transform >= to ! < */
1359   1,                            /* transform != to !(a == b) */
1360   0,                            /* leave == */
1361   FALSE,                        /* No array initializer support. */
1362   0,    //cseCostEstimation,            /* !!!no CSE cost estimation yet */
1363   NULL,                         /* no builtin functions */
1364   GPOINTER,                     /* treat unqualified pointers as "generic" pointers */
1365   1,                            /* reset labelKey to 1 */
1366   1,                            /* globals & local static allowed */
1367   PORT_MAGIC
1368 };