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