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