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