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