* src/SDCCmain.c (linkEdit): initialized linkerScriptFileName,
[fw/sdcc] / src / pic / pcode.c
1 /*-------------------------------------------------------------------------
2
3         pcode.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
23 #include "common.h"   // Include everything in the SDCC src directory
24 #include "newalloc.h"
25
26
27 #include "pcode.h"
28 #include "pcodeflow.h"
29 #include "ralloc.h"
30 #include "device.h"
31
32 pCode *findFunction(char *fname);
33
34 static void FixRegisterBanking(pBlock *pb,int cur_bank);
35
36 #if defined(__BORLANDC__) || defined(_MSC_VER)
37 #define STRCASECMP stricmp
38 #else
39 #define STRCASECMP strcasecmp
40 #endif
41
42 /****************************************************************/
43 /****************************************************************/
44
45 peepCommand peepCommands[] = {
46         
47         {NOTBITSKIP, "_NOTBITSKIP_"},
48         {BITSKIP, "_BITSKIP_"},
49         {INVERTBITSKIP, "_INVERTBITSKIP_"},
50         
51         {-1, NULL}
52 };
53
54
55
56 // Eventually this will go into device dependent files:
57 pCodeOpReg pc_status    = {{PO_STATUS,  "STATUS"}, -1, NULL,0,NULL};
58 pCodeOpReg pc_indf      = {{PO_INDF,    "INDF"}, -1, NULL,0,NULL};
59 pCodeOpReg pc_fsr       = {{PO_FSR,     "FSR"}, -1, NULL,0,NULL};
60 pCodeOpReg pc_intcon    = {{PO_INTCON,  "INTCON"}, -1, NULL,0,NULL};
61 pCodeOpReg pc_pcl       = {{PO_PCL,     "PCL"}, -1, NULL,0,NULL};
62 pCodeOpReg pc_pclath    = {{PO_PCLATH,  "PCLATH"}, -1, NULL,0,NULL};
63
64 pCodeOpReg pc_wsave     = {{PO_GPR_REGISTER,  "WSAVE"}, -1, NULL,0,NULL};
65 pCodeOpReg pc_ssave     = {{PO_GPR_REGISTER,  "SSAVE"}, -1, NULL,0,NULL};
66 pCodeOpReg pc_psave     = {{PO_GPR_REGISTER,  "PSAVE"}, -1, NULL,0,NULL};
67
68 static int mnemonics_initialized = 0;
69
70 static hTab *pic14MnemonicsHash = NULL;
71 static hTab *pic14pCodePeepCommandsHash = NULL;
72
73
74 static pFile *the_pFile = NULL;
75 static pBlock *pb_dead_pcodes = NULL;
76
77 /* Hardcoded flags to change the behavior of the PIC port */
78 static int peepOptimizing = 1;        /* run the peephole optimizer if nonzero */
79 static int functionInlining = 1;      /* inline functions if nonzero */
80 int debug_verbose = 0;                /* Set true to inundate .asm file */
81
82 // static int GpCodeSequenceNumber = 1;
83 int GpcFlowSeq = 1;
84
85 /* statistics (code size estimation) */
86 static unsigned int pcode_insns = 0;
87 static unsigned int pcode_doubles = 0;
88
89
90 unsigned maxIdx; /* This keeps track of the maximum register index for call tree register reuse */
91 unsigned peakIdx; /* This keeps track of the peak register index for call tree register reuse */
92
93 extern void RemoveUnusedRegisters(void);
94 extern void RegsUnMapLiveRanges(void);
95 extern void BuildFlowTree(pBlock *pb);
96 extern void pCodeRegOptimizeRegUsage(int level);
97 extern int picIsInitialized(void);
98 extern const char *pCodeOpType(pCodeOp *pcop);
99
100 /****************************************************************/
101 /*                      Forward declarations                    */
102 /****************************************************************/
103
104 void unlinkpCode(pCode *pc);
105 #if 0
106 static void genericAnalyze(pCode *pc);
107 static void AnalyzeGOTO(pCode *pc);
108 static void AnalyzeSKIP(pCode *pc);
109 static void AnalyzeRETURN(pCode *pc);
110 #endif
111
112 static void genericDestruct(pCode *pc);
113 static void genericPrint(FILE *of,pCode *pc);
114
115 static void pCodePrintLabel(FILE *of, pCode *pc);
116 static void pCodePrintFunction(FILE *of, pCode *pc);
117 static void pCodeOpPrint(FILE *of, pCodeOp *pcop);
118 static char *get_op_from_instruction( pCodeInstruction *pcc);
119 char *get_op( pCodeOp *pcop,char *buff,size_t buf_size);
120 int pCodePeepMatchLine(pCodePeep *peepBlock, pCode *pcs, pCode *pcd);
121 int pCodePeepMatchRule(pCode *pc);
122 void pBlockStats(FILE *of, pBlock *pb);
123 pBlock *newpBlock(void);
124 pCodeOp *popCopyGPR2Bit(pCodeOp *pc, int bitval);
125 void pCodeRegMapLiveRanges(pBlock *pb);
126
127 pBranch * pBranchAppend(pBranch *h, pBranch *n);
128
129
130 /****************************************************************/
131 /*                    PIC Instructions                          */
132 /****************************************************************/
133
134 pCodeInstruction pciADDWF = {
135         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
136                 //   genericAnalyze,
137                 genericDestruct,
138                 genericPrint},
139                 POC_ADDWF,
140                 "ADDWF",
141                 NULL, // from branch
142                 NULL, // to branch
143                 NULL, // label
144                 NULL, // operand
145                 NULL, // flow block
146                 NULL, // C source 
147                 2,    // num ops
148                 1,0,  // dest, bit instruction
149                 0,0,  // branch, skip
150                 0,    // literal operand
151                 POC_NOP,
152                 (PCC_W | PCC_REGISTER),   // inCond
153                 (PCC_REGISTER | PCC_Z) // outCond
154 };
155
156 pCodeInstruction pciADDFW = {
157         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
158                 //   genericAnalyze,
159                 genericDestruct,
160                 genericPrint},
161                 POC_ADDFW,
162                 "ADDWF",
163                 NULL, // from branch
164                 NULL, // to branch
165                 NULL, // label
166                 NULL, // operand
167                 NULL, // flow block
168                 NULL, // C source 
169                 2,    // num ops
170                 0,0,  // dest, bit instruction
171                 0,0,  // branch, skip
172                 0,    // literal operand
173                 POC_NOP,
174                 (PCC_W | PCC_REGISTER),   // inCond
175                 (PCC_W | PCC_Z) // outCond
176 };
177
178 pCodeInstruction pciADDLW = {
179         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
180                 //   genericAnalyze,
181                 genericDestruct,
182                 genericPrint},
183                 POC_ADDLW,
184                 "ADDLW",
185                 NULL, // from branch
186                 NULL, // to branch
187                 NULL, // label
188                 NULL, // operand
189                 NULL, // flow block
190                 NULL, // C source 
191                 1,    // num ops
192                 0,0,  // dest, bit instruction
193                 0,0,  // branch, skip
194                 1,    // literal operand
195                 POC_NOP,
196                 (PCC_W | PCC_LITERAL),   // inCond
197                 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
198 };
199
200 pCodeInstruction pciANDLW = {
201         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
202                 //   genericAnalyze,
203                 genericDestruct,
204                 genericPrint},
205                 POC_ANDLW,
206                 "ANDLW",
207                 NULL, // from branch
208                 NULL, // to branch
209                 NULL, // label
210                 NULL, // operand
211                 NULL, // flow block
212                 NULL, // C source 
213                 1,    // num ops
214                 0,0,  // dest, bit instruction
215                 0,0,  // branch, skip
216                 1,    // literal operand
217                 POC_NOP,
218                 (PCC_W | PCC_LITERAL),   // inCond
219                 (PCC_W | PCC_Z) // outCond
220 };
221
222 pCodeInstruction pciANDWF = {
223         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
224                 //   genericAnalyze,
225                 genericDestruct,
226                 genericPrint},
227                 POC_ANDWF,
228                 "ANDWF",
229                 NULL, // from branch
230                 NULL, // to branch
231                 NULL, // label
232                 NULL, // operand
233                 NULL, // flow block
234                 NULL, // C source 
235                 2,    // num ops
236                 1,0,  // dest, bit instruction
237                 0,0,  // branch, skip
238                 0,    // literal operand
239                 POC_NOP,
240                 (PCC_W | PCC_REGISTER),   // inCond
241                 (PCC_REGISTER | PCC_Z) // outCond
242 };
243
244 pCodeInstruction pciANDFW = {
245         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
246                 //   genericAnalyze,
247                 genericDestruct,
248                 genericPrint},
249                 POC_ANDFW,
250                 "ANDWF",
251                 NULL, // from branch
252                 NULL, // to branch
253                 NULL, // label
254                 NULL, // operand
255                 NULL, // flow block
256                 NULL, // C source 
257                 2,    // num ops
258                 0,0,  // dest, bit instruction
259                 0,0,  // branch, skip
260                 0,    // literal operand
261                 POC_NOP,
262                 (PCC_W | PCC_REGISTER),   // inCond
263                 (PCC_W | PCC_Z) // outCond
264 };
265
266 pCodeInstruction pciBCF = {
267         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
268                 //   genericAnalyze,
269                 genericDestruct,
270                 genericPrint},
271                 POC_BCF,
272                 "BCF",
273                 NULL, // from branch
274                 NULL, // to branch
275                 NULL, // label
276                 NULL, // operand
277                 NULL, // flow block
278                 NULL, // C source 
279                 2,    // num ops
280                 1,1,  // dest, bit instruction
281                 0,0,  // branch, skip
282                 0,    // literal operand
283                 POC_BSF,
284                 (PCC_REGISTER | PCC_EXAMINE_PCOP),   // inCond
285                 PCC_REGISTER // outCond
286 };
287
288 pCodeInstruction pciBSF = {
289         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
290                 //   genericAnalyze,
291                 genericDestruct,
292                 genericPrint},
293                 POC_BSF,
294                 "BSF",
295                 NULL, // from branch
296                 NULL, // to branch
297                 NULL, // label
298                 NULL, // operand
299                 NULL, // flow block
300                 NULL, // C source 
301                 2,    // num ops
302                 1,1,  // dest, bit instruction
303                 0,0,  // branch, skip
304                 0,    // literal operand
305                 POC_BCF,
306                 (PCC_REGISTER | PCC_EXAMINE_PCOP),   // inCond
307                 (PCC_REGISTER | PCC_EXAMINE_PCOP) // outCond
308 };
309
310 pCodeInstruction pciBTFSC = {
311         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
312                 //   AnalyzeSKIP,
313                 genericDestruct,
314                 genericPrint},
315                 POC_BTFSC,
316                 "BTFSC",
317                 NULL, // from branch
318                 NULL, // to branch
319                 NULL, // label
320                 NULL, // operand
321                 NULL, // flow block
322                 NULL, // C source 
323                 2,    // num ops
324                 0,1,  // dest, bit instruction
325                 1,1,  // branch, skip
326                 0,    // literal operand
327                 POC_BTFSS,
328                 (PCC_REGISTER | PCC_EXAMINE_PCOP),   // inCond
329                 PCC_EXAMINE_PCOP // outCond
330 };
331
332 pCodeInstruction pciBTFSS = {
333         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
334                 //   AnalyzeSKIP,
335                 genericDestruct,
336                 genericPrint},
337                 POC_BTFSS,
338                 "BTFSS",
339                 NULL, // from branch
340                 NULL, // to branch
341                 NULL, // label
342                 NULL, // operand
343                 NULL, // flow block
344                 NULL, // C source 
345                 2,    // num ops
346                 0,1,  // dest, bit instruction
347                 1,1,  // branch, skip
348                 0,    // literal operand
349                 POC_BTFSC,
350                 (PCC_REGISTER | PCC_EXAMINE_PCOP),   // inCond
351                 PCC_EXAMINE_PCOP // outCond
352 };
353
354 pCodeInstruction pciCALL = {
355         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
356                 //   genericAnalyze,
357                 genericDestruct,
358                 genericPrint},
359                 POC_CALL,
360                 "CALL",
361                 NULL, // from branch
362                 NULL, // to branch
363                 NULL, // label
364                 NULL, // operand
365                 NULL, // flow block
366                 NULL, // C source 
367                 1,    // num ops
368                 0,0,  // dest, bit instruction
369                 1,0,  // branch, skip
370                 0,    // literal operand
371                 POC_NOP,
372                 PCC_NONE, // inCond
373                 PCC_NONE  // outCond
374 };
375
376 pCodeInstruction pciCOMF = {
377         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
378                 //   genericAnalyze,
379                 genericDestruct,
380                 genericPrint},
381                 POC_COMF,
382                 "COMF",
383                 NULL, // from branch
384                 NULL, // to branch
385                 NULL, // label
386                 NULL, // operand
387                 NULL, // flow block
388                 NULL, // C source 
389                 2,    // num ops
390                 1,0,  // dest, bit instruction
391                 0,0,  // branch, skip
392                 0,    // literal operand
393                 POC_NOP,
394                 PCC_REGISTER,  // inCond
395                 PCC_REGISTER   // outCond
396 };
397
398 pCodeInstruction pciCOMFW = {
399         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
400                 //   genericAnalyze,
401                 genericDestruct,
402                 genericPrint},
403                 POC_COMFW,
404                 "COMF",
405                 NULL, // from branch
406                 NULL, // to branch
407                 NULL, // label
408                 NULL, // operand
409                 NULL, // flow block
410                 NULL, // C source 
411                 2,    // num ops
412                 0,0,  // dest, bit instruction
413                 0,0,  // branch, skip
414                 0,    // literal operand
415                 POC_NOP,
416                 PCC_REGISTER,  // inCond
417                 PCC_W   // outCond
418 };
419
420 pCodeInstruction pciCLRF = {
421         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
422                 //   genericAnalyze,
423                 genericDestruct,
424                 genericPrint},
425                 POC_CLRF,
426                 "CLRF",
427                 NULL, // from branch
428                 NULL, // to branch
429                 NULL, // label
430                 NULL, // operand
431                 NULL, // flow block
432                 NULL, // C source 
433                 1,    // num ops
434                 0,0,  // dest, bit instruction
435                 0,0,  // branch, skip
436                 0,    // literal operand
437                 POC_NOP,
438                 PCC_NONE, // inCond
439                 PCC_REGISTER  // outCond
440 };
441
442 pCodeInstruction pciCLRW = {
443         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
444                 //   genericAnalyze,
445                 genericDestruct,
446                 genericPrint},
447                 POC_CLRW,
448                 "CLRW",
449                 NULL, // from branch
450                 NULL, // to branch
451                 NULL, // label
452                 NULL, // operand
453                 NULL, // flow block
454                 NULL, // C source 
455                 0,    // num ops
456                 0,0,  // dest, bit instruction
457                 0,0,  // branch, skip
458                 0,    // literal operand
459                 POC_NOP,
460                 PCC_NONE, // inCond
461                 PCC_W  // outCond
462 };
463
464 pCodeInstruction pciCLRWDT = {
465         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
466                 //   genericAnalyze,
467                 genericDestruct,
468                 genericPrint},
469                 POC_CLRWDT,
470                 "CLRWDT",
471                 NULL, // from branch
472                 NULL, // to branch
473                 NULL, // label
474                 NULL, // operand
475                 NULL, // flow block
476                 NULL, // C source 
477                 0,    // num ops
478                 0,0,  // dest, bit instruction
479                 0,0,  // branch, skip
480                 0,    // literal operand
481                 POC_NOP,
482                 PCC_NONE, // inCond
483                 PCC_NONE  // outCond
484 };
485
486 pCodeInstruction pciDECF = {
487         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
488                 //   genericAnalyze,
489                 genericDestruct,
490                 genericPrint},
491                 POC_DECF,
492                 "DECF",
493                 NULL, // from branch
494                 NULL, // to branch
495                 NULL, // label
496                 NULL, // operand
497                 NULL, // flow block
498                 NULL, // C source 
499                 2,    // num ops
500                 1,0,  // dest, bit instruction
501                 0,0,  // branch, skip
502                 0,    // literal operand
503                 POC_NOP,
504                 PCC_REGISTER,   // inCond
505                 PCC_REGISTER    // outCond
506 };
507
508 pCodeInstruction pciDECFW = {
509         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
510                 //   genericAnalyze,
511                 genericDestruct,
512                 genericPrint},
513                 POC_DECFW,
514                 "DECF",
515                 NULL, // from branch
516                 NULL, // to branch
517                 NULL, // label
518                 NULL, // operand
519                 NULL, // flow block
520                 NULL, // C source 
521                 2,    // num ops
522                 0,0,  // dest, bit instruction
523                 0,0,  // branch, skip
524                 0,    // literal operand
525                 POC_NOP,
526                 PCC_REGISTER,   // inCond
527                 PCC_W    // outCond
528 };
529
530 pCodeInstruction pciDECFSZ = {
531         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
532                 //   AnalyzeSKIP,
533                 genericDestruct,
534                 genericPrint},
535                 POC_DECFSZ,
536                 "DECFSZ",
537                 NULL, // from branch
538                 NULL, // to branch
539                 NULL, // label
540                 NULL, // operand
541                 NULL, // flow block
542                 NULL, // C source 
543                 2,    // num ops
544                 1,0,  // dest, bit instruction
545                 1,1,  // branch, skip
546                 0,    // literal operand
547                 POC_NOP,
548                 PCC_REGISTER,   // inCond
549                 PCC_REGISTER    // outCond
550 };
551
552 pCodeInstruction pciDECFSZW = {
553         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
554                 //   AnalyzeSKIP,
555                 genericDestruct,
556                 genericPrint},
557                 POC_DECFSZW,
558                 "DECFSZ",
559                 NULL, // from branch
560                 NULL, // to branch
561                 NULL, // label
562                 NULL, // operand
563                 NULL, // flow block
564                 NULL, // C source 
565                 2,    // num ops
566                 0,0,  // dest, bit instruction
567                 1,1,  // branch, skip
568                 0,    // literal operand
569                 POC_NOP,
570                 PCC_REGISTER,   // inCond
571                 PCC_W           // outCond
572 };
573
574 pCodeInstruction pciGOTO = {
575         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
576                 //   AnalyzeGOTO,
577                 genericDestruct,
578                 genericPrint},
579                 POC_GOTO,
580                 "GOTO",
581                 NULL, // from branch
582                 NULL, // to branch
583                 NULL, // label
584                 NULL, // operand
585                 NULL, // flow block
586                 NULL, // C source 
587                 1,    // num ops
588                 0,0,  // dest, bit instruction
589                 1,0,  // branch, skip
590                 0,    // literal operand
591                 POC_NOP,
592                 PCC_NONE,   // inCond
593                 PCC_NONE    // outCond
594 };
595
596 pCodeInstruction pciINCF = {
597         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
598                 //   genericAnalyze,
599                 genericDestruct,
600                 genericPrint},
601                 POC_INCF,
602                 "INCF",
603                 NULL, // from branch
604                 NULL, // to branch
605                 NULL, // label
606                 NULL, // operand
607                 NULL, // flow block
608                 NULL, // C source 
609                 2,    // num ops
610                 1,0,  // dest, bit instruction
611                 0,0,  // branch, skip
612                 0,    // literal operand
613                 POC_NOP,
614                 PCC_REGISTER,   // inCond
615                 PCC_REGISTER    // outCond
616 };
617
618 pCodeInstruction pciINCFW = {
619         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
620                 //   genericAnalyze,
621                 genericDestruct,
622                 genericPrint},
623                 POC_INCFW,
624                 "INCF",
625                 NULL, // from branch
626                 NULL, // to branch
627                 NULL, // label
628                 NULL, // operand
629                 NULL, // flow block
630                 NULL, // C source 
631                 2,    // num ops
632                 0,0,  // dest, bit instruction
633                 0,0,  // branch, skip
634                 0,    // literal operand
635                 POC_NOP,
636                 PCC_REGISTER,   // inCond
637                 PCC_W    // outCond
638 };
639
640 pCodeInstruction pciINCFSZ = {
641         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
642                 //   AnalyzeSKIP,
643                 genericDestruct,
644                 genericPrint},
645                 POC_INCFSZ,
646                 "INCFSZ",
647                 NULL, // from branch
648                 NULL, // to branch
649                 NULL, // label
650                 NULL, // operand
651                 NULL, // flow block
652                 NULL, // C source 
653                 2,    // num ops
654                 1,0,  // dest, bit instruction
655                 1,1,  // branch, skip
656                 0,    // literal operand
657                 POC_NOP,
658                 PCC_REGISTER,   // inCond
659                 PCC_REGISTER    // outCond
660 };
661
662 pCodeInstruction pciINCFSZW = {
663         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
664                 //   AnalyzeSKIP,
665                 genericDestruct,
666                 genericPrint},
667                 POC_INCFSZW,
668                 "INCFSZ",
669                 NULL, // from branch
670                 NULL, // to branch
671                 NULL, // label
672                 NULL, // operand
673                 NULL, // flow block
674                 NULL, // C source 
675                 2,    // num ops
676                 0,0,  // dest, bit instruction
677                 1,1,  // branch, skip
678                 0,    // literal operand
679                 POC_NOP,
680                 PCC_REGISTER,   // inCond
681                 PCC_W           // outCond
682 };
683
684 pCodeInstruction pciIORWF = {
685         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
686                 //   genericAnalyze,
687                 genericDestruct,
688                 genericPrint},
689                 POC_IORWF,
690                 "IORWF",
691                 NULL, // from branch
692                 NULL, // to branch
693                 NULL, // label
694                 NULL, // operand
695                 NULL, // flow block
696                 NULL, // C source 
697                 2,    // num ops
698                 1,0,  // dest, bit instruction
699                 0,0,  // branch, skip
700                 0,    // literal operand
701                 POC_NOP,
702                 (PCC_W | PCC_REGISTER),   // inCond
703                 (PCC_REGISTER | PCC_Z) // outCond
704 };
705
706 pCodeInstruction pciIORFW = {
707         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
708                 //   genericAnalyze,
709                 genericDestruct,
710                 genericPrint},
711                 POC_IORFW,
712                 "IORWF",
713                 NULL, // from branch
714                 NULL, // to branch
715                 NULL, // label
716                 NULL, // operand
717                 NULL, // flow block
718                 NULL, // C source 
719                 2,    // num ops
720                 0,0,  // dest, bit instruction
721                 0,0,  // branch, skip
722                 0,    // literal operand
723                 POC_NOP,
724                 (PCC_W | PCC_REGISTER),   // inCond
725                 (PCC_W | PCC_Z) // outCond
726 };
727
728 pCodeInstruction pciIORLW = {
729         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
730                 //   genericAnalyze,
731                 genericDestruct,
732                 genericPrint},
733                 POC_IORLW,
734                 "IORLW",
735                 NULL, // from branch
736                 NULL, // to branch
737                 NULL, // label
738                 NULL, // operand
739                 NULL, // flow block
740                 NULL, // C source 
741                 1,    // num ops
742                 0,0,  // dest, bit instruction
743                 0,0,  // branch, skip
744                 1,    // literal operand
745                 POC_NOP,
746                 (PCC_W | PCC_LITERAL),   // inCond
747                 (PCC_W | PCC_Z) // outCond
748 };
749
750 pCodeInstruction pciMOVF = {
751         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
752                 //   genericAnalyze,
753                 genericDestruct,
754                 genericPrint},
755                 POC_MOVF,
756                 "MOVF",
757                 NULL, // from branch
758                 NULL, // to branch
759                 NULL, // label
760                 NULL, // operand
761                 NULL, // flow block
762                 NULL, // C source 
763                 2,    // num ops
764                 1,0,  // dest, bit instruction
765                 0,0,  // branch, skip
766                 0,    // literal operand
767                 POC_NOP,
768                 PCC_REGISTER,   // inCond
769                 PCC_Z // outCond
770 };
771
772 pCodeInstruction pciMOVFW = {
773         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
774                 //   genericAnalyze,
775                 genericDestruct,
776                 genericPrint},
777                 POC_MOVFW,
778                 "MOVF",
779                 NULL, // from branch
780                 NULL, // to branch
781                 NULL, // label
782                 NULL, // operand
783                 NULL, // flow block
784                 NULL, // C source 
785                 2,    // num ops
786                 0,0,  // dest, bit instruction
787                 0,0,  // branch, skip
788                 0,    // literal operand
789                 POC_NOP,
790                 PCC_REGISTER,   // inCond
791                 (PCC_W | PCC_Z) // outCond
792 };
793
794 pCodeInstruction pciMOVWF = {
795         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
796                 //   genericAnalyze,
797                 genericDestruct,
798                 genericPrint},
799                 POC_MOVWF,
800                 "MOVWF",
801                 NULL, // from branch
802                 NULL, // to branch
803                 NULL, // label
804                 NULL, // operand
805                 NULL, // flow block
806                 NULL, // C source 
807                 1,    // num ops
808                 0,0,  // dest, bit instruction
809                 0,0,  // branch, skip
810                 0,    // literal operand
811                 POC_NOP,
812                 PCC_W,   // inCond
813                 PCC_REGISTER // outCond
814 };
815
816 pCodeInstruction pciMOVLW = {
817         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
818                 genericDestruct,
819                 genericPrint},
820                 POC_MOVLW,
821                 "MOVLW",
822                 NULL, // from branch
823                 NULL, // to branch
824                 NULL, // label
825                 NULL, // operand
826                 NULL, // flow block
827                 NULL, // C source 
828                 1,    // num ops
829                 0,0,  // dest, bit instruction
830                 0,0,  // branch, skip
831                 1,    // literal operand
832                 POC_NOP,
833                 (PCC_NONE | PCC_LITERAL),   // inCond
834                 PCC_W // outCond
835 };
836
837 pCodeInstruction pciNOP = {
838         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
839                 genericDestruct,
840                 genericPrint},
841                 POC_NOP,
842                 "NOP",
843                 NULL, // from branch
844                 NULL, // to branch
845                 NULL, // label
846                 NULL, // operand
847                 NULL, // flow block
848                 NULL, // C source 
849                 0,    // num ops
850                 0,0,  // dest, bit instruction
851                 0,0,  // branch, skip
852                 0,    // literal operand
853                 POC_NOP,
854                 PCC_NONE,   // inCond
855                 PCC_NONE // outCond
856 };
857
858 pCodeInstruction pciRETFIE = {
859         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
860                 //   AnalyzeRETURN,
861                 genericDestruct,
862                 genericPrint},
863                 POC_RETFIE,
864                 "RETFIE",
865                 NULL, // from branch
866                 NULL, // to branch
867                 NULL, // label
868                 NULL, // operand
869                 NULL, // flow block
870                 NULL, // C source 
871                 0,    // num ops
872                 0,0,  // dest, bit instruction
873                 1,0,  // branch, skip
874                 0,    // literal operand
875                 POC_NOP,
876                 PCC_NONE,   // inCond
877                 PCC_NONE // outCond (not true... affects the GIE bit too)
878 };
879
880 pCodeInstruction pciRETLW = {
881         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
882                 //   AnalyzeRETURN,
883                 genericDestruct,
884                 genericPrint},
885                 POC_RETLW,
886                 "RETLW",
887                 NULL, // from branch
888                 NULL, // to branch
889                 NULL, // label
890                 NULL, // operand
891                 NULL, // flow block
892                 NULL, // C source 
893                 1,    // num ops
894                 0,0,  // dest, bit instruction
895                 1,0,  // branch, skip
896                 1,    // literal operand
897                 POC_NOP,
898                 PCC_LITERAL,   // inCond
899                 PCC_W // outCond
900 };
901
902 pCodeInstruction pciRETURN = {
903         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
904                 //   AnalyzeRETURN,
905                 genericDestruct,
906                 genericPrint},
907                 POC_RETURN,
908                 "RETURN",
909                 NULL, // from branch
910                 NULL, // to branch
911                 NULL, // label
912                 NULL, // operand
913                 NULL, // flow block
914                 NULL, // C source 
915                 0,    // num ops
916                 0,0,  // dest, bit instruction
917                 1,0,  // branch, skip
918                 0,    // literal operand
919                 POC_NOP,
920                 PCC_NONE,   // inCond
921                 PCC_NONE // outCond
922 };
923
924 pCodeInstruction pciRLF = {
925         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
926                 //   genericAnalyze,
927                 genericDestruct,
928                 genericPrint},
929                 POC_RLF,
930                 "RLF",
931                 NULL, // from branch
932                 NULL, // to branch
933                 NULL, // label
934                 NULL, // operand
935                 NULL, // flow block
936                 NULL, // C source 
937                 2,    // num ops
938                 1,0,  // dest, bit instruction
939                 0,0,  // branch, skip
940                 0,    // literal operand
941                 POC_NOP,
942                 (PCC_C | PCC_REGISTER),   // inCond
943                 (PCC_REGISTER | PCC_Z | PCC_C | PCC_DC) // outCond
944 };
945
946 pCodeInstruction pciRLFW = {
947         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
948                 //   genericAnalyze,
949                 genericDestruct,
950                 genericPrint},
951                 POC_RLFW,
952                 "RLF",
953                 NULL, // from branch
954                 NULL, // to branch
955                 NULL, // label
956                 NULL, // operand
957                 NULL, // flow block
958                 NULL, // C source 
959                 2,    // num ops
960                 0,0,  // dest, bit instruction
961                 0,0,  // branch, skip
962                 0,    // literal operand
963                 POC_NOP,
964                 (PCC_C | PCC_REGISTER),   // inCond
965                 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
966 };
967
968 pCodeInstruction pciRRF = {
969         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
970                 //   genericAnalyze,
971                 genericDestruct,
972                 genericPrint},
973                 POC_RRF,
974                 "RRF",
975                 NULL, // from branch
976                 NULL, // to branch
977                 NULL, // label
978                 NULL, // operand
979                 NULL, // flow block
980                 NULL, // C source 
981                 2,    // num ops
982                 1,0,  // dest, bit instruction
983                 0,0,  // branch, skip
984                 0,    // literal operand
985                 POC_NOP,
986                 (PCC_C | PCC_REGISTER),   // inCond
987                 (PCC_REGISTER | PCC_Z | PCC_C | PCC_DC) // outCond
988 };
989
990 pCodeInstruction pciRRFW = {
991         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
992                 //   genericAnalyze,
993                 genericDestruct,
994                 genericPrint},
995                 POC_RRFW,
996                 "RRF",
997                 NULL, // from branch
998                 NULL, // to branch
999                 NULL, // label
1000                 NULL, // operand
1001                 NULL, // flow block
1002                 NULL, // C source 
1003                 2,    // num ops
1004                 0,0,  // dest, bit instruction
1005                 0,0,  // branch, skip
1006                 0,    // literal operand
1007                 POC_NOP,
1008                 (PCC_C | PCC_REGISTER),   // inCond
1009                 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
1010 };
1011
1012 pCodeInstruction pciSUBWF = {
1013         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1014                 //   genericAnalyze,
1015                 genericDestruct,
1016                 genericPrint},
1017                 POC_SUBWF,
1018                 "SUBWF",
1019                 NULL, // from branch
1020                 NULL, // to branch
1021                 NULL, // label
1022                 NULL, // operand
1023                 NULL, // flow block
1024                 NULL, // C source 
1025                 2,    // num ops
1026                 1,0,  // dest, bit instruction
1027                 0,0,  // branch, skip
1028                 0,    // literal operand
1029                 POC_NOP,
1030                 (PCC_W | PCC_REGISTER),   // inCond
1031                 (PCC_REGISTER | PCC_Z) // outCond
1032 };
1033
1034 pCodeInstruction pciSUBFW = {
1035         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1036                 //   genericAnalyze,
1037                 genericDestruct,
1038                 genericPrint},
1039                 POC_SUBFW,
1040                 "SUBWF",
1041                 NULL, // from branch
1042                 NULL, // to branch
1043                 NULL, // label
1044                 NULL, // operand
1045                 NULL, // flow block
1046                 NULL, // C source 
1047                 2,    // num ops
1048                 0,0,  // dest, bit instruction
1049                 0,0,  // branch, skip
1050                 0,    // literal operand
1051                 POC_NOP,
1052                 (PCC_W | PCC_REGISTER),   // inCond
1053                 (PCC_W | PCC_Z) // outCond
1054 };
1055
1056 pCodeInstruction pciSUBLW = {
1057         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1058                 //   genericAnalyze,
1059                 genericDestruct,
1060                 genericPrint},
1061                 POC_SUBLW,
1062                 "SUBLW",
1063                 NULL, // from branch
1064                 NULL, // to branch
1065                 NULL, // label
1066                 NULL, // operand
1067                 NULL, // flow block
1068                 NULL, // C source 
1069                 1,    // num ops
1070                 0,0,  // dest, bit instruction
1071                 0,0,  // branch, skip
1072                 1,    // literal operand
1073                 POC_NOP,
1074                 (PCC_W | PCC_LITERAL),   // inCond
1075                 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
1076 };
1077
1078 pCodeInstruction pciSWAPF = {
1079         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1080                 //   genericAnalyze,
1081                 genericDestruct,
1082                 genericPrint},
1083                 POC_SWAPF,
1084                 "SWAPF",
1085                 NULL, // from branch
1086                 NULL, // to branch
1087                 NULL, // label
1088                 NULL, // operand
1089                 NULL, // flow block
1090                 NULL, // C source 
1091                 2,    // num ops
1092                 1,0,  // dest, bit instruction
1093                 0,0,  // branch, skip
1094                 0,    // literal operand
1095                 POC_NOP,
1096                 (PCC_REGISTER),   // inCond
1097                 (PCC_REGISTER) // outCond
1098 };
1099
1100 pCodeInstruction pciSWAPFW = {
1101         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1102                 //   genericAnalyze,
1103                 genericDestruct,
1104                 genericPrint},
1105                 POC_SWAPFW,
1106                 "SWAPF",
1107                 NULL, // from branch
1108                 NULL, // to branch
1109                 NULL, // label
1110                 NULL, // operand
1111                 NULL, // flow block
1112                 NULL, // C source 
1113                 2,    // num ops
1114                 0,0,  // dest, bit instruction
1115                 0,0,  // branch, skip
1116                 0,    // literal operand
1117                 POC_NOP,
1118                 (PCC_REGISTER),   // inCond
1119                 (PCC_W) // outCond
1120 };
1121
1122 pCodeInstruction pciTRIS = {
1123         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1124                 //   genericAnalyze,
1125                 genericDestruct,
1126                 genericPrint},
1127                 POC_TRIS,
1128                 "TRIS",
1129                 NULL, // from branch
1130                 NULL, // to branch
1131                 NULL, // label
1132                 NULL, // operand
1133                 NULL, // flow block
1134                 NULL, // C source 
1135                 1,    // num ops
1136                 0,0,  // dest, bit instruction
1137                 0,0,  // branch, skip
1138                 0,    // literal operand
1139                 POC_NOP,
1140                 PCC_NONE,   // inCond
1141                 PCC_REGISTER // outCond
1142 };
1143
1144 pCodeInstruction pciXORWF = {
1145         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1146                 //   genericAnalyze,
1147                 genericDestruct,
1148                 genericPrint},
1149                 POC_XORWF,
1150                 "XORWF",
1151                 NULL, // from branch
1152                 NULL, // to branch
1153                 NULL, // label
1154                 NULL, // operand
1155                 NULL, // flow block
1156                 NULL, // C source 
1157                 2,    // num ops
1158                 1,0,  // dest, bit instruction
1159                 0,0,  // branch, skip
1160                 0,    // literal operand
1161                 POC_NOP,
1162                 (PCC_W | PCC_REGISTER),   // inCond
1163                 (PCC_REGISTER | PCC_Z) // outCond
1164 };
1165
1166 pCodeInstruction pciXORFW = {
1167         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1168                 //   genericAnalyze,
1169                 genericDestruct,
1170                 genericPrint},
1171                 POC_XORFW,
1172                 "XORWF",
1173                 NULL, // from branch
1174                 NULL, // to branch
1175                 NULL, // label
1176                 NULL, // operand
1177                 NULL, // flow block
1178                 NULL, // C source 
1179                 2,    // num ops
1180                 0,0,  // dest, bit instruction
1181                 0,0,  // branch, skip
1182                 0,    // literal operand
1183                 POC_NOP,
1184                 (PCC_W | PCC_REGISTER),   // inCond
1185                 (PCC_W | PCC_Z) // outCond
1186 };
1187
1188 pCodeInstruction pciXORLW = {
1189         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1190                 //   genericAnalyze,
1191                 genericDestruct,
1192                 genericPrint},
1193                 POC_XORLW,
1194                 "XORLW",
1195                 NULL, // from branch
1196                 NULL, // to branch
1197                 NULL, // label
1198                 NULL, // operand
1199                 NULL, // flow block
1200                 NULL, // C source 
1201                 1,    // num ops
1202                 0,0,  // dest, bit instruction
1203                 0,0,  // branch, skip
1204                 1,    // literal operand
1205                 POC_NOP,
1206                 (PCC_W | PCC_LITERAL),   // inCond
1207                 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
1208 };
1209
1210
1211 pCodeInstruction pciBANKSEL = {
1212         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1213                 //   genericAnalyze,
1214                 genericDestruct,
1215                 genericPrint},
1216                 POC_BANKSEL,
1217                 "BANKSEL",
1218                 NULL, // from branch
1219                 NULL, // to branch
1220                 NULL, // label
1221                 NULL, // operand
1222                 NULL, // flow block
1223                 NULL, // C source 
1224                 1,    // num ops
1225                 0,0,  // dest, bit instruction
1226                 0,0,  // branch, skip
1227                 0,    // literal operand
1228                 POC_NOP,
1229                 PCC_NONE, // inCond
1230                 PCC_REGISTER  // outCond
1231 };
1232
1233 pCodeInstruction pciPAGESEL = {
1234         {PC_OPCODE, NULL, NULL, 0, 0, NULL, 
1235                 //   genericAnalyze,
1236                 genericDestruct,
1237                 genericPrint},
1238                 POC_PAGESEL,
1239                 "PAGESEL",
1240                 NULL, // from branch
1241                 NULL, // to branch
1242                 NULL, // label
1243                 NULL, // operand
1244                 NULL, // flow block
1245                 NULL, // C source 
1246                 1,    // num ops
1247                 0,0,  // dest, bit instruction
1248                 0,0,  // branch, skip
1249                 0,    // literal operand
1250                 POC_NOP,
1251                 PCC_NONE, // inCond
1252                 PCC_REGISTER  // outCond
1253 };
1254
1255 pCodeInstruction *pic14Mnemonics[MAX_PIC14MNEMONICS];
1256
1257
1258 /*-----------------------------------------------------------------*/
1259 /* return a unique ID number to assist pCodes debuging             */
1260 /*-----------------------------------------------------------------*/
1261 unsigned PCodeID(void) {
1262         static unsigned int pcodeId = 1; /* unique ID number to be assigned to all pCodes */
1263         /*
1264         static unsigned int stop;
1265         if (pcodeId == 1448)
1266                 stop++; // Place break point here
1267         */
1268         return pcodeId++;
1269 }
1270
1271 #ifdef HAVE_VSNPRINTF
1272 // Alas, vsnprintf is not ANSI standard, and does not exist
1273 // on Solaris (and probably other non-Gnu flavored Unixes).
1274
1275 /*-----------------------------------------------------------------*/
1276 /* SAFE_snprintf - like snprintf except the string pointer is      */
1277 /*                 after the string has been printed to. This is   */
1278 /*                 useful for printing to string as though if it   */
1279 /*                 were a stream.                                  */
1280 /*-----------------------------------------------------------------*/
1281 void SAFE_snprintf(char **str, size_t *size, const  char  *format, ...)
1282 {
1283         va_list val;
1284         int len;
1285         
1286         if(!str || !*str)
1287                 return;
1288         
1289         va_start(val, format);
1290         
1291         vsnprintf(*str, *size, format, val);
1292         
1293         va_end (val);
1294         
1295         len = strlen(*str);
1296         if((size_t)len > *size) {
1297                 fprintf(stderr,"WARNING, it looks like %s has overflowed\n",__FUNCTION__);
1298                 fprintf(stderr,"len = %d is > str size %d\n",len,(int)*size);
1299         }
1300         
1301         *str += len;
1302         *size -= len;
1303         
1304 }
1305
1306 #else  //  HAVE_VSNPRINTF
1307
1308 // This version is *not* safe, despite the name.
1309
1310 void SAFE_snprintf(char **str, size_t *size, const  char  *format, ...)
1311 {
1312         va_list val;
1313         int len;
1314         static char buffer[1024]; /* grossly conservative, but still not inherently safe */
1315         
1316         if(!str || !*str)
1317                 return;
1318         
1319         va_start(val, format);
1320         
1321         vsprintf(buffer, format, val);
1322         va_end (val);
1323         
1324         len = strlen(buffer);
1325         if(len > *size) {
1326                 fprintf(stderr,"WARNING, it looks like %s has overflowed\n",__FUNCTION__);
1327                 fprintf(stderr,"len = %d is > str size %d\n",len,*size);
1328         }
1329         
1330         strcpy(*str, buffer);
1331         *str += len;
1332         *size -= len;
1333         
1334 }
1335
1336 #endif    //  HAVE_VSNPRINTF
1337
1338
1339 extern  void initStack(int base_address, int size);
1340 extern regs *allocProcessorRegister(int rIdx, char * name, short po_type, int alias);
1341 extern regs *allocInternalRegister(int rIdx, char * name, short po_type, int alias);
1342 extern void init_pic(char *);
1343
1344 void  pCodeInitRegisters(void)
1345 {
1346         static int initialized=0;
1347         int shareBankAddress,stkSize;
1348         
1349         if(initialized)
1350                 return;
1351         initialized = 1;
1352         
1353         init_pic(port->processor);
1354         shareBankAddress = 0x7f; /* FIXME - some PIC ICs like 16C7X which do not have a shared bank need a different approach. */
1355         if ((unsigned)shareBankAddress > getMaxRam()) /* If total RAM is less than 0x7f as with 16f84 then reduce shareBankAddress to fit */
1356                 shareBankAddress = (int)getMaxRam();
1357         stkSize = 15; /* Set pseudo stack size to 15, on multi memory bank ICs this leaves room for WSAVE (used for interrupts) to fit into the shared portion of the memory bank */
1358         initStack(shareBankAddress, stkSize); /* Putting the pseudo stack in shared memory so all modules use the same register when passing fn parameters */
1359         
1360         pc_status.r = allocProcessorRegister(IDX_STATUS,"STATUS", PO_STATUS, 0x180);
1361         pc_pcl.r = allocProcessorRegister(IDX_PCL,"PCL", PO_PCL, 0x80);
1362         pc_pclath.r = allocProcessorRegister(IDX_PCLATH,"PCLATH", PO_PCLATH, 0x180);
1363         pc_fsr.r = allocProcessorRegister(IDX_FSR,"FSR", PO_FSR, 0x180);
1364         pc_indf.r = allocProcessorRegister(IDX_INDF,"INDF", PO_INDF, 0x180);
1365         pc_intcon.r = allocProcessorRegister(IDX_INTCON,"INTCON", PO_INTCON, 0x180);
1366         
1367         pc_status.rIdx = IDX_STATUS;
1368         pc_fsr.rIdx = IDX_FSR;
1369         pc_indf.rIdx = IDX_INDF;
1370         pc_intcon.rIdx = IDX_INTCON;
1371         pc_pcl.rIdx = IDX_PCL;
1372         pc_pclath.rIdx = IDX_PCLATH;
1373         
1374         pc_wsave.r = allocInternalRegister(IDX_WSAVE,pc_wsave.pcop.name,pc_wsave.pcop.type, 0x180); /* Interrupt storage for working register - must be same address in all banks ie section SHAREBANK. */
1375         pc_ssave.r = allocInternalRegister(IDX_SSAVE,pc_ssave.pcop.name,pc_ssave.pcop.type, 0); /* Interrupt storage for status register. */
1376         pc_psave.r = allocInternalRegister(IDX_PSAVE,pc_psave.pcop.name,pc_psave.pcop.type, 0); /* Interrupt storage for pclath register. */
1377         
1378         pc_wsave.rIdx = pc_wsave.r->rIdx;
1379         pc_ssave.rIdx = pc_ssave.r->rIdx;
1380         pc_psave.rIdx = pc_psave.r->rIdx;
1381         
1382         pc_wsave.r->isFixed = 1; /* Some PIC ICs do not have a sharebank - this register needs to be reserved across all banks. */
1383         pc_wsave.r->address = shareBankAddress-stkSize;
1384         pc_ssave.r->isFixed = 1; /* This register must be in the first bank. */
1385         pc_ssave.r->address = shareBankAddress-stkSize-1;
1386         pc_psave.r->isFixed = 1; /* This register must be in the first bank. */
1387         pc_psave.r->address = shareBankAddress-stkSize-2;
1388         
1389         /* probably should put this in a separate initialization routine */
1390         pb_dead_pcodes = newpBlock();
1391         
1392 }
1393
1394 /*-----------------------------------------------------------------*/
1395 /*  mnem2key - convert a pic mnemonic into a hash key              */
1396 /*   (BTW - this spreads the mnemonics quite well)                 */
1397 /*                                                                 */
1398 /*-----------------------------------------------------------------*/
1399
1400 int mnem2key(char const *mnem)
1401 {
1402         int key = 0;
1403         
1404         if(!mnem)
1405                 return 0;
1406         
1407         while(*mnem) {
1408                 
1409                 key += toupper(*mnem++) +1;
1410                 
1411         }
1412         
1413         return (key & 0x1f);
1414         
1415 }
1416
1417 void pic14initMnemonics(void)
1418 {
1419         int i = 0;
1420         int key;
1421         //  char *str;
1422         pCodeInstruction *pci;
1423         
1424         if(mnemonics_initialized)
1425                 return;
1426         
1427         //FIXME - probably should NULL out the array before making the assignments
1428         //since we check the array contents below this initialization.
1429         
1430         pic14Mnemonics[POC_ADDLW] = &pciADDLW;
1431         pic14Mnemonics[POC_ADDWF] = &pciADDWF;
1432         pic14Mnemonics[POC_ADDFW] = &pciADDFW;
1433         pic14Mnemonics[POC_ANDLW] = &pciANDLW;
1434         pic14Mnemonics[POC_ANDWF] = &pciANDWF;
1435         pic14Mnemonics[POC_ANDFW] = &pciANDFW;
1436         pic14Mnemonics[POC_BCF] = &pciBCF;
1437         pic14Mnemonics[POC_BSF] = &pciBSF;
1438         pic14Mnemonics[POC_BTFSC] = &pciBTFSC;
1439         pic14Mnemonics[POC_BTFSS] = &pciBTFSS;
1440         pic14Mnemonics[POC_CALL] = &pciCALL;
1441         pic14Mnemonics[POC_COMF] = &pciCOMF;
1442         pic14Mnemonics[POC_COMFW] = &pciCOMFW;
1443         pic14Mnemonics[POC_CLRF] = &pciCLRF;
1444         pic14Mnemonics[POC_CLRW] = &pciCLRW;
1445         pic14Mnemonics[POC_CLRWDT] = &pciCLRWDT;
1446         pic14Mnemonics[POC_DECF] = &pciDECF;
1447         pic14Mnemonics[POC_DECFW] = &pciDECFW;
1448         pic14Mnemonics[POC_DECFSZ] = &pciDECFSZ;
1449         pic14Mnemonics[POC_DECFSZW] = &pciDECFSZW;
1450         pic14Mnemonics[POC_GOTO] = &pciGOTO;
1451         pic14Mnemonics[POC_INCF] = &pciINCF;
1452         pic14Mnemonics[POC_INCFW] = &pciINCFW;
1453         pic14Mnemonics[POC_INCFSZ] = &pciINCFSZ;
1454         pic14Mnemonics[POC_INCFSZW] = &pciINCFSZW;
1455         pic14Mnemonics[POC_IORLW] = &pciIORLW;
1456         pic14Mnemonics[POC_IORWF] = &pciIORWF;
1457         pic14Mnemonics[POC_IORFW] = &pciIORFW;
1458         pic14Mnemonics[POC_MOVF] = &pciMOVF;
1459         pic14Mnemonics[POC_MOVFW] = &pciMOVFW;
1460         pic14Mnemonics[POC_MOVLW] = &pciMOVLW;
1461         pic14Mnemonics[POC_MOVWF] = &pciMOVWF;
1462         pic14Mnemonics[POC_NOP] = &pciNOP;
1463         pic14Mnemonics[POC_RETFIE] = &pciRETFIE;
1464         pic14Mnemonics[POC_RETLW] = &pciRETLW;
1465         pic14Mnemonics[POC_RETURN] = &pciRETURN;
1466         pic14Mnemonics[POC_RLF] = &pciRLF;
1467         pic14Mnemonics[POC_RLFW] = &pciRLFW;
1468         pic14Mnemonics[POC_RRF] = &pciRRF;
1469         pic14Mnemonics[POC_RRFW] = &pciRRFW;
1470         pic14Mnemonics[POC_SUBLW] = &pciSUBLW;
1471         pic14Mnemonics[POC_SUBWF] = &pciSUBWF;
1472         pic14Mnemonics[POC_SUBFW] = &pciSUBFW;
1473         pic14Mnemonics[POC_SWAPF] = &pciSWAPF;
1474         pic14Mnemonics[POC_SWAPFW] = &pciSWAPFW;
1475         pic14Mnemonics[POC_TRIS] = &pciTRIS;
1476         pic14Mnemonics[POC_XORLW] = &pciXORLW;
1477         pic14Mnemonics[POC_XORWF] = &pciXORWF;
1478         pic14Mnemonics[POC_XORFW] = &pciXORFW;
1479         pic14Mnemonics[POC_BANKSEL] = &pciBANKSEL;
1480         pic14Mnemonics[POC_PAGESEL] = &pciPAGESEL;
1481         
1482         for(i=0; i<MAX_PIC14MNEMONICS; i++)
1483                 if(pic14Mnemonics[i])
1484                         hTabAddItem(&pic14MnemonicsHash, mnem2key(pic14Mnemonics[i]->mnemonic), pic14Mnemonics[i]);
1485                 pci = hTabFirstItem(pic14MnemonicsHash, &key);
1486                 
1487                 while(pci) {
1488                         DFPRINTF((stderr, "element %d key %d, mnem %s\n",i++,key,pci->mnemonic));
1489                         pci = hTabNextItem(pic14MnemonicsHash, &key);
1490                 }
1491                 
1492                 mnemonics_initialized = 1;
1493 }
1494
1495 int getpCodePeepCommand(char *cmd);
1496
1497 int getpCode(char *mnem,unsigned dest)
1498 {
1499         
1500         pCodeInstruction *pci;
1501         int key = mnem2key(mnem);
1502         
1503         if(!mnemonics_initialized)
1504                 pic14initMnemonics();
1505         
1506         pci = hTabFirstItemWK(pic14MnemonicsHash, key);
1507         
1508         while(pci) {
1509                 
1510                 if(STRCASECMP(pci->mnemonic, mnem) == 0) {
1511                         if((pci->num_ops <= 1) || (pci->isModReg == dest) || (pci->isBitInst))
1512                                 return(pci->op);
1513                 }
1514                 
1515                 pci = hTabNextItemWK (pic14MnemonicsHash);
1516                 
1517         }
1518         
1519         return -1;
1520 }
1521
1522 /*-----------------------------------------------------------------*
1523 * pic14initpCodePeepCommands
1524 *
1525 *-----------------------------------------------------------------*/
1526 void pic14initpCodePeepCommands(void)
1527 {
1528         
1529         int key, i;
1530         peepCommand *pcmd;
1531         
1532         i = 0;
1533         do {
1534                 hTabAddItem(&pic14pCodePeepCommandsHash, 
1535                         mnem2key(peepCommands[i].cmd), &peepCommands[i]);
1536                 i++;
1537         } while (peepCommands[i].cmd);
1538         
1539         pcmd = hTabFirstItem(pic14pCodePeepCommandsHash, &key);
1540         
1541         while(pcmd) {
1542                 //fprintf(stderr, "peep command %s  key %d\n",pcmd->cmd,pcmd->id);
1543                 pcmd = hTabNextItem(pic14pCodePeepCommandsHash, &key);
1544         }
1545         
1546 }
1547
1548 /*-----------------------------------------------------------------
1549 *
1550 *
1551 *-----------------------------------------------------------------*/
1552
1553 int getpCodePeepCommand(char *cmd)
1554 {
1555         
1556         peepCommand *pcmd;
1557         int key = mnem2key(cmd);
1558         
1559         
1560         pcmd = hTabFirstItemWK(pic14pCodePeepCommandsHash, key);
1561         
1562         while(pcmd) {
1563                 // fprintf(stderr," comparing %s to %s\n",pcmd->cmd,cmd);
1564                 if(STRCASECMP(pcmd->cmd, cmd) == 0) {
1565                         return pcmd->id;
1566                 }
1567                 
1568                 pcmd = hTabNextItemWK (pic14pCodePeepCommandsHash);
1569                 
1570         }
1571         
1572         return -1;
1573 }
1574
1575 char getpBlock_dbName(pBlock *pb)
1576 {
1577         if(!pb)
1578                 return 0;
1579         
1580         if(pb->cmemmap)
1581                 return pb->cmemmap->dbName;
1582         
1583         return pb->dbName;
1584 }
1585 void pBlockConvert2ISR(pBlock *pb)
1586 {
1587         if(!pb)
1588                 return;
1589         
1590         if(pb->cmemmap)
1591                 pb->cmemmap = NULL;
1592         
1593         pb->dbName = 'I';
1594 }
1595
1596 /*-----------------------------------------------------------------*/
1597 /* movepBlock2Head - given the dbname of a pBlock, move all        */
1598 /*                   instances to the front of the doubly linked   */
1599 /*                   list of pBlocks                               */
1600 /*-----------------------------------------------------------------*/
1601
1602 void movepBlock2Head(char dbName)
1603 {
1604         pBlock *pb;
1605         
1606         if (!the_pFile)
1607                 return;
1608         
1609         pb = the_pFile->pbHead;
1610         
1611         while(pb) {
1612                 
1613                 if(getpBlock_dbName(pb) == dbName) {
1614                         pBlock *pbn = pb->next;
1615                         pb->next = the_pFile->pbHead;
1616                         the_pFile->pbHead->prev = pb;
1617                         the_pFile->pbHead = pb;
1618                         
1619                         if(pb->prev)
1620                                 pb->prev->next = pbn;
1621                         
1622                         // If the pBlock that we just moved was the last
1623                         // one in the link of all of the pBlocks, then we
1624                         // need to point the tail to the block just before
1625                         // the one we moved.
1626                         // Note: if pb->next is NULL, then pb must have 
1627                         // been the last pBlock in the chain.
1628                         
1629                         if(pbn)
1630                                 pbn->prev = pb->prev;
1631                         else
1632                                 the_pFile->pbTail = pb->prev;
1633                         
1634                         pb = pbn;
1635                         
1636                 } else
1637                         pb = pb->next;
1638                 
1639         }
1640         
1641 }
1642
1643 void copypCode(FILE *of, char dbName)
1644 {
1645         pBlock *pb;
1646         
1647         if(!of || !the_pFile)
1648                 return;
1649
1650         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
1651                 if(getpBlock_dbName(pb) == dbName) {
1652                         pBlockStats(of,pb);
1653                         printpBlock(of,pb);
1654                         fprintf (of, "\n");
1655                 }
1656         }
1657         
1658 }
1659
1660 void resetpCodeStatistics (void)
1661 {
1662   pcode_insns = pcode_doubles = 0;
1663 }
1664
1665 void dumppCodeStatistics (FILE *of)
1666 {
1667         /* dump statistics */
1668         fprintf (of, "\n");
1669         fprintf (of, ";\tcode size estimation:\n");
1670         fprintf (of, ";\t%5u+%5u = %5u instructions (%5u byte)\n", pcode_insns, pcode_doubles, pcode_insns + pcode_doubles, 2*(pcode_insns + 2*pcode_doubles));
1671         fprintf (of, "\n");
1672 }
1673
1674 void pcode_test(void)
1675 {
1676         
1677         DFPRINTF((stderr,"pcode is alive!\n"));
1678         
1679         //initMnemonics();
1680         
1681         if(the_pFile) {
1682                 
1683                 pBlock *pb;
1684                 FILE *pFile;
1685                 char buffer[100];
1686                 
1687                 /* create the file name */
1688                 strcpy(buffer,dstFileName);
1689                 strcat(buffer,".p");
1690                 
1691                 if( !(pFile = fopen(buffer, "w" ))) {
1692                         werror(E_FILE_OPEN_ERR,buffer);
1693                         exit(1);
1694                 }
1695                 
1696                 fprintf(pFile,"pcode dump\n\n");
1697                 
1698                 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
1699                         fprintf(pFile,"\n\tNew pBlock\n\n");
1700                         if(pb->cmemmap)
1701                                 fprintf(pFile,"%s",pb->cmemmap->sname);
1702                         else
1703                                 fprintf(pFile,"internal pblock");
1704                         
1705                         fprintf(pFile,", dbName =%c\n",getpBlock_dbName(pb));
1706                         printpBlock(pFile,pb);
1707                 }
1708         }
1709 }
1710 /*-----------------------------------------------------------------*/
1711 /* int RegCond(pCodeOp *pcop) - if pcop points to the STATUS reg-  */
1712 /*      ister, RegCond will return the bit being referenced.       */
1713 /*                                                                 */
1714 /* fixme - why not just OR in the pcop bit field                   */
1715 /*-----------------------------------------------------------------*/
1716
1717 static int RegCond(pCodeOp *pcop)
1718 {
1719         
1720         if(!pcop)
1721                 return 0;
1722         
1723         if (pcop->type == PO_GPR_BIT) {
1724                 char *name = pcop->name;
1725                 if (!name) 
1726                         name = PCOR(pcop)->r->name;
1727                 //      if (strcmp(name, pc_status.pcop.name) != 0) { <<< This breaks the peep 2 optimisation
1728                 switch(PCORB(pcop)->bit) {
1729                 case PIC_C_BIT:
1730                         return PCC_C;
1731                 case PIC_DC_BIT:
1732                         return PCC_DC;
1733                 case PIC_Z_BIT:
1734                         return PCC_Z;
1735                 }
1736                 //    }
1737         }
1738         
1739         return 0;
1740 }
1741
1742 /*-----------------------------------------------------------------*/
1743 /* newpCode - create and return a newly initialized pCode          */
1744 /*                                                                 */
1745 /*  fixme - rename this                                            */
1746 /*                                                                 */
1747 /* The purpose of this routine is to create a new Instruction      */
1748 /* pCode. This is called by gen.c while the assembly code is being */
1749 /* generated.                                                      */
1750 /*                                                                 */
1751 /* Inouts:                                                         */
1752 /*  PIC_OPCODE op - the assembly instruction we wish to create.    */
1753 /*                  (note that the op is analogous to but not the  */
1754 /*                  same thing as the opcode of the instruction.)  */
1755 /*  pCdoeOp *pcop - pointer to the operand of the instruction.     */
1756 /*                                                                 */
1757 /* Outputs:                                                        */
1758 /*  a pointer to the new malloc'd pCode is returned.               */
1759 /*                                                                 */
1760 /*                                                                 */
1761 /*                                                                 */
1762 /*-----------------------------------------------------------------*/
1763 pCode *newpCode (PIC_OPCODE op, pCodeOp *pcop)
1764 {
1765         pCodeInstruction *pci ;
1766         
1767         if(!mnemonics_initialized)
1768                 pic14initMnemonics();
1769         
1770         pci = Safe_calloc(1, sizeof(pCodeInstruction));
1771         
1772         if((op>=0) && (op < MAX_PIC14MNEMONICS) && pic14Mnemonics[op]) {
1773                 memcpy(pci, pic14Mnemonics[op], sizeof(pCodeInstruction));
1774                 pci->pc.id = PCodeID();
1775                 pci->pcop = pcop;
1776                 
1777                 if(pci->inCond & PCC_EXAMINE_PCOP)
1778                         pci->inCond  |= RegCond(pcop);
1779                 
1780                 if(pci->outCond & PCC_EXAMINE_PCOP)
1781                         pci->outCond  |= RegCond(pcop);
1782                 
1783                 pci->pc.prev = pci->pc.next = NULL;
1784                 return (pCode *)pci;
1785         }
1786         
1787         fprintf(stderr, "pCode mnemonic error %s,%d\n",__FUNCTION__,__LINE__);
1788         exit(1);
1789         
1790         return NULL;
1791 }       
1792
1793 /*-----------------------------------------------------------------*/
1794 /* newpCodeWild - create a "wild" as in wild card pCode            */
1795 /*                                                                 */
1796 /* Wild pcodes are used during the peep hole optimizer to serve    */
1797 /* as place holders for any instruction. When a snippet of code is */
1798 /* compared to a peep hole rule, the wild card opcode will match   */
1799 /* any instruction. However, the optional operand and label are    */
1800 /* additional qualifiers that must also be matched before the      */
1801 /* line (of assembly code) is declared matched. Note that the      */
1802 /* operand may be wild too.                                        */
1803 /*                                                                 */
1804 /*   Note, a wild instruction is specified just like a wild var:   */
1805 /*      %4     ; A wild instruction,                               */
1806 /*  See the peeph.def file for additional examples                 */
1807 /*                                                                 */
1808 /*-----------------------------------------------------------------*/
1809
1810 pCode *newpCodeWild(int pCodeID, pCodeOp *optional_operand, pCodeOp *optional_label)
1811 {
1812         
1813         pCodeWild *pcw;
1814         
1815         pcw = Safe_calloc(1,sizeof(pCodeWild));
1816         
1817         pcw->pci.pc.type = PC_WILD;
1818         pcw->pci.pc.prev = pcw->pci.pc.next = NULL;
1819         pcw->id = PCodeID();
1820         pcw->pci.from = pcw->pci.to = pcw->pci.label = NULL;
1821         pcw->pci.pc.pb = NULL;
1822         
1823         //  pcw->pci.pc.analyze = genericAnalyze;
1824         pcw->pci.pc.destruct = genericDestruct;
1825         pcw->pci.pc.print = genericPrint;
1826         
1827         pcw->id = pCodeID;              // this is the 'n' in %n
1828         pcw->operand = optional_operand;
1829         pcw->label   = optional_label;
1830         
1831         pcw->mustBeBitSkipInst = 0;
1832         pcw->mustNotBeBitSkipInst = 0;
1833         pcw->invertBitSkipInst = 0;
1834         
1835         return ( (pCode *)pcw);
1836         
1837 }
1838
1839 /*-----------------------------------------------------------------*/
1840 /* newPcodeInlineP - create a new pCode from a char string           */
1841 /*-----------------------------------------------------------------*/
1842
1843
1844 pCode *newpCodeInlineP(char *cP)
1845 {
1846         
1847         pCodeComment *pcc ;
1848         
1849         pcc = Safe_calloc(1,sizeof(pCodeComment));
1850         
1851         pcc->pc.type = PC_INLINE;
1852         pcc->pc.prev = pcc->pc.next = NULL;
1853         pcc->pc.id = PCodeID();
1854         //pcc->pc.from = pcc->pc.to = pcc->pc.label = NULL;
1855         pcc->pc.pb = NULL;
1856         
1857         //  pcc->pc.analyze = genericAnalyze;
1858         pcc->pc.destruct = genericDestruct;
1859         pcc->pc.print = genericPrint;
1860         
1861         if(cP)
1862                 pcc->comment = Safe_strdup(cP);
1863         else
1864                 pcc->comment = NULL;
1865         
1866         return ( (pCode *)pcc);
1867         
1868 }
1869
1870 /*-----------------------------------------------------------------*/
1871 /* newPcodeCharP - create a new pCode from a char string           */
1872 /*-----------------------------------------------------------------*/
1873
1874 pCode *newpCodeCharP(char *cP)
1875 {
1876         
1877         pCodeComment *pcc ;
1878         
1879         pcc = Safe_calloc(1,sizeof(pCodeComment));
1880         
1881         pcc->pc.type = PC_COMMENT;
1882         pcc->pc.prev = pcc->pc.next = NULL;
1883         pcc->pc.id = PCodeID();
1884         //pcc->pc.from = pcc->pc.to = pcc->pc.label = NULL;
1885         pcc->pc.pb = NULL;
1886         
1887         //  pcc->pc.analyze = genericAnalyze;
1888         pcc->pc.destruct = genericDestruct;
1889         pcc->pc.print = genericPrint;
1890         
1891         if(cP)
1892                 pcc->comment = Safe_strdup(cP);
1893         else
1894                 pcc->comment = NULL;
1895         
1896         return ( (pCode *)pcc);
1897         
1898 }
1899
1900 /*-----------------------------------------------------------------*/
1901 /* newpCodeFunction -                                              */
1902 /*-----------------------------------------------------------------*/
1903
1904
1905 pCode *newpCodeFunction(char *mod,char *f,int isPublic)
1906 {
1907         pCodeFunction *pcf;
1908         
1909         pcf = Safe_calloc(1,sizeof(pCodeFunction));
1910         //_ALLOC(pcf,sizeof(pCodeFunction));
1911         
1912         pcf->pc.type = PC_FUNCTION;
1913         pcf->pc.prev = pcf->pc.next = NULL;
1914         pcf->pc.id = PCodeID();
1915         //pcf->pc.from = pcf->pc.to = pcf->pc.label = NULL;
1916         pcf->pc.pb = NULL;
1917         
1918         //  pcf->pc.analyze = genericAnalyze;
1919         pcf->pc.destruct = genericDestruct;
1920         pcf->pc.print = pCodePrintFunction;
1921         
1922         pcf->ncalled = 0;
1923         
1924         if(mod) {
1925                 //_ALLOC_ATOMIC(pcf->modname,strlen(mod)+1);
1926                 pcf->modname = Safe_calloc(1,strlen(mod)+1);
1927                 strcpy(pcf->modname,mod);
1928         } else
1929                 pcf->modname = NULL;
1930         
1931         if(f) {
1932                 //_ALLOC_ATOMIC(pcf->fname,strlen(f)+1);
1933                 pcf->fname = Safe_calloc(1,strlen(f)+1);
1934                 strcpy(pcf->fname,f);
1935         } else
1936                 pcf->fname = NULL;
1937         
1938         pcf->isPublic = (unsigned)isPublic;
1939         
1940         return ( (pCode *)pcf);
1941         
1942 }
1943
1944 /*-----------------------------------------------------------------*/
1945 /* newpCodeFlow                                                    */
1946 /*-----------------------------------------------------------------*/
1947 void destructpCodeFlow(pCode *pc)
1948 {
1949         if(!pc || !isPCFL(pc))
1950                 return;
1951         
1952                 /*
1953                 if(PCFL(pc)->from)
1954                 if(PCFL(pc)->to)
1955         */
1956         unlinkpCode(pc);
1957         
1958         deleteSet(&PCFL(pc)->registers);
1959         deleteSet(&PCFL(pc)->from);
1960         deleteSet(&PCFL(pc)->to);
1961         free(pc);
1962         
1963 }
1964
1965 pCode *newpCodeFlow(void )
1966 {
1967         pCodeFlow *pcflow;
1968         
1969         //_ALLOC(pcflow,sizeof(pCodeFlow));
1970         pcflow = Safe_calloc(1,sizeof(pCodeFlow));
1971         
1972         pcflow->pc.type = PC_FLOW;
1973         pcflow->pc.prev = pcflow->pc.next = NULL;
1974         pcflow->pc.pb = NULL;
1975         
1976         //  pcflow->pc.analyze = genericAnalyze;
1977         pcflow->pc.destruct = destructpCodeFlow;
1978         pcflow->pc.print = genericPrint;
1979         
1980         pcflow->pc.seq = GpcFlowSeq++;
1981         
1982         pcflow->from = pcflow->to = NULL;
1983         
1984         pcflow->inCond = PCC_NONE;
1985         pcflow->outCond = PCC_NONE;
1986         
1987         pcflow->firstBank = 'U'; /* Undetermined */
1988         pcflow->lastBank = 'U'; /* Undetermined */
1989         
1990         pcflow->FromConflicts = 0;
1991         pcflow->ToConflicts = 0;
1992         
1993         pcflow->end = NULL;
1994         
1995         pcflow->registers = newSet();
1996         
1997         return ( (pCode *)pcflow);
1998         
1999 }
2000
2001 /*-----------------------------------------------------------------*/
2002 /*-----------------------------------------------------------------*/
2003 pCodeFlowLink *newpCodeFlowLink(pCodeFlow *pcflow)
2004 {
2005         pCodeFlowLink *pcflowLink;
2006         
2007         pcflowLink = Safe_calloc(1,sizeof(pCodeFlowLink));
2008         
2009         pcflowLink->pcflow = pcflow;
2010         pcflowLink->bank_conflict = 0;
2011         
2012         return pcflowLink;
2013 }
2014
2015 /*-----------------------------------------------------------------*/
2016 /* newpCodeCSource - create a new pCode Source Symbol              */
2017 /*-----------------------------------------------------------------*/
2018
2019 pCode *newpCodeCSource(int ln, char *f, const char *l)
2020 {
2021         
2022         pCodeCSource *pccs;
2023         
2024         pccs = Safe_calloc(1,sizeof(pCodeCSource));
2025         
2026         pccs->pc.type = PC_CSOURCE;
2027         pccs->pc.prev = pccs->pc.next = NULL;
2028         pccs->pc.id = PCodeID();
2029         pccs->pc.pb = NULL;
2030         
2031         pccs->pc.destruct = genericDestruct;
2032         pccs->pc.print = genericPrint;
2033         
2034         pccs->line_number = ln;
2035         if(l)
2036                 pccs->line = Safe_strdup(l);
2037         else
2038                 pccs->line = NULL;
2039         
2040         if(f)
2041                 pccs->file_name = Safe_strdup(f);
2042         else
2043                 pccs->file_name = NULL;
2044         
2045         return ( (pCode *)pccs);
2046         
2047 }
2048
2049 /*******************************************************************/
2050 /* pic16_newpCodeAsmDir - create a new pCode Assembler Directive   */
2051 /*                        added by VR 6-Jun-2003                   */
2052 /*******************************************************************/
2053
2054 pCode *newpCodeAsmDir(char *asdir, char *argfmt, ...)
2055 {
2056   pCodeAsmDir *pcad;
2057   va_list ap;
2058   char buffer[512];
2059   char *lbp=buffer;
2060
2061   pcad = Safe_calloc(1, sizeof(pCodeAsmDir));
2062   pcad->pci.pc.type = PC_ASMDIR;
2063   pcad->pci.pc.prev = pcad->pci.pc.next = NULL;
2064   pcad->pci.pc.pb = NULL;
2065   pcad->pci.pc.destruct = genericDestruct;
2066   pcad->pci.pc.print = genericPrint;
2067
2068   if(asdir && *asdir) {
2069
2070     while(isspace(*asdir))asdir++;      // strip any white space from the beginning
2071
2072     pcad->directive = Safe_strdup( asdir );
2073   }
2074
2075   va_start(ap, argfmt);
2076
2077   memset(buffer, 0, sizeof(buffer));
2078   if(argfmt && *argfmt)
2079     vsprintf(buffer, argfmt, ap);
2080
2081   va_end(ap);
2082
2083   while(isspace(*lbp))lbp++;
2084
2085   if(lbp && *lbp)
2086     pcad->arg = Safe_strdup( lbp );
2087
2088   return ((pCode *)pcad);
2089 }
2090
2091 /*-----------------------------------------------------------------*/
2092 /* pCodeLabelDestruct - free memory used by a label.               */
2093 /*-----------------------------------------------------------------*/
2094 static void pCodeLabelDestruct(pCode *pc)
2095 {
2096         
2097         if(!pc)
2098                 return;
2099         
2100         if((pc->type == PC_LABEL) && PCL(pc)->label)
2101                 free(PCL(pc)->label);
2102         
2103         free(pc);
2104         
2105 }
2106
2107 pCode *newpCodeLabel(char *name, int key)
2108 {
2109         
2110         char *s = buffer;
2111         pCodeLabel *pcl;
2112         
2113         pcl = Safe_calloc(1,sizeof(pCodeLabel) );
2114         
2115         pcl->pc.type = PC_LABEL;
2116         pcl->pc.prev = pcl->pc.next = NULL;
2117         pcl->pc.id = PCodeID();
2118         //pcl->pc.from = pcl->pc.to = pcl->pc.label = NULL;
2119         pcl->pc.pb = NULL;
2120         
2121         //  pcl->pc.analyze = genericAnalyze;
2122         pcl->pc.destruct = pCodeLabelDestruct;
2123         pcl->pc.print = pCodePrintLabel;
2124         
2125         pcl->key = key;
2126         
2127         pcl->label = NULL;
2128         if(key>0) {
2129                 sprintf(s,"_%05d_DS_",key);
2130         } else
2131                 s = name;
2132         
2133         if(s)
2134                 pcl->label = Safe_strdup(s);
2135         
2136         //fprintf(stderr,"newpCodeLabel: key=%d, name=%s\n",key, ((s)?s:""));
2137         return ( (pCode *)pcl);
2138         
2139 }
2140
2141
2142 /*-----------------------------------------------------------------*/
2143 /* newpBlock - create and return a pointer to a new pBlock         */
2144 /*-----------------------------------------------------------------*/
2145 pBlock *newpBlock(void)
2146 {
2147         
2148         pBlock *PpB;
2149         
2150         PpB = Safe_calloc(1,sizeof(pBlock) );
2151         PpB->next = PpB->prev = NULL;
2152         
2153         PpB->function_entries = PpB->function_exits = PpB->function_calls = NULL;
2154         PpB->tregisters = NULL;
2155         PpB->visited = 0;
2156         PpB->FlowTree = NULL;
2157         
2158         return PpB;
2159         
2160 }
2161
2162 /*-----------------------------------------------------------------*/
2163 /* newpCodeChain - create a new chain of pCodes                    */
2164 /*-----------------------------------------------------------------*
2165 *
2166 *  This function will create a new pBlock and the pointer to the
2167 *  pCode that is passed in will be the first pCode in the block.
2168 *-----------------------------------------------------------------*/
2169
2170
2171 pBlock *newpCodeChain(memmap *cm,char c, pCode *pc)
2172 {
2173         
2174         pBlock *pB  = newpBlock();
2175         
2176         pB->pcHead  = pB->pcTail = pc;
2177         pB->cmemmap = cm;
2178         pB->dbName  = c;
2179         
2180         return pB;
2181 }
2182
2183 /*-----------------------------------------------------------------*/
2184 /* newpCodeOpLabel - Create a new label given the key              */
2185 /*  Note, a negative key means that the label is part of wild card */
2186 /*  (and hence a wild card label) used in the pCodePeep            */
2187 /*   optimizations).                                               */
2188 /*-----------------------------------------------------------------*/
2189
2190 pCodeOp *newpCodeOpLabel(char *name, int key)
2191 {
2192         char *s=NULL;
2193         static int label_key=-1;
2194         
2195         pCodeOp *pcop;
2196         
2197         pcop = Safe_calloc(1,sizeof(pCodeOpLabel) );
2198         pcop->type = PO_LABEL;
2199         
2200         pcop->name = NULL;
2201         
2202         if(key>0)
2203                 sprintf(s=buffer,"_%05d_DS_",key);
2204         else 
2205                 s = name, key = label_key--;
2206         
2207         PCOLAB(pcop)->offset = 0;
2208         if(s)
2209                 pcop->name = Safe_strdup(s);
2210         
2211         ((pCodeOpLabel *)pcop)->key = key;
2212         
2213         //fprintf(stderr,"newpCodeOpLabel: key=%d, name=%s\n",key,((s)?s:""));
2214         return pcop;
2215 }
2216
2217 /*-----------------------------------------------------------------*/
2218 /*-----------------------------------------------------------------*/
2219 pCodeOp *newpCodeOpLit(int lit)
2220 {
2221         char *s = buffer;
2222         pCodeOp *pcop;
2223         
2224         
2225         pcop = Safe_calloc(1,sizeof(pCodeOpLit) );
2226         pcop->type = PO_LITERAL;
2227         
2228         pcop->name = NULL;
2229         if(lit>=0) {
2230                 sprintf(s,"0x%02x",lit);
2231                 if(s)
2232                         pcop->name = Safe_strdup(s);
2233         }
2234         
2235         ((pCodeOpLit *)pcop)->lit = lit;
2236         
2237         return pcop;
2238 }
2239
2240 /*-----------------------------------------------------------------*/
2241 /*-----------------------------------------------------------------*/
2242 pCodeOp *newpCodeOpImmd(char *name, int offset, int index, int code_space, int is_func)
2243 {
2244         pCodeOp *pcop;
2245         
2246         pcop = Safe_calloc(1,sizeof(pCodeOpImmd) );
2247         pcop->type = PO_IMMEDIATE;
2248         if(name) {
2249                 regs *r = NULL;
2250                 pcop->name = Safe_strdup(name);
2251                 
2252                 if(!is_func) 
2253                         r = dirregWithName(name);
2254                 
2255                 PCOI(pcop)->r = r;
2256                 if(r) {
2257                         //fprintf(stderr, " newpCodeOpImmd reg %s exists\n",name);
2258                         PCOI(pcop)->rIdx = r->rIdx;
2259                 } else {
2260                         //fprintf(stderr, " newpCodeOpImmd reg %s doesn't exist\n",name);
2261                         PCOI(pcop)->rIdx = -1;
2262                 }
2263                 //fprintf(stderr,"%s %s %d\n",__FUNCTION__,name,offset);
2264         } else {
2265                 pcop->name = NULL;
2266         }
2267         
2268         PCOI(pcop)->index = index;
2269         PCOI(pcop)->offset = offset;
2270         PCOI(pcop)->_const = code_space;
2271         PCOI(pcop)->_function = is_func;
2272         
2273         return pcop;
2274 }
2275
2276 /*-----------------------------------------------------------------*/
2277 /*-----------------------------------------------------------------*/
2278 pCodeOp *newpCodeOpWild(int id, pCodeWildBlock *pcwb, pCodeOp *subtype)
2279 {
2280         char *s = buffer;
2281         pCodeOp *pcop;
2282         
2283         
2284         if(!pcwb || !subtype) {
2285                 fprintf(stderr, "Wild opcode declaration error: %s-%d\n",__FILE__,__LINE__);
2286                 exit(1);
2287         }
2288         
2289         pcop = Safe_calloc(1,sizeof(pCodeOpWild));
2290         pcop->type = PO_WILD;
2291         sprintf(s,"%%%d",id);
2292         pcop->name = Safe_strdup(s);
2293         
2294         PCOW(pcop)->id = id;
2295         PCOW(pcop)->pcwb = pcwb;
2296         PCOW(pcop)->subtype = subtype;
2297         PCOW(pcop)->matched = NULL;
2298         
2299         return pcop;
2300 }
2301 /*-----------------------------------------------------------------*/
2302 /* Find a symbol with matching name                                */
2303 /*-----------------------------------------------------------------*/
2304 static symbol *symFindWithName(memmap * map, const char *name)
2305 {
2306         symbol *sym;
2307         
2308         for (sym = setFirstItem(map->syms); sym; sym = setNextItem (map->syms)) {
2309                 if (sym->rname && (strcmp(sym->rname,name)==0))
2310                         return sym;
2311         }
2312         return 0;
2313 }
2314
2315 /*-----------------------------------------------------------------*/
2316 /*-----------------------------------------------------------------*/
2317 pCodeOp *newpCodeOpBit(char *name, int ibit, int inBitSpace)
2318 {
2319         pCodeOp *pcop;
2320         struct regs *r = 0;
2321         
2322         pcop = Safe_calloc(1,sizeof(pCodeOpRegBit) );
2323         pcop->type = PO_GPR_BIT;
2324         
2325         PCORB(pcop)->bit = ibit;
2326         PCORB(pcop)->inBitSpace = inBitSpace;
2327         
2328         if (name) r = regFindWithName(name);
2329         if (!r) {
2330                 // Register has not been allocated - check for symbol information
2331                 symbol *sym;
2332                 sym = symFindWithName(bit, name);
2333                 if (!sym) sym = symFindWithName(sfrbit, name);
2334                 if (!sym) sym = symFindWithName(sfr, name);
2335                 if (sym) {
2336                         r = allocNewDirReg(sym->etype,name);
2337                 }
2338         }
2339         if (r) {
2340                 pcop->name = NULL;
2341                 PCOR(pcop)->r = r;
2342                 PCOR(pcop)->rIdx = r->rIdx;
2343         } else {
2344                 pcop->name = Safe_strdup(name);   
2345                 PCOR(pcop)->r = NULL;
2346                 PCOR(pcop)->rIdx = 0;
2347         }
2348         return pcop;
2349 }
2350
2351 /*-----------------------------------------------------------------*
2352 * pCodeOp *newpCodeOpReg(int rIdx) - allocate a new register
2353 *
2354 * If rIdx >=0 then a specific register from the set of registers
2355 * will be selected. If rIdx <0, then a new register will be searched
2356 * for.
2357 *-----------------------------------------------------------------*/
2358
2359 pCodeOp *newpCodeOpReg(int rIdx)
2360 {
2361         pCodeOp *pcop;
2362         
2363         pcop = Safe_calloc(1,sizeof(pCodeOpReg) );
2364         
2365         pcop->name = NULL;
2366         
2367         if(rIdx >= 0) {
2368                 PCOR(pcop)->rIdx = rIdx;
2369                 PCOR(pcop)->r = pic14_regWithIdx(rIdx);
2370         } else {
2371                 PCOR(pcop)->r = pic14_findFreeReg(REG_GPR);
2372                 
2373                 if(PCOR(pcop)->r)
2374                         PCOR(pcop)->rIdx = PCOR(pcop)->r->rIdx;
2375         }
2376         
2377         if(PCOR(pcop)->r)
2378                 pcop->type = PCOR(pcop)->r->pc_type;
2379         
2380         return pcop;
2381 }
2382
2383 pCodeOp *newpCodeOpRegFromStr(char *name)
2384 {
2385         pCodeOp *pcop;
2386         
2387         pcop = Safe_calloc(1,sizeof(pCodeOpReg) );
2388         PCOR(pcop)->r = allocRegByName(name, 1);
2389         PCOR(pcop)->rIdx = PCOR(pcop)->r->rIdx;
2390         pcop->type = PCOR(pcop)->r->pc_type;
2391         pcop->name = PCOR(pcop)->r->name;
2392         
2393         return pcop;
2394 }
2395
2396 pCodeOp *newpCodeOpStr(char *name)
2397 {
2398         pCodeOp *pcop;
2399         
2400         pcop = Safe_calloc(1,sizeof(pCodeOpStr));
2401         pcop->type = PO_STR;
2402         pcop->name = Safe_strdup(name);   
2403         
2404         PCOS(pcop)->isPublic = 0;
2405         
2406         return pcop;
2407 }
2408
2409
2410 /*-----------------------------------------------------------------*/
2411 /*-----------------------------------------------------------------*/
2412
2413 pCodeOp *newpCodeOp(char *name, PIC_OPTYPE type)
2414 {
2415         pCodeOp *pcop;
2416         
2417         switch(type) {
2418         case PO_BIT:
2419         case PO_GPR_BIT:
2420                 pcop = newpCodeOpBit(name, -1,0);
2421                 break;
2422                 
2423         case PO_LITERAL:
2424                 pcop = newpCodeOpLit(-1);
2425                 break;
2426                 
2427         case PO_LABEL:
2428                 pcop = newpCodeOpLabel(NULL,-1);
2429                 break;
2430                 
2431         case PO_GPR_TEMP:
2432                 pcop = newpCodeOpReg(-1);
2433                 break;
2434                 
2435         case PO_GPR_POINTER:
2436         case PO_GPR_REGISTER:
2437                 if(name)
2438                         pcop = newpCodeOpRegFromStr(name);
2439                 else
2440                         pcop = newpCodeOpReg(-1);
2441                 break;
2442                 
2443         case PO_STR:
2444                 pcop = newpCodeOpStr(name);
2445                 break;
2446                 
2447         default:
2448                 pcop = Safe_calloc(1,sizeof(pCodeOp) );
2449                 pcop->type = type;
2450                 if(name)
2451                         pcop->name = Safe_strdup(name);   
2452                 else
2453                         pcop->name = NULL;
2454         }
2455         
2456         return pcop;
2457 }
2458
2459 /*-----------------------------------------------------------------*/
2460 /*-----------------------------------------------------------------*/
2461 void pCodeConstString(char *name, char *value)
2462 {
2463         pBlock *pb;
2464         unsigned i;
2465         
2466         //  fprintf(stderr, " %s  %s  %s\n",__FUNCTION__,name,value);
2467         
2468         if(!name || !value)
2469                 return;
2470         
2471         pb = newpCodeChain(NULL, 'P',newpCodeCharP("; Starting pCode block"));
2472         
2473         addpBlock(pb);
2474         
2475         sprintf(buffer,"; %s = %s",name,value);
2476         for (i=strlen(buffer); i--; ) {
2477                 unsigned char c = buffer[i];
2478                 if (c=='\r' || c=='\n') {
2479                         memmove(buffer+i+1,buffer+i,strlen(buffer)-i+1);
2480                         buffer[i] = '\\';
2481                         if (c=='\r') buffer[i+1] = 'r';
2482                         else if (c=='\n') buffer[i+1] = 'n';
2483                 }
2484         }
2485         
2486         addpCode2pBlock(pb,newpCodeCharP(buffer));
2487         addpCode2pBlock(pb,newpCodeLabel(name,-1));
2488         
2489         do {
2490                 addpCode2pBlock(pb,newpCode(POC_RETLW,newpCodeOpLit(*value)));
2491         }while (*value++);
2492         
2493         
2494 }
2495
2496 /*-----------------------------------------------------------------*/
2497 /*-----------------------------------------------------------------*/
2498 void pCodeReadCodeTable(void)
2499 {
2500         pBlock *pb;
2501         
2502         fprintf(stderr, " %s\n",__FUNCTION__);
2503         
2504         pb = newpCodeChain(NULL, 'P',newpCodeCharP("; Starting pCode block"));
2505         
2506         addpBlock(pb);
2507         
2508         addpCode2pBlock(pb,newpCodeCharP("; ReadCodeTable - built in function"));
2509         addpCode2pBlock(pb,newpCodeCharP("; Inputs: temp1,temp2 = code pointer"));
2510         addpCode2pBlock(pb,newpCodeCharP("; Outpus: W (from RETLW at temp2:temp1)"));
2511         addpCode2pBlock(pb,newpCodeLabel("ReadCodeTable:",-1));
2512         
2513         addpCode2pBlock(pb,newpCode(POC_MOVFW,newpCodeOpRegFromStr("temp2")));
2514         addpCode2pBlock(pb,newpCode(POC_MOVWF,newpCodeOpRegFromStr("PCLATH")));
2515         addpCode2pBlock(pb,newpCode(POC_MOVFW,newpCodeOpRegFromStr("temp1")));
2516         addpCode2pBlock(pb,newpCode(POC_MOVWF,newpCodeOpRegFromStr("PCL")));
2517         
2518         
2519 }
2520
2521 /*-----------------------------------------------------------------*/
2522 /* addpCode2pBlock - place the pCode into the pBlock linked list   */
2523 /*-----------------------------------------------------------------*/
2524 void addpCode2pBlock(pBlock *pb, pCode *pc)
2525 {
2526         
2527         if(!pc)
2528                 return;
2529         
2530         if(!pb->pcHead) {
2531         /* If this is the first pcode to be added to a block that
2532         * was initialized with a NULL pcode, then go ahead and
2533                 * make this pcode the head and tail */
2534                 pb->pcHead  = pb->pcTail = pc;
2535         } else {
2536                 //    if(pb->pcTail)
2537                 pb->pcTail->next = pc;
2538                 
2539                 pc->prev = pb->pcTail;
2540                 pc->pb = pb;
2541                 
2542                 pb->pcTail = pc;
2543         }
2544 }
2545
2546 /*-----------------------------------------------------------------*/
2547 /* addpBlock - place a pBlock into the pFile                       */
2548 /*-----------------------------------------------------------------*/
2549 void addpBlock(pBlock *pb)
2550 {
2551         // fprintf(stderr," Adding pBlock: dbName =%c\n",getpBlock_dbName(pb));
2552         
2553         if(!the_pFile) {
2554                 /* First time called, we'll pass through here. */
2555                 //_ALLOC(the_pFile,sizeof(pFile));
2556                 the_pFile = Safe_calloc(1,sizeof(pFile));
2557                 the_pFile->pbHead = the_pFile->pbTail = pb;
2558                 the_pFile->functions = NULL;
2559                 return;
2560         }
2561         
2562         the_pFile->pbTail->next = pb;
2563         pb->prev = the_pFile->pbTail;
2564         pb->next = NULL;
2565         the_pFile->pbTail = pb;
2566 }
2567
2568 /*-----------------------------------------------------------------*/
2569 /* removepBlock - remove a pBlock from the pFile                   */
2570 /*-----------------------------------------------------------------*/
2571 void removepBlock(pBlock *pb)
2572 {
2573         pBlock *pbs;
2574         
2575         if(!the_pFile)
2576                 return;
2577         
2578         
2579         //fprintf(stderr," Removing pBlock: dbName =%c\n",getpBlock_dbName(pb));
2580         
2581         for(pbs = the_pFile->pbHead; pbs; pbs = pbs->next) {
2582                 if(pbs == pb) {
2583                         
2584                         if(pbs == the_pFile->pbHead)
2585                                 the_pFile->pbHead = pbs->next;
2586                         
2587                         if (pbs == the_pFile->pbTail) 
2588                                 the_pFile->pbTail = pbs->prev;
2589                         
2590                         if(pbs->next)
2591                                 pbs->next->prev = pbs->prev;
2592                         
2593                         if(pbs->prev)
2594                                 pbs->prev->next = pbs->next;
2595                         
2596                         return;
2597                         
2598                 }
2599         }
2600         
2601         fprintf(stderr, "Warning: call to %s:%s didn't find pBlock\n",__FILE__,__FUNCTION__);
2602         
2603 }
2604
2605 /*-----------------------------------------------------------------*/
2606 /* printpCode - write the contents of a pCode to a file            */
2607 /*-----------------------------------------------------------------*/
2608 void printpCode(FILE *of, pCode *pc)
2609 {
2610         
2611         if(!pc || !of)
2612                 return;
2613         
2614         if(pc->print) {
2615                 pc->print(of,pc);
2616                 return;
2617         }
2618         
2619         fprintf(of,"warning - unable to print pCode\n");
2620 }
2621
2622 /*-----------------------------------------------------------------*/
2623 /* printpBlock - write the contents of a pBlock to a file          */
2624 /*-----------------------------------------------------------------*/
2625 void printpBlock(FILE *of, pBlock *pb)
2626 {
2627         pCode *pc;
2628         
2629         if(!pb)
2630                 return;
2631         
2632         if(!of)
2633                 of = stderr;
2634         
2635         for(pc = pb->pcHead; pc; pc = pc->next) {
2636                 printpCode(of,pc);
2637
2638                 if (isPCI(pc))
2639                 {
2640                         if (isPCI(pc) && (PCI(pc)->op == POC_PAGESEL || PCI(pc)->op == POC_BANKSEL)) {
2641                                 pcode_doubles++;
2642                         } else {
2643                                 pcode_insns++;
2644                         }
2645                 }
2646         } // for
2647
2648 }
2649
2650 /*-----------------------------------------------------------------*/
2651 /*                                                                 */
2652 /*       pCode processing                                          */
2653 /*                                                                 */
2654 /*                                                                 */
2655 /*                                                                 */
2656 /*-----------------------------------------------------------------*/
2657
2658 void unlinkpCode(pCode *pc)
2659 {
2660         
2661         
2662         if(pc) {
2663 #ifdef PCODE_DEBUG
2664                 fprintf(stderr,"Unlinking: ");
2665                 printpCode(stderr, pc);
2666 #endif
2667                 if(pc->prev) 
2668                         pc->prev->next = pc->next;
2669                 if(pc->next)
2670                         pc->next->prev = pc->prev;
2671
2672 #if 0
2673                 /* RN: I believe this should be right here, but this did not
2674                  *     cure the bug I was hunting... */
2675                 /* must keep labels -- attach to following instruction */
2676                 if (isPCI(pc) && PCI(pc)->label && pc->next)
2677                 {
2678                   pCodeInstruction *pcnext = PCI(findNextInstruction (pc->next));
2679                   if (pcnext)
2680                   {
2681                     pBranchAppend (pcnext->label, PCI(pc)->label);
2682                   }
2683                 }
2684 #endif
2685                 pc->prev = pc->next = NULL;
2686         }
2687 }
2688
2689 /*-----------------------------------------------------------------*/
2690 /*-----------------------------------------------------------------*/
2691
2692 static void genericDestruct(pCode *pc)
2693 {
2694         
2695         unlinkpCode(pc);
2696         
2697         if(isPCI(pc)) {
2698         /* For instructions, tell the register (if there's one used)
2699                 * that it's no longer needed */
2700                 regs *reg = getRegFromInstruction(pc);
2701                 if(reg)
2702                         deleteSetItem (&(reg->reglives.usedpCodes),pc);
2703         }
2704         
2705         /* Instead of deleting the memory used by this pCode, mark
2706         * the object as bad so that if there's a pointer to this pCode
2707         * dangling around somewhere then (hopefully) when the type is
2708         * checked we'll catch it.
2709         */
2710         
2711         pc->type = PC_BAD;
2712         
2713         addpCode2pBlock(pb_dead_pcodes, pc);
2714         
2715         //free(pc);
2716         
2717 }
2718
2719
2720 /*-----------------------------------------------------------------*/
2721 /*  Copies the pCodeInstruction flow pointer from source pCode     */
2722 /*-----------------------------------------------------------------*/
2723 static void CopyFlow(pCodeInstruction *pcd, pCode *pcs) {
2724         pCode *p;
2725         pCodeFlow *pcflow = 0;
2726         for (p=pcs; p; p=p->prev) {
2727                 if (isPCI(p)) {
2728                         pcflow = PCI(p)->pcflow;
2729                         break;
2730                 }
2731                 if (isPCF(p)) {
2732                         pcflow = (pCodeFlow*)p;
2733                         break;
2734                 }
2735         }
2736         PCI(pcd)->pcflow = pcflow;
2737 }
2738
2739 /*-----------------------------------------------------------------*/
2740 /*  pCodeInsertAfter - splice in the pCode chain starting with pc2 */
2741 /*                     into the pCode chain containing pc1         */
2742 /*-----------------------------------------------------------------*/
2743 void pCodeInsertAfter(pCode *pc1, pCode *pc2)
2744 {
2745         
2746         if(!pc1 || !pc2)
2747                 return;
2748         
2749         pc2->next = pc1->next;
2750         if(pc1->next)
2751                 pc1->next->prev = pc2;
2752         
2753         pc2->pb = pc1->pb;
2754         pc2->prev = pc1;
2755         pc1->next = pc2;
2756         
2757         /* If this is an instrution type propogate the flow */
2758         if (isPCI(pc2))
2759                 CopyFlow(PCI(pc2),pc1);
2760 }
2761
2762 /*------------------------------------------------------------------*/
2763 /*  pCodeInsertBefore - splice in the pCode chain starting with pc2 */
2764 /*                      into the pCode chain containing pc1         */
2765 /*------------------------------------------------------------------*/
2766 void pCodeInsertBefore(pCode *pc1, pCode *pc2)
2767 {
2768         
2769         if(!pc1 || !pc2)
2770                 return;
2771         
2772         pc2->prev = pc1->prev;
2773         if(pc1->prev)
2774                 pc1->prev->next = pc2;
2775         
2776         pc2->pb = pc1->pb;
2777         pc2->next = pc1;
2778         pc1->prev = pc2;
2779         
2780         /* If this is an instrution type propogate the flow */
2781         if (isPCI(pc2))
2782                 CopyFlow(PCI(pc2),pc1);
2783 }
2784
2785 /*-----------------------------------------------------------------*/
2786 /* pCodeOpCopy - copy a pcode operator                             */
2787 /*-----------------------------------------------------------------*/
2788 pCodeOp *pCodeOpCopy(pCodeOp *pcop)
2789 {
2790         pCodeOp *pcopnew=NULL;
2791         
2792         if(!pcop)
2793                 return NULL;
2794         
2795         switch(pcop->type) { 
2796         case PO_CRY:
2797         case PO_BIT:
2798                 //DFPRINTF((stderr,"pCodeOpCopy bit\n"));
2799                 pcopnew = Safe_calloc(1,sizeof(pCodeOpRegBit) );
2800                 PCORB(pcopnew)->bit = PCORB(pcop)->bit;
2801                 PCORB(pcopnew)->inBitSpace = PCORB(pcop)->inBitSpace;
2802                 
2803                 break;
2804                 
2805         case PO_WILD:
2806                 /* Here we expand the wild card into the appropriate type: */
2807                 /* By recursively calling pCodeOpCopy */
2808                 //DFPRINTF((stderr,"pCodeOpCopy wild\n"));
2809                 if(PCOW(pcop)->matched)
2810                         pcopnew = pCodeOpCopy(PCOW(pcop)->matched);
2811                 else {
2812                         // Probably a label
2813                         pcopnew = pCodeOpCopy(PCOW(pcop)->subtype);
2814                         pcopnew->name = Safe_strdup(PCOW(pcop)->pcwb->vars[PCOW(pcop)->id]);
2815                         //DFPRINTF((stderr,"copied a wild op named %s\n",pcopnew->name));
2816                 }
2817                 
2818                 return pcopnew;
2819                 break;
2820                 
2821         case PO_LABEL:
2822                 //DFPRINTF((stderr,"pCodeOpCopy label\n"));
2823                 pcopnew = Safe_calloc(1,sizeof(pCodeOpLabel) );
2824                 PCOLAB(pcopnew)->key =  PCOLAB(pcop)->key;
2825                 break;
2826                 
2827         case PO_IMMEDIATE:
2828                 pcopnew = Safe_calloc(1,sizeof(pCodeOpImmd) );
2829                 PCOI(pcopnew)->index = PCOI(pcop)->index;
2830                 PCOI(pcopnew)->offset = PCOI(pcop)->offset;
2831                 PCOI(pcopnew)->_const = PCOI(pcop)->_const;
2832                 PCOI(pcopnew)->_function = PCOI(pcop)->_function;
2833                 break;
2834                 
2835         case PO_LITERAL:
2836                 //DFPRINTF((stderr,"pCodeOpCopy lit\n"));
2837                 pcopnew = Safe_calloc(1,sizeof(pCodeOpLit) );
2838                 PCOL(pcopnew)->lit = PCOL(pcop)->lit;
2839                 break;
2840                 
2841         case PO_GPR_BIT:
2842                 
2843                 pcopnew = newpCodeOpBit(pcop->name, PCORB(pcop)->bit,PCORB(pcop)->inBitSpace);
2844                 PCOR(pcopnew)->r = PCOR(pcop)->r;
2845                 PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
2846                 DFPRINTF((stderr," pCodeOpCopy Bit -register index\n"));
2847                 return pcopnew;
2848                 break;
2849                 
2850         case PO_GPR_POINTER:
2851         case PO_GPR_REGISTER:
2852         case PO_GPR_TEMP:
2853         case PO_FSR:
2854         case PO_INDF:
2855                 //DFPRINTF((stderr,"pCodeOpCopy GPR register\n"));
2856                 pcopnew = Safe_calloc(1,sizeof(pCodeOpReg) );
2857                 PCOR(pcopnew)->r = PCOR(pcop)->r;
2858                 PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
2859                 PCOR(pcopnew)->instance = PCOR(pcop)->instance;
2860                 DFPRINTF((stderr," register index %d\n", PCOR(pcop)->r->rIdx));
2861                 break;
2862                 
2863         case PO_DIR:
2864                 //fprintf(stderr,"pCodeOpCopy PO_DIR\n");
2865                 pcopnew = Safe_calloc(1,sizeof(pCodeOpReg) );
2866                 PCOR(pcopnew)->r = PCOR(pcop)->r;
2867                 PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
2868                 PCOR(pcopnew)->instance = PCOR(pcop)->instance;
2869                 break;
2870         case PO_STATUS:
2871                 DFPRINTF((stderr,"pCodeOpCopy PO_STATUS\n"));
2872         case PO_SFR_REGISTER:
2873         case PO_STR:
2874         case PO_NONE:
2875         case PO_W:
2876         case PO_INTCON:
2877         case PO_PCL:
2878         case PO_PCLATH:
2879                 
2880                 //DFPRINTF((stderr,"pCodeOpCopy register type %d\n", pcop->type));
2881                 pcopnew = Safe_calloc(1,sizeof(pCodeOp) );
2882                 
2883         }
2884         
2885         pcopnew->type = pcop->type;
2886         if(pcop->name)
2887                 pcopnew->name = Safe_strdup(pcop->name);
2888         else
2889                 pcopnew->name = NULL;
2890         
2891         return pcopnew;
2892 }
2893
2894 /*-----------------------------------------------------------------*/
2895 /* popCopyReg - copy a pcode operator                              */
2896 /*-----------------------------------------------------------------*/
2897 pCodeOp *popCopyReg(pCodeOpReg *pc)
2898 {
2899         pCodeOpReg *pcor;
2900         
2901         pcor = Safe_calloc(1,sizeof(pCodeOpReg) );
2902         pcor->pcop.type = pc->pcop.type;
2903         if(pc->pcop.name) {
2904                 if(!(pcor->pcop.name = Safe_strdup(pc->pcop.name)))
2905                         fprintf(stderr,"oops %s %d",__FILE__,__LINE__);
2906         } else
2907                 pcor->pcop.name = NULL;
2908         
2909         if (pcor->pcop.type == PO_IMMEDIATE){
2910                 PCOL(pcor)->lit = PCOL(pc)->lit;
2911         } else {
2912                 pcor->r = pc->r;
2913                 pcor->rIdx = pc->rIdx;
2914                 if (pcor->r)
2915                         pcor->r->wasUsed=1;
2916         }       
2917         //DEBUGpic14_emitcode ("; ***","%s  , copying %s, rIdx=%d",__FUNCTION__,pc->pcop.name,pc->rIdx);
2918         
2919         return PCOP(pcor);
2920 }
2921
2922 /*-----------------------------------------------------------------*/
2923 /* pCodeInstructionCopy - copy a pCodeInstructionCopy              */
2924 /*-----------------------------------------------------------------*/
2925 pCode *pCodeInstructionCopy(pCodeInstruction *pci,int invert)
2926 {
2927         pCodeInstruction *new_pci;
2928         
2929         if(invert)
2930                 new_pci = PCI(newpCode(pci->inverted_op,pci->pcop));
2931         else
2932                 new_pci = PCI(newpCode(pci->op,pci->pcop));
2933         
2934         new_pci->pc.pb = pci->pc.pb;
2935         new_pci->from = pci->from;
2936         new_pci->to   = pci->to;
2937         new_pci->label = pci->label;
2938         new_pci->pcflow = pci->pcflow;
2939         
2940         return PCODE(new_pci);
2941 }
2942
2943 /*-----------------------------------------------------------------*/
2944 /*-----------------------------------------------------------------*/
2945 void pCodeDeleteChain(pCode *f,pCode *t)
2946 {
2947         pCode *pc;
2948         
2949         while(f && f!=t) {
2950                 DFPRINTF((stderr,"delete pCode:\n"));
2951                 pc = f->next;
2952                 //f->print(stderr,f);
2953                 //f->delete(f);  this dumps core...
2954                 f = pc;
2955         }
2956 }
2957
2958 /*-----------------------------------------------------------------*/
2959 /*-----------------------------------------------------------------*/
2960 void pBlockRegs(FILE *of, pBlock *pb)
2961 {
2962         
2963         regs  *r;
2964         
2965         r = setFirstItem(pb->tregisters);
2966         while (r) {
2967                 r = setNextItem(pb->tregisters);
2968         }
2969 }
2970
2971
2972 /*-----------------------------------------------------------------*/
2973 /*-----------------------------------------------------------------*/
2974 char *get_op(pCodeOp *pcop,char *buffer, size_t size)
2975 {
2976         regs *r;
2977         static char b[50];
2978         char *s;
2979         int use_buffer = 1;    // copy the string to the passed buffer pointer
2980         
2981         if(!buffer) {
2982                 buffer = b;
2983                 size = sizeof(b);
2984                 use_buffer = 0;     // Don't bother copying the string to the buffer.
2985         } 
2986         
2987         if(pcop) {
2988                 switch(pcop->type) {
2989                 case PO_INDF:
2990                 case PO_FSR:
2991                         if(use_buffer) {
2992                                 SAFE_snprintf(&buffer,&size,"%s",PCOR(pcop)->r->name);
2993                                 return buffer;
2994                         }
2995                         //return PCOR(pcop)->r->name;
2996                         return pcop->name;
2997                         break;
2998                 case PO_GPR_TEMP:
2999                         if (PCOR(pcop)->r->type == REG_STK)
3000                                 r = typeRegWithIdx(PCOR(pcop)->r->rIdx,REG_STK,1);
3001                         else
3002                                 r = pic14_regWithIdx(PCOR(pcop)->r->rIdx);
3003                         
3004                         if(use_buffer) {
3005                                 SAFE_snprintf(&buffer,&size,"%s",r->name);
3006                                 return buffer;
3007                         }
3008                         
3009                         return r->name;
3010                         
3011                         
3012                 case PO_IMMEDIATE:
3013                         s = buffer;
3014                         if(PCOI(pcop)->_const) {
3015                                 
3016                                 if( PCOI(pcop)->offset >= 0 && PCOI(pcop)->offset<4) {
3017                                         switch(PCOI(pcop)->offset) {
3018                                         case 0:
3019                                                 SAFE_snprintf(&s,&size,"low (%s+%d)",pcop->name, PCOI(pcop)->index);
3020                                                 break;
3021                                         case 1:
3022                                                 SAFE_snprintf(&s,&size,"high (%s+%d)",pcop->name, PCOI(pcop)->index);
3023                                                 break;
3024                                         default:
3025                                                 fprintf (stderr, "PO_IMMEDIATE/_const/offset=%d\n", PCOI(pcop)->offset);
3026                                                 assert ( !"offset too large" );
3027                                                 SAFE_snprintf(&s,&size,"(((%s+%d) >> %d)&0xff)",
3028                                                         pcop->name,
3029                                                         PCOI(pcop)->index,
3030                                                         8 * PCOI(pcop)->offset );
3031                                         }
3032                                 } else
3033                                         SAFE_snprintf(&s,&size,"LOW (%s+%d)",pcop->name,PCOI(pcop)->index);
3034                         } else {
3035                                 if( !PCOI(pcop)->offset) { // && PCOI(pcc->pcop)->offset<4) {
3036                                         SAFE_snprintf(&s,&size,"(%s + %d)",
3037                                                 pcop->name,
3038                                                 PCOI(pcop)->index);
3039                                 } else {
3040                                         switch(PCOI(pcop)->offset) {
3041                                         case 0:
3042                                                 SAFE_snprintf(&s,&size,"(%s + %d)",pcop->name, PCOI(pcop)->index);
3043                                                 break;
3044                                         case 1:
3045                                                 SAFE_snprintf(&s,&size,"high (%s + %d)",pcop->name, PCOI(pcop)->index);
3046                                                 break;
3047                                         default:
3048                                                 fprintf (stderr, "PO_IMMEDIATE/mutable/offset=%d\n", PCOI(pcop)->offset);
3049                                                 assert ( !"offset too large" );
3050                                                 SAFE_snprintf(&s,&size,"((%s + %d) >> %d)&0xff",pcop->name, PCOI(pcop)->index, 8*PCOI(pcop)->offset);
3051                                                 break;
3052                                         }
3053                                 }
3054                         }
3055                         
3056                         return buffer;
3057                         
3058                 case PO_DIR:
3059                         s = buffer;
3060                         //size = sizeof(buffer);
3061                         if( PCOR(pcop)->instance) {
3062                                 SAFE_snprintf(&s,&size,"(%s + %d)",
3063                                         pcop->name,
3064                                         PCOR(pcop)->instance );
3065                                 //fprintf(stderr,"PO_DIR %s\n",buffer);
3066                         } else
3067                                 SAFE_snprintf(&s,&size,"%s",pcop->name);
3068                         return buffer;
3069                         
3070                 case PO_LABEL:
3071                         s = buffer;
3072                         if  (pcop->name) {
3073                                 if(PCOLAB(pcop)->offset == 1)
3074                                         SAFE_snprintf(&s,&size,"HIGH(%s)",pcop->name);
3075                                 else
3076                                         SAFE_snprintf(&s,&size,"%s",pcop->name);
3077                         }
3078                         return buffer;
3079                         
3080                 case PO_GPR_BIT:
3081                         if(PCOR(pcop)->r) {
3082                                 if(use_buffer) {
3083                                         SAFE_snprintf(&buffer,&size,"%s",PCOR(pcop)->r->name);
3084                                         return buffer;
3085                                 }
3086                                 return PCOR(pcop)->r->name;
3087                         }
3088                         
3089                         /* fall through to the default case */
3090                 default:
3091                         if(pcop->name) {
3092                                 if(use_buffer) {
3093                                         SAFE_snprintf(&buffer,&size,"%s",pcop->name);
3094                                         return buffer;
3095                                 }
3096                                 return pcop->name;
3097                         }
3098                 }
3099         }
3100
3101         printf("PIC port internal warning: (%s:%d) %s not found\n",
3102           __FUNCTION__,
3103           __LINE__,
3104           pCodeOpType(pcop));
3105
3106         return "NO operand";
3107
3108 }
3109
3110 /*-----------------------------------------------------------------*/
3111 /*-----------------------------------------------------------------*/
3112 static char *get_op_from_instruction( pCodeInstruction *pcc)
3113 {
3114         
3115         if(pcc)
3116                 return get_op(pcc->pcop,NULL,0);
3117         
3118         return ("ERROR Null: get_op_from_instruction");
3119         
3120 }
3121
3122 /*-----------------------------------------------------------------*/
3123 /*-----------------------------------------------------------------*/
3124 static void pCodeOpPrint(FILE *of, pCodeOp *pcop)
3125 {
3126         fprintf(of,"pcodeopprint- not implemented\n");
3127 }
3128
3129 /*-----------------------------------------------------------------*/
3130 /* pCode2str - convert a pCode instruction to string               */
3131 /*-----------------------------------------------------------------*/
3132 char *pCode2str(char *str, size_t size, pCode *pc)
3133 {
3134   char *s = str;
3135
3136   switch(pc->type) {
3137
3138   case PC_OPCODE:
3139
3140     SAFE_snprintf(&s,&size, "\t%s\t", PCI(pc)->mnemonic);
3141
3142     if( (PCI(pc)->num_ops >= 1) && (PCI(pc)->pcop)) {
3143
3144       if(PCI(pc)->isBitInst) {
3145         if(PCI(pc)->pcop->type == PO_GPR_BIT) {
3146           char *name = PCI(pc)->pcop->name;
3147           if (!name)
3148             name = PCOR(PCI(pc)->pcop)->r->name;
3149           if( (((pCodeOpRegBit *)(PCI(pc)->pcop))->inBitSpace) )
3150             SAFE_snprintf(&s,&size,"(%s >> 3), (%s & 7)", name, name);
3151           else
3152             SAFE_snprintf(&s,&size,"%s,%d", name, 
3153             (((pCodeOpRegBit *)(PCI(pc)->pcop))->bit)&7);
3154         } else if(PCI(pc)->pcop->type == PO_GPR_BIT) {
3155           SAFE_snprintf(&s,&size,"%s,%d", get_op_from_instruction(PCI(pc)),PCORB(PCI(pc)->pcop)->bit);
3156       } else
3157           SAFE_snprintf(&s,&size,"%s,0 ; ?bug", get_op_from_instruction(PCI(pc)));
3158         //PCI(pc)->pcop->t.bit );
3159       } else {
3160         if(PCI(pc)->pcop->type == PO_GPR_BIT) {
3161           if( PCI(pc)->num_ops == 2)
3162             SAFE_snprintf(&s,&size,"(%s >> 3),%c",get_op_from_instruction(PCI(pc)),((PCI(pc)->isModReg) ? 'F':'W'));
3163           else
3164             SAFE_snprintf(&s,&size,"(1 << (%s & 7))",get_op_from_instruction(PCI(pc)));
3165         } else {
3166           SAFE_snprintf(&s,&size,"%s",get_op_from_instruction(PCI(pc)));
3167           if( PCI(pc)->num_ops == 2)
3168             SAFE_snprintf(&s,&size,",%c", ( (PCI(pc)->isModReg) ? 'F':'W'));
3169         }
3170       }
3171     }
3172     break;
3173
3174   case PC_COMMENT:
3175     /* assuming that comment ends with a \n */
3176     SAFE_snprintf(&s,&size,";%s", ((pCodeComment *)pc)->comment);
3177     break;
3178
3179   case PC_INLINE:
3180     /* assuming that inline code ends with a \n */
3181     SAFE_snprintf(&s,&size,"%s", ((pCodeComment *)pc)->comment);
3182     break;
3183
3184   case PC_LABEL:
3185     SAFE_snprintf(&s,&size,";label=%s, key=%d\n",PCL(pc)->label,PCL(pc)->key);
3186     break;
3187   case PC_FUNCTION:
3188     SAFE_snprintf(&s,&size,";modname=%s,function=%s: id=%d\n",PCF(pc)->modname,PCF(pc)->fname);
3189     break;
3190   case PC_WILD:
3191     SAFE_snprintf(&s,&size,";\tWild opcode: id=%d\n",PCW(pc)->id);
3192     break;
3193   case PC_FLOW:
3194     SAFE_snprintf(&s,&size,";\t--FLOW change\n");
3195     break;
3196   case PC_CSOURCE:
3197     SAFE_snprintf(&s,&size,";#CSRC\t%s %d\n; %s\n", PCCS(pc)->file_name, PCCS(pc)->line_number, PCCS(pc)->line);
3198     break;
3199   case PC_ASMDIR:
3200     if(PCAD(pc)->directive) {
3201       SAFE_snprintf(&s,&size,"\t%s%s%s\n", PCAD(pc)->directive, PCAD(pc)->arg?"\t":"", PCAD(pc)->arg?PCAD(pc)->arg:"");
3202     } else if(PCAD(pc)->arg) {
3203       /* special case to handle inline labels without a tab */
3204       SAFE_snprintf(&s,&size,"%s\n", PCAD(pc)->arg);
3205     }
3206     break;
3207
3208   case PC_BAD:
3209     SAFE_snprintf(&s,&size,";A bad pCode is being used\n");
3210   }
3211
3212   return str;
3213 }
3214
3215 /*-----------------------------------------------------------------*/
3216 /* genericPrint - the contents of a pCode to a file                */
3217 /*-----------------------------------------------------------------*/
3218 static void genericPrint(FILE *of, pCode *pc)
3219 {
3220   if(!pc || !of)
3221     return;
3222
3223   switch(pc->type) {
3224   case PC_COMMENT:
3225     fprintf(of,";%s\n", ((pCodeComment *)pc)->comment);
3226     break;
3227
3228   case PC_INLINE:
3229     fprintf(of,"%s\n", ((pCodeComment *)pc)->comment);
3230     break;
3231
3232   case PC_OPCODE:
3233     // If the opcode has a label, print that first
3234     {
3235       char str[256];
3236       pCodeInstruction *pci = PCI(pc);
3237       pBranch *pbl = pci->label;
3238       while(pbl && pbl->pc) {
3239         if(pbl->pc->type == PC_LABEL)
3240           pCodePrintLabel(of, pbl->pc);
3241         pbl = pbl->next;
3242       }
3243
3244       if(pci->cline)
3245         genericPrint(of,PCODE(pci->cline));
3246
3247
3248       pCode2str(str, 256, pc);
3249
3250       fprintf(of,"%s",str);
3251
3252       /* Debug */
3253       if(debug_verbose) {
3254         pCodeOpReg *pcor = PCOR(pci->pcop);
3255         fprintf(of, "\t;id=%u,key=%03x",pc->id,pc->seq);
3256         if(pci->pcflow)
3257           fprintf(of,",flow seq=%03x",pci->pcflow->pc.seq);
3258         if (pcor && pcor->pcop.type==PO_GPR_TEMP && !pcor->r->isFixed)
3259           fprintf(of,",rIdx=r0x%X",pcor->rIdx);
3260       }
3261     }
3262 #if 0
3263     {
3264       pBranch *dpb = pc->to;   // debug
3265       while(dpb) {
3266         switch ( dpb->pc->type) {
3267         case PC_OPCODE:
3268           fprintf(of, "\t;%s", PCI(dpb->pc)->mnemonic);
3269           break;
3270         case PC_LABEL:
3271           fprintf(of, "\t;label %d", PCL(dpb->pc)->key);
3272           break;
3273         case PC_FUNCTION:
3274           fprintf(of, "\t;function %s", ( (PCF(dpb->pc)->fname) ? (PCF(dpb->pc)->fname) : "[END]"));
3275           break;
3276         case PC_FLOW:
3277           fprintf(of, "\t;flow");
3278           break;
3279         case PC_COMMENT:
3280         case PC_WILD:
3281           break;
3282         }
3283         dpb = dpb->next;
3284       }
3285     }
3286 #endif
3287     fprintf(of,"\n");
3288     break;
3289
3290   case PC_WILD:
3291     fprintf(of,";\tWild opcode: id=%d\n",PCW(pc)->id);
3292     if(PCW(pc)->pci.label)
3293       pCodePrintLabel(of, PCW(pc)->pci.label->pc);
3294     
3295     if(PCW(pc)->operand) {
3296       fprintf(of,";\toperand  ");
3297       pCodeOpPrint(of,PCW(pc)->operand );
3298     }
3299     break;
3300
3301   case PC_FLOW:
3302     if(debug_verbose) {
3303       fprintf(of,";<>Start of new flow, seq=0x%x",pc->seq);
3304       if(PCFL(pc)->ancestor)
3305         fprintf(of," ancestor = 0x%x", PCODE(PCFL(pc)->ancestor)->seq);
3306       fprintf(of,"\n");
3307     }
3308     break;
3309
3310   case PC_CSOURCE:
3311     fprintf(of,";#CSRC\t%s %d\n;  %s\n", PCCS(pc)->file_name, PCCS(pc)->line_number, PCCS(pc)->line);
3312     break;
3313
3314   case PC_ASMDIR:
3315     {
3316       pBranch *pbl = PCAD(pc)->pci.label;
3317       while(pbl && pbl->pc) {
3318         if(pbl->pc->type == PC_LABEL)
3319           pCodePrintLabel(of, pbl->pc);
3320         pbl = pbl->next;
3321       }
3322     }
3323     if(PCAD(pc)->directive) {
3324       fprintf(of, "\t%s%s%s\n", PCAD(pc)->directive, PCAD(pc)->arg?"\t":"", PCAD(pc)->arg?PCAD(pc)->arg:"");
3325     } else
3326     if(PCAD(pc)->arg) {
3327       /* special case to handle inline labels without tab */
3328       fprintf(of, "%s\n", PCAD(pc)->arg);
3329     }
3330     break;
3331
3332   case PC_LABEL:
3333   default:
3334     fprintf(of,"unknown pCode type %d\n",pc->type);
3335   }
3336 }
3337
3338 /*-----------------------------------------------------------------*/
3339 /* pCodePrintFunction - prints function begin/end                  */
3340 /*-----------------------------------------------------------------*/
3341
3342 static void pCodePrintFunction(FILE *of, pCode *pc)
3343 {
3344         
3345         if(!pc || !of)
3346                 return;
3347         
3348         if( ((pCodeFunction *)pc)->modname) 
3349                 fprintf(of,"F_%s",((pCodeFunction *)pc)->modname);
3350         
3351         if(PCF(pc)->fname) {
3352                 pBranch *exits = PCF(pc)->to;
3353                 int i=0;
3354                 fprintf(of,"%s\t;Function start\n",PCF(pc)->fname);
3355                 while(exits) {
3356                         i++;
3357                         exits = exits->next;
3358                 }
3359                 //if(i) i--;
3360                 fprintf(of,"; %d exit point%c\n",i, ((i==1) ? ' ':'s'));
3361                 
3362         }else {
3363                 if((PCF(pc)->from && 
3364                         PCF(pc)->from->pc->type == PC_FUNCTION &&
3365                         PCF(PCF(pc)->from->pc)->fname) )
3366                         fprintf(of,"; exit point of %s\n",PCF(PCF(pc)->from->pc)->fname);
3367                 else
3368                         fprintf(of,"; exit point [can't find entry point]\n");
3369         }
3370 }
3371 /*-----------------------------------------------------------------*/
3372 /* pCodePrintLabel - prints label                                  */
3373 /*-----------------------------------------------------------------*/
3374
3375 static void pCodePrintLabel(FILE *of, pCode *pc)
3376 {
3377         
3378         if(!pc || !of)
3379                 return;
3380         
3381         if(PCL(pc)->label) 
3382                 fprintf(of,"%s\n",PCL(pc)->label);
3383         else if (PCL(pc)->key >=0) 
3384                 fprintf(of,"_%05d_DS_:\n",PCL(pc)->key);
3385         else
3386                 fprintf(of,";wild card label: id=%d\n",-PCL(pc)->key);
3387         
3388 }
3389
3390 /*-----------------------------------------------------------------*/
3391 /* unlinkpCodeFromBranch - Search for a label in a pBranch and     */
3392 /*                         remove it if it is found.               */
3393 /*-----------------------------------------------------------------*/
3394 static void unlinkpCodeFromBranch(pCode *pcl , pCode *pc)
3395 {
3396   pBranch *b, *bprev;
3397
3398   bprev = NULL;
3399
3400   if(pcl->type == PC_OPCODE || pcl->type == PC_INLINE || pcl->type == PC_ASMDIR)
3401     b = PCI(pcl)->label;
3402   else {
3403     fprintf(stderr, "LINE %d. can't unlink from non opcode\n",__LINE__);
3404     exit(1);
3405   }
3406   
3407   //fprintf (stderr, "%s \n",__FUNCTION__);
3408   //pcl->print(stderr,pcl);
3409   //pc->print(stderr,pc);
3410   while(b) {
3411     if(b->pc == pc) {
3412       //fprintf (stderr, "found label\n");
3413       
3414       /* Found a label */
3415       if(bprev) {
3416         bprev->next = b->next;  /* Not first pCode in chain */
3417         free(b);
3418       } else {
3419         pc->destruct(pc);
3420         PCI(pcl)->label = b->next;   /* First pCode in chain */
3421         free(b);
3422       }
3423       return;  /* A label can't occur more than once */
3424     }
3425     bprev = b;
3426     b = b->next;
3427   }
3428 }
3429
3430 /*-----------------------------------------------------------------*/
3431 /*-----------------------------------------------------------------*/
3432 pBranch * pBranchAppend(pBranch *h, pBranch *n)
3433 {
3434         pBranch *b;
3435         
3436         if(!h)
3437                 return n;
3438         
3439         if(h == n)
3440                 return n;
3441         
3442         b = h;
3443         while(b->next)
3444                 b = b->next;
3445         
3446         b->next = n;
3447         
3448         return h;
3449         
3450 }  
3451 /*-----------------------------------------------------------------*/
3452 /* pBranchLink - given two pcodes, this function will link them    */
3453 /*               together through their pBranches                  */
3454 /*-----------------------------------------------------------------*/
3455 static void pBranchLink(pCodeFunction *f, pCodeFunction *t)
3456 {
3457         pBranch *b;
3458         
3459         // Declare a new branch object for the 'from' pCode.
3460         
3461         //_ALLOC(b,sizeof(pBranch));
3462         b = Safe_calloc(1,sizeof(pBranch));
3463         b->pc = PCODE(t);             // The link to the 'to' pCode.
3464         b->next = NULL;
3465         
3466         f->to = pBranchAppend(f->to,b);
3467         
3468         // Now do the same for the 'to' pCode.
3469         
3470         //_ALLOC(b,sizeof(pBranch));
3471         b = Safe_calloc(1,sizeof(pBranch));
3472         b->pc = PCODE(f);
3473         b->next = NULL;
3474         
3475         t->from = pBranchAppend(t->from,b);
3476         
3477 }
3478
3479 #if 0
3480 /*-----------------------------------------------------------------*/
3481 /* pBranchFind - find the pBranch in a pBranch chain that contains */
3482 /*               a pCode                                           */
3483 /*-----------------------------------------------------------------*/
3484 static pBranch *pBranchFind(pBranch *pb,pCode *pc)
3485 {
3486         while(pb) {
3487                 
3488                 if(pb->pc == pc)
3489                         return pb;
3490                 
3491                 pb = pb->next;
3492         }
3493         
3494         return NULL;
3495 }
3496
3497 /*-----------------------------------------------------------------*/
3498 /* pCodeUnlink - Unlink the given pCode from its pCode chain.      */
3499 /*-----------------------------------------------------------------*/
3500 static void pCodeUnlink(pCode *pc)
3501 {
3502         pBranch *pb1,*pb2;
3503         pCode *pc1;
3504         
3505         if(!pc->prev || !pc->next) {
3506                 fprintf(stderr,"unlinking bad pCode in %s:%d\n",__FILE__,__LINE__);
3507                 exit(1);
3508         }
3509         
3510         /* first remove the pCode from the chain */
3511         pc->prev->next = pc->next;
3512         pc->next->prev = pc->prev;
3513         
3514         /* Now for the hard part... */
3515         
3516         /* Remove the branches */
3517         
3518         pb1 = pc->from;
3519         while(pb1) {
3520         pc1 = pb1->pc;    /* Get the pCode that branches to the
3521         * one we're unlinking */
3522         
3523         /* search for the link back to this pCode (the one we're
3524         * unlinking) */
3525         if(pb2 = pBranchFind(pc1->to,pc)) {
3526                 pb2->pc = pc->to->pc;  // make the replacement
3527                 
3528                                                            /* if the pCode we're unlinking contains multiple 'to'
3529                                                            * branches (e.g. this a skip instruction) then we need
3530                 * to copy these extra branches to the chain. */
3531                 if(pc->to->next)
3532                         pBranchAppend(pb2, pc->to->next);
3533         }
3534         
3535         pb1 = pb1->next;
3536         }
3537         
3538         
3539 }
3540 #endif
3541 /*-----------------------------------------------------------------*/
3542 /*-----------------------------------------------------------------*/
3543 #if 0
3544 static void genericAnalyze(pCode *pc)
3545 {
3546         switch(pc->type) {
3547         case PC_WILD:
3548         case PC_COMMENT:
3549                 return;
3550         case PC_LABEL:
3551         case PC_FUNCTION:
3552         case PC_OPCODE:
3553                 {
3554                         // Go through the pCodes that are in pCode chain and link
3555                         // them together through the pBranches. Note, the pCodes
3556                         // are linked together as a contiguous stream like the 
3557                         // assembly source code lines. The linking here mimics this
3558                         // except that comments are not linked in.
3559                         // 
3560                         pCode *npc = pc->next;
3561                         while(npc) {
3562                                 if(npc->type == PC_OPCODE || npc->type == PC_LABEL) {
3563                                         pBranchLink(pc,npc);
3564                                         return;
3565                                 } else
3566                                         npc = npc->next;
3567                         }
3568                         /* reached the end of the pcode chain without finding
3569                         * an instruction we could link to. */
3570                 }
3571                 break;
3572         case PC_FLOW:
3573                 fprintf(stderr,"analyze PC_FLOW\n");
3574                 
3575                 return;
3576         case PC_BAD:
3577                 fprintf(stderr,";A bad pCode is being used\n");
3578                 
3579         }
3580 }
3581 #endif
3582
3583 /*-----------------------------------------------------------------*/
3584 /*-----------------------------------------------------------------*/
3585 int compareLabel(pCode *pc, pCodeOpLabel *pcop_label)
3586 {
3587   pBranch *pbr;
3588   
3589   if(pc->type == PC_LABEL) {
3590     if( ((pCodeLabel *)pc)->key ==  pcop_label->key)
3591       return TRUE;
3592   }
3593   if(pc->type == PC_OPCODE || pc->type == PC_ASMDIR) {
3594     pbr = PCI(pc)->label;
3595     while(pbr) {
3596       if(pbr->pc->type == PC_LABEL) {
3597         if( ((pCodeLabel *)(pbr->pc))->key ==  pcop_label->key)
3598           return TRUE;
3599       }
3600       pbr = pbr->next;
3601     }
3602   }
3603   
3604   return FALSE;
3605 }
3606
3607 /*-----------------------------------------------------------------*/
3608 /*-----------------------------------------------------------------*/
3609 int checkLabel(pCode *pc)
3610 {
3611         pBranch *pbr;
3612         
3613         if(pc && isPCI(pc)) {
3614                 pbr = PCI(pc)->label;
3615                 while(pbr) {
3616                         if(isPCL(pbr->pc) && (PCL(pbr->pc)->key >= 0))
3617                                 return TRUE;
3618                         
3619                         pbr = pbr->next;
3620                 }
3621         }
3622         
3623         return FALSE;
3624 }
3625
3626 /*-----------------------------------------------------------------*/
3627 /* findLabelinpBlock - Search the pCode for a particular label     */
3628 /*-----------------------------------------------------------------*/
3629 pCode * findLabelinpBlock(pBlock *pb,pCodeOpLabel *pcop_label)
3630 {
3631         pCode  *pc;
3632         
3633         if(!pb)
3634                 return NULL;
3635         
3636         for(pc = pb->pcHead; pc; pc = pc->next) 
3637                 if(compareLabel(pc,pcop_label))
3638                         return pc;
3639                 
3640                 return NULL;
3641 }
3642
3643 /*-----------------------------------------------------------------*/
3644 /* findLabel - Search the pCode for a particular label             */
3645 /*-----------------------------------------------------------------*/
3646 pCode * findLabel(pCodeOpLabel *pcop_label)
3647 {
3648         pBlock *pb;
3649         pCode  *pc;
3650         
3651         if(!the_pFile)
3652                 return NULL;
3653         
3654         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
3655                 if( (pc = findLabelinpBlock(pb,pcop_label)) != NULL)
3656                         return pc;
3657         }
3658         
3659         fprintf(stderr,"Couldn't find label %s\n", pcop_label->pcop.name);
3660         return NULL;
3661 }
3662
3663 /*-----------------------------------------------------------------*/
3664 /* findNextpCode - given a pCode, find the next of type 'pct'      */
3665 /*                 in the linked list                              */
3666 /*-----------------------------------------------------------------*/
3667 pCode * findNextpCode(pCode *pc, PC_TYPE pct)
3668 {
3669         
3670         while(pc) {
3671                 if(pc->type == pct)
3672                         return pc;
3673                 
3674                 pc = pc->next;
3675         }
3676         
3677         return NULL;
3678 }
3679
3680 /*-----------------------------------------------------------------*/
3681 /* findPrevpCode - given a pCode, find the previous of type 'pct'  */
3682 /*                 in the linked list                              */
3683 /*-----------------------------------------------------------------*/
3684 pCode * findPrevpCode(pCode *pc, PC_TYPE pct)
3685 {
3686         
3687         while(pc) {
3688                 if(pc->type == pct) {
3689                         /*
3690                         static unsigned int stop;
3691                         if (pc->id == 524)
3692                                 stop++; // Place break point here
3693                         */
3694                         return pc;
3695                 }
3696                 
3697                 pc = pc->prev;
3698         }
3699         
3700         return NULL;
3701 }
3702
3703 /*-----------------------------------------------------------------*/
3704 /* findNextInstruction - given a pCode, find the next instruction  */
3705 /*                       in the linked list                        */
3706 /*-----------------------------------------------------------------*/
3707 pCode * findNextInstruction(pCode *pci)
3708 {
3709   pCode *pc = pci;
3710
3711   while(pc) {
3712   if((pc->type == PC_OPCODE)
3713     || (pc->type == PC_WILD)
3714     || (pc->type == PC_ASMDIR))
3715       return pc;
3716
3717 #ifdef PCODE_DEBUG
3718     fprintf(stderr,"findNextInstruction:  ");
3719     printpCode(stderr, pc);
3720 #endif
3721     pc = pc->next;
3722   }
3723
3724   //fprintf(stderr,"Couldn't find instruction\n");
3725   return NULL;
3726 }
3727
3728 /*-----------------------------------------------------------------*/
3729 /* findNextInstruction - given a pCode, find the next instruction  */
3730 /*                       in the linked list                        */
3731 /*-----------------------------------------------------------------*/
3732 pCode * findPrevInstruction(pCode *pci)
3733 {
3734   pCode *pc = pci;
3735
3736   while(pc) {
3737
3738     if((pc->type == PC_OPCODE)
3739       || (pc->type == PC_WILD)
3740       || (pc->type == PC_ASMDIR))
3741       return pc;
3742       
3743
3744 #ifdef PCODE_DEBUG
3745     fprintf(stderr,"pic16_findPrevInstruction:  ");
3746     printpCode(stderr, pc);
3747 #endif
3748     pc = pc->prev;
3749   }
3750
3751   //fprintf(stderr,"Couldn't find instruction\n");
3752   return NULL;
3753 }
3754
3755 /*-----------------------------------------------------------------*/
3756 /* findFunctionEnd - given a pCode find the end of the function    */
3757 /*                   that contains it                              */
3758 /*-----------------------------------------------------------------*/
3759 pCode * findFunctionEnd(pCode *pc)
3760 {
3761         while(pc) {
3762                 if(pc->type == PC_FUNCTION &&  !(PCF(pc)->fname))
3763                         return pc;
3764                 
3765                 pc = pc->next;
3766         }
3767         
3768         fprintf(stderr,"Couldn't find function end\n");
3769         return NULL;
3770 }
3771
3772 #if 0
3773 /*-----------------------------------------------------------------*/
3774 /* AnalyzeLabel - if the pCode is a label, then merge it with the  */
3775 /*                instruction with which it is associated.         */
3776 /*-----------------------------------------------------------------*/
3777 static void AnalyzeLabel(pCode *pc)
3778 {
3779         
3780         pCodeUnlink(pc);
3781         
3782 }
3783 #endif
3784
3785 #if 0
3786 static void AnalyzeGOTO(pCode *pc)
3787 {
3788         
3789         pBranchLink(pc,findLabel( (pCodeOpLabel *) (PCI(pc)->pcop) ));
3790         
3791 }
3792
3793 static void AnalyzeSKIP(pCode *pc)
3794 {
3795         
3796         pBranchLink(pc,findNextInstruction(pc->next));
3797         pBranchLink(pc,findNextInstruction(pc->next->next));
3798         
3799 }
3800
3801 static void AnalyzeRETURN(pCode *pc)
3802 {
3803         
3804         //  branch_link(pc,findFunctionEnd(pc->next));
3805         
3806 }
3807
3808 #endif
3809
3810 /*-----------------------------------------------------------------*/
3811 /*-----------------------------------------------------------------*/
3812 regs * getRegFromInstruction(pCode *pc)
3813 {
3814         regs *r;
3815         if(!pc                   || 
3816                 !isPCI(pc)            ||
3817                 !PCI(pc)->pcop        ||
3818                 PCI(pc)->num_ops == 0 )
3819                 return NULL;
3820         
3821         switch(PCI(pc)->pcop->type) {
3822         case PO_INDF:
3823         case PO_FSR:
3824                 return PCOR(PCI(pc)->pcop)->r;
3825
3826         case PO_BIT:
3827         case PO_GPR_TEMP:
3828                 return PCOR(PCI(pc)->pcop)->r;
3829                 
3830         case PO_IMMEDIATE:
3831                 r = PCOI(PCI(pc)->pcop)->r;
3832                 if (r)
3833                         return r;
3834                 return dirregWithName(PCI(pc)->pcop->name);
3835                 
3836         case PO_GPR_BIT:
3837                 r = PCOR(PCI(pc)->pcop)->r;
3838                 if (r)
3839                         return r;
3840                 return dirregWithName(PCI(pc)->pcop->name);
3841                 
3842         case PO_GPR_REGISTER:
3843         case PO_DIR:
3844                 r = PCOR(PCI(pc)->pcop)->r;
3845                 if (r)
3846                         return r;
3847                 return dirregWithName(PCI(pc)->pcop->name);
3848         case PO_LITERAL:
3849                 break;
3850                 
3851         default:
3852                 break;
3853         }
3854         
3855         return NULL;
3856         
3857 }
3858
3859 /*-----------------------------------------------------------------*/
3860 /*-----------------------------------------------------------------*/
3861
3862 void AnalyzepBlock(pBlock *pb)
3863 {
3864         pCode *pc;
3865         
3866         if(!pb)
3867                 return;
3868         
3869                 /* Find all of the registers used in this pBlock 
3870                 * by looking at each instruction and examining it's
3871                 * operands
3872         */
3873         for(pc = pb->pcHead; pc; pc = pc->next) {
3874                 
3875                 /* Is this an instruction with operands? */
3876                 if(pc->type == PC_OPCODE && PCI(pc)->pcop) {
3877                         
3878                         if((PCI(pc)->pcop->type == PO_GPR_TEMP) 
3879                                 || ((PCI(pc)->pcop->type == PO_GPR_BIT) && PCOR(PCI(pc)->pcop)->r && (PCOR(PCI(pc)->pcop)->r->pc_type == PO_GPR_TEMP))) {
3880                                 
3881                                 /* Loop through all of the registers declared so far in
3882                                 this block and see if we find this one there */
3883                                 
3884                                 regs *r = setFirstItem(pb->tregisters);
3885                                 
3886                                 while(r) {
3887                                         if((r->rIdx == PCOR(PCI(pc)->pcop)->r->rIdx) && (r->type == PCOR(PCI(pc)->pcop)->r->type)) {
3888                                                 PCOR(PCI(pc)->pcop)->r = r;
3889                                                 break;
3890                                         }
3891                                         r = setNextItem(pb->tregisters);
3892                                 }
3893                                 
3894                                 if(!r) {
3895                                         /* register wasn't found */
3896                                         //r = Safe_calloc(1, sizeof(regs));
3897                                         //memcpy(r,PCOR(PCI(pc)->pcop)->r, sizeof(regs));
3898                                         //addSet(&pb->tregisters, r);
3899                                         addSet(&pb->tregisters, PCOR(PCI(pc)->pcop)->r);
3900                                         //PCOR(PCI(pc)->pcop)->r = r;
3901                                         //fprintf(stderr,"added register to pblock: reg %d\n",r->rIdx);
3902                                         }/* else 
3903                                          fprintf(stderr,"found register in pblock: reg %d\n",r->rIdx);
3904                                 */
3905                         }
3906                         if(PCI(pc)->pcop->type == PO_GPR_REGISTER) {
3907                                 if(PCOR(PCI(pc)->pcop)->r) {
3908                                         pic14_allocWithIdx (PCOR(PCI(pc)->pcop)->r->rIdx);
3909                                         DFPRINTF((stderr,"found register in pblock: reg 0x%x\n",PCOR(PCI(pc)->pcop)->r->rIdx));
3910                                 } else {
3911                                         if(PCI(pc)->pcop->name)
3912                                                 fprintf(stderr,"ERROR: %s is a NULL register\n",PCI(pc)->pcop->name );
3913                                         else
3914                                                 fprintf(stderr,"ERROR: NULL register\n");
3915                                 }
3916                         }
3917                 }
3918                 
3919                 
3920         }
3921 }
3922
3923 /*-----------------------------------------------------------------*/
3924 /* */
3925 /*-----------------------------------------------------------------*/
3926 void InsertpFlow(pCode *pc, pCode **pflow)
3927 {
3928         if(*pflow)
3929                 PCFL(*pflow)->end = pc;
3930         
3931         if(!pc || !pc->next)
3932                 return;
3933         
3934         *pflow = newpCodeFlow();
3935         pCodeInsertAfter(pc, *pflow);
3936 }
3937
3938 /*-----------------------------------------------------------------*/
3939 /* BuildFlow(pBlock *pb) - examine the code in a pBlock and build  */
3940 /*                         the flow blocks.                        */
3941 /*
3942 * BuildFlow inserts pCodeFlow objects into the pCode chain at each
3943 * point the instruction flow changes. 
3944 */
3945 /*-----------------------------------------------------------------*/
3946 void BuildFlow(pBlock *pb)
3947 {
3948         pCode *pc;
3949         pCode *last_pci=NULL;
3950         pCode *pflow=NULL;
3951         int seq = 0;
3952         
3953         if(!pb)
3954                 return;
3955         
3956         //fprintf (stderr,"build flow start seq %d  ",GpcFlowSeq);
3957         /* Insert a pCodeFlow object at the beginning of a pBlock */
3958         
3959         InsertpFlow(pb->pcHead, &pflow);
3960         
3961         //pflow = newpCodeFlow();    /* Create a new Flow object */
3962         //pflow->next = pb->pcHead;  /* Make the current head the next object */
3963         //pb->pcHead->prev = pflow;  /* let the current head point back to the flow object */
3964         //pb->pcHead = pflow;        /* Make the Flow object the head */
3965         //pflow->pb = pb;
3966         
3967         for( pc = findNextInstruction(pb->pcHead);
3968         pc != NULL;
3969         pc=findNextInstruction(pc)) { 
3970                 
3971                 pc->seq = seq++;
3972                 PCI(pc)->pcflow = PCFL(pflow);
3973                 
3974                 //fprintf(stderr," build: ");
3975                 //pflow->print(stderr,pflow);
3976                 
3977                 if( PCI(pc)->isSkip) {
3978                         
3979                 /* The two instructions immediately following this one 
3980                         * mark the beginning of a new flow segment */
3981                         
3982                         while(pc && PCI(pc)->isSkip) {
3983                                 
3984                                 PCI(pc)->pcflow = PCFL(pflow);
3985                                 pc->seq = seq-1;
3986                                 seq = 1;
3987                                 
3988                                 InsertpFlow(pc, &pflow);
3989                                 pc=findNextInstruction(pc->next);
3990                         }
3991                         
3992                         seq = 0;
3993                         
3994                         if(!pc)
3995                                 break;
3996                         
3997                         PCI(pc)->pcflow = PCFL(pflow);
3998                         pc->seq = 0;
3999                         InsertpFlow(pc, &pflow);
4000                         
4001                 } else if ( PCI(pc)->isBranch && !checkLabel(findNextInstruction(pc->next)))  {
4002                         
4003                         InsertpFlow(pc, &pflow);
4004                         seq = 0;
4005                         
4006                 } else if (checkLabel(pc)) { 
4007                         
4008                 /* This instruction marks the beginning of a
4009                         * new flow segment */
4010                         
4011                         pc->seq = 0;
4012                         seq = 1;
4013                         
4014                         /* If the previous pCode is not a flow object, then 
4015                         * insert a new flow object. (This check prevents 
4016                         * two consecutive flow objects from being insert in
4017                         * the case where a skip instruction preceeds an
4018                         * instruction containing a label.) */
4019                         
4020                         if(last_pci && (PCI(last_pci)->pcflow == PCFL(pflow)))
4021                                 InsertpFlow(findPrevInstruction(pc->prev), &pflow);
4022                         
4023                         PCI(pc)->pcflow = PCFL(pflow);
4024                         
4025                 }
4026                 last_pci = pc;
4027                 pc = pc->next;
4028         }
4029         
4030         //fprintf (stderr,",end seq %d",GpcFlowSeq);
4031         if(pflow)
4032                 PCFL(pflow)->end = pb->pcTail;
4033 }
4034
4035 /*-------------------------------------------------------------------*/
4036 /* unBuildFlow(pBlock *pb) - examine the code in a pBlock and build  */
4037 /*                           the flow blocks.                        */
4038 /*
4039 * unBuildFlow removes pCodeFlow objects from a pCode chain
4040 */
4041 /*-----------------------------------------------------------------*/
4042 void unBuildFlow(pBlock *pb)
4043 {
4044         pCode *pc,*pcnext;
4045         
4046         if(!pb)
4047                 return;
4048         
4049         pc = pb->pcHead;
4050         
4051         while(pc) {
4052                 pcnext = pc->next;
4053                 
4054                 if(isPCI(pc)) {
4055                         
4056                         pc->seq = 0;
4057                         if(PCI(pc)->pcflow) {
4058                                 //free(PCI(pc)->pcflow);
4059                                 PCI(pc)->pcflow = NULL;
4060                         }
4061                         
4062                 } else if(isPCFL(pc) )
4063                         pc->destruct(pc);
4064                 
4065                 pc = pcnext;
4066         }
4067         
4068         
4069 }
4070
4071 /*-----------------------------------------------------------------*/
4072 /*-----------------------------------------------------------------*/
4073 void dumpCond(int cond)
4074 {
4075         
4076         static char *pcc_str[] = {
4077                 //"PCC_NONE",
4078                 "PCC_REGISTER",
4079                         "PCC_C",
4080                         "PCC_Z",
4081                         "PCC_DC",
4082                         "PCC_W",
4083                         "PCC_EXAMINE_PCOP",
4084                         "PCC_REG_BANK0",
4085                         "PCC_REG_BANK1",
4086                         "PCC_REG_BANK2",
4087                         "PCC_REG_BANK3"
4088         };
4089         
4090         int ncond = sizeof(pcc_str) / sizeof(char *);
4091         int i,j;
4092         
4093         fprintf(stderr, "0x%04X\n",cond);
4094         
4095         for(i=0,j=1; i<ncond; i++, j<<=1)
4096                 if(cond & j)
4097                         fprintf(stderr, "  %s\n",pcc_str[i]);
4098                 
4099 }
4100
4101 /*-----------------------------------------------------------------*/
4102 /*-----------------------------------------------------------------*/
4103 void FlowStats(pCodeFlow *pcflow)
4104 {
4105         
4106         pCode *pc;
4107         
4108         if(!isPCFL(pcflow))
4109                 return;
4110         
4111         fprintf(stderr, " FlowStats - flow block (seq=%d)\n", pcflow->pc.seq);
4112         
4113         pc = findNextpCode(PCODE(pcflow), PC_OPCODE); 
4114         
4115         if(!pc) {
4116                 fprintf(stderr, " FlowStats - empty flow (seq=%d)\n", pcflow->pc.seq);
4117                 return;
4118         }
4119         
4120         
4121         fprintf(stderr, "  FlowStats inCond: ");
4122         dumpCond(pcflow->inCond);
4123         fprintf(stderr, "  FlowStats outCond: ");
4124         dumpCond(pcflow->outCond);
4125         
4126 }
4127
4128 /*-----------------------------------------------------------------*
4129 * int isBankInstruction(pCode *pc) - examine the pCode *pc to determine
4130 *    if it affects the banking bits. 
4131
4132 * return: -1 == Banking bits are unaffected by this pCode.
4133 *
4134 * return: > 0 == Banking bits are affected.
4135 *
4136 *  If the banking bits are affected, then the returned value describes
4137 * which bits are affected and how they're affected. The lower half
4138 * of the integer maps to the bits that are affected, the upper half
4139 * to whether they're set or cleared.
4140 *
4141 *-----------------------------------------------------------------*/
4142 /*
4143 #define SET_BANK_BIT (1 << 16)
4144 #define CLR_BANK_BIT 0
4145
4146 static int isBankInstruction(pCode *pc)
4147 {
4148         regs *reg;
4149         int bank = -1;
4150         
4151         if(!isPCI(pc))
4152                 return -1;
4153         
4154         if( ( (reg = getRegFromInstruction(pc)) != NULL) && isSTATUS_REG(reg)) {
4155                 
4156                 // Check to see if the register banks are changing
4157                 if(PCI(pc)->isModReg) {
4158                         
4159                         pCodeOp *pcop = PCI(pc)->pcop;
4160                         switch(PCI(pc)->op) {
4161                                 
4162                         case POC_BSF:
4163                                 if(PCORB(pcop)->bit == PIC_RP0_BIT) {
4164                                         //fprintf(stderr, "  isBankInstruction - Set RP0\n");
4165                                         return  SET_BANK_BIT | PIC_RP0_BIT;
4166                                 }
4167                                 
4168                                 if(PCORB(pcop)->bit == PIC_RP1_BIT) {
4169                                         //fprintf(stderr, "  isBankInstruction - Set RP1\n");
4170                                         return  CLR_BANK_BIT | PIC_RP0_BIT;
4171                                 }
4172                                 break;
4173                                 
4174                         case POC_BCF:
4175                                 if(PCORB(pcop)->bit == PIC_RP0_BIT) {
4176                                         //fprintf(stderr, "  isBankInstruction - Clr RP0\n");
4177                                         return  CLR_BANK_BIT | PIC_RP1_BIT;
4178                                 }
4179                                 if(PCORB(pcop)->bit == PIC_RP1_BIT) {
4180                                         //fprintf(stderr, "  isBankInstruction - Clr RP1\n");
4181                                         return  CLR_BANK_BIT | PIC_RP1_BIT;
4182                                 }
4183                                 break;
4184                         default:
4185                                 //fprintf(stderr, "  isBankInstruction - Status register is getting Modified by:\n");
4186                                 //genericPrint(stderr, pc);
4187                                 ;
4188                         }
4189                 }
4190                 
4191                                 }
4192                                 
4193         return bank;
4194 }
4195 */
4196
4197 /*-----------------------------------------------------------------*/
4198 /*-----------------------------------------------------------------*/
4199 /*
4200 static void FillFlow(pCodeFlow *pcflow)
4201 {
4202         pCode *pc;
4203         int cur_bank;
4204         
4205         if(!isPCFL(pcflow))
4206                 return;
4207         
4208         //  fprintf(stderr, " FillFlow - flow block (seq=%d)\n", pcflow->pc.seq);
4209         
4210         pc = findNextpCode(PCODE(pcflow), PC_OPCODE); 
4211         
4212         if(!pc) {
4213                 //fprintf(stderr, " FillFlow - empty flow (seq=%d)\n", pcflow->pc.seq);
4214                 return;
4215         }
4216         
4217         cur_bank = -1;
4218         
4219         do {
4220                 isBankInstruction(pc);
4221                 pc = pc->next;
4222         } while (pc && (pc != pcflow->end) && !isPCFL(pc));
4223         / *
4224                 if(!pc ) {
4225                         fprintf(stderr, "  FillFlow - Bad end of flow\n");
4226                 } else {
4227                         fprintf(stderr, "  FillFlow - Ending flow with\n  ");
4228                         pc->print(stderr,pc);
4229                 }
4230                 
4231                 fprintf(stderr, "  FillFlow inCond: ");
4232                 dumpCond(pcflow->inCond);
4233                 fprintf(stderr, "  FillFlow outCond: ");
4234                 dumpCond(pcflow->outCond);
4235                 * /
4236 }
4237 */
4238
4239 /*-----------------------------------------------------------------*/
4240 /*-----------------------------------------------------------------*/
4241 void LinkFlow_pCode(pCodeInstruction *from, pCodeInstruction *to)
4242 {
4243         pCodeFlowLink *fromLink, *toLink;
4244         
4245         if(!from || !to || !to->pcflow || !from->pcflow)
4246                 return;
4247         
4248         fromLink = newpCodeFlowLink(from->pcflow);
4249         toLink   = newpCodeFlowLink(to->pcflow);
4250         
4251         addSetIfnotP(&(from->pcflow->to), toLink);   //to->pcflow);
4252         addSetIfnotP(&(to->pcflow->from), fromLink); //from->pcflow);
4253         
4254 }
4255
4256 /*-----------------------------------------------------------------*
4257 * void LinkFlow(pBlock *pb)
4258 *
4259 * In BuildFlow, the PIC code has been partitioned into contiguous
4260 * non-branching segments. In LinkFlow, we determine the execution
4261 * order of these segments. For example, if one of the segments ends
4262 * with a skip, then we know that there are two possible flow segments
4263 * to which control may be passed.
4264 *-----------------------------------------------------------------*/
4265 void LinkFlow(pBlock *pb)
4266 {
4267         pCode *pc=NULL;
4268         pCode *pcflow;
4269         pCode *pct;
4270         
4271         //fprintf(stderr,"linkflow \n");
4272         
4273         for( pcflow = findNextpCode(pb->pcHead, PC_FLOW); 
4274         pcflow != NULL;
4275         pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4276                 
4277                 if(!isPCFL(pcflow))
4278                         fprintf(stderr, "LinkFlow - pcflow is not a flow object ");
4279                 
4280                 //fprintf(stderr," link: ");
4281                 //pcflow->print(stderr,pcflow);
4282                 
4283                 //FillFlow(PCFL(pcflow));
4284                 
4285                 pc = PCFL(pcflow)->end;
4286                 
4287                 //fprintf(stderr, "LinkFlow - flow block (seq=%d) ", pcflow->seq);
4288                 if(isPCI_SKIP(pc)) {
4289                         //fprintf(stderr, "ends with skip\n");
4290                         //pc->print(stderr,pc);
4291                         pct=findNextInstruction(pc->next);
4292                         LinkFlow_pCode(PCI(pc),PCI(pct));
4293                         pct=findNextInstruction(pct->next);
4294                         LinkFlow_pCode(PCI(pc),PCI(pct));
4295                         continue;
4296                 }
4297                 
4298                 if(isPCI_BRANCH(pc)) {
4299                         pCodeOpLabel *pcol = PCOLAB(PCI(pc)->pcop);
4300                         
4301                         //fprintf(stderr, "ends with branch\n  ");
4302                         //pc->print(stderr,pc);
4303                         
4304                         if(!(pcol && isPCOLAB(pcol))) {
4305                                 if((PCI(pc)->op != POC_RETLW) && (PCI(pc)->op != POC_RETURN) && (PCI(pc)->op != POC_CALL) && (PCI(pc)->op != POC_RETFIE) ) {
4306                                         pc->print(stderr,pc);
4307                                         fprintf(stderr, "ERROR: %s, branch instruction doesn't have label\n",__FUNCTION__);
4308                                 }
4309                                 continue;
4310                         }
4311                         
4312                         if( (pct = findLabelinpBlock(pb,pcol)) != NULL)
4313                                 LinkFlow_pCode(PCI(pc),PCI(pct));
4314                         else
4315                                 fprintf(stderr, "ERROR: %s, couldn't find label. key=%d,lab=%s\n",
4316                                 __FUNCTION__,pcol->key,((PCOP(pcol)->name)?PCOP(pcol)->name:"-"));
4317                         //fprintf(stderr,"newpCodeOpLabel: key=%d, name=%s\n",key,((s)?s:""));
4318                         
4319                         continue;
4320                 }
4321                 
4322                 if(isPCI(pc)) {
4323                         //fprintf(stderr, "ends with non-branching instruction:\n");
4324                         //pc->print(stderr,pc);
4325                         
4326                         LinkFlow_pCode(PCI(pc),PCI(findNextInstruction(pc->next)));
4327                         
4328                         continue;
4329                 }
4330                 
4331                 if(pc) {
4332                         //fprintf(stderr, "ends with unknown\n");
4333                         //pc->print(stderr,pc);
4334                         continue;
4335                 }
4336                 
4337                 //fprintf(stderr, "ends with nothing: ERROR\n");
4338                 
4339         }
4340 }
4341 /*-----------------------------------------------------------------*/
4342 /*-----------------------------------------------------------------*/
4343
4344 /*-----------------------------------------------------------------*/
4345 /*-----------------------------------------------------------------*/
4346 int isPCinFlow(pCode *pc, pCode *pcflow)
4347 {
4348         
4349         if(!pc || !pcflow)
4350                 return 0;
4351         
4352         if(!isPCI(pc) || !PCI(pc)->pcflow || !isPCFL(pcflow) )
4353                 return 0;
4354         
4355         if( PCI(pc)->pcflow->pc.seq == pcflow->seq)
4356                 return 1;
4357         
4358         return 0;
4359 }
4360
4361 /*-----------------------------------------------------------------*/
4362 /*-----------------------------------------------------------------*/
4363 /*
4364 static void BanksUsedFlow2(pCode *pcflow)
4365 {
4366         pCode *pc=NULL;
4367         
4368         int bank = -1;
4369         bool RegUsed = 0;
4370         
4371         regs *reg;
4372         
4373         if(!isPCFL(pcflow)) {
4374                 fprintf(stderr, "BanksUsed - pcflow is not a flow object ");
4375                 return;
4376         }
4377         
4378         pc = findNextInstruction(pcflow->next);
4379         
4380         PCFL(pcflow)->lastBank = -1;
4381         
4382         while(isPCinFlow(pc,pcflow)) {
4383                 
4384                 int bank_selected = isBankInstruction(pc);
4385                 
4386                 //if(PCI(pc)->pcflow) 
4387                 //fprintf(stderr,"BanksUsedFlow2, looking at seq %d\n",PCI(pc)->pcflow->pc.seq);
4388                 
4389                 if(bank_selected > 0) {
4390                         //fprintf(stderr,"BanksUsed - mucking with bank %d\n",bank_selected);
4391                         
4392                         // This instruction is modifying banking bits before accessing registers
4393                         if(!RegUsed)
4394                                 PCFL(pcflow)->firstBank = -1;
4395                         
4396                         if(PCFL(pcflow)->lastBank == -1)
4397                                 PCFL(pcflow)->lastBank = 0;
4398                         
4399                         bank = (1 << (bank_selected & (PIC_RP0_BIT | PIC_RP1_BIT)));
4400                         if(bank_selected & SET_BANK_BIT)
4401                                 PCFL(pcflow)->lastBank |= bank;
4402                         
4403                         
4404                 } else { 
4405                         reg = getRegFromInstruction(pc);
4406                         
4407                         if(reg && !isREGinBank(reg, bank)) {
4408                                 int allbanks = REGallBanks(reg);
4409                                 if(bank == -1)
4410                                         PCFL(pcflow)->firstBank = allbanks;
4411                                 
4412                                 PCFL(pcflow)->lastBank = allbanks;
4413                                 
4414                                 bank = allbanks;
4415                         }
4416                         RegUsed = 1;
4417                                                                 }
4418                                                                 
4419                 pc = findNextInstruction(pc->next);
4420         }
4421         
4422         //  fprintf(stderr,"BanksUsedFlow2 flow seq=%3d, first bank = 0x%03x, Last bank 0x%03x\n",
4423         //    pcflow->seq,PCFL(pcflow)->firstBank,PCFL(pcflow)->lastBank);
4424 }
4425 */
4426 /*-----------------------------------------------------------------*/
4427 /*-----------------------------------------------------------------*/
4428 /*
4429 static void BanksUsedFlow(pBlock *pb)
4430 {
4431         pCode *pcflow;
4432         
4433         
4434         //pb->pcHead->print(stderr, pb->pcHead);
4435         
4436         pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4437         //pcflow->print(stderr,pcflow);
4438         
4439         for( pcflow = findNextpCode(pb->pcHead, PC_FLOW); 
4440         pcflow != NULL;
4441         pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4442                 
4443                 BanksUsedFlow2(pcflow);
4444         }
4445         
4446 }
4447 */
4448
4449 /*-----------------------------------------------------------------*/
4450 /* Inserts a new pCodeInstruction before an existing one           */
4451 /*-----------------------------------------------------------------*/
4452 static void insertPCodeInstruction(pCodeInstruction *pci, pCodeInstruction *new_pci)
4453 {
4454         
4455         pCodeInsertAfter(pci->pc.prev, &new_pci->pc);
4456         
4457         /* Move the label, if there is one */
4458         
4459         if(pci->label) {
4460                 new_pci->label = pci->label;
4461                 pci->label = NULL;
4462         }
4463         
4464         /* Move the C code comment, if there is one */
4465         
4466         if(pci->cline) {
4467                 new_pci->cline = pci->cline;
4468                 pci->cline = NULL;
4469         }
4470         
4471         /* The new instruction has the same pcflow block */
4472         new_pci->pcflow = pci->pcflow;
4473         
4474 }
4475
4476 /*-----------------------------------------------------------------*/
4477 /*-----------------------------------------------------------------*/
4478 static void insertBankSwitch(pCodeInstruction *pci, int Set_Clear, int RP_BankBit)
4479 {
4480         pCode *new_pc;
4481         
4482         new_pc = newpCode((Set_Clear?POC_BSF:POC_BCF),popCopyGPR2Bit(PCOP(&pc_status),RP_BankBit));
4483         
4484         insertPCodeInstruction(pci, PCI(new_pc));
4485 }
4486
4487 /*-----------------------------------------------------------------*/
4488 /*-----------------------------------------------------------------*/
4489 static void insertBankSel(pCodeInstruction  *pci, const char *name)
4490 {
4491         pCode *new_pc;
4492         
4493         pCodeOp *pcop = popCopyReg(PCOR(pci->pcop));
4494         pcop->type = PO_GPR_REGISTER; // Sometimes the type is set to legacy 8051 - so override it
4495         if (pcop->name == 0)
4496                 pcop->name = strdup(name);
4497         new_pc = newpCode(POC_BANKSEL, pcop);
4498         
4499         insertPCodeInstruction(pci, PCI(new_pc));
4500 }
4501
4502 /*-----------------------------------------------------------------*/
4503 /* If the register is a fixed known addess then we can assign the  */
4504 /* bank selection bits. Otherwise the linker is going to assign    */
4505 /* the register location and thus has to set bank selection bits   */
4506 /* through the banksel directive.                                  */
4507 /* One critical assumption here is that within this C module all   */ 
4508 /* the locally allocated registers are in the same udata sector.   */
4509 /* Therefore banksel is only called for external registers or the  */
4510 /* first time a local register is encountered.                     */
4511 /*-----------------------------------------------------------------*/
4512 static int LastRegIdx; /* If the previous register is the same one again then no need to change bank. */
4513 static int BankSelect(pCodeInstruction *pci, int cur_bank, regs *reg)
4514 {
4515         int bank;
4516         int a = reg->alias>>7;
4517         if ((a&3) == 3) {
4518                 return cur_bank; // This register is available in all banks
4519         } else if ((a&1)&&((cur_bank==0)||(cur_bank==1))) {
4520                 return cur_bank; // This register is available in banks 0 & 1
4521         } else if (a&2) {
4522                 if (reg->address&0x80) {
4523                         if ((cur_bank==1)||(cur_bank==3)) {
4524                                 return cur_bank; // This register is available in banks 1 & 3
4525                         }
4526                 } else {
4527                         if ((cur_bank==0)||(cur_bank==1)) {
4528                                 return cur_bank; // This register is available in banks 0 & 2
4529                         }
4530                 }
4531         }
4532         
4533 #if 1
4534         if (LastRegIdx == reg->rIdx) // If this is the same register as last time then it is in same bank
4535                 return cur_bank;
4536         LastRegIdx = reg->rIdx;
4537 #endif
4538         
4539         if (reg->isFixed) {
4540                 bank = REG_BANK(reg);
4541         } else if (reg->isExtern) {
4542                 bank = 'E'; // Unfixed extern registers are allocated by the linker therefore its bank is unknown
4543         } else {
4544                 bank = 'L'; // Unfixed local registers are allocated by the linker therefore its bank is unknown
4545         }
4546         if ((cur_bank == 'L')&&(bank == 'L')) { // If current bank and new bank are both allocated locally by the linker, then assume it is in same bank.
4547                 return 'L'; // Local registers are presumed to be in same linker assigned bank
4548         } else if ((bank == 'L')&&(cur_bank != 'L')) { // Reg is now local and linker to assign bank
4549                 insertBankSel(pci, reg->name); // Let linker choose the bank selection
4550         } else if (bank == 'E') { // Reg is now extern and linker to assign bank
4551                 insertBankSel(pci, reg->name); // Let linker choose the bank selection
4552         } else if ((cur_bank == -1)||(cur_bank == 'L')||(cur_bank == 'E')) { // Current bank unknown and new register bank is known then can set bank bits
4553                 insertBankSwitch(pci, bank&1, PIC_RP0_BIT);
4554                 if (getMaxRam()&0x100)
4555                         insertBankSwitch(pci, bank&2, PIC_RP1_BIT);
4556         } else { // Current bank and new register banks known - can set bank bits
4557                 switch((cur_bank^bank) & 3) {
4558                 case 0:
4559                         break;
4560                 case 1:
4561                         insertBankSwitch(pci, bank&1, PIC_RP0_BIT);
4562                         break;
4563                 case 2:
4564                         insertBankSwitch(pci, bank&2, PIC_RP1_BIT);
4565                         break;
4566                 case 3:
4567                         insertBankSwitch(pci, bank&1, PIC_RP0_BIT);
4568                         if (getMaxRam()&0x100)
4569                                 insertBankSwitch(pci, bank&2, PIC_RP1_BIT);
4570                         break;
4571                 }
4572         }
4573         
4574         return bank;
4575 }
4576
4577 /*-----------------------------------------------------------------*/
4578 /* Check for bank selection pcodes instructions and modify         */
4579 /* cur_bank to match.                                              */
4580 /*-----------------------------------------------------------------*/
4581 static int IsBankChange(pCode *pc, regs *reg, int *cur_bank) {
4582         
4583         if (isSTATUS_REG(reg)) {
4584                 
4585                 if (PCI(pc)->op == POC_BCF) {
4586                         int old_bank = *cur_bank;
4587                         if (PCORB(PCI(pc)->pcop)->bit == PIC_RP0_BIT) {
4588                                 /* If current bank is unknown or linker assigned then set to 0 else just change the bit */
4589                                 if (*cur_bank & ~(0x3))
4590                                         *cur_bank = 0;
4591                                 else
4592                                         *cur_bank = *cur_bank&0x2;
4593                                 LastRegIdx = reg->rIdx;
4594                         } else if (PCORB(PCI(pc)->pcop)->bit == PIC_RP1_BIT) {
4595                                 /* If current bank is unknown or linker assigned then set to 0 else just change the bit */
4596                                 if (*cur_bank & ~(0x3))
4597                                         *cur_bank = 0;
4598                                 else
4599                                         *cur_bank = *cur_bank&0x1;
4600                                 LastRegIdx = reg->rIdx;
4601                         }
4602                         return old_bank != *cur_bank;
4603                 }
4604                 
4605                 if (PCI(pc)->op == POC_BSF) {
4606                         int old_bank = *cur_bank;
4607                         if (PCORB(PCI(pc)->pcop)->bit == PIC_RP0_BIT) {
4608                                 /* If current bank is unknown or linker assigned then set to bit else just change the bit */
4609                                 if (*cur_bank & ~(0x3))
4610                                         *cur_bank = 0x1;
4611                                 else
4612                                         *cur_bank = (*cur_bank&0x2) | 0x1;
4613                                 LastRegIdx = reg->rIdx;
4614                         } else if (PCORB(PCI(pc)->pcop)->bit == PIC_RP1_BIT) {
4615                                 /* If current bank is unknown or linker assigned then set to bit else just change the bit */
4616                                 if (*cur_bank & ~(0x3))
4617                                         *cur_bank = 0x2;
4618                                 else
4619                                         *cur_bank = (*cur_bank&0x1) | 0x2;
4620                                 LastRegIdx = reg->rIdx;
4621                         }
4622                         return old_bank != *cur_bank;
4623                 }
4624                 
4625         } else if (PCI(pc)->op == POC_BANKSEL) {
4626                 int old_bank = *cur_bank;
4627                 regs *r = PCOR(PCI(pc)->pcop)->r;
4628                 *cur_bank = (!r || r->isExtern) ? 'E' : 'L';
4629                 LastRegIdx = reg->rIdx;
4630                 return old_bank != *cur_bank;
4631         }
4632         
4633         return 0;
4634 }
4635
4636 /*-----------------------------------------------------------------*/
4637 /* Set bank selection if necessary                                 */
4638 /*-----------------------------------------------------------------*/
4639 static int DoBankSelect(pCode *pc, int cur_bank) {
4640         pCode *pcprev;
4641         regs *reg;
4642         
4643         if(!isPCI(pc))
4644                 return cur_bank;
4645         
4646         if (isCALL(pc)) {
4647                 pCode *pcf = findFunction(get_op_from_instruction(PCI(pc)));
4648                 LastRegIdx = -1; /* do not know which register is touched in the called function... */
4649                 if (pcf && isPCF(pcf)) {
4650                         pCode *pcfr;
4651                         int rbank = 'U'; // Undetermined
4652                         FixRegisterBanking(pcf->pb,cur_bank); // Ensure this block has had its banks selection done
4653                         // Check all the returns to work out what bank is selected
4654                         for (pcfr=pcf->pb->pcHead; pcfr; pcfr=pcfr->next) {
4655                                 if (isPCI(pcfr)) {
4656                                         if ((PCI(pcfr)->op==POC_RETURN) || (PCI(pcfr)->op==POC_RETLW)) {
4657                                                 if (rbank == 'U')
4658                                                         rbank = PCI(pcfr)->pcflow->lastBank;
4659                                                 else
4660                                                         if (rbank != PCI(pcfr)->pcflow->lastBank)
4661                                                                 return -1; // Unknown bank - multiple returns with different banks
4662                                         }
4663                                 }
4664                         }
4665                         if (rbank == 'U')
4666                                 return -1; // Unknown bank
4667                         return rbank;
4668                 } else if (isPCOS(PCI(pc)->pcop) && PCOS(PCI(pc)->pcop)->isPublic) {
4669                         /* Extern functions may use registers in different bank - must call banksel */
4670                         return -1; /* Unknown bank */
4671                 }
4672                 /* play safe... */
4673                 return -1;
4674         }
4675         
4676         if ((isPCI(pc)) && (PCI(pc)->op == POC_BANKSEL)) {
4677                 return -1; /* New bank unknown - linkers choice. */
4678         }
4679         
4680         reg = getRegFromInstruction(pc);
4681         if (reg) {
4682                 if (IsBankChange(pc,reg,&cur_bank))
4683                         return cur_bank;
4684                 if (!isPCI_LIT(pc)) {
4685                         
4686                         /* Examine the instruction before this one to make sure it is
4687                         * not a skip type instruction */
4688                         pcprev = findPrevpCode(pc->prev, PC_OPCODE);
4689                         
4690                         if(!pcprev || (pcprev && !isPCI_SKIP(pcprev))) {
4691                                 cur_bank = BankSelect(PCI(pc),cur_bank,reg);
4692                         } else {
4693                                 cur_bank = BankSelect(PCI(pcprev),cur_bank,reg);
4694                         }
4695                         if (!PCI(pc)->pcflow)
4696                                 fprintf(stderr,"PCI ID=%d missing flow pointer ???\n",pc->id);
4697                         else
4698                                 PCI(pc)->pcflow->lastBank = cur_bank; /* Maintain pCodeFlow lastBank state */
4699                 }
4700         }
4701         return cur_bank;
4702 }
4703
4704 /*-----------------------------------------------------------------*/
4705 /*-----------------------------------------------------------------*/
4706 /*
4707 static void FixRegisterBankingInFlow(pCodeFlow *pcfl, int cur_bank)
4708 {
4709         pCode *pc=NULL;
4710         pCode *pcprev=NULL;
4711         
4712         if(!pcfl)
4713                 return;
4714         
4715         pc = findNextInstruction(pcfl->pc.next);
4716         
4717         while(isPCinFlow(pc,PCODE(pcfl))) {
4718                 
4719                 cur_bank = DoBankSelect(pc,cur_bank);
4720                 pcprev = pc;
4721                 pc = findNextInstruction(pc->next);
4722                 
4723         }
4724         
4725         if(pcprev && cur_bank) {
4726                 // Set bank state to unknown at the end of each flow block
4727                 cur_bank = -1;
4728         }
4729         
4730 }
4731 */
4732 /*-----------------------------------------------------------------*/
4733 /*int compareBankFlow - compare the banking requirements between   */
4734 /*  flow objects. */
4735 /*-----------------------------------------------------------------*/
4736 /*
4737 int compareBankFlow(pCodeFlow *pcflow, pCodeFlowLink *pcflowLink, int toORfrom)
4738 {
4739         
4740         if(!pcflow || !pcflowLink || !pcflowLink->pcflow)
4741                 return 0;
4742         
4743         if(!isPCFL(pcflow) || !isPCFL(pcflowLink->pcflow))
4744                 return 0;
4745         
4746         if(pcflow->firstBank == -1)
4747                 return 0;
4748         
4749         
4750         if(pcflowLink->pcflow->firstBank == -1) {
4751                 pCodeFlowLink *pctl = setFirstItem( toORfrom ? 
4752                         pcflowLink->pcflow->to : 
4753                 pcflowLink->pcflow->from);
4754                 return compareBankFlow(pcflow, pctl, toORfrom);
4755         }
4756         
4757         if(toORfrom) {
4758                 if(pcflow->lastBank == pcflowLink->pcflow->firstBank)
4759                         return 0;
4760                 
4761                 pcflowLink->bank_conflict++;
4762                 pcflowLink->pcflow->FromConflicts++;
4763                 pcflow->ToConflicts++;
4764         } else {
4765                 
4766                 if(pcflow->firstBank == pcflowLink->pcflow->lastBank)
4767                         return 0;
4768                 
4769                 pcflowLink->bank_conflict++;
4770                 pcflowLink->pcflow->ToConflicts++;
4771                 pcflow->FromConflicts++;
4772                 
4773         }
4774         / *
4775                 fprintf(stderr,"compare flow found conflict: seq %d from conflicts %d, to conflicts %d\n",
4776                 pcflowLink->pcflow->pc.seq,
4777                 pcflowLink->pcflow->FromConflicts,
4778                 pcflowLink->pcflow->ToConflicts);
4779         * /
4780                 return 1;
4781         
4782 }
4783 */
4784 /*-----------------------------------------------------------------*/
4785 /*-----------------------------------------------------------------*/
4786 /*
4787 void FixBankFlow(pBlock *pb)
4788 {
4789         pCode *pc=NULL;
4790         pCode *pcflow;
4791         pCodeFlowLink *pcfl;
4792         
4793         pCode *pcflow_max_To=NULL;
4794         pCode *pcflow_max_From=NULL;
4795         int max_ToConflicts=0;
4796         int max_FromConflicts=0;
4797         
4798         /fprintf(stderr,"Fix Bank flow \n");
4799         pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4800         
4801         
4802         / *
4803                 First loop through all of the flow objects in this pcode block
4804                 and fix the ones that have banking conflicts between the 
4805                 entry and exit.
4806                 * /
4807                 
4808         //fprintf(stderr, "FixBankFlow - Phase 1\n");
4809         
4810         for( pcflow = findNextpCode(pb->pcHead, PC_FLOW); 
4811         pcflow != NULL;
4812         pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4813                 
4814                 if(!isPCFL(pcflow)) {
4815                         fprintf(stderr, "FixBankFlow - pcflow is not a flow object ");
4816                         continue;
4817                 }
4818                 
4819                 if(PCFL(pcflow)->firstBank != PCFL(pcflow)->lastBank  &&
4820                         PCFL(pcflow)->firstBank >= 0 &&
4821                         PCFL(pcflow)->lastBank >= 0 ) {
4822                         
4823                         int cur_bank = (PCFL(pcflow)->firstBank < PCFL(pcflow)->lastBank) ?
4824                                 PCFL(pcflow)->firstBank : PCFL(pcflow)->lastBank;
4825                         
4826                         FixRegisterBankingInFlow(PCFL(pcflow),cur_bank);
4827                         BanksUsedFlow2(pcflow);
4828                         
4829                 }
4830         }
4831         
4832         //fprintf(stderr, "FixBankFlow - Phase 2\n");
4833         
4834         for( pcflow = findNextpCode(pb->pcHead, PC_FLOW); 
4835         pcflow != NULL;
4836         pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4837                 
4838                 int nFlows;
4839                 int nConflicts;
4840                 
4841                 if(!isPCFL(pcflow)) {
4842                         fprintf(stderr, "FixBankFlow - pcflow is not a flow object ");
4843                         continue;
4844                 }
4845                 
4846                 PCFL(pcflow)->FromConflicts = 0;
4847                 PCFL(pcflow)->ToConflicts = 0;
4848                 
4849                 nFlows = 0;
4850                 nConflicts = 0;
4851                 
4852                 //fprintf(stderr, " FixBankFlow flow seq %d\n",pcflow->seq);
4853                 pcfl = setFirstItem(PCFL(pcflow)->from);
4854                 while (pcfl) {
4855                         
4856                         pc = PCODE(pcfl->pcflow);
4857                         
4858                         if(!isPCFL(pc)) {
4859                                 fprintf(stderr,"oops dumpflow - to is not a pcflow\n");
4860                                 pc->print(stderr,pc);
4861                         }
4862                         
4863                         nConflicts += compareBankFlow(PCFL(pcflow), pcfl, 0);
4864                         nFlows++;
4865                         
4866                         pcfl=setNextItem(PCFL(pcflow)->from);
4867                 }
4868                 
4869                 if((nFlows >= 2) && nConflicts && (PCFL(pcflow)->firstBank>0)) {
4870                         //fprintf(stderr, " From conflicts flow seq %d, nflows %d ,nconflicts %d\n",pcflow->seq,nFlows, nConflicts);
4871                         
4872                         FixRegisterBankingInFlow(PCFL(pcflow),-1);
4873                         BanksUsedFlow2(pcflow);
4874                         
4875                         continue;  / * Don't need to check the flow from here - it's already been fixed * /
4876                                 
4877                 }
4878                 
4879                 nFlows = 0;
4880                 nConflicts = 0;
4881                 
4882                 pcfl = setFirstItem(PCFL(pcflow)->to);
4883                 while (pcfl) {
4884                         
4885                         pc = PCODE(pcfl->pcflow);
4886                         if(!isPCFL(pc)) {
4887                                 fprintf(stderr,"oops dumpflow - to is not a pcflow\n");
4888                                 pc->print(stderr,pc);
4889                         }
4890                         
4891                         nConflicts += compareBankFlow(PCFL(pcflow), pcfl, 1);
4892                         nFlows++;
4893                         
4894                         pcfl=setNextItem(PCFL(pcflow)->to);
4895                 }
4896                 
4897                 if((nFlows >= 2) && nConflicts &&(nConflicts != nFlows) && (PCFL(pcflow)->lastBank>0)) {
4898                         //fprintf(stderr, " To conflicts flow seq %d, nflows %d ,nconflicts %d\n",pcflow->seq,nFlows, nConflicts);
4899                         
4900                         FixRegisterBankingInFlow(PCFL(pcflow),-1);
4901                         BanksUsedFlow2(pcflow);
4902                 }
4903         }
4904         
4905         / *
4906                 Loop through the flow objects again and find the ones with the 
4907                 maximum conflicts
4908                 * /
4909                 
4910                 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW); 
4911                 pcflow != NULL;
4912                 pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4913                         
4914                         if(PCFL(pcflow)->ToConflicts > max_ToConflicts)
4915                                 pcflow_max_To = pcflow;
4916                         
4917                         if(PCFL(pcflow)->FromConflicts > max_FromConflicts)
4918                                 pcflow_max_From = pcflow;
4919                 }
4920                 / *
4921                         if(pcflow_max_To)
4922                                 fprintf(stderr,"compare flow Max To conflicts: seq %d conflicts %d\n",
4923                                 PCFL(pcflow_max_To)->pc.seq,
4924                                 PCFL(pcflow_max_To)->ToConflicts);
4925                         
4926                         if(pcflow_max_From)
4927                                 fprintf(stderr,"compare flow Max From conflicts: seq %d conflicts %d\n",
4928                                 PCFL(pcflow_max_From)->pc.seq,
4929                                 PCFL(pcflow_max_From)->FromConflicts);
4930                         * /
4931 }
4932 */
4933
4934 /*-----------------------------------------------------------------*/
4935 /*-----------------------------------------------------------------*/
4936 void DumpFlow(pBlock *pb)
4937 {
4938         pCode *pc=NULL;
4939         pCode *pcflow;
4940         pCodeFlowLink *pcfl;
4941         
4942         
4943         fprintf(stderr,"Dump flow \n");
4944         pb->pcHead->print(stderr, pb->pcHead);
4945         
4946         pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4947         pcflow->print(stderr,pcflow);
4948         
4949         for( pcflow = findNextpCode(pb->pcHead, PC_FLOW); 
4950         pcflow != NULL;
4951         pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4952                 
4953                 if(!isPCFL(pcflow)) {
4954                         fprintf(stderr, "DumpFlow - pcflow is not a flow object ");
4955                         continue;
4956                 }
4957                 fprintf(stderr,"dumping: ");
4958                 pcflow->print(stderr,pcflow);
4959                 FlowStats(PCFL(pcflow));
4960                 
4961                 for(pcfl = setFirstItem(PCFL(pcflow)->to); pcfl; pcfl=setNextItem(PCFL(pcflow)->to)) {
4962                         
4963                         pc = PCODE(pcfl->pcflow);
4964                         
4965                         fprintf(stderr, "    from seq %d:\n",pc->seq);
4966                         if(!isPCFL(pc)) {
4967                                 fprintf(stderr,"oops dumpflow - from is not a pcflow\n");
4968                                 pc->print(stderr,pc);
4969                         }
4970                         
4971                 }
4972                 
4973                 for(pcfl = setFirstItem(PCFL(pcflow)->to); pcfl; pcfl=setNextItem(PCFL(pcflow)->to)) {
4974                         
4975                         pc = PCODE(pcfl->pcflow);
4976                         
4977                         fprintf(stderr, "    to seq %d:\n",pc->seq);
4978                         if(!isPCFL(pc)) {
4979                                 fprintf(stderr,"oops dumpflow - to is not a pcflow\n");
4980                                 pc->print(stderr,pc);
4981                         }
4982                         
4983                 }
4984                 
4985         }
4986         
4987 }
4988
4989 /*-----------------------------------------------------------------*/
4990 /*-----------------------------------------------------------------*/
4991 int OptimizepBlock(pBlock *pb)
4992 {
4993         pCode *pc, *pcprev;
4994         int matches =0;
4995         
4996         if(!pb || !peepOptimizing)
4997                 return 0;
4998         
4999         DFPRINTF((stderr," Optimizing pBlock: %c\n",getpBlock_dbName(pb)));
5000         /*
5001         for(pc = pb->pcHead; pc; pc = pc->next)
5002         matches += pCodePeepMatchRule(pc);
5003         */
5004         
5005         pc = findNextInstruction(pb->pcHead);
5006         if(!pc)
5007                 return 0;
5008         
5009         pcprev = pc->prev;
5010         do {
5011                 
5012                 
5013                 if(pCodePeepMatchRule(pc)) {
5014                         
5015                         matches++;
5016                         
5017                         if(pcprev)
5018                                 pc = findNextInstruction(pcprev->next);
5019                         else 
5020                                 pc = findNextInstruction(pb->pcHead);
5021                 } else
5022                         pc = findNextInstruction(pc->next);
5023         } while(pc);
5024         
5025         if(matches)
5026                 DFPRINTF((stderr," Optimizing pBlock: %c - matches=%d\n",getpBlock_dbName(pb),matches));
5027         return matches;
5028         
5029 }
5030
5031 /*-----------------------------------------------------------------*/
5032 /* pBlockRemoveUnusedLabels - remove the pCode labels from the     */
5033 /*-----------------------------------------------------------------*/
5034 pCode * findInstructionUsingLabel(pCodeLabel *pcl, pCode *pcs)
5035 {
5036   pCode *pc;
5037
5038   for(pc = pcs; pc; pc = pc->next) {
5039
5040     if(((pc->type == PC_OPCODE) || (pc->type == PC_INLINE) || (pc->type == PC_ASMDIR)) &&
5041       (PCI(pc)->pcop) && 
5042       (PCI(pc)->pcop->type == PO_LABEL) &&
5043       (PCOLAB(PCI(pc)->pcop)->key == pcl->key))
5044       return pc;
5045   }
5046
5047   return NULL;
5048 }
5049
5050 /*-----------------------------------------------------------------*/
5051 /*-----------------------------------------------------------------*/
5052 void exchangeLabels(pCodeLabel *pcl, pCode *pc)
5053 {
5054         
5055         char *s=NULL;
5056         
5057         if(isPCI(pc) && 
5058                 (PCI(pc)->pcop) && 
5059                 (PCI(pc)->pcop->type == PO_LABEL)) {
5060                 
5061                 pCodeOpLabel *pcol = PCOLAB(PCI(pc)->pcop);
5062                 
5063                 //fprintf(stderr,"changing label key from %d to %d\n",pcol->key, pcl->key);
5064                 if(pcol->pcop.name)
5065                         free(pcol->pcop.name);
5066                 
5067                         /* If the key is negative, then we (probably) have a label to
5068                 * a function and the name is already defined */
5069                 
5070                 if(pcl->key>0)
5071                         sprintf(s=buffer,"_%05d_DS_",pcl->key);
5072                 else 
5073                         s = pcl->label;
5074                 
5075                 //sprintf(buffer,"_%05d_DS_",pcl->key);
5076                 if(!s) {
5077                         fprintf(stderr, "ERROR %s:%d function label is null\n",__FUNCTION__,__LINE__);
5078                 }
5079                 pcol->pcop.name = Safe_strdup(s);
5080                 pcol->key = pcl->key;
5081                 //pc->print(stderr,pc);
5082                 
5083         }
5084         
5085         
5086 }
5087
5088 /*-----------------------------------------------------------------*/
5089 /* pBlockRemoveUnusedLabels - remove the pCode labels from the     */
5090 /*                            pCode chain if they're not used.     */
5091 /*-----------------------------------------------------------------*/
5092 void pBlockRemoveUnusedLabels(pBlock *pb)
5093 {
5094         pCode *pc; pCodeLabel *pcl;
5095         
5096         if(!pb)
5097                 return;
5098         
5099         for(pc = pb->pcHead; (pc=findNextInstruction(pc->next)) != NULL; ) {
5100                 
5101                 pBranch *pbr = PCI(pc)->label;
5102                 if(pbr && pbr->next) {
5103                         pCode *pcd = pb->pcHead;
5104                         
5105                         //fprintf(stderr, "multiple labels\n");
5106                         //pc->print(stderr,pc);
5107                         
5108                         pbr = pbr->next;
5109                         while(pbr) {
5110                                 
5111                                 while ( (pcd = findInstructionUsingLabel(PCL(PCI(pc)->label->pc), pcd)) != NULL) {
5112                                         //fprintf(stderr,"Used by:\n");
5113                                         //pcd->print(stderr,pcd);
5114                                         
5115                                         exchangeLabels(PCL(pbr->pc),pcd);
5116                                         
5117                                         pcd = pcd->next;
5118                                 }
5119                                 pbr = pbr->next;
5120                         }
5121                 }
5122         }
5123         
5124         for(pc = pb->pcHead; pc; pc = pc->next) {
5125                 
5126                 if(isPCL(pc)) // Label pcode
5127                         pcl = PCL(pc);
5128                 else if (isPCI(pc) && PCI(pc)->label) // pcode instruction with a label
5129                         pcl = PCL(PCI(pc)->label->pc);
5130                 else continue;
5131                 
5132                 //fprintf(stderr," found  A LABEL !!! key = %d, %s\n", pcl->key,pcl->label);
5133                 
5134                 /* This pCode is a label, so search the pBlock to see if anyone
5135                 * refers to it */
5136                 
5137                 if( (pcl->key>0) && (!findInstructionUsingLabel(pcl, pb->pcHead))) {
5138                         //if( !findInstructionUsingLabel(pcl, pb->pcHead)) {
5139                         /* Couldn't find an instruction that refers to this label
5140                         * So, unlink the pCode label from it's pCode chain
5141                         * and destroy the label */
5142                         //fprintf(stderr," removed  A LABEL !!! key = %d, %s\n", pcl->key,pcl->label);
5143                         
5144                         DFPRINTF((stderr," !!! REMOVED A LABEL !!! key = %d, %s\n", pcl->key,pcl->label));
5145                         if(pc->type == PC_LABEL) {
5146                                 unlinkpCode(pc);
5147                                 pCodeLabelDestruct(pc);
5148                         } else {
5149                                 unlinkpCodeFromBranch(pc, PCODE(pcl));
5150                                 /*if(pc->label->next == NULL && pc->label->pc == NULL) {
5151                                 free(pc->label);
5152                         }*/
5153                         }
5154                         
5155                 }
5156         }
5157         
5158 }
5159
5160
5161 /*-----------------------------------------------------------------*/
5162 /* pBlockMergeLabels - remove the pCode labels from the pCode      */
5163 /*                     chain and put them into pBranches that are  */
5164 /*                     associated with the appropriate pCode       */
5165 /*                     instructions.                               */
5166 /*-----------------------------------------------------------------*/
5167 void pBlockMergeLabels(pBlock *pb)
5168 {
5169         pBranch *pbr;
5170         pCode *pc, *pcnext=NULL;
5171         
5172         if(!pb)
5173                 return;
5174         
5175         /* First, Try to remove any unused labels */
5176         //pBlockRemoveUnusedLabels(pb);
5177         
5178         /* Now loop through the pBlock and merge the labels with the opcodes */
5179         
5180         pc = pb->pcHead;
5181         //  for(pc = pb->pcHead; pc; pc = pc->next) {
5182         
5183         while(pc) {
5184                 pCode *pcn = pc->next;
5185                 
5186                 if(pc->type == PC_LABEL) {
5187                         
5188                         //fprintf(stderr," checking merging label %s\n",PCL(pc)->label);
5189                         //fprintf(stderr,"Checking label key = %d\n",PCL(pc)->key);
5190                         if((pcnext = findNextInstruction(pc) )) {
5191                                 
5192                                 // Unlink the pCode label from it's pCode chain
5193                                 unlinkpCode(pc);
5194                                 
5195                                 //fprintf(stderr,"Merged label key = %d\n",PCL(pc)->key);
5196                                 // And link it into the instruction's pBranch labels. (Note, since
5197                                 // it's possible to have multiple labels associated with one instruction
5198                                 // we must provide a means to accomodate the additional labels. Thus
5199                                 // the labels are placed into the singly-linked list "label" as 
5200                                 // opposed to being a single member of the pCodeInstruction.)
5201                                 
5202                                 //_ALLOC(pbr,sizeof(pBranch));
5203                                 pbr = Safe_calloc(1,sizeof(pBranch));
5204                                 pbr->pc = pc;
5205                                 pbr->next = NULL;
5206                                 
5207                                 PCI(pcnext)->label = pBranchAppend(PCI(pcnext)->label,pbr);
5208                                 
5209                         } else {
5210                                 fprintf(stderr, "WARNING: couldn't associate label %s with an instruction\n",PCL(pc)->label);
5211                         }
5212                 } else if(pc->type == PC_CSOURCE) {
5213                         
5214                         /* merge the source line symbolic info into the next instruction */
5215                         if((pcnext = findNextInstruction(pc) )) {
5216                                 
5217                                 // Unlink the pCode label from it's pCode chain
5218                                 unlinkpCode(pc);
5219                                 PCI(pcnext)->cline = PCCS(pc);
5220                                 //fprintf(stderr, "merging CSRC\n");
5221                                 //genericPrint(stderr,pcnext);
5222                         }
5223                         
5224                 }
5225                 pc = pcn;
5226         }
5227         pBlockRemoveUnusedLabels(pb);
5228         
5229 }
5230
5231 /*-----------------------------------------------------------------*/
5232 /*-----------------------------------------------------------------*/
5233 int OptimizepCode(char dbName)
5234 {
5235 #define MAX_PASSES 4
5236         
5237         int matches = 0;
5238         int passes = 0;
5239         pBlock *pb;
5240         
5241         if(!the_pFile)
5242                 return 0;
5243         
5244         DFPRINTF((stderr," Optimizing pCode\n"));
5245         
5246         do {
5247                 matches = 0;
5248                 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5249                         if('*' == dbName || getpBlock_dbName(pb) == dbName)
5250                                 matches += OptimizepBlock(pb);
5251                 }
5252         }
5253         while(matches && ++passes < MAX_PASSES);
5254         
5255         return matches;
5256 }
5257
5258 /*-----------------------------------------------------------------*/
5259 /* popCopyGPR2Bit - copy a pcode operator                          */
5260 /*-----------------------------------------------------------------*/
5261
5262 pCodeOp *popCopyGPR2Bit(pCodeOp *pc, int bitval)
5263 {
5264         pCodeOp *pcop;
5265         
5266         pcop = newpCodeOpBit(pc->name, bitval, 0);
5267         
5268         if( !( (pcop->type == PO_LABEL) ||
5269                 (pcop->type == PO_LITERAL) ||
5270                 (pcop->type == PO_STR) ))
5271                 PCOR(pcop)->r = PCOR(pc)->r;  /* This is dangerous... */
5272         
5273         return pcop;
5274 }
5275
5276
5277 /*-----------------------------------------------------------------*/
5278 /*-----------------------------------------------------------------*/
5279 static void FixRegisterBanking(pBlock *pb,int cur_bank)
5280 {
5281         pCode *pc;
5282         int firstBank = 'U';
5283         
5284         if(!pb)
5285                 return;
5286         
5287         for (pc=pb->pcHead; pc; pc=pc->next) {
5288                 if (isPCFL(pc)) {
5289                         firstBank = PCFL(pc)->firstBank;
5290                         break;
5291                 }
5292         }
5293         if (firstBank != 'U') {
5294                 /* This block has already been done */
5295                 if (firstBank != cur_bank) {
5296                         /* This block has started with a different bank - must adjust it */ 
5297                         if ((firstBank != -1)&&(firstBank != 'E')) { /* The first bank start off unknown or extern then need not worry as banksel will be called */
5298                                 while (pc) {
5299                                         if (isPCI(pc)) {
5300                                                 regs *reg = getRegFromInstruction(pc);
5301                                                 if (reg) {
5302                                                         DoBankSelect(pc,cur_bank);
5303                                                 }
5304                                         }
5305                                         pc = pc->next;
5306                                 }
5307                         }
5308                 }
5309                 return;
5310         }
5311         
5312         /* loop through all of the pCodes within this pblock setting the bank selection, ignoring any branching */
5313         LastRegIdx = -1;
5314         cur_bank = -1;
5315         for (pc=pb->pcHead; pc; pc=pc->next) {
5316                 if (isPCFL(pc)) {
5317                         PCFL(pc)->firstBank = cur_bank;
5318                         continue;
5319                 }
5320                 cur_bank = DoBankSelect(pc,cur_bank);
5321         }
5322         
5323         /* Trace through branches and set the bank selection as required. */
5324         LastRegIdx = -1;
5325         cur_bank = -1;
5326         for (pc=pb->pcHead; pc; pc=pc->next) {
5327                 if (isPCFL(pc)) {
5328                         PCFL(pc)->firstBank = cur_bank;
5329                         continue;
5330                 }
5331                 if (isPCI(pc)) {
5332                         if (PCI(pc)->op == POC_GOTO) {
5333                                 int lastRegIdx = LastRegIdx;
5334                                 pCode *pcb = pc;
5335                                 /* Trace through branch */
5336                                 pCode *pcl = findLabel(PCOLAB(PCI(pcb)->pcop));
5337                                 while (pcl) {
5338                                         if (isPCI(pcl)) {
5339                                                 regs *reg = getRegFromInstruction(pcl);
5340                                                 if (reg) {
5341                                                         int bankUnknown = -1;
5342                                                         if (IsBankChange(pcl,reg,&bankUnknown)) /* Look for any bank change */
5343                                                                 break;
5344                                                         if (cur_bank != DoBankSelect(pcl,cur_bank)) /* Set bank selection if necessary */
5345                                                                 break;
5346                                                 }
5347                                         }
5348                                         pcl = pcl->next;
5349                                 }
5350                                 LastRegIdx = lastRegIdx;
5351                         } else {
5352                                 /* Keep track out current bank */
5353                                 regs *reg = getRegFromInstruction(pc);
5354                                 if (reg)
5355                                         IsBankChange(pc,reg,&cur_bank);
5356                         }
5357                 }
5358         }
5359 }
5360
5361
5362 /*-----------------------------------------------------------------*/
5363 /*-----------------------------------------------------------------*/
5364 void pBlockDestruct(pBlock *pb)
5365 {
5366         
5367         if(!pb)
5368                 return;
5369         
5370         
5371         free(pb);
5372         
5373 }
5374
5375 /*-----------------------------------------------------------------*/
5376 /* void mergepBlocks(char dbName) - Search for all pBlocks with the*/
5377 /*                                  name dbName and combine them   */
5378 /*                                  into one block                 */
5379 /*-----------------------------------------------------------------*/
5380 void mergepBlocks(char dbName)
5381 {
5382         
5383         pBlock *pb, *pbmerged = NULL,*pbn;
5384         
5385         pb = the_pFile->pbHead;
5386         
5387         //fprintf(stderr," merging blocks named %c\n",dbName);
5388         while(pb) {
5389                 
5390                 pbn = pb->next;
5391                 //fprintf(stderr,"looking at %c\n",getpBlock_dbName(pb));
5392                 if( getpBlock_dbName(pb) == dbName) {
5393                         
5394                         //fprintf(stderr," merged block %c\n",dbName);
5395                         
5396                         if(!pbmerged) {
5397                                 pbmerged = pb;
5398                         } else {
5399                                 addpCode2pBlock(pbmerged, pb->pcHead);
5400                                 /* addpCode2pBlock doesn't handle the tail: */
5401                                 pbmerged->pcTail = pb->pcTail;
5402                                 
5403                                 pb->prev->next = pbn;
5404                                 if(pbn) 
5405                                         pbn->prev = pb->prev;
5406                                 
5407                                 
5408                                 pBlockDestruct(pb);
5409                         }
5410                         //printpBlock(stderr, pbmerged);
5411                 } 
5412                 pb = pbn;
5413         }
5414         
5415 }
5416
5417 /*-----------------------------------------------------------------*/
5418 /* AnalyzeFlow - Examine the flow of the code and optimize         */
5419 /*                                                                 */
5420 /* level 0 == minimal optimization                                 */
5421 /*   optimize registers that are used only by two instructions     */
5422 /* level 1 == maximal optimization                                 */
5423 /*   optimize by looking at pairs of instructions that use the     */
5424 /*   register.                                                     */
5425 /*-----------------------------------------------------------------*/
5426
5427 void AnalyzeFlow(int level)
5428 {
5429         static int times_called=0;
5430         
5431         pBlock *pb;
5432         
5433         if(!the_pFile)
5434                 return;
5435         
5436         
5437                 /* if this is not the first time this function has been called,
5438         then clean up old flow information */
5439         if(times_called++) {
5440                 for(pb = the_pFile->pbHead; pb; pb = pb->next)
5441                         unBuildFlow(pb);
5442                 
5443                 RegsUnMapLiveRanges();
5444                 
5445         }
5446         
5447         GpcFlowSeq = 1;
5448         
5449         /* Phase 2 - Flow Analysis - Register Banking
5450         *
5451         * In this phase, the individual flow blocks are examined
5452         * and register banking is fixed.
5453         */
5454         
5455         //for(pb = the_pFile->pbHead; pb; pb = pb->next)
5456         //FixRegisterBanking(pb);
5457         
5458         /* Phase 2 - Flow Analysis
5459         *
5460         * In this phase, the pCode is partition into pCodeFlow 
5461         * blocks. The flow blocks mark the points where a continuous
5462         * stream of instructions changes flow (e.g. because of
5463         * a call or goto or whatever).
5464         */
5465         
5466         for(pb = the_pFile->pbHead; pb; pb = pb->next)
5467                 BuildFlow(pb);
5468         
5469         
5470                 /* Phase 2 - Flow Analysis - linking flow blocks
5471                 *
5472                 * In this phase, the individual flow blocks are examined
5473                 * to determine their order of excution.
5474         */
5475         
5476         for(pb = the_pFile->pbHead; pb; pb = pb->next)
5477                 LinkFlow(pb);
5478         
5479                 /* Phase 3 - Flow Analysis - Flow Tree
5480                 *
5481                 * In this phase, the individual flow blocks are examined
5482                 * to determine their order of excution.
5483         */
5484         
5485         for(pb = the_pFile->pbHead; pb; pb = pb->next)
5486                 BuildFlowTree(pb);
5487         
5488         
5489                 /* Phase x - Flow Analysis - Used Banks
5490                 *
5491                 * In this phase, the individual flow blocks are examined
5492                 * to determine the Register Banks they use
5493         */
5494         
5495         //  for(pb = the_pFile->pbHead; pb; pb = pb->next)
5496         //    FixBankFlow(pb);
5497         
5498         
5499         for(pb = the_pFile->pbHead; pb; pb = pb->next)
5500                 pCodeRegMapLiveRanges(pb);
5501         
5502         RemoveUnusedRegisters();
5503         
5504         //  for(pb = the_pFile->pbHead; pb; pb = pb->next)
5505         pCodeRegOptimizeRegUsage(level);
5506         
5507         OptimizepCode('*');
5508         
5509         
5510         /*
5511         for(pb = the_pFile->pbHead; pb; pb = pb->next)
5512         DumpFlow(pb);
5513         */
5514         /* debug stuff */
5515         /*
5516         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5517     pCode *pcflow;
5518     for( pcflow = findNextpCode(pb->pcHead, PC_FLOW); 
5519     (pcflow = findNextpCode(pcflow, PC_FLOW)) != NULL;
5520     pcflow = pcflow->next) {
5521     
5522           FillFlow(PCFL(pcflow));
5523           }
5524           }
5525         */
5526         /*
5527         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5528     pCode *pcflow;
5529     for( pcflow = findNextpCode(pb->pcHead, PC_FLOW); 
5530     (pcflow = findNextpCode(pcflow, PC_FLOW)) != NULL;
5531     pcflow = pcflow->next) {
5532         
5533           FlowStats(PCFL(pcflow));
5534           }
5535           }
5536         */
5537 }
5538
5539 /*-----------------------------------------------------------------*/
5540 /* AnalyzeBanking - Called after the memory addresses have been    */
5541 /*                  assigned to the registers.                     */
5542 /*                                                                 */
5543 /*-----------------------------------------------------------------*/
5544
5545 void AnalyzeBanking(void)
5546 {
5547         pBlock  *pb;
5548         
5549         if(!picIsInitialized()) {
5550                 setDefMaxRam(); // Max RAM has not been included, so use default setting
5551         }
5552         
5553         /* Phase x - Flow Analysis - Used Banks
5554         *
5555         * In this phase, the individual flow blocks are examined
5556         * to determine the Register Banks they use
5557         */
5558         
5559         AnalyzeFlow(0);
5560         AnalyzeFlow(1);
5561         
5562         //  for(pb = the_pFile->pbHead; pb; pb = pb->next)
5563         //    BanksUsedFlow(pb);
5564         for(pb = the_pFile->pbHead; pb; pb = pb->next)
5565                 FixRegisterBanking(pb,-1); // cur_bank is unknown
5566         
5567 }
5568
5569 /*-----------------------------------------------------------------*/
5570 /*-----------------------------------------------------------------*/
5571 DEFSETFUNC (resetrIdx)
5572 {
5573         regs *r = (regs *)item;
5574         if (!r->isFixed) {
5575                 r->rIdx = 0;
5576         }
5577         
5578         return 0;
5579 }
5580
5581 /*-----------------------------------------------------------------*/
5582 /* InitRegReuse - Initialises variables for code analyzer          */
5583 /*-----------------------------------------------------------------*/
5584
5585 void InitReuseReg(void)
5586 {
5587         /* Find end of statically allocated variables for start idx */
5588         unsigned maxIdx = 0x20; /* Start from begining of GPR. Note may not be 0x20 on some PICs */
5589         regs *r;
5590         for (r = setFirstItem(dynDirectRegs); r; r = setNextItem(dynDirectRegs)) {
5591                 if (r->type != REG_SFR) {
5592                         maxIdx += r->size; /* Increment for all statically allocated variables */
5593                 }
5594         }
5595         peakIdx = maxIdx;
5596         applyToSet(dynAllocRegs,resetrIdx); /* Reset all rIdx to zero. */
5597 }
5598
5599 /*-----------------------------------------------------------------*/
5600 /*-----------------------------------------------------------------*/
5601 static unsigned register_reassign(pBlock *pb, unsigned idx)
5602 {
5603         pCode *pc;
5604         
5605         /* check recursion */
5606         pc = setFirstItem(pb->function_entries);
5607         if(!pc)
5608                 return idx;
5609         
5610         pb->visited = 1;
5611         
5612         DFPRINTF((stderr," reassigning registers for function \"%s\"\n",PCF(pc)->fname));
5613         
5614         if (pb->tregisters) {
5615                 regs *r;
5616                 for (r = setFirstItem(pb->tregisters); r; r = setNextItem(pb->tregisters)) {
5617                         if (r->type == REG_GPR) {
5618                                 if (!r->isFixed) {
5619                                         if (r->rIdx < (int)idx) {
5620                                                 char s[20];
5621                                                 r->rIdx = idx++;
5622                                                 if (peakIdx < idx) peakIdx = idx;
5623                                                 sprintf(s,"r0x%02X", r->rIdx);
5624                                                 DFPRINTF((stderr," reassigning register \"%s\" to \"%s\"\n",r->name,s));
5625                                                 free(r->name);
5626                                                 r->name = Safe_strdup(s);
5627                                         }
5628                                 }
5629                         }
5630                 }
5631         }
5632         for(pc = setFirstItem(pb->function_calls); pc; pc = setNextItem(pb->function_calls)) {
5633                 
5634                 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
5635                         char *dest = get_op_from_instruction(PCI(pc));
5636                         
5637                         pCode *pcn = findFunction(dest);
5638                         if(pcn) {
5639                                 register_reassign(pcn->pb,idx);
5640                         }
5641                 }
5642                 
5643         }
5644         
5645         return idx;
5646 }
5647
5648 /*------------------------------------------------------------------*/
5649 /* ReuseReg were call tree permits                                  */
5650 /*                                                                  */
5651 /*  Re-allocate the GPR for optimum reuse for a given pblock        */ 
5652 /*  eg  if a function m() calls function f1() and f2(), where f1    */
5653 /*  allocates a local variable vf1 and f2 allocates a local         */
5654 /*  variable vf2. Then providing f1 and f2 do not call each other   */
5655 /*  they may share the same general purpose registers for vf1 and   */
5656 /*  vf2.                                                            */
5657 /*  This is done by first setting the the regs rIdx to start after  */
5658 /*  all the global variables, then walking through the call tree    */
5659 /*  renaming the registers to match their new idx and incrementng   */
5660 /*  it as it goes. If a function has already been called it will    */
5661 /*  only rename the registers if it has already used up those       */
5662 /*  registers ie rIdx of the function's registers is lower than the */
5663 /*  current rIdx. That way the register will not be reused while    */
5664 /*  still being used by an eariler function call.                   */
5665 /*                                                                  */
5666 /*  Note for this to work the functions need to be declared static. */
5667 /*                                                                  */
5668 /*------------------------------------------------------------------*/
5669 void ReuseReg(void)
5670 {
5671         pBlock  *pb;
5672         InitReuseReg();
5673         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5674                 /* Non static functions can be called from other modules so their registers must reassign */
5675                 if (pb->function_entries&&(PCF(setFirstItem(pb->function_entries))->isPublic||!pb->visited))
5676                         register_reassign(pb,peakIdx);
5677         }
5678 }
5679
5680 /*-----------------------------------------------------------------*/
5681 /* buildCallTree - look at the flow and extract all of the calls   */
5682 /*                                                                 */
5683 /*-----------------------------------------------------------------*/
5684
5685 void buildCallTree(void    )
5686 {
5687         pBranch *pbr;
5688         pBlock  *pb;
5689         pCode   *pc;
5690         
5691         if(!the_pFile)
5692                 return;
5693         
5694                 /* Now build the call tree.
5695                 First we examine all of the pCodes for functions.
5696                 Keep in mind that the function boundaries coincide
5697                 with pBlock boundaries. 
5698                 
5699                   The algorithm goes something like this:
5700                   We have two nested loops. The outer loop iterates
5701                   through all of the pBlocks/functions. The inner
5702                   loop iterates through all of the pCodes for
5703                   a given pBlock. When we begin iterating through
5704                   a pBlock, the variable pc_fstart, pCode of the start
5705                   of a function, is cleared. We then search for pCodes
5706                   of type PC_FUNCTION. When one is encountered, we
5707                   initialize pc_fstart to this and at the same time
5708                   associate a new pBranch object that signifies a 
5709                   branch entry. If a return is found, then this signifies
5710                   a function exit point. We'll link the pCodes of these
5711                   returns to the matching pc_fstart.
5712                   
5713                         When we're done, a doubly linked list of pBranches
5714                         will exist. The head of this list is stored in
5715                         `the_pFile', which is the meta structure for all
5716                         of the pCode. Look at the printCallTree function
5717                         on how the pBranches are linked together.
5718                         
5719         */
5720         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5721                 pCode *pc_fstart=NULL;
5722                 for(pc = pb->pcHead; pc; pc = pc->next) {
5723                         if(isPCF(pc)) {
5724                                 pCodeFunction *pcf = PCF(pc);
5725                                 if (pcf->fname) {
5726                                         
5727                                         if(STRCASECMP(pcf->fname, "_main") == 0) {
5728                                                 //fprintf(stderr," found main \n");
5729                                                 pb->cmemmap = NULL;  /* FIXME do we need to free ? */
5730                                                 pb->dbName = 'M';
5731                                         }
5732                                         
5733                                         pbr = Safe_calloc(1,sizeof(pBranch));
5734                                         pbr->pc = pc_fstart = pc;
5735                                         pbr->next = NULL;
5736                                         
5737                                         the_pFile->functions = pBranchAppend(the_pFile->functions,pbr);
5738                                         
5739                                         // Here's a better way of doing the same:
5740                                         addSet(&pb->function_entries, pc);
5741                                         
5742                                 } else {
5743                                         // Found an exit point in a function, e.g. return
5744                                         // (Note, there may be more than one return per function)
5745                                         if(pc_fstart)
5746                                                 pBranchLink(PCF(pc_fstart), pcf);
5747                                         
5748                                         addSet(&pb->function_exits, pc);
5749                                 }
5750                         } else if(isCALL(pc)) {
5751                                 addSet(&pb->function_calls,pc);
5752                         }
5753                 }
5754         }
5755 }
5756
5757 /*-----------------------------------------------------------------*/
5758 /* AnalyzepCode - parse the pCode that has been generated and form */
5759 /*                all of the logical connections.                  */
5760 /*                                                                 */
5761 /* Essentially what's done here is that the pCode flow is          */
5762 /* determined.                                                     */
5763 /*-----------------------------------------------------------------*/
5764
5765 void AnalyzepCode(char dbName)
5766 {
5767         pBlock *pb;
5768         int i,changes;
5769         
5770         if(!the_pFile)
5771                 return;
5772         
5773         mergepBlocks('D');
5774         
5775         
5776         /* Phase 1 - Register allocation and peep hole optimization
5777         *
5778         * The first part of the analysis is to determine the registers
5779         * that are used in the pCode. Once that is done, the peep rules
5780         * are applied to the code. We continue to loop until no more
5781         * peep rule optimizations are found (or until we exceed the
5782         * MAX_PASSES threshold). 
5783         *
5784         * When done, the required registers will be determined.
5785         *
5786         */
5787         i = 0;
5788         do {
5789                 
5790                 DFPRINTF((stderr," Analyzing pCode: PASS #%d\n",i+1));
5791                 
5792                 /* First, merge the labels with the instructions */
5793                 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5794                         if('*' == dbName || getpBlock_dbName(pb) == dbName) {
5795                                 
5796                                 DFPRINTF((stderr," analyze and merging block %c\n",dbName));
5797                                 pBlockMergeLabels(pb);
5798                                 AnalyzepBlock(pb);
5799                         } else {
5800                                 DFPRINTF((stderr," skipping block analysis dbName=%c blockname=%c\n",dbName,getpBlock_dbName));
5801                         }
5802                 }
5803                 
5804                 changes = OptimizepCode(dbName);
5805                 
5806         } while(changes && (i++ < MAX_PASSES));
5807         
5808         buildCallTree();
5809 }
5810
5811 /*-----------------------------------------------------------------*/
5812 /* ispCodeFunction - returns true if *pc is the pCode of a         */
5813 /*                   function                                      */
5814 /*-----------------------------------------------------------------*/
5815 bool ispCodeFunction(pCode *pc)
5816 {
5817         
5818         if(pc && pc->type == PC_FUNCTION && PCF(pc)->fname)
5819                 return 1;
5820         
5821         return 0;
5822 }
5823
5824 /*-----------------------------------------------------------------*/
5825 /* findFunction - Search for a function by name (given the name)   */
5826 /*                in the set of all functions that are in a pBlock */
5827 /* (note - I expect this to change because I'm planning to limit   */
5828 /*  pBlock's to just one function declaration                      */
5829 /*-----------------------------------------------------------------*/
5830 pCode *findFunction(char *fname)
5831 {
5832         pBlock *pb;
5833         pCode *pc;
5834         if(!fname)
5835                 return NULL;
5836         
5837         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5838                 
5839                 pc = setFirstItem(pb->function_entries);
5840                 while(pc) {
5841                         
5842                         if((pc->type == PC_FUNCTION) &&
5843                                 (PCF(pc)->fname) && 
5844                                 (strcmp(fname, PCF(pc)->fname)==0))
5845                                 return pc;
5846                         
5847                         pc = setNextItem(pb->function_entries);
5848                         
5849                 }
5850                 
5851         }
5852         return NULL;
5853 }
5854
5855 void MarkUsedRegisters(set *regset)
5856 {
5857         
5858         regs *r1,*r2;
5859         
5860         for(r1=setFirstItem(regset); r1; r1=setNextItem(regset)) {
5861                 r2 = pic14_regWithIdx(r1->rIdx);
5862                 if (r2) {
5863                         r2->isFree = 0;
5864                         r2->wasUsed = 1;
5865                 }
5866         }
5867 }
5868
5869 void pBlockStats(FILE *of, pBlock *pb)
5870 {
5871         
5872         pCode *pc;
5873         regs  *r;
5874         
5875         fprintf(of,";***\n;  pBlock Stats: dbName = %c\n;***\n",getpBlock_dbName(pb));
5876         
5877         // for now just print the first element of each set
5878         pc = setFirstItem(pb->function_entries);
5879         if(pc) {
5880                 fprintf(of,";entry:  ");
5881                 pc->print(of,pc);
5882         }
5883         pc = setFirstItem(pb->function_exits);
5884         if(pc) {
5885                 fprintf(of,";has an exit\n");
5886                 //pc->print(of,pc);
5887         }
5888         
5889         pc = setFirstItem(pb->function_calls);
5890         if(pc) {
5891                 fprintf(of,";functions called:\n");
5892                 
5893                 while(pc) {
5894                         if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
5895                                 fprintf(of,";   %s\n",get_op_from_instruction(PCI(pc)));
5896                         }
5897                         pc = setNextItem(pb->function_calls);
5898                 }
5899         }
5900         
5901         r = setFirstItem(pb->tregisters);
5902         if(r) {
5903                 int n = elementsInSet(pb->tregisters);
5904                 
5905                 fprintf(of,";%d compiler assigned register%c:\n",n, ( (n!=1) ? 's' : ' '));
5906                 
5907                 while (r) {
5908                         fprintf(of,";   %s\n",r->name);
5909                         r = setNextItem(pb->tregisters);
5910                 }
5911         }
5912 }
5913
5914 /*-----------------------------------------------------------------*/
5915 /*-----------------------------------------------------------------*/
5916 #if 0
5917 static void sequencepCode(void)
5918 {
5919         pBlock *pb;
5920         pCode *pc;
5921         
5922         
5923         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5924                 
5925                 pb->seq = GpCodeSequenceNumber+1;
5926                 
5927                 for( pc = pb->pcHead; pc; pc = pc->next)
5928                         pc->seq = ++GpCodeSequenceNumber;
5929         }
5930         
5931 }
5932 #endif
5933
5934 /*-----------------------------------------------------------------*/
5935 /*-----------------------------------------------------------------*/
5936 /*
5937 set *register_usage(pBlock *pb)
5938 {
5939         pCode *pc,*pcn;
5940         set *registers=NULL;
5941         set *registersInCallPath = NULL;
5942         
5943         / * check recursion * /
5944                 
5945                 pc = setFirstItem(pb->function_entries);
5946         
5947         if(!pc)
5948                 return registers;
5949         
5950         pb->visited = 1;
5951         
5952         if(pc->type != PC_FUNCTION)
5953                 fprintf(stderr,"%s, first pc is not a function???\n",__FUNCTION__);
5954         
5955         pc = setFirstItem(pb->function_calls);
5956         for( ; pc; pc = setNextItem(pb->function_calls)) {
5957                 
5958                 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
5959                         char *dest = get_op_from_instruction(PCI(pc));
5960                         
5961                         pcn = findFunction(dest);
5962                         if(pcn) 
5963                                 registersInCallPath = register_usage(pcn->pb);
5964                 } else
5965                         fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
5966                 
5967         }
5968         
5969 #ifdef PCODE_DEBUG
5970         pBlockStats(stderr,pb);  // debug
5971 #endif
5972         
5973         // Mark the registers in this block as used.
5974         
5975         MarkUsedRegisters(pb->tregisters);
5976         if(registersInCallPath) {
5977                 / * registers were used in the functions this pBlock has called * /
5978                 / * so now, we need to see if these collide with the ones we are * /
5979                 / * using here * /
5980                 
5981                         regs *r1,*r2, *newreg;
5982                 
5983                 DFPRINTF((stderr,"comparing registers\n"));
5984                 
5985                 r1 = setFirstItem(registersInCallPath);
5986                 while(r1) {
5987                         if (r1->type != REG_STK) {
5988                                 r2 = setFirstItem(pb->tregisters);
5989                                 
5990                                 while(r2 && (r2->type != REG_STK)) {
5991                                         
5992                                         if(r2->rIdx == r1->rIdx) {
5993                                                 newreg = pic14_findFreeReg(REG_GPR);
5994                                                 
5995                                                 
5996                                                 if(!newreg) {
5997                                                         DFPRINTF((stderr,"Bummer, no more registers.\n"));
5998                                                         exit(1);
5999                                                 }
6000                                                 
6001                                                 DFPRINTF((stderr,"Cool found register collision nIdx=%d moving to %d\n",
6002                                                         r1->rIdx, newreg->rIdx));
6003                                                 r2->rIdx = newreg->rIdx;
6004                                                 if(newreg->name)
6005                                                         r2->name = Safe_strdup(newreg->name);
6006                                                 else
6007                                                         r2->name = NULL;
6008                                                 newreg->isFree = 0;
6009                                                 newreg->wasUsed = 1;
6010                                         }
6011                                         r2 = setNextItem(pb->tregisters);
6012                                 }
6013                         }
6014                         
6015                         r1 = setNextItem(registersInCallPath);
6016                 }
6017                 
6018                 / * Collisions have been resolved. Now free the registers in the call path * /
6019                 r1 = setFirstItem(registersInCallPath);
6020                 while(r1) {
6021                         newreg = pic14_regWithIdx(r1->rIdx);
6022                         if (newreg) newreg->isFree = 1;
6023                         r1 = setNextItem(registersInCallPath);
6024                 }
6025                 
6026         }// else
6027         //      MarkUsedRegisters(pb->registers);
6028         
6029         registers = unionSets(pb->tregisters, registersInCallPath, THROW_NONE);
6030 #ifdef PCODE_DEBUG
6031         if(registers) 
6032                 DFPRINTF((stderr,"returning regs\n"));
6033         else
6034                 DFPRINTF((stderr,"not returning regs\n"));
6035         
6036         DFPRINTF((stderr,"pBlock after register optim.\n"));
6037         pBlockStats(stderr,pb);  // debug
6038 #endif
6039         
6040         return registers;
6041 }
6042 */
6043
6044 /*-----------------------------------------------------------------*/
6045 /* printCallTree - writes the call tree to a file                  */
6046 /*                                                                 */
6047 /*-----------------------------------------------------------------*/
6048 void pct2(FILE *of,pBlock *pb,int indent)
6049 {
6050         pCode *pc,*pcn;
6051         int i;
6052         //  set *registersInCallPath = NULL;
6053         
6054         if(!of)
6055                 return;
6056         
6057         if(indent > 10)
6058                 return; //recursion ?
6059         
6060         pc = setFirstItem(pb->function_entries);
6061         
6062         if(!pc)
6063                 return;
6064         
6065         pb->visited = 0;
6066         
6067         for(i=0;i<indent;i++)   // Indentation
6068                 fputc(' ',of);
6069         
6070         if(pc->type == PC_FUNCTION)
6071                 fprintf(of,"%s\n",PCF(pc)->fname);
6072         else
6073                 return;  // ???
6074         
6075         
6076         pc = setFirstItem(pb->function_calls);
6077         for( ; pc; pc = setNextItem(pb->function_calls)) {
6078                 
6079                 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
6080                         char *dest = get_op_from_instruction(PCI(pc));
6081                         
6082                         pcn = findFunction(dest);
6083                         if(pcn) 
6084                                 pct2(of,pcn->pb,indent+1);
6085                 } else
6086                         fprintf(of,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
6087                 
6088         }
6089         
6090         
6091 }
6092
6093
6094 /*-----------------------------------------------------------------*/
6095 /* printCallTree - writes the call tree to a file                  */
6096 /*                                                                 */
6097 /*-----------------------------------------------------------------*/
6098
6099 void printCallTree(FILE *of)
6100 {
6101         pBranch *pbr;
6102         pBlock  *pb;
6103         pCode   *pc;
6104         
6105         if(!the_pFile)
6106                 return;
6107         
6108         if(!of)
6109                 of = stderr;
6110         
6111         fprintf(of, "\npBlock statistics\n");
6112         for(pb = the_pFile->pbHead; pb;  pb = pb->next )
6113                 pBlockStats(of,pb);
6114         
6115         
6116         
6117         fprintf(of,"Call Tree\n");
6118         pbr = the_pFile->functions;
6119         while(pbr) {
6120                 if(pbr->pc) {
6121                         pc = pbr->pc;
6122                         if(!ispCodeFunction(pc))
6123                                 fprintf(of,"bug in call tree");
6124                         
6125                         
6126                         fprintf(of,"Function: %s\n", PCF(pc)->fname);
6127                         
6128                         while(pc->next && !ispCodeFunction(pc->next)) {
6129                                 pc = pc->next;
6130                                 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL)
6131                                         fprintf(of,"\t%s\n",get_op_from_instruction(PCI(pc)));
6132                         }
6133                 }
6134                 
6135                 pbr = pbr->next;
6136         }
6137         
6138         
6139         fprintf(of,"\n**************\n\na better call tree\n");
6140         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
6141                 if(pb->visited)
6142                         pct2(of,pb,0);
6143         }
6144         
6145         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
6146                 fprintf(of,"block dbname: %c\n", getpBlock_dbName(pb));
6147         }
6148 }
6149
6150
6151
6152 /*-----------------------------------------------------------------*/
6153 /*                                                                 */
6154 /*-----------------------------------------------------------------*/
6155
6156 void InlineFunction(pBlock *pb)
6157 {
6158         pCode *pc;
6159         pCode *pc_call;
6160         
6161         if(!pb)
6162                 return;
6163         
6164         pc = setFirstItem(pb->function_calls);
6165         
6166         for( ; pc; pc = setNextItem(pb->function_calls)) {
6167                 
6168                 if(isCALL(pc)) {
6169                         pCode *pcn = findFunction(get_op_from_instruction(PCI(pc)));
6170                         pCode *pcp = pc->prev;
6171                         pCode *pct;
6172                         pCode *pce;
6173                         
6174                         pBranch *pbr;
6175                         
6176                         if(pcn && isPCF(pcn) && (PCF(pcn)->ncalled == 1) && !PCF(pcn)->isPublic && (pcp && (isPCI_BITSKIP(pcp)||!isPCI_SKIP(pcp)))) { /* Bit skips can be inverted other skips can not */
6177                                 
6178                                 InlineFunction(pcn->pb);
6179                                 
6180                                 /*
6181                                 At this point, *pc points to a CALL mnemonic, and
6182                                 *pcn points to the function that is being called.
6183                                 
6184                                   To in-line this call, we need to remove the CALL
6185                                   and RETURN(s), and link the function pCode in with
6186                                   the CALLee pCode.
6187                                   
6188                                 */
6189                                 
6190                                 pc_call = pc;
6191                                 
6192                                 /* Check if previous instruction was a bit skip */
6193                                 if (isPCI_BITSKIP(pcp)) {
6194                                         pCodeLabel *pcl;
6195                                         /* Invert skip instruction and add a goto */
6196                                         PCI(pcp)->op = (PCI(pcp)->op == POC_BTFSS) ? POC_BTFSC : POC_BTFSS;
6197                                         
6198                                         if(isPCL(pc_call->next)) { // Label pcode
6199                                                 pcl = PCL(pc_call->next);
6200                                         } else if (isPCI(pc_call->next) && PCI(pc_call->next)->label) { // pcode instruction with a label
6201                                                 pcl = PCL(PCI(pc_call->next)->label->pc);
6202                                         } else {
6203                                                 pcl = PCL(newpCodeLabel(NULL, newiTempLabel(NULL)->key+100));
6204                                                 PCI(pc_call->next)->label->pc = (struct pCode*)pcl;
6205                                         }
6206                                         pCodeInsertAfter(pcp, newpCode(POC_GOTO, newpCodeOp(pcl->label,PO_STR)));
6207                                 }
6208                                 
6209                                 /* remove callee pBlock from the pBlock linked list */
6210                                 removepBlock(pcn->pb);
6211                                 
6212                                 pce = pcn;
6213                                 while(pce) {
6214                                         pce->pb = pb;
6215                                         pce = pce->next;
6216                                 }
6217                                 
6218                                 /* Remove the Function pCode */
6219                                 pct = findNextInstruction(pcn->next);
6220                                 
6221                                 /* Link the function with the callee */
6222                                 if (pcp) pcp->next = pcn->next;
6223                                 pcn->next->prev = pcp;
6224                                 
6225                                 /* Convert the function name into a label */
6226                                 
6227                                 pbr = Safe_calloc(1,sizeof(pBranch));
6228                                 pbr->pc = newpCodeLabel(PCF(pcn)->fname, -1);
6229                                 pbr->next = NULL;
6230                                 PCI(pct)->label = pBranchAppend(PCI(pct)->label,pbr);
6231                                 PCI(pct)->label = pBranchAppend(PCI(pct)->label,PCI(pc_call)->label);
6232                                 
6233                                 /* turn all of the return's except the last into goto's */
6234                                 /* check case for 2 instruction pBlocks */
6235                                 pce = findNextInstruction(pcn->next);
6236                                 while(pce) {
6237                                         pCode *pce_next = findNextInstruction(pce->next);
6238                                         
6239                                         if(pce_next == NULL) {
6240                                                 /* found the last return */
6241                                                 pCode *pc_call_next =  findNextInstruction(pc_call->next);
6242                                                 
6243                                                 //fprintf(stderr,"found last return\n");
6244                                                 //pce->print(stderr,pce);
6245                                                 pce->prev->next = pc_call->next;
6246                                                 pc_call->next->prev = pce->prev;
6247                                                 PCI(pc_call_next)->label = pBranchAppend(PCI(pc_call_next)->label,
6248                                                         PCI(pce)->label);
6249                                         }
6250                                         
6251                                         pce = pce_next;
6252                                 }
6253                                 
6254                         }
6255                 } else
6256                         fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
6257                 
6258         }
6259         
6260 }
6261
6262 /*-----------------------------------------------------------------*/
6263 /*                                                                 */
6264 /*-----------------------------------------------------------------*/
6265
6266 void InlinepCode(void)
6267 {
6268         
6269         pBlock  *pb;
6270         pCode   *pc;
6271         
6272         if(!the_pFile)
6273                 return;
6274         
6275         if(!functionInlining)
6276                 return;
6277         
6278                 /* Loop through all of the function definitions and count the
6279         * number of times each one is called */
6280         //fprintf(stderr,"inlining %d\n",__LINE__);
6281         
6282         for(pb = the_pFile->pbHead; pb; pb = pb->next) {
6283                 
6284                 pc = setFirstItem(pb->function_calls);
6285                 
6286                 for( ; pc; pc = setNextItem(pb->function_calls)) {
6287                         
6288                         if(isCALL(pc)) {
6289                                 pCode *pcn = findFunction(get_op_from_instruction(PCI(pc)));
6290                                 if(pcn && isPCF(pcn)) {
6291                                         PCF(pcn)->ncalled++;
6292                                 }
6293                         } else
6294                                 fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
6295                         
6296                 }
6297         }
6298         
6299         //fprintf(stderr,"inlining %d\n",__LINE__);
6300         
6301         /* Now, Loop through the function definitions again, but this
6302         * time inline those functions that have only been called once. */
6303         
6304         InlineFunction(the_pFile->pbHead);
6305         //fprintf(stderr,"inlining %d\n",__LINE__);
6306         
6307         for(pb = the_pFile->pbHead; pb; pb = pb->next)
6308                 unBuildFlow(pb);
6309         
6310 }