1 /*-------------------------------------------------------------------------
3 main.c - pic16 specific general functions.
5 Written by - Scott Dattalo scott@dattalo.com
6 Ported to PIC16 by - Martin Dubuc m.debuc@rogers.com
8 Note that mlh prepended _pic16_ on the static functions. Makes
9 it easier to set a breakpoint using the debugger.
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
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.
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 -------------------------------------------------------------------------*/
37 static char _defaultRules[] =
42 /* list of key words used by pic16 */
43 static char *_pic16_keywords[] =
72 pic16_sectioninfo_t pic16_sectioninfo;
75 extern char *pic16_processor_base_name(void);
77 void pic16_pCodeInitRegisters(void);
79 void pic16_assignRegisters (eBBlock ** ebbs, int count);
81 static int regParmFlg = 0; /* determine if we can register a parameter */
83 pic16_options_t pic16_options;
85 extern set *includeDirsSet;
86 extern set *dataDirsSet;
87 extern set *libFilesSet;
89 /* Also defined in gen.h, but the #include is commented out */
90 /* for an unknowned reason. - EEP */
91 void pic16_emitDebuggerSymbol (char *);
93 extern regs* newReg(short type, short pc_type, int rIdx, char *name, int size, int alias, operand *refop);
94 extern void pic16_emitConfigRegs(FILE *of);
95 extern void pic16_emitIDRegs(FILE *of);
102 asm_addTree (&asm_asxxxx_mapping);
103 pic16_pCodeInitRegisters();
106 /* set pic16 port options to defaults */
107 pic16_options.no_banksel = 0;
108 pic16_options.opt_banksel = 0;
109 pic16_options.omit_configw = 0;
110 pic16_options.omit_ivt = 0;
111 pic16_options.leave_reset = 0;
112 pic16_options.stack_model = 0; /* 0 for 'small', 1 for 'large' */
113 pic16_options.ivt_loc = 0x000000; /* default location of interrupt vectors */
114 pic16_options.nodefaultlibs = 0; /* link default libraries */
115 pic16_options.dumpcalltree = 0;
119 _pic16_reset_regparm ()
125 _pic16_regparm (sym_link * l)
127 /* for this processor it is simple
128 * can pass only the first parameter in a register */
130 if(regParmFlg)return 0;
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 */
144 set *sectNames=NULL; /* list of section listed in pragma directives */
145 set *sectSyms=NULL; /* list of symbols set in a specific section */
149 _process_pragma(const char *sz)
151 static const char *WHITE = " \t\n";
153 char *ptr = strtok((char *)sz, WHITE);
155 /* #pragma maxram [maxram] */
156 if (startsWith (ptr, "maxram")) {
157 char *maxRAM = strtok((char *)NULL, WHITE);
159 if (maxRAM != (char *)NULL) {
163 maxRAMVal = constVal(maxRAM);
164 maxRAMaddress = (int)floatFromVal(maxRAMVal);
165 pic16_setMaxRAM(maxRAMaddress);
169 /* #pragma stack [stack-position] [stack-len] */
170 if(startsWith(ptr, "stack")) {
171 char *stackPosS = strtok((char *)NULL, WHITE);
172 char *stackLenS = strtok((char *)NULL, WHITE);
178 stackPosVal = constVal( stackPosS );
179 stackPos = (unsigned int)floatFromVal( stackPosVal );
183 stackLenVal = constVal( stackLenS );
184 stackLen = (unsigned int)floatFromVal( stackLenVal );
189 fprintf(stderr, "%s:%d setting stack to default size 0x%x\n", __FILE__, __LINE__, stackLen);
192 // fprintf(stderr, "Initializing stack pointer at 0x%x len 0x%x\n", stackPos, stackLen);
194 reg=newReg(REG_SFR, PO_SFR_REGISTER, stackPos, "_stack", stackLen-1, 0, NULL);
195 addSet(&pic16_fix_udata, reg);
197 reg = newReg(REG_SFR, PO_SFR_REGISTER, stackPos + stackLen-1, "_stack_end", 1, 0, NULL);
198 addSet(&pic16_fix_udata, reg);
200 sym = newSymbol("stack", 0);
201 sprintf(sym->rname, "_%s", sym->name);
202 addSet(&publics, sym);
204 sym = newSymbol("stack_end", 0);
205 sprintf(sym->rname, "_%s", sym->name);
206 addSet(&publics, sym);
208 initsfpnt = 1; // force glue() to initialize stack/frame pointers */
213 /* #pragma code [symbol] [location] */
214 if(startsWith(ptr, "code")) {
215 char *symname = strtok((char *)NULL, WHITE);
216 char *location = strtok((char *)NULL, WHITE);
220 absS = Safe_calloc(1, sizeof(absSym));
221 absS->name = Safe_strdup( symname );
222 addr = constVal( location );
223 absS->address = (unsigned int)floatFromVal( addr );
225 addSet(&absSymSet, absS);
226 fprintf(stderr, "%s:%d symbol %s will be placed in location 0x%06x in code memory\n",
227 __FILE__, __LINE__, symname, absS->address);
232 /* #pragma udata [section-name] [symbol] */
233 if(startsWith(ptr, "udata")) {
234 char *sectname = strtok((char *)NULL, WHITE);
235 char *symname = strtok((char *)NULL, WHITE);
242 ssym = Safe_calloc(1, sizeof(sectSyms));
243 ssym->name = Safe_calloc(1, strlen(symname)+2);
244 sprintf(ssym->name, "_%s", symname);
247 addSet(§Syms, ssym);
250 for(snam=setFirstItem(sectNames);snam;snam=setNextItem(sectNames)) {
251 if(!strcmp(sectname, snam->name)){ found=1; break; }
255 snam = Safe_calloc(1, sizeof(sectNames));
256 snam->name = Safe_strdup( sectname );
257 snam->regsSet = NULL;
259 addSet(§Names, snam);
262 ssym->section = snam;
264 // fprintf(stderr, "%s:%d placing symbol %s at section %s (%p)\n", __FILE__, __LINE__,
265 // ssym->name, snam->name, snam);
267 symname = strtok((char *)NULL, WHITE);
276 #define REP_UDATA "--preplace-udata-with="
278 #define STACK_MODEL "--pstack-model="
279 #define OPT_BANKSEL "--obanksel="
281 #define ALT_ASM "--asm="
282 #define ALT_LINK "--link="
284 #define IVT_LOC "--ivt-loc"
285 #define NO_DEFLIBS "--nodefaultlibs"
286 #define MPLAB_COMPAT "--mplab-comp"
291 int pic16_mplab_comp=0;
292 extern int pic16_debug_verbose;
293 extern int pic16_ralloc_debug;
294 extern int pic16_pcode_verbose;
296 int pic16_enable_peeps=0;
298 OPTION pic16_optionsTable[]= {
299 { 0, NO_DEFLIBS, &pic16_options.nodefaultlibs, "do not link default libraries when linking"},
300 { 0, "--pno-banksel", &pic16_options.no_banksel, "do not generate BANKSEL assembler directives"},
301 { 0, OPT_BANKSEL, NULL, "set banksel optimization level (default=0 no)"},
302 { 0, "--pomit-config-words", &pic16_options.omit_configw, "omit the generation of configuration words"},
303 { 0, "--pomit-ivt", &pic16_options.omit_ivt, "omit the generation of the Interrupt Vector Table"},
304 { 0, "--pleave-reset-vector",&pic16_options.leave_reset, "when omitting IVT leave RESET vector"},
305 { 0, STACK_MODEL, NULL, "use stack model 'small' (default) or 'large'"},
307 { 0, "--debug-xtra", &pic16_debug_verbose, "show more debug info in assembly output"},
308 { 0, "--debug-ralloc", &pic16_ralloc_debug, "dump register allocator debug file *.d"},
309 { 0, "--pcode-verbose", &pic16_pcode_verbose, "dump pcode related info"},
311 { 0, REP_UDATA, NULL, "Place udata variables at another section: udata_acs, udata_ovr, udata_shr"},
313 { 0, ALT_ASM, NULL, "Use alternative assembler"},
314 { 0, ALT_LINK, NULL, "Use alternative linker"},
316 { 0, "--denable-peeps", &pic16_enable_peeps, "explicit enable of peepholes"},
317 { 0, IVT_LOC, NULL, "<nnnn> interrupt vector table location"},
318 { 0, "--calltree", &pic16_options.dumpcalltree, "dump call tree in .calltree file"},
319 { 0, MPLAB_COMPAT, &pic16_mplab_comp, "enable compatibility mode for MPLAB utilities (MPASM/MPLINK)"},
320 { 0, NULL, NULL, NULL}
324 #define ISOPT(str) !strncmp(argv[ *i ], str, strlen(str) )
326 extern char *getStringArg(const char *, char **, int *, int);
327 extern int getIntArg(const char *, char **, int *, int);
330 _pic16_parseOptions (int *pargc, char **argv, int *i)
335 /* TODO: allow port-specific command line options to specify
336 * segment names here.
338 /* check for arguments that have associated an integer variable */
339 while(pic16_optionsTable[j].pparameter) {
340 if(ISOPT( pic16_optionsTable[j].longOpt )) {
341 (*pic16_optionsTable[j].pparameter)++;
348 if(ISOPT(STACK_MODEL)) {
349 stkmodel = getStringArg(STACK_MODEL, argv, i, *pargc);
350 if(STRCASECMP(stkmodel, "small"))pic16_options.stack_model = 0;
351 else if(STRCASECMP(stkmodel, "large"))pic16_options.stack_model = 1;
353 fprintf(stderr, "Unknown stack model: %s", stkmodel);
359 if(ISOPT(OPT_BANKSEL)) {
360 pic16_options.opt_banksel = getIntArg(OPT_BANKSEL, argv, i, *pargc);
364 if(ISOPT(REP_UDATA)) {
365 pic16_sectioninfo.at_udata = Safe_strdup(getStringArg(REP_UDATA, argv, i, *pargc));
370 alt_asm = Safe_strdup(getStringArg(ALT_ASM, argv, i, *pargc));
374 if(ISOPT(ALT_LINK)) {
375 alt_link = Safe_strdup(getStringArg(ALT_LINK, argv, i, *pargc));
380 pic16_options.ivt_loc = getIntArg(IVT_LOC, argv, i, *pargc);
387 static void _pic16_initPaths(void)
389 char pic16incDir[512];
390 char pic16libDir[512];
391 set *pic16incDirsSet;
392 set *pic16libDirsSet;
395 setMainValue("mcu", pic16->name[2] );
396 addSet(&preArgvSet, Safe_strdup("-D{mcu}"));
398 sprintf(pic16incDir, "%s%cpic16", INCLUDE_DIR_SUFFIX, DIR_SEPARATOR_CHAR);
399 sprintf(pic16libDir, "%s%cpic16", LIB_DIR_SUFFIX, DIR_SEPARATOR_CHAR);
401 if(!options.nostdinc) {
402 /* setup pic16 include directory */
403 pic16incDirsSet = appendStrSet(dataDirsSet, NULL, pic16incDir);
404 mergeSets(&includeDirsSet, pic16incDirsSet);
407 if(!options.nostdlib) {
408 /* setup pic16 library directory */
409 pic16libDirsSet = appendStrSet(dataDirsSet, NULL, pic16libDir);
410 mergeSets(&libDirsSet, pic16libDirsSet);
413 if(!pic16_options.nodefaultlibs) {
414 /* now add the library for the device */
415 sprintf(devlib, "%s.lib", pic16->name[2]);
416 addSet(&libFilesSet, Safe_strdup(devlib));
420 extern set *linkOptionsSet;
421 char *msprintf(hTab *pvals, const char *pformat, ...);
422 int my_system(const char *cmd);
424 /* custom function to link objects */
425 static void _pic16_linkEdit(void)
427 hTab *linkValues=NULL;
435 * link command format:
436 * {linker} {incdirs} {lflags} -o {outfile} {spec_ofiles} {ofiles} {libs}
440 sprintf(lfrm, "{linker} {incdirs} {lflags} -o {outfile} {spec_ofiles} {ofiles} {libs}");
442 shash_add(&linkValues, "linker", "gplink");
444 mergeSets(&tSet, libDirsSet);
445 mergeSets(&tSet, libPathsSet);
447 shash_add(&linkValues, "incdirs", joinStrSet( appendStrSet(tSet, "-I\"", "\"")));
448 shash_add(&linkValues, "lflags", joinStrSet(linkOptionsSet));
450 shash_add(&linkValues, "outfile", dstFileName);
452 if(fullSrcFileName) {
453 sprintf(temp, "%s.o", dstFileName);
454 // shash_add(&linkValues, "srcofile", temp);
455 addSetHead(&relFilesSet, temp);
458 // shash_add(&linkValues, "spec_ofiles", "crt0i.o");
459 shash_add(&linkValues, "ofiles", joinStrSet(relFilesSet));
460 shash_add(&linkValues, "libs", joinStrSet(libFilesSet));
462 lcmd = msprintf(linkValues, lfrm);
464 ret = my_system( lcmd );
473 /* forward declarations */
474 extern const char *pic16_linkCmd[];
475 extern const char *pic16_asmCmd[];
478 _pic16_finaliseOptions (void)
480 port->mem.default_local_map = data;
481 port->mem.default_globl_map = data;
483 /* peepholes are disabled for the time being */
486 /* explicit enable peepholes for testing */
487 if(pic16_enable_peeps)
490 options.all_callee_saves = 1; // always callee saves
491 // options.float_rent = 1;
492 // options.intlong_rent = 1;
495 if(alt_asm && strlen(alt_asm))
496 pic16_asmCmd[0] = alt_asm;
498 if(alt_link && strlen(alt_link))
499 pic16_linkCmd[0] = alt_link;
503 /* all the rest is commented ifdef'd out */
505 /* Hack-o-matic: if we are using the flat24 model,
506 * adjust pointer sizes.
508 if (options.model == MODEL_FLAT24)
511 fprintf (stderr, "*** WARNING: you should use the '-mds390' option "
512 "for DS80C390 support. This code generator is "
513 "badly out of date and probably broken.\n");
515 port->s.fptr_size = 3;
516 port->s.gptr_size = 4;
517 port->stack.isr_overhead++; /* Will save dpx on ISR entry. */
519 port->stack.call_overhead++; /* This acounts for the extra byte
520 * of return addres on the stack.
521 * but is ugly. There must be a
525 fReturn = fReturn390;
529 if (options.model == MODEL_LARGE)
531 port->mem.default_local_map = xdata;
532 port->mem.default_globl_map = xdata;
536 port->mem.default_local_map = data;
537 port->mem.default_globl_map = data;
540 if (options.stack10bit)
542 if (options.model != MODEL_FLAT24)
545 "*** warning: 10 bit stack mode is only supported in flat24 model.\n");
546 fprintf (stderr, "\t10 bit stack mode disabled.\n");
547 options.stack10bit = 0;
551 /* Fixup the memory map for the stack; it is now in
552 * far space and requires a FPOINTER to access it.
555 istack->ptrType = FPOINTER;
562 _pic16_setDefaultOptions (void)
564 /* initialize to defaults section locations, names and addresses */
565 pic16_sectioninfo.at_udata = "udata";
567 /* set pic16 port options to defaults */
568 pic16_options.no_banksel = 0;
569 pic16_options.opt_banksel = 0;
570 pic16_options.omit_configw = 0;
571 pic16_options.omit_ivt = 0;
572 pic16_options.leave_reset = 0;
573 pic16_options.stack_model = 0; /* 0 for 'small', 1 for 'large' */
574 pic16_options.ivt_loc = 0x000000;
575 pic16_options.nodefaultlibs = 0;
576 pic16_options.dumpcalltree = 0;
580 _pic16_getRegName (struct regs *reg)
589 static char *_pic16_mangleFunctionName(char *sz)
591 // fprintf(stderr, "mangled function name: %s\n", sz);
599 _pic16_genAssemblerPreamble (FILE * of)
601 char *name = pic16_processor_base_name();
605 fprintf(stderr,"WARNING: No Pic has been selected, defaulting to %s\n",name);
608 fprintf (of, "\tlist\tp=%s\n",&name[1]);
610 if(!pic16_options.omit_configw) {
611 pic16_emitConfigRegs(of);
613 pic16_emitIDRegs(of);
616 fprintf (of, "\tradix dec\n");
619 /* Generate interrupt vector table. */
621 _pic16_genIVT (FILE * of, symbol ** interrupts, int maxInterrupts)
624 /* PIC18F family has only two interrupts, the high and the low
625 * priority interrupts, which reside at 0x0008 and 0x0018 respectively - VR */
627 if((!pic16_options.omit_ivt) || (pic16_options.omit_ivt && pic16_options.leave_reset)) {
628 fprintf(of, "; RESET vector\n");
629 fprintf(of, "\tgoto\t__sdcc_gsinit_startup\n");
632 if(!pic16_options.omit_ivt) {
633 fprintf(of, "\tres 4\n");
636 fprintf(of, "; High priority interrupt vector 0x0008\n");
638 fprintf(of, "\tgoto\t%s\n", interrupts[1]->rname);
639 fprintf(of, "\tres\t12\n");
641 fprintf(of, "\tretfie\n");
642 fprintf(of, "\tres\t14\n");
645 fprintf(of, "; Low priority interrupt vector 0x0018\n");
647 fprintf(of, "\tgoto\t%s\n", interrupts[2]->rname);
649 fprintf(of, "\tretfie\n");
656 /* return True if the port can handle the type,
657 * False to convert it to function call */
658 static bool _hasNativeMulFor (iCode *ic, sym_link *left, sym_link *right)
660 // fprintf(stderr,"checking for native mult for %c (size: %d)\n", ic->op, getSize(OP_SYMBOL(IC_RESULT(ic))->type));
663 /* multiplication is fixed */
664 /* support mul for char/int/long */
665 if((getSize(OP_SYMBOL(IC_LEFT(ic))->type ) <= 4)
666 && (ic->op == '*'))return TRUE;
670 /* support div for char/int/long */
671 if((getSize(OP_SYMBOL(IC_LEFT(ic))->type ) <= 0)
672 && (ic->op == '/'))return TRUE;
680 /* Do CSE estimation */
681 static bool cseCostEstimation (iCode *ic, iCode *pdic)
683 // operand *result = IC_RESULT(ic);
684 // sym_link *result_type = operandType(result);
687 /* VR -- this is an adhoc. Put here after conversation
688 * with Erik Epetrich */
692 || ic->op == EQ_OP) {
694 fprintf(stderr, "%d %s\n", __LINE__, __FUNCTION__);
699 /* if it is a pointer then return ok for now */
700 if (IC_RESULT(ic) && IS_PTR(result_type)) return 1;
702 /* if bitwise | add & subtract then no since mcs51 is pretty good at it
703 so we will cse only if they are local (i.e. both ic & pdic belong to
704 the same basic block */
705 if (IS_BITWISE_OP(ic) || ic->op == '+' || ic->op == '-') {
706 /* then if they are the same Basic block then ok */
707 if (ic->eBBlockNum == pdic->eBBlockNum) return 1;
712 /* for others it is cheaper to do the cse */
718 /* Indicate which extended bit operations this port supports */
720 hasExtBitOp (int op, int size)
724 /* || op == GETHBIT */ /* GETHBIT doesn't look complete for PIC */
731 /* Indicate the expense of an access to an output storage class */
733 oclsExpense (struct memmap *oclass)
735 /* The IN_FARSPACE test is compatible with historical behaviour, */
736 /* but I don't think it is applicable to PIC. If so, please feel */
737 /* free to remove this test -- EEP */
738 if (IN_FARSPACE(oclass))
744 /** $1 is the input object file (PIC16 specific) // >>always the basename<<.
745 $2 is always the output file.
746 $3 -L path and -l libraries
747 $l is the list of extra options that should be there somewhere...
748 MUST be terminated with a NULL.
750 const char *pic16_linkCmd[] =
752 "gplink", "$l", "-o \"$2\"", "\"$1\"","$3", NULL
757 /** $1 is always the basename.
758 $2 is always the output file.
759 $3 varies (nothing currently)
760 $l is the list of extra options that should be there somewhere...
761 MUST be terminated with a NULL.
763 const char *pic16_asmCmd[] =
765 "gpasm", "$l", "$3", "-c", "\"$1.asm\"", "-o \"$2\"", NULL
774 "MCU PIC16", /* Target name */
775 "p18f452", /* Processor */
778 TRUE, /* Emit glue around main */
779 MODEL_SMALL | MODEL_LARGE | MODEL_FLAT24,
783 pic16_asmCmd, /* assembler command and arguments */
784 NULL, /* alternate macro based form */
785 "-g", /* arguments for debug mode */
786 NULL, /* arguments for normal mode */
787 0, /* print externs as global */
788 ".asm", /* assembler file extension */
789 NULL /* no do_assemble function */
792 NULL, // pic16_linkCmd, /* linker command and arguments */
793 NULL, /* alternate macro based form */
794 _pic16_linkEdit, //NULL, /* no do_link function */
795 ".o", /* extension for object files */
796 0 /* no need for linker file */
808 3, /* fptr, far pointers (see Microchip) */
815 "XSEG (XDATA)", // xstack
816 "STACK (DATA)", // istack
817 "CSEG (CODE)", // code
818 "DSEG (DATA)", // data
819 "ISEG (DATA)", // idata
820 "XSEG (XDATA)", // xdata
822 "RSEG (DATA)", // reg
823 "GSINIT (CODE)", // static
824 "OSEG (OVR,DATA)", // overlay
825 "GSFINAL (CODE)", // post static
826 "HOME (CODE)", // home
829 NULL, // default location for auto vars
830 NULL, // default location for global vars
831 1 // code is read only 1=yes
834 NULL, /* genExtraAreaDeclaration */
835 NULL /* genExatrAreaLinkOptions */
838 /* stack related information */
839 -1, /* -1 stack grows downwards, +1 upwards */
840 1, /* extra overhead when calling between banks */
841 4, /* extra overhead when the function is an ISR */
842 1, /* extra overhead for a function call */
843 1, /* re-entrant space */
844 0 /* 'banked' call overhead, mild overlap with bank_overhead */
846 /* pic16 has an 8 bit mul */
851 pic16_emitDebuggerSymbol
858 _pic16_finaliseOptions,
859 _pic16_setDefaultOptions,
860 pic16_assignRegisters,
863 _pic16_genAssemblerPreamble,
864 NULL, /* no genAssemblerEnd */
866 NULL, // _pic16_genXINIT
867 NULL, /* genInitStartup */
868 _pic16_reset_regparm,
870 _process_pragma, /* process a pragma */
871 _pic16_mangleFunctionName, /* mangles function name */
873 hasExtBitOp, /* hasExtBitOp */
874 oclsExpense, /* oclsExpense */
876 TRUE, /* little endian */
879 1, /* transform <= to ! > */
880 1, /* transform >= to ! < */
881 1, /* transform != to !(a == b) */
883 FALSE, /* No array initializer support. */
884 0, //cseCostEstimation, /* !!!no CSE cost estimation yet */
885 NULL, /* no builtin functions */
886 GPOINTER, /* treat unqualified pointers as "generic" pointers */
887 1, /* reset labelKey to 1 */
888 1, /* globals & local static allowed */