Numerous bug fixes in PIC Port (pointers, shifting, bank selection,...)
[fw/sdcc] / src / pic / pcodepeep.c
1 /*-------------------------------------------------------------------------
2
3    pcodepeep.c - post code generation
4    Written By -  Scott Dattalo scott@dattalo.com
5
6    This program is free software; you can redistribute it and/or modify it
7    under the terms of the GNU General Public License as published by the
8    Free Software Foundation; either version 2, or (at your option) any
9    later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 -------------------------------------------------------------------------*/
20
21 #include <stdio.h>
22 #include <stdlib.h>
23
24 #include "common.h"   // Include everything in the SDCC src directory
25 #include "newalloc.h"
26
27
28 #include "pcode.h"
29 #include "pcodeflow.h"
30 #include "ralloc.h"
31
32 #if defined(__BORLANDC__) || defined(_MSC_VER)
33 #define STRCASECMP stricmp
34 #else
35 #define STRCASECMP strcasecmp
36 #endif
37
38 pCodeOp *popCopyGPR2Bit(pCodeOpReg *pc, int bitval);
39
40
41 pCodeOp *newpCodeOpWild(int id, pCodeWildBlock *pcwb, pCodeOp *subtype);
42 pCode *newpCodeWild(int pCodeID, pCodeOp *optional_operand, pCodeOp *optional_label);
43 pCode * findNextInstruction(pCode *pc);
44 int getpCode(char *mnem,int dest);
45 int getpCodePeepCommand(char *cmd);
46 void pBlockMergeLabels(pBlock *pb);
47 char *pCode2str(char *str, int size, pCode *pc);
48 char *get_op( pCodeOp *pcop);
49
50 extern pCodeInstruction *pic14Mnemonics[];
51
52
53 #define IS_PCCOMMENT(x) ( x && (x->type==PC_COMMENT))
54
55 /****************************************************************/
56 /*
57  * rootRules - defined in SDCCpeep.c
58  *  This is a pointer to the (parsed) peephole rules that are
59  * defined in peep.def.
60  */
61
62 //extern peepRule *rootRules;
63
64
65
66
67 /****************************************************************/
68 /****************************************************************/
69 typedef struct _DLL {
70   struct _DLL *prev;
71   struct _DLL *next;
72   //  void *data;
73 } _DLL;
74
75
76 typedef struct pCodePeepSnippets
77 {
78   _DLL dll;
79   pCodePeep *peep;
80 } pCodePeepSnippets;
81
82
83 /****************************************************************/
84 /*                                                              */
85 /* peepSnippets -                                               */
86 /*                                                              */
87 /****************************************************************/
88
89 static pCodePeepSnippets  *peepSnippets=NULL;
90
91 /****************************************************************/
92 /*                                                              */
93 /* curPeep                                                      */
94 /*                                                              */
95 /****************************************************************/
96
97 //static pCodePeep          *curPeep=NULL;
98
99 /****************************************************************/
100 /*                                                              */
101 /* curBlock                                                     */
102 /*                                                              */
103 /****************************************************************/
104
105 //static pBlock             *curBlock=NULL;
106
107
108 /****************************************************************/
109 /*                                                              */
110 /* max wild cards in a peep rule                                */
111 /*                                                              */
112 /****************************************************************/
113
114 //static int                sMaxWildVar   = 0;
115 //static int                sMaxWildMnem  = 0;
116
117
118 typedef struct pCodeToken 
119 {
120   int tt;  // token type;
121   union {
122     char c;  // character
123     int  n;  // number
124     char *s; // string
125   } tok;
126
127 } pCodeToken;
128
129 pCodeToken tokArr[50];
130 unsigned   tokIdx=0;
131
132
133 typedef enum  {
134   PCT_NULL=0,
135   PCT_SPACE=1,
136   PCT_PERCENT,
137   PCT_LESSTHAN,
138   PCT_GREATERTHAN,
139   PCT_COLON,
140   PCT_COMMA,
141   PCT_COMMENT,
142   PCT_STRING,
143   PCT_NUMBER
144
145 } pCodeTokens;
146
147
148 typedef struct parsedPattern {
149   struct pcPattern *pcp;
150   pCodeToken *pct;
151 } parsedPattern;
152
153 #define MAX_PARSEDPATARR 50
154 parsedPattern parsedPatArr[MAX_PARSEDPATARR];
155 unsigned int parsedPatIdx=0;
156
157
158 typedef enum {
159   PCP_LABEL=1,
160   PCP_NUMBER,
161   PCP_STR,
162   PCP_WILDVAR,
163   PCP_WILDSTR,
164   PCP_COMMA,
165   PCP_COMMENT
166 } pCodePatterns;
167
168 static char pcpat_label[]      = {PCT_PERCENT, PCT_NUMBER, PCT_COLON, 0};
169 static char pcpat_number[]     = {PCT_NUMBER, 0};
170 static char pcpat_string[]     = {PCT_STRING, 0};
171 static char pcpat_wildString[] = {PCT_PERCENT, PCT_STRING, 0};
172 static char pcpat_wildVar[]    = {PCT_PERCENT, PCT_NUMBER, 0};
173 static char pcpat_comma[]      = {PCT_COMMA, 0};
174 static char pcpat_comment[]    = {PCT_COMMENT, 0};
175
176
177 typedef struct pcPattern {
178   char pt;                 // Pattern type
179   char *tokens;           // list of tokens that describe the pattern
180   void * (*f) (void *,pCodeWildBlock *);
181 } pcPattern;
182
183 pcPattern pcpArr[] = {
184   {PCP_LABEL,     pcpat_label,      NULL},
185   {PCP_WILDSTR,   pcpat_wildString, NULL},
186   {PCP_STR,       pcpat_string,     NULL},
187   {PCP_WILDVAR,   pcpat_wildVar,    NULL},
188   {PCP_COMMA,     pcpat_comma,      NULL},
189   {PCP_COMMENT,   pcpat_comment,    NULL},
190   {PCP_NUMBER,    pcpat_number,     NULL}
191 };
192
193 #define PCPATTERNS (sizeof(pcpArr)/sizeof(pcPattern))
194
195 // Assembly Line Token
196 typedef enum {
197   ALT_LABEL=1,
198   ALT_COMMENT,
199   ALT_MNEM0,
200   ALT_MNEM0A,
201   ALT_MNEM1,
202   ALT_MNEM1A,
203   ALT_MNEM1B,
204   ALT_MNEM2,
205   ALT_MNEM2A
206 } altPatterns;
207
208 static char alt_comment[]   = { PCP_COMMENT, 0};
209 static char alt_label[]     = { PCP_LABEL, 0};
210 static char alt_mnem0[]     = { PCP_STR, 0};
211 static char alt_mnem0a[]    = { PCP_WILDVAR, 0};
212 static char alt_mnem1[]     = { PCP_STR, PCP_STR, 0};
213 static char alt_mnem1a[]    = { PCP_STR, PCP_WILDVAR, 0};
214 static char alt_mnem1b[]    = { PCP_STR, PCP_NUMBER, 0};
215 static char alt_mnem2[]     = { PCP_STR, PCP_STR, PCP_COMMA, PCP_STR, 0};
216 static char alt_mnem2a[]    = { PCP_STR, PCP_WILDVAR, PCP_COMMA, PCP_STR, 0};
217
218 static void * cvt_altpat_label(void *pp,pCodeWildBlock *pcwb);
219 static void * cvt_altpat_comment(void *pp,pCodeWildBlock *pcwb);
220 static void * cvt_altpat_mnem0(void *pp,pCodeWildBlock *pcwb);
221 static void * cvt_altpat_mnem0a(void *pp,pCodeWildBlock *pcwb);
222 static void * cvt_altpat_mnem1(void *pp,pCodeWildBlock *pcwb);
223 static void * cvt_altpat_mnem1a(void *pp,pCodeWildBlock *pcwb);
224 static void * cvt_altpat_mnem1b(void *pp,pCodeWildBlock *pcwb);
225 static void * cvt_altpat_mnem2(void *pp,pCodeWildBlock *pcwb);
226 static void * cvt_altpat_mnem2a(void *pp,pCodeWildBlock *pcwb);
227
228 pcPattern altArr[] = {
229   {ALT_LABEL,        alt_label,  cvt_altpat_label},
230   {ALT_COMMENT,      alt_comment,cvt_altpat_comment},
231   {ALT_MNEM2A,       alt_mnem2a, cvt_altpat_mnem2a},
232   {ALT_MNEM2,        alt_mnem2,  cvt_altpat_mnem2},
233   {ALT_MNEM1B,       alt_mnem1b, cvt_altpat_mnem1b},
234   {ALT_MNEM1A,       alt_mnem1a, cvt_altpat_mnem1a},
235   {ALT_MNEM1,        alt_mnem1,  cvt_altpat_mnem1},
236   {ALT_MNEM0A,       alt_mnem0a, cvt_altpat_mnem0a},
237   {ALT_MNEM0,        alt_mnem0,  cvt_altpat_mnem0},
238
239 };
240
241 #define ALTPATTERNS (sizeof(altArr)/sizeof(pcPattern))
242
243 // forward declarations
244 static void * DLL_append(_DLL *list, _DLL *next);
245
246 /*-----------------------------------------------------------------*/
247 /* cvt_extract_destination - helper function extracts the register */
248 /*                           destination from a parsedPattern.     */
249 /*                                                                 */
250 /*-----------------------------------------------------------------*/
251 static int cvt_extract_destination(parsedPattern *pp)
252 {
253
254   if(pp->pct[0].tt == PCT_STRING) {
255
256     // just check first letter for now
257
258     if(toupper(*pp->pct[0].tok.s) == 'F')
259       return 1;
260
261   } else if (pp->pct[0].tt == PCT_NUMBER) {
262
263     if(pp->pct[0].tok.n)
264       return 1;
265   }
266
267   return 0;
268
269 }
270
271 /*-----------------------------------------------------------------*/
272 /*  pCodeOp *cvt_extract_status(char *reg, char *bit)              */
273 /*     if *reg is the "status" register and *bit is one of the     */
274 /*     status bits, then this function will create a new pCode op  */
275 /*     containing the status register.                             */
276 /*-----------------------------------------------------------------*/
277
278 static pCodeOp *cvt_extract_status(char *reg, char *bit)
279 {
280   int len;
281
282   if(STRCASECMP(reg, pc_status.pcop.name))
283     return NULL;
284
285   len = strlen(bit);
286
287   if(len == 1) {
288     // check C,Z
289     if(toupper(*bit) == 'C')
290       return PCOP(popCopyGPR2Bit(&pc_status,PIC_C_BIT));
291     if(toupper(*bit) == 'Z')
292       return PCOP(popCopyGPR2Bit(&pc_status,PIC_Z_BIT));
293   }
294
295   // Check DC
296   if(len ==2 && toupper(bit[0]) == 'D' && toupper(bit[1]) == 'C')
297     return PCOP(popCopyGPR2Bit(&pc_status,PIC_DC_BIT));
298
299   return NULL;
300
301 }
302
303 /*-----------------------------------------------------------------*/
304 /* cvt_altpat_label - convert assembly line type to a pCode label  */
305 /* INPUT: pointer to the parsedPattern                             */
306 /*                                                                 */
307 /*  pp[0] - label                                                  */
308 /*                                                                 */
309 /* label pattern => '%' number ':'                                 */
310 /* at this point, we wish to extract only the 'number'             */
311 /*                                                                 */
312 /*-----------------------------------------------------------------*/
313 static void * cvt_altpat_label(void *pp,pCodeWildBlock *pcwb)
314 {
315   parsedPattern *p = pp;
316
317   DFPRINTF((stderr,"altpat_label with ID = %d\n",p->pct[1].tok.n));
318   return newpCodeLabel(NULL,-p->pct[1].tok.n);
319
320 }
321
322 /*-----------------------------------------------------------------*/
323 /* cvt_altpat_comment - convert assembly line type to a comment    */
324 /* INPUT: pointer to the parsedPattern                             */
325 /*                                                                 */
326 /*  pp[0] - comment                                                */
327 /*                                                                 */
328 /*                                                                 */
329 /*-----------------------------------------------------------------*/
330 static void * cvt_altpat_comment(void *pp,pCodeWildBlock *pcwb)
331 {
332   parsedPattern *p = pp;
333
334   DFPRINTF((stderr,"altpat_comment  = %s\n",p->pct[0].tok.s));
335   return newpCodeCharP(p->pct[0].tok.s);
336
337 }
338
339 /*-----------------------------------------------------------------*/
340 /* cvt_altpat_mem0  - convert assembly line type to a wild pCode   */
341 /*                    instruction                                  */
342 /*                                                                 */
343 /*  pp[0] - str                                                    */
344 /*                                                                 */
345 /*-----------------------------------------------------------------*/
346 static void * cvt_altpat_mnem0(void *pp,pCodeWildBlock *pcwb)
347 {
348   parsedPattern *p = pp;
349   int opcode;
350
351   pCodeInstruction *pci=NULL;
352
353   DFPRINTF((stderr,"altpat_mnem0 %s\n",  p->pct[0].tok.s));
354
355   opcode = getpCode(p->pct[0].tok.s,0);
356
357   if(opcode < 0) {
358     /* look for special command strings like _NOTBITSKIP_ */
359
360     //fprintf(stderr, "Bad mnemonic\n");
361
362     opcode  = getpCodePeepCommand(p->pct[0].tok.s);
363     //if(opcode > 0)
364     //  fprintf(stderr,"  but valid peep command: %s, key = %d\n",p->pct[0].tok.s,opcode);
365     return NULL;
366   }
367
368   pci = PCI(newpCode(opcode, NULL));
369
370   if(!pci)
371     fprintf(stderr,"couldn't find mnemonic\n");
372
373
374   return pci;
375 }
376
377 /*-----------------------------------------------------------------*/
378 /* cvt_altpat_mem0a - convert assembly line type to a wild pCode   */
379 /*                    instruction                                  */
380 /*                                                                 */
381 /*  pp[0] - wild var                                               */
382 /*                                                                 */
383 /*-----------------------------------------------------------------*/
384 static void * cvt_altpat_mnem0a(void *pp, pCodeWildBlock *pcwb)
385 {
386   parsedPattern *p = pp;
387
388   DFPRINTF((stderr,"altpat_mnem0a wild mnem # %d\n",  p[0].pct[1].tok.n));
389
390   /* Save the index of the maximum wildcard mnemonic */
391
392   //if(p[0].pct[1].tok.n > sMaxWildVar)
393   //  sMaxWildMnem = p[0].pct[1].tok.n;
394
395   if(p[0].pct[1].tok.n > pcwb->nwildpCodes)
396     pcwb->nwildpCodes = p[0].pct[1].tok.n;
397
398   return newpCodeWild(p[0].pct[1].tok.n,NULL,NULL);
399
400 }
401
402 /*-----------------------------------------------------------------*/
403 /* cvt_altpat_mem1 - convert assembly line type to a pCode         */
404 /*                   instruction with 1 operand.                   */
405 /*                                                                 */
406 /*  pp[0] - mnem                                                   */
407 /*  pp[1] - Operand                                                */
408 /*                                                                 */
409 /*-----------------------------------------------------------------*/
410 static void * cvt_altpat_mnem1(void *pp,pCodeWildBlock *pcwb)
411 {
412
413   parsedPattern *p = pp;
414   int opcode;
415
416   pCodeInstruction *pci=NULL;
417   pCodeOp *pcosubtype;
418
419   DFPRINTF((stderr,"altpat_mnem1 %s var %s\n",  p->pct[0].tok.s,p[1].pct[0].tok.s));
420
421   opcode = getpCode(p->pct[0].tok.s,0);
422   if(opcode < 0) {
423     //fprintf(stderr, "Bad mnemonic\n");
424     opcode  = getpCodePeepCommand(p->pct[0].tok.s);
425     //if(opcode > 0)
426     //fprintf(stderr,"  but valid peep command: %s, key = %d\n",p->pct[0].tok.s,opcode);
427
428     return NULL;
429   }
430
431   if(pic14Mnemonics[opcode]->isBitInst)
432     pcosubtype = newpCodeOp(p[1].pct[0].tok.s,PO_BIT);
433   else
434     pcosubtype = newpCodeOp(p[1].pct[0].tok.s,PO_GPR_REGISTER);
435
436
437   pci = PCI(newpCode(opcode, pcosubtype));
438
439   if(!pci)
440     fprintf(stderr,"couldn't find mnemonic\n");
441
442
443   return pci;
444 }
445
446 /*-----------------------------------------------------------------*/
447 /* cvt_altpat_mem1a - convert assembly line type to a pCode        */
448 /*                    instruction with 1 wild operand.             */
449 /*                                                                 */
450 /*  pp[0] - mnem                                                   */
451 /*  pp[1] - wild var                                               */
452 /*                                                                 */
453 /*-----------------------------------------------------------------*/
454 static void * cvt_altpat_mnem1a(void *pp,pCodeWildBlock *pcwb)
455 {
456   parsedPattern *p = pp;
457   int opcode;
458
459   pCodeInstruction *pci=NULL;
460   pCodeOp *pcosubtype;
461
462   DFPRINTF((stderr,"altpat_mnem1a %s var %d\n",  p->pct[0].tok.s,p[1].pct[1].tok.n));
463
464   opcode = getpCode(p->pct[0].tok.s,0);
465   if(opcode < 0) {
466     int cmd_id = getpCodePeepCommand(p->pct[0].tok.s);
467     pCode *pc=NULL;
468
469     if(cmd_id<0) {
470       fprintf(stderr, "Bad mnemonic\n");
471       return NULL;
472     }
473
474     if(p[0].pct[1].tok.n > pcwb->nwildpCodes)
475       pcwb->nwildpCodes = p[0].pct[1].tok.n;
476
477     pc =  newpCodeWild(p[1].pct[1].tok.n,NULL,NULL);
478
479     switch(cmd_id) {
480     case NOTBITSKIP:
481       PCW(pc)->mustNotBeBitSkipInst = 1;
482       break;
483     case BITSKIP:
484       PCW(pc)->mustBeBitSkipInst = 1;
485       break;
486     case INVERTBITSKIP:
487       PCW(pc)->invertBitSkipInst = 1;
488     }
489     return pc;
490   }
491
492   if(pic14Mnemonics[opcode]->isBitInst)
493     pcosubtype = newpCodeOpBit(NULL,-1,0);
494   else
495     pcosubtype = newpCodeOp(NULL,PO_GPR_REGISTER);
496
497
498   pci = PCI(newpCode(opcode,
499                      newpCodeOpWild(p[1].pct[1].tok.n, pcwb, pcosubtype)));
500
501   /* Save the index of the maximum wildcard variable */
502   //if(p[1].pct[1].tok.n > sMaxWildVar)
503   //  sMaxWildVar = p[1].pct[1].tok.n;
504
505   if(p[1].pct[1].tok.n > pcwb->nvars)
506     pcwb->nvars = p[1].pct[1].tok.n;
507
508   if(!pci)
509     fprintf(stderr,"couldn't find mnemonic\n");
510
511
512   return pci;
513 }
514
515 /*-----------------------------------------------------------------*/
516 /*-----------------------------------------------------------------*/
517 static void * cvt_altpat_mnem1b(void *pp,pCodeWildBlock *pcwb)
518 {
519   parsedPattern *p = pp;
520   int opcode;
521
522   pCodeInstruction *pci=NULL;
523
524   DFPRINTF((stderr,"altpat_mnem1b %s var %d\n",  p->pct[0].tok.s,p[1].pct[0].tok.n));
525
526   opcode = getpCode(p->pct[0].tok.s,0);
527   if(opcode < 0) {
528     fprintf(stderr, "Bad mnemonic\n");
529     return NULL;
530   }
531
532   pci = PCI(newpCode(opcode, newpCodeOpLit(p[1].pct[0].tok.n) ));
533
534   if(!pci)
535     fprintf(stderr,"couldn't find mnemonic\n");
536
537
538   return pci;
539 }
540
541 /*-----------------------------------------------------------------*/
542 /*-----------------------------------------------------------------*/
543 static void * cvt_altpat_mnem2(void *pp,pCodeWildBlock *pcwb)
544 {
545   parsedPattern *p = pp;
546   int opcode;
547   int dest;
548
549   pCodeInstruction *pci=NULL;
550   pCodeOp *pcosubtype;
551
552   dest = cvt_extract_destination(&p[3]);
553
554   DFPRINTF((stderr,"altpat_mnem2 %s var %s destination %s(%d)\n",
555           p->pct[0].tok.s,
556           p[1].pct[0].tok.s,
557           p[3].pct[0].tok.s,
558           dest));
559
560
561   opcode = getpCode(p->pct[0].tok.s,dest);
562   if(opcode < 0) {
563     fprintf(stderr, "Bad mnemonic\n");
564     return NULL;
565   }
566
567   if(pic14Mnemonics[opcode]->isBitInst) {
568     pcosubtype = cvt_extract_status(p[1].pct[0].tok.s, p[3].pct[0].tok.s);
569     if(pcosubtype == NULL) {
570       fprintf(stderr, "bad operand?\n");
571       return NULL;
572     }
573       
574   } else
575     pcosubtype = newpCodeOp(p[1].pct[0].tok.s,PO_GPR_REGISTER);
576
577
578   pci = PCI(newpCode(opcode,pcosubtype));
579
580   if(!pci)
581     fprintf(stderr,"couldn't find mnemonic\n");
582
583   return pci;
584
585 }
586
587 /*-----------------------------------------------------------------*/
588 /* cvt_altpat_mem2a - convert assembly line type to a pCode        */
589 /*                    instruction with 1 wild operand and a        */
590 /*                    destination operand (e.g. w or f)            */
591 /*                                                                 */
592 /*  pp[0] - mnem                                                   */
593 /*  pp[1] - wild var                                               */
594 /*  pp[2] - comma                                                  */
595 /*  pp[3] - destination                                            */
596 /*                                                                 */
597 /*-----------------------------------------------------------------*/
598 static void * cvt_altpat_mnem2a(void *pp,pCodeWildBlock *pcwb)
599 {
600   parsedPattern *p = pp;
601   int opcode;
602   int dest;
603
604   pCodeInstruction *pci=NULL;
605   pCodeOp *pcosubtype;
606
607   dest = cvt_extract_destination(&p[3]);
608
609   DFPRINTF((stderr,"altpat_mnem2a %s var %d destination %s(%d)\n",
610           p->pct[0].tok.s,
611           p[1].pct[1].tok.n,
612           p[3].pct[0].tok.s,
613           dest));
614
615
616   opcode = getpCode(p->pct[0].tok.s,dest);
617   if(opcode < 0) {
618     fprintf(stderr, "Bad mnemonic\n");
619     return NULL;
620   }
621
622   if(pic14Mnemonics[opcode]->isBitInst)
623     pcosubtype = newpCodeOp(NULL,PO_BIT);
624   else
625     pcosubtype = newpCodeOp(NULL,PO_GPR_REGISTER);
626
627
628   pci = PCI(newpCode(opcode,
629                      newpCodeOpWild(p[1].pct[1].tok.n, pcwb, pcosubtype)));
630
631   /* Save the index of the maximum wildcard variable */
632   //if(p[1].pct[1].tok.n > sMaxWildVar)
633   //  sMaxWildVar = p[1].pct[1].tok.n;
634
635   if(p[1].pct[1].tok.n > pcwb->nvars)
636     pcwb->nvars = p[1].pct[1].tok.n;
637
638   if(!pci)
639     fprintf(stderr,"couldn't find mnemonic\n");
640
641   return pci;
642
643 }
644
645 /*-----------------------------------------------------------------*/
646 /* tokenizeLineNode - Convert a string (of char's) that was parsed */
647 /*                    by SDCCpeeph.c into a string of tokens.      */
648 /*                                                                 */
649 /*                                                                 */
650 /* The tokenizer is of the classic type. When an item is encounterd*/
651 /* it is converted into a token. The token is a structure that     */
652 /* encodes the item's type and it's value (when appropriate).      */
653 /*                                                                 */
654 /* Accepted token types:                                           */
655 /*    SPACE  NUMBER STRING  %  : ,  ;                              */
656 /*                                                                 */
657 /*                                                                 */
658 /*                                                                 */
659 /*-----------------------------------------------------------------*/
660
661
662 static void tokenizeLineNode(char *ln)
663 {
664
665   tokIdx = 0;               // Starting off at the beginning
666   tokArr[0].tt = PCT_NULL;  // and assume invalid character for first token.
667
668   if(!ln || !*ln)
669     return;
670
671   while(*ln) {
672
673     if(isspace(*ln)) {
674       // add a SPACE token and eat the extra spaces.
675       tokArr[tokIdx++].tt = PCT_SPACE;
676       while (isspace (*ln))
677         ln++;
678       continue;
679     }
680
681     if(isdigit(*ln)) {
682
683       tokArr[tokIdx].tt = PCT_NUMBER;
684       tokArr[tokIdx++].tok.n = strtol(ln, &ln, 0);
685
686       continue;
687
688     }
689
690     switch(*ln) {
691     case '%':
692       tokArr[tokIdx++].tt = PCT_PERCENT;
693       break;
694     case '<':
695       tokArr[tokIdx++].tt = PCT_LESSTHAN;
696       break;
697     case '>':
698       tokArr[tokIdx++].tt = PCT_GREATERTHAN;
699       break;
700     case ':':
701       tokArr[tokIdx++].tt = PCT_COLON;
702       break;
703     case ';':
704       tokArr[tokIdx].tok.s = Safe_strdup(ln);
705       tokArr[tokIdx++].tt = PCT_COMMENT;
706       tokArr[tokIdx].tt = PCT_NULL;
707       return;
708     case ',':
709       tokArr[tokIdx++].tt = PCT_COMMA;
710       break;
711
712
713     default:
714       if(isalpha(*ln) || (*ln == '_') ) {
715         char buffer[50];
716         int i=0;
717
718         while( (isalpha(*ln)  ||  isdigit(*ln) || (*ln == '_')) && i<49)
719           buffer[i++] = *ln++;
720
721         ln--;
722         buffer[i] = 0;
723
724         tokArr[tokIdx].tok.s = Safe_strdup(buffer);
725         tokArr[tokIdx++].tt = PCT_STRING;
726
727       }
728     }
729
730     /* Advance to next character in input string .
731      * Note, if none of the tests passed above, then 
732      * we effectively ignore the `bad' character.
733      * Since the line has already been parsed by SDCCpeeph,
734      * chance are that there are no invalid characters... */
735
736     ln++;
737
738   }
739
740   tokArr[tokIdx].tt = 0;
741 }
742
743
744 /*-----------------------------------------------------------------*/
745 /*-----------------------------------------------------------------*/
746
747
748
749 void dump1Token(pCodeTokens tt)
750 {
751 #ifdef PCODE_DEBUG
752   switch(tt) {
753   case PCT_SPACE:
754     fprintf(stderr, " space ");
755     break;
756   case PCT_PERCENT:
757     fprintf(stderr, " pct %%");
758     break;
759   case PCT_LESSTHAN:
760     fprintf(stderr, " pct <");
761     break;
762   case PCT_GREATERTHAN:
763     fprintf(stderr, " pct >");
764     break;
765   case PCT_COLON:
766     fprintf(stderr, " col :");
767     break;
768   case PCT_COMMA:
769     fprintf(stderr, " comma , ");
770     break;
771   case PCT_COMMENT:
772     fprintf(stderr, " comment ");
773     //fprintf(stderr,"%s",tokArr[i].tok.s);
774     break;
775   case PCT_STRING:
776     fprintf(stderr, " str ");
777     //fprintf(stderr,"%s",tokArr[i].tok.s);
778     break;
779   case PCT_NUMBER:
780     fprintf(stderr, " num ");
781     //fprintf(stderr,"%d",tokArr[i].tok.n);
782     break;
783   case PCT_NULL:
784     fprintf(stderr, " null ");
785
786   }
787 #endif
788 }
789
790
791 /*-----------------------------------------------------------------*/
792 /*-----------------------------------------------------------------*/
793
794 int pcComparePattern(pCodeToken *pct, char *pat, int max_tokens)
795 {
796   int i=0;
797
798   if(!pct || !pat || !*pat)
799     return 0;
800
801   //DFPRINTF((stderr,"comparing against:\n"));
802
803   while(i < max_tokens) {
804
805     if(*pat == 0){
806       //DFPRINTF((stderr,"matched\n"));
807       return (i+1);
808     }
809
810     //dump1Token(*pat); DFPRINTF((stderr,"\n"));
811
812     if(pct->tt != *pat) 
813       return 0;
814
815
816     pct++;
817     pat++;
818   }
819
820   return 0;
821
822 }
823
824 /*-----------------------------------------------------------------*/
825 /*-----------------------------------------------------------------*/
826
827 int altComparePattern( char *pct, parsedPattern *pat, int max_tokens)
828 {
829   int i=0;
830   
831   if(!pct || !pat || !*pct)
832     return 0;
833
834
835   while(i < max_tokens) {
836
837     if(*pct == 0) {
838       //DFPRINTF((stderr,"matched\n"));
839       return i;
840     }
841
842     //dump1Token(*pat); DFPRINTF((stderr,"\n"));
843
844     if( !pat || !pat->pcp )
845       return 0;
846
847     if (pat->pcp->pt != *pct)  
848       return 0;
849
850     //DFPRINTF((stderr," pct=%d\n",*pct));
851     pct++;
852     pat++;
853     i++;
854   }
855
856   return 0;
857
858 }
859 /*-----------------------------------------------------------------*/
860 /*-----------------------------------------------------------------*/
861
862 int advTokIdx(int *v, int amt)
863 {
864
865   if((unsigned) (*v + amt) > tokIdx)
866     return 1;
867
868   *v += amt;
869   return 0;
870
871 }
872
873 /*-----------------------------------------------------------------*/
874 /* parseTokens - convert the tokens corresponding to a single line */
875 /*               of a peep hole assembly into a pCode object.      */
876 /*                                                                 */
877 /*                                                                 */
878 /*                                                                 */
879 /*                                                                 */
880 /* This is a simple parser that looks for strings of the type      */
881 /* allowed in the peep hole definition file. Essentially the format*/
882 /* is the same as a line of assembly:                              */
883 /*                                                                 */
884 /*  label:    mnemonic   op1, op2, op3    ; comment                */
885 /*                                                                 */
886 /* Some of these items aren't present. It's the job of the parser  */
887 /* to determine which are and convert those into the appropriate   */
888 /* pcode.                                                          */
889 /*-----------------------------------------------------------------*/
890
891 void parseTokens(pCodeWildBlock *pcwb)
892 {
893   unsigned i;
894   pCode *pc;
895
896   if(!tokIdx)
897     return;
898
899   for(i=0; i<=tokIdx; i++)
900     dump1Token(tokArr[i].tt);
901 #ifdef PCODE_DEBUG
902   fputc('\n',stderr);
903 #endif
904   {
905     int lparsedPatIdx=0;
906     int lpcpIdx;
907     int ltokIdx =0;
908     int matching = 0;
909     int j=0;
910     int k=0;
911
912     char * cPmnem  = NULL;     // Pointer to non-wild mnemonic (if any)
913     char * cP1stop = NULL;
914     char * cP2ndop = NULL;
915
916     //pCodeOp *pcl   = NULL;       // Storage for a label
917     //pCodeOp *pco1  = NULL;       // 1st operand
918     //pCodeOp *pco2  = NULL;       // 2nd operand
919     //pCode   *pc    = NULL;       // Mnemonic
920
921     typedef enum {
922       PS_START,
923       PS_HAVE_LABEL,
924       PS_HAVE_MNEM,
925       PS_HAVE_1OPERAND,
926       PS_HAVE_COMMA,
927       PS_HAVE_2OPERANDS
928     } ParseStates;
929
930     ParseStates state = PS_START;
931
932     do {
933
934       lpcpIdx=0;
935       matching = 0;
936
937       if(  ((tokArr[ltokIdx].tt == PCT_SPACE) )
938            && (advTokIdx(&ltokIdx, 1)) ) // eat space
939         break;
940
941       do {
942         j = pcComparePattern(&tokArr[ltokIdx], pcpArr[lpcpIdx].tokens, tokIdx +1);
943         if( j ) {
944
945           switch(pcpArr[lpcpIdx].pt) {
946           case  PCP_LABEL:
947             if(state == PS_START){
948               DFPRINTF((stderr,"  label\n"));
949               state = PS_HAVE_LABEL;
950             } else 
951               DFPRINTF((stderr,"  bad state (%d) for label\n",state));
952             break;
953
954           case  PCP_STR:
955             DFPRINTF((stderr,"  %s is",tokArr[ltokIdx].tok.s));
956             switch(state) {
957             case PS_START:
958             case PS_HAVE_LABEL:
959               DFPRINTF((stderr,"  mnem\n"));
960               cPmnem = tokArr[ltokIdx].tok.s;
961               state = PS_HAVE_MNEM;
962               break;
963             case PS_HAVE_MNEM:
964               DFPRINTF((stderr,"  1st operand\n"));
965               cP1stop = tokArr[ltokIdx].tok.s;
966               //pco1 = newpCodeOp(NULL,PO_GPR_REGISTER);
967               state = PS_HAVE_1OPERAND;
968               break;
969             case PS_HAVE_1OPERAND:
970               DFPRINTF((stderr,"  error expecting comma\n"));
971               break;
972             case PS_HAVE_COMMA:
973               DFPRINTF((stderr,"  2 operands\n"));
974               cP2ndop = tokArr[ltokIdx].tok.s;
975               break;
976             case PS_HAVE_2OPERANDS:
977               break;
978             }
979             break;
980
981           case  PCP_WILDVAR:
982             switch(state) {
983             case PS_START:
984             case PS_HAVE_LABEL:
985               DFPRINTF((stderr,"  wild mnem\n"));
986               state = PS_HAVE_MNEM;
987               break;
988             case PS_HAVE_MNEM:
989               DFPRINTF((stderr,"  1st operand is wild\n"));
990               state = PS_HAVE_1OPERAND;
991               break;
992             case PS_HAVE_1OPERAND:
993               DFPRINTF((stderr,"  error expecting comma\n"));
994               break;
995             case PS_HAVE_COMMA:
996               DFPRINTF((stderr,"  2nd operand is wild\n"));
997               break;
998             case PS_HAVE_2OPERANDS:
999               break;
1000             }
1001             break;
1002
1003           case  PCP_NUMBER:
1004             switch(state) {
1005             case PS_START:
1006             case PS_HAVE_LABEL:
1007               fprintf(stderr,"  ERROR number\n");
1008               break;
1009             case PS_HAVE_MNEM:
1010               DFPRINTF((stderr,"  1st operand is a number\n"));
1011               state = PS_HAVE_1OPERAND;
1012               break;
1013             case PS_HAVE_1OPERAND:
1014               fprintf(stderr,"  error expecting comma\n");
1015               break;
1016             case PS_HAVE_COMMA:
1017               DFPRINTF((stderr,"  2nd operand is a number\n"));
1018               break;
1019             case PS_HAVE_2OPERANDS:
1020               break;
1021             }
1022             break;
1023
1024           case  PCP_WILDSTR:
1025             break;
1026           case  PCP_COMMA:
1027             if(state == PS_HAVE_1OPERAND){
1028               DFPRINTF((stderr,"  got a comma\n"));
1029               state = PS_HAVE_COMMA;
1030             } else
1031               fprintf(stderr,"  unexpected comma\n");
1032           }
1033
1034           matching = 1;
1035           parsedPatArr[lparsedPatIdx].pcp = &pcpArr[lpcpIdx];
1036           parsedPatArr[lparsedPatIdx].pct = &tokArr[ltokIdx];
1037           lparsedPatIdx++;
1038
1039           //dump1Token(tokArr[ltokIdx].tt);
1040
1041           if(advTokIdx(&ltokIdx, strlen(pcpArr[lpcpIdx].tokens) ) ) {
1042             DFPRINTF((stderr," reached end \n"));
1043             matching = 0;
1044             //return;
1045           }
1046         }
1047
1048
1049       } while ((++lpcpIdx < PCPATTERNS) && !matching);
1050
1051     } while (matching);
1052
1053     parsedPatArr[lparsedPatIdx].pcp = NULL;
1054     parsedPatArr[lparsedPatIdx].pct = NULL;
1055
1056     j=k=0;
1057     do {
1058       int c;
1059
1060       if( (c=altComparePattern( altArr[k].tokens, &parsedPatArr[j],10) ) ) {
1061
1062         if( altArr[k].f) {
1063           pc = altArr[k].f(&parsedPatArr[j],pcwb);
1064           //if(pc && pc->print)
1065           //  pc->print(stderr,pc);
1066           //if(pc && pc->destruct) pc->destruct(pc); dumps core?
1067
1068           //if(curBlock && pc)
1069           //addpCode2pBlock(curBlock, pc);
1070           addpCode2pBlock(pcwb->pb, pc);
1071         }
1072         j += c;
1073       }
1074       k++;
1075     }
1076     while(j<=lparsedPatIdx && k<ALTPATTERNS);
1077
1078 /*
1079     DFPRINTF((stderr,"\nConverting parsed line to pCode:\n\n"));
1080
1081     j = 0;
1082     do {
1083       if(parsedPatArr[j].pcp && parsedPatArr[j].pcp->f )
1084         parsedPatArr[j].pcp->f(&parsedPatArr[j]);
1085       DFPRINTF((stderr,"  %d",parsedPatArr[j].pcp->pt));
1086       j++;
1087     }
1088     while(j<lparsedPatIdx);
1089 */
1090     DFPRINTF((stderr,"\n"));
1091
1092   }
1093
1094
1095 }
1096
1097 /*-----------------------------------------------------------------*/
1098 /*                                                                 */
1099 /*-----------------------------------------------------------------*/
1100 void  peepRuleBlock2pCodeBlock(  lineNode *ln, pCodeWildBlock *pcwb)
1101 {
1102
1103   if(!ln)
1104     return;
1105
1106   for( ; ln; ln = ln->next) {
1107
1108     //DFPRINTF((stderr,"%s\n",ln->line));
1109
1110     tokenizeLineNode(ln->line);
1111     parseTokens(pcwb);
1112
1113   }
1114 }
1115
1116 /*-----------------------------------------------------------------*/
1117 /* peepRuleCondition                                               */
1118 /*-----------------------------------------------------------------*/
1119 static void   peepRuleCondition(char *cond, pCodePeep *pcp)
1120 {
1121   if(!cond || !pcp)
1122     return;
1123
1124   //DFPRINTF((stderr,"\nCondition:  %s\n",cond));
1125   /* brute force compares for now */
1126
1127   if(STRCASECMP(cond, "NZ") == 0) {
1128     //DFPRINTF((stderr,"found NZ\n"));
1129     pcp->postFalseCond = PCC_Z;
1130
1131   }
1132
1133 }
1134
1135
1136 void initpCodeWildBlock(pCodeWildBlock *pcwb)
1137 {
1138   
1139   //  pcwb = Safe_calloc(1,sizeof(pCodeWildBlock));
1140
1141   if(!pcwb)
1142     return;
1143
1144   pcwb->vars = NULL; 
1145   pcwb->wildpCodes = NULL;
1146   pcwb->wildpCodeOps = NULL;
1147
1148   pcwb->nvars = 0; 
1149   pcwb->nwildpCodes = 0;
1150   pcwb->nops = 0;
1151
1152 }
1153
1154 void postinit_pCodeWildBlock(pCodeWildBlock *pcwb)
1155 {
1156   
1157   if(!pcwb)
1158     return;
1159
1160   pcwb->nvars++;
1161   pcwb->nops = pcwb->nvars;
1162
1163   pcwb->vars = Safe_calloc(pcwb->nvars, sizeof(char *));
1164   pcwb->wildpCodeOps = Safe_calloc(pcwb->nvars, sizeof(pCodeOp *));
1165
1166   pcwb->nwildpCodes++;
1167   pcwb->wildpCodes = Safe_calloc(pcwb->nwildpCodes, sizeof(pCode *));
1168
1169 }
1170
1171 void initpCodePeep(pCodePeep *pcp)
1172 {
1173   
1174   //  pcwb = Safe_calloc(1,sizeof(pCodeWildBlock));
1175
1176   if(!pcp)
1177     return;
1178
1179   initpCodeWildBlock(&pcp->target);
1180   pcp->target.pb = newpCodeChain(NULL, 'W', NULL);
1181
1182   initpCodeWildBlock(&pcp->replace);
1183   pcp->replace.pb = newpCodeChain(NULL, 'W', NULL);
1184
1185 }
1186
1187 /*-----------------------------------------------------------------*/
1188 /* peepRules2pCode - parse the "parsed" peep hole rules to generate*/
1189 /*                   pCode.                                        */
1190 /*                                                                 */
1191 /* SDCCpeeph parses the peep rules file and extracts variables,    */
1192 /* removes white space, and checks the syntax. This function       */
1193 /* extends that processing to produce pCode objects. You can kind  */
1194 /* think of this function as an "assembler", though instead of     */
1195 /* taking raw text to produce machine code, it produces pCode.     */
1196 /*                                                                 */
1197 /*-----------------------------------------------------------------*/
1198 extern void pic14initpCodePeepCommands(void);
1199
1200 void  peepRules2pCode(peepRule *rules)
1201 {
1202   peepRule *pr;
1203
1204   pCodePeep *currentRule;
1205   pCodePeepSnippets *pcps;
1206
1207   pic14initpCodePeepCommands();
1208
1209   /* The rules are in a linked-list. Each rule has two portions */
1210   /* There's the `target' and there's the `replace'. The target */
1211   /* is compared against the SDCC generated code and if it      */
1212   /* matches, it gets replaced by the `replace' block of code.  */
1213   /*                                                            */
1214   /* Here we loop through each rule and convert the target's and*/
1215   /* replace's into pCode target and replace blocks             */
1216
1217   for (pr = rules; pr; pr = pr->next) {
1218
1219     //DFPRINTF((stderr,"\nRule:\n\n"));
1220
1221     pcps = Safe_calloc(1,sizeof(pCodePeepSnippets));
1222     peepSnippets = DLL_append((_DLL*)peepSnippets,(_DLL*)pcps);
1223
1224 /*
1225     curPeep = pcps->peep  = Safe_calloc(1,sizeof(pCodePeep));
1226
1227     curPeep->vars = NULL; 
1228     curPeep->wildpCodes = NULL; curPeep->wildpCodeOps = NULL;
1229     curPeep->postFalseCond = PCC_NONE;
1230     curPeep->postTrueCond  = PCC_NONE;
1231
1232
1233     curPeep->target = curBlock = newpCodeChain(NULL, 'W', NULL);
1234     sMaxWildVar  = 0;
1235     sMaxWildMnem = 0;
1236 */
1237     currentRule = pcps->peep  = Safe_calloc(1,sizeof(pCodePeep));
1238     initpCodePeep(currentRule);
1239
1240     /* Convert the target block */
1241     peepRuleBlock2pCodeBlock(pr->match, &currentRule->target);
1242
1243     //DFPRINTF((stderr,"finished target, here it is in pcode form:\n"));
1244     //printpBlock(stderr, curBlock);
1245
1246     //DFPRINTF((stderr,"target with labels merged:\n"));
1247     //pBlockMergeLabels(curBlock);
1248     pBlockMergeLabels(currentRule->target.pb);
1249     //printpBlock(stderr, currentRule->replace.pb);
1250
1251     //#ifdef PCODE_DEBUG
1252     //    printpBlock(stderr, curBlock);
1253     //#endif
1254     //DFPRINTF((stderr,"\nReplaced by:\n"));
1255
1256
1257     //curPeep->replace = curBlock = newpCodeChain(NULL, 'W', NULL);
1258
1259     /* Convert the replace block */
1260     peepRuleBlock2pCodeBlock(pr->replace, &currentRule->replace);
1261
1262     //DFPRINTF((stderr,"finished replace block, here it is in pcode form:\n"));
1263     //printpBlock(stderr, curBlock);
1264
1265     //DFPRINTF((stderr,"replace with labels merged:\n"));
1266     //pBlockMergeLabels(curBlock);
1267     pBlockMergeLabels(currentRule->replace.pb);
1268     //printpBlock(stderr, currentRule->replace.pb);
1269
1270     peepRuleCondition(pr->cond,currentRule);
1271
1272     /* The rule has been converted to pCode. Now allocate
1273      * space for the wildcards */
1274     
1275 /*
1276      ++sMaxWildVar;
1277     curPeep->nvars = sMaxWildVar;
1278     curPeep->vars = Safe_calloc(sMaxWildVar, sizeof(char *));
1279
1280     curPeep->nops = sMaxWildVar;
1281     curPeep->wildpCodeOps = Safe_calloc(sMaxWildVar, sizeof(pCodeOp *));
1282
1283     curPeep->nwildpCodes = ++sMaxWildMnem;
1284     curPeep->wildpCodes = Safe_calloc(sMaxWildMnem, sizeof(char *));
1285 */
1286     postinit_pCodeWildBlock(&currentRule->target);
1287
1288     //return; // debug ... don't want to go through all the rules yet
1289   }
1290
1291   {
1292     pCodePeep *peepBlock;
1293     _DLL *peeprules;
1294
1295     peeprules = (_DLL *)peepSnippets;
1296     //fprintf(stderr,"target rules\n");
1297     while(peeprules) {
1298       //fprintf(stderr,"   rule:\n");
1299       peepBlock = ((pCodePeepSnippets*)peeprules)->peep;
1300       //printpBlock(stderr, peepBlock->target.pb);
1301       peeprules = peeprules->next;
1302     }
1303     //fprintf(stderr," ... done\n");
1304   }
1305
1306 }
1307
1308 void printpCodeString(FILE *of, pCode *pc, int max)
1309 {
1310   int i=0;
1311
1312   while(pc && (i++<max)) {
1313     pc->print(of,pc);
1314     pc = pc->next;
1315   }
1316 }
1317
1318 /*-----------------------------------------------------------------*/
1319 /* _DLL * DLL_append                                               */
1320 /*                                                                 */ 
1321 /*  Append a _DLL object to the end of a _DLL (doubly linked list) */ 
1322 /* If The list to which we want to append is non-existant then one */ 
1323 /* is created. Other wise, the end of the list is sought out and   */ 
1324 /* a new DLL object is appended to it. In either case, the void    */
1325 /* *data is added to the newly created DLL object.                 */
1326 /*-----------------------------------------------------------------*/
1327
1328 static void * DLL_append(_DLL *list, _DLL *next)
1329 {
1330   _DLL *b;
1331
1332
1333   /* If there's no list, then create one: */
1334   if(!list) {
1335     next->next = next->prev = NULL;
1336     return next;
1337   }
1338
1339
1340   /* Search for the end of the list. */
1341   b = list;
1342   while(b->next)
1343     b = b->next;
1344
1345   /* Now append the new DLL object */
1346   b->next = next;
1347   b->next->prev = b;
1348   b = b->next; 
1349   b->next = NULL;
1350
1351   return list;
1352   
1353 }  
1354
1355
1356 /*-----------------------------------------------------------------
1357
1358   pCode peephole optimization
1359
1360
1361   The pCode "peep hole" optimization is not too unlike the peep hole
1362   optimization in SDCCpeeph.c. The major difference is that here we
1363   use pCode's whereas there we use ASCII strings. The advantage with
1364   pCode's is that we can ascertain flow information in the instructions
1365   being optimized.
1366
1367
1368 <FIX ME> - elaborate...
1369
1370   -----------------------------------------------------------------*/
1371
1372
1373
1374 /*-----------------------------------------------------------------*/
1375 /* pCodeSearchCondition - Search a pCode chain for a 'condition'   */
1376 /*                                                                 */
1377 /* return conditions                                               */
1378 /*  1 - The Condition was found for a pCode's input                */
1379 /*  0 - No matching condition was found for the whole chain        */
1380 /* -1 - The Condition was found for a pCode's output               */
1381 /*                                                                 */
1382 /*-----------------------------------------------------------------*/
1383 int pCodeSearchCondition(pCode *pc, unsigned int cond)
1384 {
1385
1386   while(pc) {
1387
1388     /* If we reach a function end (presumably an end since we most
1389        probably began the search in the middle of a function), then
1390        the condition was not found. */
1391     if(pc->type == PC_FUNCTION)
1392       return 0;
1393
1394     if(pc->type == PC_OPCODE) {
1395       if(PCI(pc)->inCond & cond)
1396         return 1;
1397       if(PCI(pc)->outCond & cond)
1398         return -1;
1399     }
1400
1401     pc = pc->next;
1402   }
1403
1404   return 0;
1405 }
1406
1407 /*-----------------------------------------------------------------
1408  * int pCodeOpCompare(pCodeOp *pcops, pCodeOp *pcopd)
1409  *
1410  * Compare two pCodeOp's and return 1 if they're the same
1411  *-----------------------------------------------------------------*/
1412 int pCodeOpCompare(pCodeOp *pcops, pCodeOp *pcopd)
1413 {
1414
1415   if(!pcops || !pcopd)
1416     return 0;
1417
1418   fprintf(stderr," Comparing operands %s",
1419           get_op( pcops));
1420
1421   fprintf(stderr," to %s\n",
1422           get_op( pcopd));
1423
1424   if(pcops->type != pcopd->type) {
1425     fprintf(stderr,"  - fail - diff types\n");
1426     return 0;  // different types
1427   }
1428
1429   if(!pcops->name ||  !pcopd->name || strcmp(pcops->name,pcopd->name)) {
1430     fprintf(stderr,"  - fail - diff names\n");
1431     return 0;  // different names
1432   }
1433
1434   switch(pcops->type) {
1435   case PO_DIR:
1436     if( PCOR(pcops)->instance != PCOR(pcopd)->instance) {
1437       fprintf(stderr, "  - fail different instances\n");
1438       return 0;
1439     }
1440     break;
1441   default:
1442     break;
1443   }
1444
1445   fprintf(stderr,"  - pass\n");
1446
1447   return 1;
1448 }
1449
1450 int pCodePeepMatchLabels(pCodePeep *peepBlock, pCode *pcs, pCode *pcd)
1451 {
1452   int labindex;
1453
1454   /* Check for a label associated with this wild pCode */
1455   // If the wild card has a label, make sure the source code does too.
1456   if(PCI(pcd)->label) {
1457     pCode *pcl;
1458
1459     if(!PCI(pcs)->label)
1460       return 0;
1461
1462     pcl = PCI(pcd)->label->pc;
1463
1464     labindex = -PCL(pcl)->key;
1465     //DFPRINTF((stderr,"label id = %d (labindex = %d)\n",PCL(pcl)->key,labindex));
1466     if(peepBlock->target.vars[labindex] == NULL) {
1467       // First time to encounter this label
1468       peepBlock->target.vars[labindex] = PCL(PCI(pcs)->label->pc)->label;
1469       //DFPRINTF((stderr,"first time for a label: %d %s\n",labindex, peepBlock->vars[labindex]));
1470     } else {
1471       if(strcmp(peepBlock->target.vars[labindex],PCL(PCI(pcs)->label->pc)->label) != 0) {
1472         // DFPRINTF((stderr,"labels don't match\n"));
1473         return 0;
1474       }
1475       //DFPRINTF((stderr,"matched a label\n"));
1476     }
1477   } else {
1478     // DFPRINTF((stderr,"destination doesn't have a label\n"));
1479
1480     if(PCI(pcs)->label)
1481       return 0;
1482   }
1483
1484   return 1;
1485     
1486 }
1487
1488 /*-----------------------------------------------------------------*/
1489 /* pCodePeepMatchLine - Compare source and destination pCodes to   */
1490 /*                      see they're the same.                      */
1491 /*                                                                 */
1492 /* In this context, "source" refers to the coded generated by gen.c*/
1493 /* and "destination" refers to a pcode in a peep rule. If the dest-*/
1494 /* ination has no wild cards, then MatchLine will compare the two  */
1495 /* pcodes (src and dest) for a one-to-one match. If the destination*/
1496 /* has wildcards, then those get expanded. When a wild card is     */
1497 /* encountered for the first time it autmatically is considered a  */
1498 /* match and the object that matches it is referenced in the       */
1499 /* variables or opcodes array (depending on the type of match).    */
1500 /*                                                                 */
1501 /*                                                                 */
1502 /* Inputs:                                                         */
1503 /*  *peepBlock - A pointer to the peepBlock that contains the      */
1504 /*               entire rule to which the destination pcode belongs*/
1505 /*  *pcs - a pointer to the source pcode                           */
1506 /*  *pcd - a pointer to the destination pcode                      */
1507 /*                                                                 */
1508 /* Returns:                                                        */
1509 /*  1 - pcodes match                                               */
1510 /*  0 - pcodes don't match                                         */
1511 /*                                                                 */
1512 /*                                                                 */
1513 /*-----------------------------------------------------------------*/
1514
1515 int pCodePeepMatchLine(pCodePeep *peepBlock, pCode *pcs, pCode *pcd)
1516 {
1517   int index;   // index into wild card arrays
1518
1519   /* one-for-one match. Here the source and destination opcodes 
1520    * are not wild. However, there may be a label or a wild operand */
1521
1522   if(pcs->type == pcd->type) {
1523
1524     if(pcs->type == PC_OPCODE) {
1525
1526       /* If the opcodes don't match then the line doesn't match */
1527       if(PCI(pcs)->op != PCI(pcd)->op)
1528         return 0;
1529
1530       /*
1531       DFPRINTF((stderr,"%s comparing\n",__FUNCTION__));
1532       pcs->print(stderr,pcs);
1533       pcd->print(stderr,pcd);
1534       */
1535
1536       if(!pCodePeepMatchLabels(peepBlock, pcs, pcd))
1537         return 0;
1538
1539       /* Compare the operands */
1540       if(PCI(pcd)->pcop) {
1541         if (PCI(pcd)->pcop->type == PO_WILD) {
1542           index = PCOW(PCI(pcd)->pcop)->id;
1543
1544           //DFPRINTF((stderr,"destination is wild\n"));
1545 #ifdef DEBUG_PCODEPEEP
1546           if (index > peepBlock->nops) {
1547             DFPRINTF((stderr,"%s - variables exceeded\n",__FUNCTION__));
1548             exit(1);
1549           }
1550 #endif
1551
1552           PCOW(PCI(pcd)->pcop)->matched = PCI(pcs)->pcop;
1553           if(!peepBlock->target.wildpCodeOps[index]) {
1554             peepBlock->target.wildpCodeOps[index] = PCI(pcs)->pcop;
1555
1556             //if(PCI(pcs)->pcop->type == PO_GPR_TEMP) 
1557
1558           } else {
1559             pcs->print(stderr,pcs);
1560             pcd->print(stderr,pcd);
1561
1562             fprintf(stderr, "comparing operands of these instructions, result %d\n",
1563                     pCodeOpCompare(PCI(pcs)->pcop, peepBlock->target.wildpCodeOps[index])
1564                     );
1565
1566             return pCodeOpCompare(PCI(pcs)->pcop, peepBlock->target.wildpCodeOps[index]);
1567           }
1568
1569           {
1570             char *n;
1571
1572             switch(PCI(pcs)->pcop->type) {
1573             case PO_GPR_TEMP:
1574             case PO_FSR:
1575               //case PO_INDF:
1576               n = PCOR(PCI(pcs)->pcop)->r->name;
1577
1578               break;
1579             default:
1580               n = PCI(pcs)->pcop->name;
1581             }
1582
1583             if(peepBlock->target.vars[index])
1584               return  (strcmp(peepBlock->target.vars[index],n) == 0);
1585             else {
1586               // DFPRINTF((stderr,"first time for a variable: %d, %s\n",index,n));
1587               peepBlock->target.vars[index] = n;
1588               return 1;
1589             }
1590           }
1591
1592         }
1593         /* FIXME - need an else to check the case when the destination 
1594          * isn't a wild card */
1595       } else
1596         /* The pcd has no operand. Lines match if pcs has no operand either*/
1597         return (PCI(pcs)->pcop == NULL);
1598     }
1599   }
1600
1601   /* Compare a wild instruction to a regular one. */
1602
1603   if((pcd->type == PC_WILD) && (pcs->type == PC_OPCODE)) {
1604
1605
1606     index = PCW(pcd)->id;
1607
1608     //    DFPRINTF((stderr,"%s comparing wild cards\n",__FUNCTION__));
1609     //pcs->print(stderr,pcs);
1610     //pcd->print(stderr,pcd);
1611
1612     peepBlock->target.wildpCodes[PCW(pcd)->id] = pcs;
1613
1614     if(!pCodePeepMatchLabels(peepBlock, pcs, pcd))
1615       return 0;
1616
1617     if(PCW(pcd)->mustBeBitSkipInst & !(PCI(pcs)->isBitInst && PCI(pcs)->isSkip)) {
1618       // doesn't match because the wild pcode must be a bit skip
1619       //fprintf(stderr," Failing match because bit skip is req:\n");
1620       //pcd->print(stderr,pcd);
1621       //pcs->print(stderr,pcs);
1622       return 0;
1623     } 
1624
1625     if(PCW(pcd)->mustNotBeBitSkipInst & (PCI(pcs)->isBitInst && PCI(pcs)->isSkip)) {
1626       // doesn't match because the wild pcode must *not* be a bit skip
1627       //fprintf(stderr," Failing match because don't want skip :\n");
1628       //pcd->print(stderr,pcd);
1629       //pcs->print(stderr,pcs);
1630       return 0;
1631     } 
1632
1633     if(PCW(pcd)->operand) {
1634       PCOW(PCI(pcd)->pcop)->matched = PCI(pcs)->pcop;
1635       if(peepBlock->target.vars[index]) {
1636         int i = (strcmp(peepBlock->target.vars[index],PCI(pcs)->pcop->name) == 0);
1637         /*
1638         if(i)
1639           DFPRINTF((stderr," (matched)\n"));
1640         else {
1641           DFPRINTF((stderr," (no match: wild card operand mismatch\n"));
1642           DFPRINTF((stderr,"  peepblock= %s,  pcodeop= %s\n"),
1643                   peepBlock->vars[index],
1644                   PCI(pcs)->pcop->name);
1645         }
1646         */
1647         return i;
1648       } else {
1649         peepBlock->target.vars[index] = PCI(pcs)->pcop->name;
1650         return 1;
1651       }
1652     }
1653
1654     pcs = findNextInstruction(pcs->next); 
1655     if(pcs) {
1656       //DFPRINTF((stderr," (next to match)\n"));
1657       //pcs->print(stderr,pcs);
1658     } else if(pcd->next) {
1659       /* oops, we ran out of code, but there's more to the rule */
1660       return 0;
1661     }
1662
1663     return 1; /*  wild card matches */
1664   }
1665
1666   return 0;
1667 }
1668
1669 /*-----------------------------------------------------------------*/
1670 /*-----------------------------------------------------------------*/
1671 void pCodePeepClrVars(pCodePeep *pcp)
1672 {
1673
1674   int i;
1675   if(!pcp)
1676     return;
1677
1678   for(i=0;i<pcp->target.nvars; i++) {
1679     pcp->target.vars[i] = NULL;
1680     pcp->target.wildpCodeOps[i] = NULL;
1681   }
1682 }
1683
1684 /*-----------------------------------------------------------------*/
1685 /*  pCodeInsertAfter - splice in the pCode chain starting with pc2 */
1686 /*                     into the pCode chain containing pc1         */
1687 /*-----------------------------------------------------------------*/
1688 void pCodeInsertAfter(pCode *pc1, pCode *pc2)
1689 {
1690
1691   if(!pc1 || !pc2)
1692     return;
1693
1694   pc2->next = pc1->next;
1695   if(pc1->next)
1696     pc1->next->prev = pc2;
1697
1698   pc2->pb = pc1->pb;
1699   pc2->prev = pc1;
1700   pc1->next = pc2;
1701
1702 }
1703
1704 /*-----------------------------------------------------------------*/
1705 /* pCodeOpCopy - copy a pcode operator                             */
1706 /*-----------------------------------------------------------------*/
1707 pCodeOp *pCodeOpCopy(pCodeOp *pcop)
1708 {
1709   pCodeOp *pcopnew=NULL;
1710
1711   if(!pcop)
1712     return NULL;
1713
1714   switch(pcop->type) { 
1715   case PO_CRY:
1716   case PO_BIT:
1717     //DFPRINTF((stderr,"pCodeOpCopy bit\n"));
1718     pcopnew = Safe_calloc(1,sizeof(pCodeOpRegBit) );
1719     PCORB(pcopnew)->bit = PCORB(pcop)->bit;
1720     PCORB(pcopnew)->inBitSpace = PCORB(pcop)->inBitSpace;
1721
1722     break;
1723
1724   case PO_WILD:
1725     /* Here we expand the wild card into the appropriate type: */
1726     /* By recursively calling pCodeOpCopy */
1727     //DFPRINTF((stderr,"pCodeOpCopy wild\n"));
1728     if(PCOW(pcop)->matched)
1729       pcopnew = pCodeOpCopy(PCOW(pcop)->matched);
1730     else {
1731       // Probably a label
1732       pcopnew = pCodeOpCopy(PCOW(pcop)->subtype);
1733       pcopnew->name = Safe_strdup(PCOW(pcop)->pcwb->vars[PCOW(pcop)->id]);
1734       //DFPRINTF((stderr,"copied a wild op named %s\n",pcopnew->name));
1735     }
1736
1737     return pcopnew;
1738     break;
1739
1740   case PO_LABEL:
1741     //DFPRINTF((stderr,"pCodeOpCopy label\n"));
1742     pcopnew = Safe_calloc(1,sizeof(pCodeOpLabel) );
1743     PCOLAB(pcopnew)->key =  PCOLAB(pcop)->key;
1744     break;
1745
1746   case PO_IMMEDIATE:
1747     pcopnew = Safe_calloc(1,sizeof(pCodeOpImmd) );
1748     PCOI(pcopnew)->index = PCOI(pcop)->index;
1749     PCOI(pcopnew)->offset = PCOI(pcop)->offset;
1750     PCOI(pcopnew)->_const = PCOI(pcop)->_const;
1751     break;
1752
1753   case PO_LITERAL:
1754     //DFPRINTF((stderr,"pCodeOpCopy lit\n"));
1755     pcopnew = Safe_calloc(1,sizeof(pCodeOpLit) );
1756     PCOL(pcopnew)->lit = PCOL(pcop)->lit;
1757     break;
1758
1759   case PO_GPR_BIT:
1760
1761     pcopnew = newpCodeOpBit(pcop->name, PCORB(pcop)->bit,PCORB(pcop)->inBitSpace);
1762     PCOR(pcopnew)->r = PCOR(pcop)->r;
1763     PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
1764     DFPRINTF((stderr," pCodeOpCopy Bit -register index\n"));
1765     return pcopnew;
1766     break;
1767
1768   case PO_GPR_REGISTER:
1769   case PO_GPR_TEMP:
1770   case PO_FSR:
1771   case PO_INDF:
1772     //DFPRINTF((stderr,"pCodeOpCopy GPR register\n"));
1773     pcopnew = Safe_calloc(1,sizeof(pCodeOpReg) );
1774     PCOR(pcopnew)->r = PCOR(pcop)->r;
1775     PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
1776     PCOR(pcopnew)->instance = PCOR(pcop)->instance;
1777     DFPRINTF((stderr," register index %d\n", PCOR(pcop)->r->rIdx));
1778     break;
1779
1780   case PO_DIR:
1781     fprintf(stderr,"pCodeOpCopy PO_DIR\n");
1782     pcopnew = Safe_calloc(1,sizeof(pCodeOpReg) );
1783     PCOR(pcopnew)->r = PCOR(pcop)->r;
1784     PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
1785     PCOR(pcopnew)->instance = PCOR(pcop)->instance;
1786     break;
1787   case PO_STATUS:
1788     DFPRINTF((stderr,"pCodeOpCopy PO_STATUS\n"));
1789   case PO_SFR_REGISTER:
1790   case PO_STR:
1791   case PO_NONE:
1792   case PO_W:
1793   case PO_INTCON:
1794   case PO_PCL:
1795   case PO_PCLATH:
1796
1797     //DFPRINTF((stderr,"pCodeOpCopy register type %d\n", pcop->type));
1798     pcopnew = Safe_calloc(1,sizeof(pCodeOp) );
1799
1800   }
1801
1802   pcopnew->type = pcop->type;
1803   if(pcop->name)
1804     pcopnew->name = Safe_strdup(pcop->name);
1805   else
1806     pcopnew->name = NULL;
1807
1808   return pcopnew;
1809 }
1810
1811
1812 /*-----------------------------------------------------------------*/
1813 /* pCodeCopy - copy a pcode                                        */
1814 /*-----------------------------------------------------------------*/
1815 static pCode *pCodeInstructionCopy(pCodeInstruction *pci,int invert)
1816 {
1817   pCodeInstruction *new_pci;
1818
1819   if(invert)
1820     new_pci = PCI(newpCode(pci->inverted_op,pci->pcop));
1821   else
1822     new_pci = PCI(newpCode(pci->op,pci->pcop));
1823
1824   new_pci->pc.pb = pci->pc.pb;
1825   new_pci->from = pci->from;
1826   new_pci->to   = pci->to;
1827   new_pci->label = pci->label;
1828   new_pci->pcflow = pci->pcflow;
1829
1830   return PCODE(new_pci);
1831 }
1832
1833 /*-----------------------------------------------------------------*/
1834 /*-----------------------------------------------------------------*/
1835 void pCodeDeleteChain(pCode *f,pCode *t)
1836 {
1837   pCode *pc;
1838
1839
1840   while(f && f!=t) {
1841     DFPRINTF((stderr,"delete pCode:\n"));
1842     pc = f->next;
1843     f->print(stderr,f);
1844     //f->delete(f);  this dumps core...
1845
1846     f = pc;
1847
1848   }
1849
1850 }
1851 /*-----------------------------------------------------------------*/
1852 /*-----------------------------------------------------------------*/
1853 int pCodePeepMatchRule(pCode *pc)
1854 {
1855   pCodePeep *peepBlock;
1856   pCode *pct, *pcin;
1857   _DLL *peeprules;
1858   int matched;
1859
1860   peeprules = (_DLL *)peepSnippets;
1861
1862   while(peeprules) {
1863     peepBlock = ((pCodePeepSnippets*)peeprules)->peep;
1864
1865     if(!peepBlock || /*!peepBlock->target ||*/ !peepBlock->target.pb->pcHead) {
1866       fprintf(stderr, "skipping rule because target pb is NULL\n");
1867       goto next_rule;
1868     }
1869
1870     pCodePeepClrVars(peepBlock);
1871
1872     pcin = pc;
1873     if(IS_PCCOMMENT(pcin))
1874       pc = pcin = findNextInstruction(pcin->next);
1875
1876     pct = peepBlock->target.pb->pcHead;
1877     matched = 0;
1878     while(pct && pcin) {
1879
1880       if(! (matched = pCodePeepMatchLine(peepBlock, pcin,pct)))
1881         break;
1882
1883       pcin = findNextInstruction(pcin->next);
1884       pct = pct->next;
1885       //debug:
1886       //DFPRINTF((stderr,"    matched\n"));
1887       if(!pcin)
1888         DFPRINTF((stderr," end of code\n"));
1889       if(!pct)
1890         DFPRINTF((stderr," end of rule\n"));
1891     }
1892
1893     if(matched) {
1894
1895       /* So far we matched the rule up to the point of the conditions .
1896        * In other words, all of the opcodes match. Now we need to see
1897        * if the post conditions are satisfied.
1898        * First we check the 'postFalseCond'. This means that we check
1899        * to see if any of the subsequent pCode's in the pCode chain 
1900        * following the point just past where we have matched depend on
1901        * the `postFalseCond' as input then we abort the match
1902        */
1903       DFPRINTF((stderr,"    matched rule so far, now checking conditions\n"));
1904       if (pcin && peepBlock->postFalseCond && 
1905           (pCodeSearchCondition(pcin,peepBlock->postFalseCond) > 0) )
1906         matched = 0;
1907     }
1908
1909     if(matched) {
1910
1911       pCode *pcprev;
1912       pCode *pcr;
1913
1914
1915       /* We matched a rule! Now we have to go through and remove the
1916          inefficient code with the optimized version */
1917 #ifdef PCODE_DEBUG
1918       DFPRINTF((stderr, "Found a pcode peep match:\nRule:\n"));
1919       printpCodeString(stderr,peepBlock->target.pb->pcHead,10);
1920       DFPRINTF((stderr,"first thing matched\n"));
1921       pc->print(stderr,pc);
1922 #endif
1923       if(pcin) {
1924         DFPRINTF((stderr,"last thing matched\n"));
1925         pcin->print(stderr,pcin);
1926       }
1927
1928       /* Unlink the original code */
1929       pcprev = pc->prev;
1930       pcprev->next = pcin;
1931       if(pcin) 
1932         pcin->prev = pc->prev;
1933
1934       {
1935         /*     DEBUG    */
1936         /* Converted the deleted pCodes into comments */
1937
1938         char buf[256];
1939
1940         buf[0] = ';';
1941         buf[1] = '#';
1942
1943         while(pc &&  pc!=pcin) {
1944           pCode2str(&buf[2], 254, pc);
1945           pCodeInsertAfter(pcprev, newpCodeCharP(buf));
1946           pcprev = pcprev->next;
1947           pc = pc->next;
1948         }
1949       }
1950
1951       if(pcin)
1952         pCodeDeleteChain(pc,pcin);
1953
1954       /* Generate the replacement code */
1955       pc = pcprev;
1956       pcr = peepBlock->replace.pb->pcHead;  // This is the replacement code
1957       while (pcr) {
1958         pCodeOp *pcop=NULL;
1959         /* If the replace pcode is an instruction with an operand, */
1960         /* then duplicate the operand (and expand wild cards in the process). */
1961         if(pcr->type == PC_OPCODE) {
1962           if(PCI(pcr)->pcop) {
1963             /* The replacing instruction has an operand.
1964              * Is it wild? */
1965             if(PCI(pcr)->pcop->type == PO_WILD) {
1966               int index = PCOW(PCI(pcr)->pcop)->id;
1967               //DFPRINTF((stderr,"copying wildopcode\n"));
1968               if(peepBlock->target.wildpCodeOps[index])
1969                 pcop = pCodeOpCopy(peepBlock->target.wildpCodeOps[index]);
1970               else
1971                 DFPRINTF((stderr,"error, wildopcode in replace but not source?\n"));
1972             } else
1973               pcop = pCodeOpCopy(PCI(pcr)->pcop);
1974           }
1975           //DFPRINTF((stderr,"inserting pCode\n"));
1976           pCodeInsertAfter(pc, newpCode(PCI(pcr)->op,pcop));
1977         } else if (pcr->type == PC_WILD) {
1978           if(PCW(pcr)->invertBitSkipInst)
1979             DFPRINTF((stderr,"We need to invert the bit skip instruction\n"));
1980           pCodeInsertAfter(pc,
1981                            pCodeInstructionCopy(PCI(peepBlock->target.wildpCodes[PCW(pcr)->id]),
1982                                                 PCW(pcr)->invertBitSkipInst));
1983         } else if (pcr->type == PC_COMMENT) {
1984           pCodeInsertAfter(pc, newpCodeCharP( ((pCodeComment *)(pcr))->comment));
1985         }
1986
1987
1988         pc = pc->next;
1989         //if(pc)
1990         //  pc->print(stderr,pc);
1991         pcr = pcr->next;
1992       }
1993
1994       return 1;
1995     }
1996   next_rule:
1997     peeprules = peeprules->next;
1998   }
1999
2000   return 0;
2001 }