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