* src/pic/pcode.c (InsertBankSel): suppress BANKSELs for one bank
[fw/sdcc] / src / pic / main.c
1 /** @file main.c
2     pic14 specific general functions.
3
4     Note that mlh prepended _pic14_ on the static functions.  Makes
5     it easier to set a breakpoint using the debugger.
6 */
7 #include "common.h"
8 #include "main.h"
9 #include "ralloc.h"
10 #include "device.h"
11 #include "SDCCutil.h"
12 #include "SDCCmacro.h"
13 #include "MySystem.h"
14 #include "glue.h"
15 #include <errno.h>
16 //#include "gen.h"
17
18
19 static char _defaultRules[] =
20 {
21 #include "peeph.rul"
22         ""
23 };
24
25 /* list of key words used by pic14 */
26 static char *_pic14_keywords[] =
27 {
28         "at",
29         //"bit",
30         "code",
31         "critical",
32         "data",
33         "far",
34         "idata",
35         "interrupt",
36         "near",
37         "pdata",
38         "reentrant",
39         "sfr",
40         //"sbit",
41         "using",
42         "xdata",
43         "_data",
44         "_code",
45         "_generic",
46         "_near",
47         "_xdata",
48         "_pdata",
49         "_idata",
50         NULL
51 };
52
53 pic14_options_t pic14_options;
54
55 #define ARG_STACKLOC    "--stack-loc"
56 #define ARG_STACKSIZ    "--stack-size"
57
58 extern int debug_verbose;       /* from pcode.c */
59 static OPTION _pic14_poptions[] = {
60         { 0 , "--debug-xtra", &debug_verbose, "show more debug info in assembly output" },
61         { 0 , "--no-pcode-opt", &pic14_options.disable_df, "disable (slightly faulty) optimization on pCode" },
62         { 0 , ARG_STACKLOC, NULL, "sets the lowest address of the argument passing stack" },
63         { 0 , ARG_STACKSIZ, NULL, "sets the size if the argument passing stack (default: 16, minimum: 4)" },
64         { 0 , NULL, NULL, NULL }
65 };
66
67 void  pCodeInitRegisters(void);
68
69 void pic14_assignRegisters (ebbIndex *);
70
71 /* Also defined in gen.h, but the #include is commented out */
72 /* for an unknowned reason. - EEP */
73 void pic14_emitDebuggerSymbol (char *);
74
75 static int regParmFlg = 0;      /* determine if we can register a parameter */
76
77 static void
78 _pic14_init (void)
79 {
80         asm_addTree (&asm_asxxxx_mapping);
81         memset (&pic14_options, 0, sizeof (pic14_options));
82 }
83
84 static void
85 _pic14_reset_regparm (void)
86 {
87         regParmFlg = 0;
88 }
89
90 static int
91 _pic14_regparm (sym_link * l, bool reentrant)
92 {
93 /* for this processor it is simple
94         can pass only the first parameter in a register */
95         //if (regParmFlg)
96         //  return 0;
97         
98         regParmFlg++;// = 1;
99         return 1;
100 }
101
102 static int
103 _process_pragma(const char *sz)
104 {
105         static const char *WHITE = " \t";
106         char    *ptr = strtok((char *)sz, WHITE);
107         
108         if (startsWith (ptr, "memmap"))
109         {
110                 char    *start;
111                 char    *end;
112                 char    *type;
113                 char    *alias;
114                 
115                 start = strtok((char *)NULL, WHITE);
116                 end = strtok((char *)NULL, WHITE);
117                 type = strtok((char *)NULL, WHITE);
118                 alias = strtok((char *)NULL, WHITE);
119                 
120                 if (start != (char *)NULL
121                         && end != (char *)NULL
122                         && type != (char *)NULL) {
123                         value           *startVal = constVal(start);
124                         value           *endVal = constVal(end);
125                         value           *aliasVal;
126                         memRange        r;
127                         
128                         if (alias == (char *)NULL) {
129                                 aliasVal = constVal(0);
130                         } else {
131                                 aliasVal = constVal(alias);
132                         }
133                         
134                         r.start_address = (int)floatFromVal(startVal);
135                         r.end_address = (int)floatFromVal(endVal);
136                         r.alias = (int)floatFromVal(aliasVal);
137                         r.bank = (r.start_address >> 7) & 3;
138                         
139                         if (strcmp(type, "RAM") == 0) {
140                                 addMemRange(&r, 0);
141                         } else if (strcmp(type, "SFR") == 0) {
142                                 addMemRange(&r, 1);
143                         } else {
144                                 return 1;
145                         }
146                 }
147                 
148                 return 0;
149         } else if (startsWith (ptr, "maxram")) {
150                 // not used any more - comes from device config file pic14devices.txt instead
151                 return 0;
152         }
153         return 1;
154 }
155
156 extern char *udata_section_name;
157
158 static bool
159 _pic14_parseOptions (int *pargc, char **argv, int *i)
160 {
161         char buf[128];
162         
163         /* TODO: allow port-specific command line options to specify
164         * segment names here.
165         */
166         
167         /* This is a temporary hack, to solve problems with some processors
168         * that do not have udata section. It will be changed when a more
169         * robust solution is figured out -- VR 27-11-2003 FIXME
170         */
171         strcpy(buf, "--udata-section-name");
172         if(!strncmp(buf, argv[ *i ], strlen(buf))) {
173                 if(strlen(argv[ *i ]) <= strlen(buf)+1) {
174                         fprintf(stderr, "WARNING: no `%s' entered\n", buf+2);
175                         exit(EXIT_FAILURE);
176                 } else {
177                         udata_section_name = strdup( strchr(argv[*i], '=') + 1 );
178                 }
179                 return 1;
180         }
181
182         return FALSE;
183 }
184
185 extern set *dataDirsSet;
186 extern set *includeDirsSet;
187 /* pic14 port uses include/pic and lib/pic instead of
188  * include/pic14 and lib/pic14 as indicated by SDCCmain.c's
189  * setIncludePaths routine. */
190 static void
191 _pic14_initPaths (void)
192 {
193   char *p;
194   char *p2=NULL;
195   set *tempSet=NULL;
196
197   if (options.nostdinc)
198       return;
199
200   tempSet = appendStrSet(dataDirsSet, NULL, INCLUDE_DIR_SUFFIX DIR_SEPARATOR_STRING "pic");
201   mergeSets(&includeDirsSet, tempSet);
202
203   if ((p = getenv(SDCC_INCLUDE_NAME)) != NULL)
204   {
205     addSetHead(&includeDirsSet, p);
206     p2=Safe_alloc(strlen(p)+strlen(DIR_SEPARATOR_STRING)+strlen("pic")+1);
207     if(p2!=NULL)
208     {
209         strcpy(p2, p);
210         strcat(p2, DIR_SEPARATOR_STRING);
211         strcat(p2, "pic");
212         addSetHead(&includeDirsSet, p2);
213     }
214   }
215 }
216
217 static void
218 _pic14_finaliseOptions (void)
219 {
220         pCodeInitRegisters();
221         
222         port->mem.default_local_map = data;
223         port->mem.default_globl_map = data;
224 #if 0
225         /* Hack-o-matic: if we are using the flat24 model,
226         * adjust pointer sizes.
227         */
228         if (options.model == MODEL_FLAT24)
229         {
230                 
231                 fprintf (stderr, "*** WARNING: you should use the '-mds390' option "
232                         "for DS80C390 support. This code generator is "
233                         "badly out of date and probably broken.\n");
234                 
235                 port->s.fptr_size = 3;
236                 port->s.gptr_size = 4;
237                 port->stack.isr_overhead++;     /* Will save dpx on ISR entry. */
238 #if 1
239                 port->stack.call_overhead++;    /* This acounts for the extra byte 
240                                                  * of return addres on the stack.
241                                                  * but is ugly. There must be a 
242                                                  * better way.
243                                                  */
244 #endif
245                 fReturn = fReturn390;
246                 fReturnSize = 5;
247         }
248         
249         if (options.model == MODEL_LARGE)
250         {
251                 port->mem.default_local_map = xdata;
252                 port->mem.default_globl_map = xdata;
253         }
254         else
255         {
256                 port->mem.default_local_map = data;
257                 port->mem.default_globl_map = data;
258         }
259         
260         if (options.stack10bit)
261         {
262                 if (options.model != MODEL_FLAT24)
263                 {
264                         fprintf (stderr,
265                                 "*** warning: 10 bit stack mode is only supported in flat24 model.\n");
266                         fprintf (stderr, "\t10 bit stack mode disabled.\n");
267                         options.stack10bit = 0;
268                 }
269                 else
270                 {
271                 /* Fixup the memory map for the stack; it is now in
272                 * far space and requires a FPOINTER to access it.
273                 */
274                         istack->fmap = 1;
275                         istack->ptrType = FPOINTER;
276                 }
277         }
278 #endif
279 }
280
281 static void
282 _pic14_setDefaultOptions (void)
283 {
284 }
285
286 static const char *
287 _pic14_getRegName (struct regs *reg)
288 {
289         if (reg)
290                 return reg->name;
291         return "err";
292 }
293
294 extern char *processor_base_name(void);
295
296 static void
297 _pic14_genAssemblerPreamble (FILE * of)
298 {
299         char * name = processor_base_name();
300         
301         if(!name) {
302                 
303                 name = "16f877";
304                 fprintf(stderr,"WARNING: No Pic has been selected, defaulting to %s\n",name);
305         }
306         
307         fprintf (of, "\tlist\tp=%s\n",name);
308         fprintf (of, "\tradix dec\n");
309         fprintf (of, "\tinclude \"p%s.inc\"\n",name);
310 }
311
312 /* Generate interrupt vector table. */
313 static int
314 _pic14_genIVT (FILE * of, symbol ** interrupts, int maxInterrupts)
315 {
316         int i;
317         
318         if (options.model != MODEL_FLAT24)
319         {
320                 /* Let the default code handle it. */
321                 return FALSE;
322         }
323         
324         fprintf (of, "\t;ajmp\t__sdcc_gsinit_startup\n");
325         
326         /* now for the other interrupts */
327         for (i = 0; i < maxInterrupts; i++)
328         {
329                 if (interrupts[i])
330                 {
331                         fprintf (of, "\t;ljmp\t%s\n\t.ds\t4\n", interrupts[i]->rname);
332                 }
333                 else
334                 {
335                         fprintf (of, "\t;reti\n\t.ds\t7\n");
336                 }
337         }
338         
339         return TRUE;
340 }
341
342 static bool
343 _hasNativeMulFor (iCode *ic, sym_link *left, sym_link *right)
344 {
345 /*
346 sym_link *test = NULL;
347 value *val;
348         */
349         
350         //fprintf(stderr,"checking for native mult\n");
351         
352         if ( ic->op != '*')
353         {
354                 return FALSE;
355         }
356         
357         /* multiply chars in-place */
358         if (getSize(left) == 1 && getSize(right) == 1)
359                 return TRUE;
360         
361         /* use library functions for more complex maths */
362         return FALSE;
363
364         /*
365         if ( IS_LITERAL (left))
366         {
367         fprintf(stderr,"left is lit\n");
368         test = left;
369         val = OP_VALUE (IC_LEFT (ic));
370         }
371         else if ( IS_LITERAL (right))
372         {
373         fprintf(stderr,"right is lit\n");
374         test = left;
375         val = OP_VALUE (IC_RIGHT (ic));
376         }
377         else
378         {
379         fprintf(stderr,"oops, neither is lit so no\n");
380         return FALSE;
381         }
382         
383           if ( getSize (test) <= 2)
384           {
385           fprintf(stderr,"yep\n");
386           return TRUE;
387           }
388           fprintf(stderr,"nope\n");
389           
390                 return FALSE;
391         */
392 }
393
394 /* Indicate which extended bit operations this port supports */
395 static bool
396 hasExtBitOp (int op, int size)
397 {
398         if (op == RRC
399                 || op == RLC
400                 /* || op == GETHBIT */ /* GETHBIT doesn't look complete for PIC */
401                 )
402                 return TRUE;
403         else
404                 return FALSE;
405 }
406
407 /* Indicate the expense of an access to an output storage class */
408 static int
409 oclsExpense (struct memmap *oclass)
410 {
411         /* The IN_FARSPACE test is compatible with historical behaviour, */
412         /* but I don't think it is applicable to PIC. If so, please feel */
413         /* free to remove this test -- EEP */
414         if (IN_FARSPACE(oclass))
415                 return 1;
416
417         return 0;
418 }
419
420 /** $1 is always the basename.
421 $2 is always the output file.
422 $3 varies
423 $l is the list of extra options that should be there somewhere...
424 MUST be terminated with a NULL.
425 */
426 static const char *_linkCmd[] =
427 {
428         "gplink", "$l", "-w", "-r", "-o \"$2\"", "\"$1\"", "$3", NULL
429 };
430
431 static const char *_asmCmd[] =
432 {
433         "gpasm", "$l", "-c", "\"$1.asm\"", NULL
434                 
435 };
436
437 extern set *libFilesSet;
438 extern set *libDirsSet;
439 extern set *libPathsSet;
440 extern set *includeDirsSet;
441 extern set *userIncDirsSet;
442 extern set *dataDirsSetSet;
443 extern set *relFilesSet;
444 extern set *linkOptionsSet;
445
446 static void _pic14_do_link (void)
447 {
448   hTab *linkValues=NULL;
449   char lfrm[256];
450   char *lcmd;
451   char temp[128];
452   set *tSet=NULL;
453   int ret;
454   char * procName;
455   
456   /*
457    * link command format:
458    * {linker} {incdirs} {lflags} -o {outfile} {spec_ofiles} {ofiles} {libs}
459    *
460    */
461
462   sprintf(lfrm, "{linker} {incdirs} {sysincdirs} {lflags} -w -r -o {outfile} {user_ofile} {spec_ofiles} {ofiles} {libs}");
463
464   shash_add(&linkValues, "linker", "gplink");
465
466   /* LIBRARY SEARCH DIRS */
467   mergeSets(&tSet, libPathsSet);
468   mergeSets(&tSet, libDirsSet);
469   shash_add(&linkValues, "incdirs", joinStrSet(appendStrSet(tSet, "-I\"", "\"")));
470
471   SNPRINTF (&temp[0], 128, "%cpic\"", DIR_SEPARATOR_CHAR);
472   joinStrSet(appendStrSet(libDirsSet, "-I\"", &temp[0]));
473   shash_add(&linkValues, "sysincdirs", joinStrSet(appendStrSet(libDirsSet, "-I\"", &temp[0])));
474   
475   shash_add(&linkValues, "lflags", joinStrSet(linkOptionsSet));
476
477   shash_add(&linkValues, "outfile", fullDstFileName ? fullDstFileName : dstFileName);
478
479   if(fullSrcFileName) {
480     sprintf(temp, "%s.o", fullDstFileName ? fullDstFileName : dstFileName );
481     shash_add(&linkValues, "user_ofile", temp);
482   }
483
484   shash_add(&linkValues, "ofiles", joinStrSet(relFilesSet));
485
486   /* LIBRARIES */
487   procName = processor_base_name();
488   if (!procName) {
489      procName = "16f877";
490   }
491         
492   addSet(&libFilesSet, "libsdcc.lib");
493   SNPRINTF(&temp[0], 128, "pic%s.lib", procName);
494   addSet(&libFilesSet, temp);
495   shash_add(&linkValues, "libs", joinStrSet(libFilesSet));
496
497   lcmd = msprintf(linkValues, lfrm);
498
499   ret = my_system( lcmd );
500
501   Safe_free( lcmd );
502
503   if(ret)
504     exit(1);
505 }
506
507 /* Globals */
508 PORT pic_port =
509 {
510         TARGET_ID_PIC,
511         "pic14",
512         "MCU pic",                      /* Target name */
513         "",                    /* Processor */
514         {
515                 picglue,
516                 TRUE,                   /* Emit glue around main */
517                 MODEL_SMALL | MODEL_LARGE | MODEL_FLAT24,
518                 MODEL_SMALL
519         },
520         {
521                 _asmCmd,
522                 NULL,
523                 NULL,
524                 NULL,
525                 //"-plosgffc",          /* Options with debug */
526                 //"-plosgff",           /* Options without debug */
527                 0,
528                 ".asm",
529                 NULL                    /* no do_assemble function */
530         },
531         {
532                 _linkCmd,
533                 NULL,
534                 _pic14_do_link,         /* own do link function */
535                 ".o",
536                 0
537         },
538         {
539                 _defaultRules
540         },
541         {
542                 /* Sizes: char, short, int, long, ptr, fptr, gptr, bit, float, max */
543                 1, 2, 2, 4, 2, 2, 3, 1, 4, 4
544                 /* TSD - I changed the size of gptr from 3 to 1. However, it should be
545                    2 so that we can accomodate the PIC's with 4 register banks (like the
546                    16f877)
547                  */
548         },
549         /* tags for generic pointers */
550         { 0x00, 0x00, 0x00, 0x80 },             /* far, near, xstack, code */
551         {
552                 "XSEG    (XDATA)",
553                 "STACK   (DATA)",
554                 "code",
555                 "DSEG    (DATA)",
556                 "ISEG    (DATA)",
557                 NULL, /* pdata */
558                 "XSEG    (XDATA)",
559                 "BSEG    (BIT)",
560                 "RSEG    (DATA)",
561                 "GSINIT  (CODE)",
562                 "udata_ovr",
563                 "GSFINAL (CODE)",
564                 "HOME    (CODE)",
565                 NULL, // xidata
566                 NULL, // xinit
567                 "CONST   (CODE)",               // const_name - const data (code or not)
568                 "CABS    (ABS,CODE)",   // cabs_name - const absolute data (code or not)
569                 NULL,
570                 NULL,
571                 1        // code is read only
572         },
573         { NULL, NULL },
574         {
575                 +1, 1, 4, 1, 1, 0
576         },
577                 /* pic14 has an 8 bit mul */
578         {
579                 1, -1
580         },
581         {
582                 pic14_emitDebuggerSymbol
583         },
584         {
585                 255/3,      /* maxCount */
586                 3,          /* sizeofElement */
587                 /* The rest of these costs are bogus. They approximate */
588                 /* the behavior of src/SDCCicode.c 1.207 and earlier.  */
589                 {4,4,4},    /* sizeofMatchJump[] */
590                 {0,0,0},    /* sizeofRangeCompare[] */
591                 0,          /* sizeofSubtract */
592                 3,          /* sizeofDispatch */
593         },
594         "_",
595         _pic14_init,
596         _pic14_parseOptions,
597         _pic14_poptions,
598         _pic14_initPaths,
599         _pic14_finaliseOptions,
600         _pic14_setDefaultOptions,
601         pic14_assignRegisters,
602         _pic14_getRegName,
603         _pic14_keywords,
604         _pic14_genAssemblerPreamble,
605         NULL,                           /* no genAssemblerEnd */
606         _pic14_genIVT,
607         NULL, // _pic14_genXINIT
608         NULL,                           /* genInitStartup */
609         _pic14_reset_regparm,
610         _pic14_regparm,
611         _process_pragma,                                /* process a pragma */
612         NULL,
613         _hasNativeMulFor,
614         hasExtBitOp,                    /* hasExtBitOp */
615         oclsExpense,                    /* oclsExpense */
616         FALSE,
617 //      TRUE,                           /* little endian */
618         FALSE,                          /* little endian - PIC code enumlates big endian */
619         0,                              /* leave lt */
620         0,                              /* leave gt */
621         1,                              /* transform <= to ! > */
622         1,                              /* transform >= to ! < */
623         1,                              /* transform != to !(a == b) */
624         0,                              /* leave == */
625         FALSE,                        /* No array initializer support. */
626         0,                            /* no CSE cost estimation yet */
627         NULL,                   /* no builtin functions */
628         GPOINTER,                       /* treat unqualified pointers as "generic" pointers */
629         1,                              /* reset labelKey to 1 */
630         1,                              /* globals & local static allowed */
631         PORT_MAGIC
632 };