]> git.sur5r.net Git - cc65/blob - src/cc65/codeseg.c
More debugging output
[cc65] / src / cc65 / codeseg.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 codeseg.c                                 */
4 /*                                                                           */
5 /*                          Code segment structure                           */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001-2004 Ullrich von Bassewitz                                       */
10 /*               Römerstrasse 52                                             */
11 /*               D-70794 Filderstadt                                         */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <string.h>
37 #include <ctype.h>
38
39 /* common */
40 #include "chartype.h"
41 #include "check.h"
42 #include "debugflag.h"
43 #include "global.h"
44 #include "hashstr.h"
45 #include "strutil.h"
46 #include "xmalloc.h"
47 #include "xsprintf.h"
48
49 /* cc65 */
50 #include "asmlabel.h"
51 #include "codeent.h"
52 #include "codeinfo.h"
53 #include "datatype.h"
54 #include "error.h"
55 #include "ident.h"
56 #include "symentry.h"
57 #include "codeseg.h"
58
59
60
61 /*****************************************************************************/
62 /*                             Helper functions                              */
63 /*****************************************************************************/
64
65
66
67 static void CS_PrintFunctionHeader (const CodeSeg* S, FILE* F)
68 /* Print a comment with the function signature to the given file */
69 {
70     /* Get the associated function */
71     const SymEntry* Func = S->Func;
72
73     /* If this is a global code segment, do nothing */
74     if (Func) {
75         fprintf (F,
76                  "; ---------------------------------------------------------------\n"
77                  "; ");
78         PrintFuncSig (F, Func->Name, Func->Type);
79         fprintf (F,
80                  "\n"
81                  "; ---------------------------------------------------------------\n"
82                  "\n");
83     }
84 }
85
86
87
88 static void CS_MoveLabelsToEntry (CodeSeg* S, CodeEntry* E)
89 /* Move all labels from the label pool to the given entry and remove them
90  * from the pool.
91  */
92 {
93     /* Transfer the labels if we have any */
94     unsigned I;
95     unsigned LabelCount = CollCount (&S->Labels);
96     for (I = 0; I < LabelCount; ++I) {
97
98         /* Get the label */
99         CodeLabel* L = CollAt (&S->Labels, I);
100
101         /* Attach it to the entry */
102         CE_AttachLabel (E, L);
103     }
104
105     /* Delete the transfered labels */
106     CollDeleteAll (&S->Labels);
107 }
108
109
110
111 static void CS_MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
112 /* Move the labels of the code entry E to the label pool of the code segment */
113 {
114     unsigned LabelCount = CE_GetLabelCount (E);
115     while (LabelCount--) {
116         CodeLabel* L = CE_GetLabel (E, LabelCount);
117         L->Owner = 0;
118         CollAppend (&S->Labels, L);
119     }
120     CollDeleteAll (&E->Labels);
121 }
122
123
124
125 static CodeLabel* CS_FindLabel (CodeSeg* S, const char* Name, unsigned Hash)
126 /* Find the label with the given name. Return the label or NULL if not found */
127 {
128     /* Get the first hash chain entry */
129     CodeLabel* L = S->LabelHash[Hash];
130
131     /* Search the list */
132     while (L) {
133         if (strcmp (Name, L->Name) == 0) {
134             /* Found */
135             break;
136         }
137         L = L->Next;
138     }
139     return L;
140 }
141
142
143
144 static CodeLabel* CS_NewCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
145 /* Create a new label and insert it into the label hash table */
146 {
147     /* Create a new label */
148     CodeLabel* L = NewCodeLabel (Name, Hash);
149
150     /* Enter the label into the hash table */
151     L->Next = S->LabelHash[L->Hash];
152     S->LabelHash[L->Hash] = L;
153
154     /* Return the new label */
155     return L;
156 }
157
158
159
160 static void CS_RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
161 /* Remove the given code label from the hash list */
162 {
163     /* Get the first entry in the hash chain */
164     CodeLabel* List = S->LabelHash[L->Hash];
165     CHECK (List != 0);
166
167     /* First, remove the label from the hash chain */
168     if (List == L) {
169         /* First entry in hash chain */
170         S->LabelHash[L->Hash] = L->Next;
171     } else {
172         /* Must search through the chain */
173         while (List->Next != L) {
174             /* If we've reached the end of the chain, something is *really* wrong */
175             CHECK (List->Next != 0);
176             /* Next entry */
177             List = List->Next;
178         }
179         /* The next entry is the one, we have been searching for */
180         List->Next = L->Next;
181     }
182 }
183
184
185
186 /*****************************************************************************/
187 /*                    Functions for parsing instructions                     */
188 /*****************************************************************************/
189
190
191
192 static const char* SkipSpace (const char* S)
193 /* Skip white space and return an updated pointer */
194 {
195     while (IsSpace (*S)) {
196         ++S;
197     }
198     return S;
199 }
200
201
202
203 static const char* ReadToken (const char* L, const char* Term,
204                               char* Buf, unsigned BufSize)
205 /* Read the next token into Buf, return the updated line pointer. The
206  * token is terminated by one of the characters given in term.
207  */
208 {
209     /* Read/copy the token */
210     unsigned I = 0;
211     unsigned ParenCount = 0;
212     while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
213         if (I < BufSize-1) {
214             Buf[I] = *L;
215         } else if (I == BufSize-1) {
216             /* Cannot store this character, this is an input error (maybe
217              * identifier too long or similar).
218              */
219             Error ("ASM code error: syntax error");
220         }
221         ++I;
222         if (*L == ')') {
223             --ParenCount;
224         } else if (*L == '(') {
225             ++ParenCount;
226         }
227         ++L;
228     }
229
230     /* Terminate the buffer contents */
231     Buf[I] = '\0';
232
233     /* Return the updated line pointer */
234     return L;
235 }
236
237
238
239 static CodeEntry* ParseInsn (CodeSeg* S, LineInfo* LI, const char* L)
240 /* Parse an instruction nnd generate a code entry from it. If the line contains
241  * errors, output an error message and return NULL.
242  * For simplicity, we don't accept the broad range of input a "real" assembler
243  * does. The instruction and the argument are expected to be separated by
244  * white space, for example.
245  */
246 {
247     char                Mnemo[IDENTSIZE+10];
248     const OPCDesc*      OPC;
249     am_t                AM = 0;         /* Initialize to keep gcc silent */
250     char                Arg[IDENTSIZE+10];
251     char                Reg;
252     CodeEntry*          E;
253     CodeLabel*          Label;
254
255     /* Read the first token and skip white space after it */
256     L = SkipSpace (ReadToken (L, " \t:", Mnemo, sizeof (Mnemo)));
257
258     /* Check if we have a label */
259     if (*L == ':') {
260
261         /* Skip the colon and following white space */
262         L = SkipSpace (L+1);
263
264         /* Add the label */
265         CS_AddLabel (S, Mnemo);
266
267         /* If we have reached end of line, bail out, otherwise a mnemonic
268          * may follow.
269          */
270         if (*L == '\0') {
271             return 0;
272         }
273
274         L = SkipSpace (ReadToken (L, " \t", Mnemo, sizeof (Mnemo)));
275     }
276
277     /* Try to find the opcode description for the mnemonic */
278     OPC = FindOP65 (Mnemo);
279
280     /* If we didn't find the opcode, print an error and bail out */
281     if (OPC == 0) {
282         Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
283         return 0;
284     }
285
286     /* Get the addressing mode */
287     Arg[0] = '\0';
288     switch (*L) {
289
290         case '\0':
291             /* Implicit */
292             AM = AM65_IMP;
293             break;
294
295         case '#':
296             /* Immidiate */
297             StrCopy (Arg, sizeof (Arg), L+1);
298             AM = AM65_IMM;
299             break;
300
301         case '(':
302             /* Indirect */
303             L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
304
305             /* Check for errors */
306             if (*L == '\0') {
307                 Error ("ASM code error: syntax error");
308                 return 0;
309             }
310
311             /* Check the different indirect modes */
312             if (*L == ',') {
313                 /* Expect zp x indirect */
314                 L = SkipSpace (L+1);
315                 if (toupper (*L) != 'X') {
316                     Error ("ASM code error: `X' expected");
317                     return 0;
318                 }
319                 L = SkipSpace (L+1);
320                 if (*L != ')') {
321                     Error ("ASM code error: `)' expected");
322                     return 0;
323                 }
324                 L = SkipSpace (L+1);
325                 if (*L != '\0') {
326                     Error ("ASM code error: syntax error");
327                     return 0;
328                 }
329                 AM = AM65_ZPX_IND;
330             } else if (*L == ')') {
331                 /* zp indirect or zp indirect, y */
332                 L = SkipSpace (L+1);
333                 if (*L == ',') {
334                     L = SkipSpace (L+1);
335                     if (toupper (*L) != 'Y') {
336                         Error ("ASM code error: `Y' expected");
337                         return 0;
338                     }
339                     L = SkipSpace (L+1);
340                     if (*L != '\0') {
341                         Error ("ASM code error: syntax error");
342                         return 0;
343                     }
344                     AM = AM65_ZP_INDY;
345                 } else if (*L == '\0') {
346                     AM = AM65_ZP_IND;
347                 } else {
348                     Error ("ASM code error: syntax error");
349                     return 0;
350                 }
351             }
352             break;
353
354         case 'a':
355         case 'A':
356             /* Accumulator? */
357             if (L[1] == '\0') {
358                 AM = AM65_ACC;
359                 break;
360             }
361             /* FALLTHROUGH */
362
363         default:
364             /* Absolute, maybe indexed */
365             L = ReadToken (L, ",", Arg, sizeof (Arg));
366             if (*L == '\0') {
367                 /* Absolute, zeropage or branch */
368                 if ((OPC->Info & OF_BRA) != 0) {
369                     /* Branch */
370                     AM = AM65_BRA;
371                 } else if (GetZPInfo(Arg) != 0) {
372                     AM = AM65_ZP;
373                 } else {
374                     AM = AM65_ABS;
375                 }
376             } else if (*L == ',') {
377                 /* Indexed */
378                 L = SkipSpace (L+1);
379                 if (*L == '\0') {
380                     Error ("ASM code error: syntax error");
381                     return 0;
382                 } else {
383                     Reg = toupper (*L);
384                     L = SkipSpace (L+1);
385                     if (Reg == 'X') {
386                         if (GetZPInfo(Arg) != 0) {
387                             AM = AM65_ZPX;
388                         } else {
389                             AM = AM65_ABSX;
390                         }
391                     } else if (Reg == 'Y') {
392                         AM = AM65_ABSY;
393                     } else {
394                         Error ("ASM code error: syntax error");
395                         return 0;
396                     }
397                     if (*L != '\0') {
398                         Error ("ASM code error: syntax error");
399                         return 0;
400                     }
401                 }
402             }
403             break;
404
405     }
406
407     /* If the instruction is a branch, check for the label and generate it
408      * if it does not exist. This may lead to unused labels (if the label
409      * is actually an external one) which are removed by the CS_MergeLabels
410      * function later.
411      */
412     Label = 0;
413     if (AM == AM65_BRA) {
414
415         /* Generate the hash over the label, then search for the label */
416         unsigned Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
417         Label = CS_FindLabel (S, Arg, Hash);
418
419         /* If we don't have the label, it's a forward ref - create it */
420         if (Label == 0) {
421             /* Generate a new label */
422             Label = CS_NewCodeLabel (S, Arg, Hash);
423         }
424     }
425
426     /* We do now have the addressing mode in AM. Allocate a new CodeEntry
427      * structure and initialize it.
428      */
429     E = NewCodeEntry (OPC->OPC, AM, Arg, Label, LI);
430
431     /* Return the new code entry */
432     return E;
433 }
434
435
436
437 /*****************************************************************************/
438 /*                                   Code                                    */
439 /*****************************************************************************/
440
441
442
443 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
444 /* Create a new code segment, initialize and return it */
445 {
446     unsigned I;
447     const type* RetType;
448
449     /* Allocate memory */
450     CodeSeg* S = xmalloc (sizeof (CodeSeg));
451
452     /* Initialize the fields */
453     S->SegName  = xstrdup (SegName);
454     S->Func     = Func;
455     InitCollection (&S->Entries);
456     InitCollection (&S->Labels);
457     for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
458         S->LabelHash[I] = 0;
459     }
460
461     /* If we have a function given, get the return type of the function.
462      * Assume ANY return type besides void will use the A and X registers.
463      */
464     if (S->Func && !IsTypeVoid ((RetType = GetFuncReturn (Func->Type)))) {
465         if (SizeOf (RetType) == SizeOf (type_long)) {
466             S->ExitRegs = REG_EAX;
467         } else {
468             S->ExitRegs = REG_AX;
469         }
470     } else {
471         S->ExitRegs = REG_NONE;
472     }
473
474     /* Return the new struct */
475     return S;
476 }
477
478
479
480 void CS_AddEntry (CodeSeg* S, struct CodeEntry* E)
481 /* Add an entry to the given code segment */
482 {
483     /* Transfer the labels if we have any */
484     CS_MoveLabelsToEntry (S, E);
485
486     /* Add the entry to the list of code entries in this segment */
487     CollAppend (&S->Entries, E);
488 }
489
490
491
492 void CS_AddVLine (CodeSeg* S, LineInfo* LI, const char* Format, va_list ap)
493 /* Add a line to the given code segment */
494 {
495     const char* L;
496     CodeEntry*  E;
497     char        Token[IDENTSIZE+10];
498
499     /* Format the line */
500     char Buf [256];
501     xvsprintf (Buf, sizeof (Buf), Format, ap);
502
503     /* Skip whitespace */
504     L = SkipSpace (Buf);
505
506     /* Check which type of instruction we have */
507     E = 0;      /* Assume no insn created */
508     switch (*L) {
509
510         case '\0':
511             /* Empty line, just ignore it */
512             break;
513
514         case ';':
515             /* Comment or hint, ignore it for now */
516             break;
517
518         case '.':
519             /* Control instruction */
520             ReadToken (L, " \t", Token, sizeof (Token));
521             Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
522             break;
523
524         default:
525             E = ParseInsn (S, LI, L);
526             break;
527     }
528
529     /* If we have a code entry, transfer the labels and insert it */
530     if (E) {
531         CS_AddEntry (S, E);
532     }
533 }
534
535
536
537 void CS_AddLine (CodeSeg* S, LineInfo* LI, const char* Format, ...)
538 /* Add a line to the given code segment */
539 {
540     va_list ap;
541     va_start (ap, Format);
542     CS_AddVLine (S, LI, Format, ap);
543     va_end (ap);
544 }
545
546
547
548 void CS_InsertEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
549 /* Insert the code entry at the index given. Following code entries will be
550  * moved to slots with higher indices.
551  */
552 {
553     /* Insert the entry into the collection */
554     CollInsert (&S->Entries, E, Index);
555 }
556
557
558
559 void CS_DelEntry (CodeSeg* S, unsigned Index)
560 /* Delete an entry from the code segment. This includes moving any associated
561  * labels, removing references to labels and even removing the referenced labels
562  * if the reference count drops to zero.
563  * Note: Labels are moved forward if possible, that is, they are moved to the
564  * next insn (not the preceeding one).
565  */
566 {
567     /* Get the code entry for the given index */
568     CodeEntry* E = CS_GetEntry (S, Index);
569
570     /* If the entry has a labels, we have to move this label to the next insn.
571      * If there is no next insn, move the label into the code segement label
572      * pool. The operation is further complicated by the fact that the next
573      * insn may already have a label. In that case change all reference to
574      * this label and delete the label instead of moving it.
575      */
576     unsigned Count = CE_GetLabelCount (E);
577     if (Count > 0) {
578
579         /* The instruction has labels attached. Check if there is a next
580          * instruction.
581          */
582         if (Index == CS_GetEntryCount (S)-1) {
583
584             /* No next instruction, move to the codeseg label pool */
585             CS_MoveLabelsToPool (S, E);
586
587         } else {
588
589             /* There is a next insn, get it */
590             CodeEntry* N = CS_GetEntry (S, Index+1);
591
592             /* Move labels to the next entry */
593             CS_MoveLabels (S, E, N);
594
595         }
596     }
597
598     /* If this insn references a label, remove the reference. And, if the
599      * the reference count for this label drops to zero, remove this label.
600      */
601     if (E->JumpTo) {
602         /* Remove the reference */
603         CS_RemoveLabelRef (S, E);
604     }
605
606     /* Delete the pointer to the insn */
607     CollDelete (&S->Entries, Index);
608
609     /* Delete the instruction itself */
610     FreeCodeEntry (E);
611 }
612
613
614
615 void CS_DelEntries (CodeSeg* S, unsigned Start, unsigned Count)
616 /* Delete a range of code entries. This includes removing references to labels,
617  * labels attached to the entries and so on.
618  */
619 {
620     /* Start deleting the entries from the rear, because this involves less
621      * memory moving.
622      */
623     while (Count--) {
624         CS_DelEntry (S, Start + Count);
625     }
626 }
627
628
629
630 void CS_MoveEntries (CodeSeg* S, unsigned Start, unsigned Count, unsigned NewPos)
631 /* Move a range of entries from one position to another. Start is the index
632  * of the first entry to move, Count is the number of entries and NewPos is
633  * the index of the target entry. The entry with the index Start will later
634  * have the index NewPos. All entries with indices NewPos and above are
635  * moved to higher indices. If the code block is moved to the end of the
636  * current code, and if pending labels exist, these labels will get attached
637  * to the first instruction of the moved block (the first one after the
638  * current code end)
639  */
640 {
641     /* If NewPos is at the end of the code segment, move any labels from the
642      * label pool to the first instruction of the moved range.
643      */
644     if (NewPos == CS_GetEntryCount (S)) {
645         CS_MoveLabelsToEntry (S, CS_GetEntry (S, Start));
646     }
647
648     /* Move the code block to the destination */
649     CollMoveMultiple (&S->Entries, Start, Count, NewPos);
650 }
651
652
653
654 struct CodeEntry* CS_GetPrevEntry (CodeSeg* S, unsigned Index)
655 /* Get the code entry preceeding the one with the index Index. If there is no
656  * preceeding code entry, return NULL.
657  */
658 {
659     if (Index == 0) {
660         /* This is the first entry */
661         return 0;
662     } else {
663         /* Previous entry available */
664         return CollAtUnchecked (&S->Entries, Index-1);
665     }
666 }
667
668
669
670 struct CodeEntry* CS_GetNextEntry (CodeSeg* S, unsigned Index)
671 /* Get the code entry following the one with the index Index. If there is no
672  * following code entry, return NULL.
673  */
674 {
675     if (Index >= CollCount (&S->Entries)-1) {
676         /* This is the last entry */
677         return 0;
678     } else {
679         /* Code entries left */
680         return CollAtUnchecked (&S->Entries, Index+1);
681     }
682 }
683
684
685
686 int CS_GetEntries (CodeSeg* S, struct CodeEntry** List,
687                    unsigned Start, unsigned Count)
688 /* Get Count code entries into List starting at index start. Return true if
689  * we got the lines, return false if not enough lines were available.
690  */
691 {
692     /* Check if enough entries are available */
693     if (Start + Count > CollCount (&S->Entries)) {
694         return 0;
695     }
696
697     /* Copy the entries */
698     while (Count--) {
699         *List++ = CollAtUnchecked (&S->Entries, Start++);
700     }
701
702     /* We have the entries */
703     return 1;
704 }
705
706
707
708 unsigned CS_GetEntryIndex (CodeSeg* S, struct CodeEntry* E)
709 /* Return the index of a code entry */
710 {
711     int Index = CollIndex (&S->Entries, E);
712     CHECK (Index >= 0);
713     return Index;
714 }
715
716
717
718 int CS_RangeHasLabel (CodeSeg* S, unsigned Start, unsigned Count)
719 /* Return true if any of the code entries in the given range has a label
720  * attached. If the code segment does not span the given range, check the
721  * possible span instead.
722  */
723 {
724     unsigned EntryCount = CS_GetEntryCount(S);
725
726     /* Adjust count. We expect at least Start to be valid. */
727     CHECK (Start < EntryCount);
728     if (Start + Count > EntryCount) {
729         Count = EntryCount - Start;
730     }
731
732     /* Check each entry. Since we have validated the index above, we may
733      * use the unchecked access function in the loop which is faster.
734      */
735     while (Count--) {
736         const CodeEntry* E = CollAtUnchecked (&S->Entries, Start++);
737         if (CE_HasLabel (E)) {
738             return 1;
739         }
740     }
741
742     /* No label in the complete range */
743     return 0;
744 }
745
746
747
748 CodeLabel* CS_AddLabel (CodeSeg* S, const char* Name)
749 /* Add a code label for the next instruction to follow */
750 {
751     /* Calculate the hash from the name */
752     unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
753
754     /* Try to find the code label if it does already exist */
755     CodeLabel* L = CS_FindLabel (S, Name, Hash);
756
757     /* Did we find it? */
758     if (L) {
759         /* We found it - be sure it does not already have an owner */
760         if (L->Owner) {
761             Error ("ASM label `%s' is already defined", Name);
762             return L;
763         }
764     } else {
765         /* Not found - create a new one */
766         L = CS_NewCodeLabel (S, Name, Hash);
767     }
768
769     /* Safety. This call is quite costly, but safety is better */
770     if (CollIndex (&S->Labels, L) >= 0) {
771         Error ("ASM label `%s' is already defined", Name);
772         return L;
773     }
774
775     /* We do now have a valid label. Remember it for later */
776     CollAppend (&S->Labels, L);
777
778     /* Return the label */
779     return L;
780 }
781
782
783
784 CodeLabel* CS_GenLabel (CodeSeg* S, struct CodeEntry* E)
785 /* If the code entry E does already have a label, return it. Otherwise
786  * create a new label, attach it to E and return it.
787  */
788 {
789     CodeLabel* L;
790
791     if (CE_HasLabel (E)) {
792
793         /* Get the label from this entry */
794         L = CE_GetLabel (E, 0);
795
796     } else {
797
798         /* Get a new name */
799         const char* Name = LocalLabelName (GetLocalLabel ());
800
801         /* Generate the hash over the name */
802         unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
803
804         /* Create a new label */
805         L = CS_NewCodeLabel (S, Name, Hash);
806
807         /* Attach this label to the code entry */
808         CE_AttachLabel (E, L);
809
810     }
811
812     /* Return the label */
813     return L;
814 }
815
816
817
818 void CS_DelLabel (CodeSeg* S, CodeLabel* L)
819 /* Remove references from this label and delete it. */
820 {
821     unsigned Count, I;
822
823     /* First, remove the label from the hash chain */
824     CS_RemoveLabelFromHash (S, L);
825
826     /* Remove references from insns jumping to this label */
827     Count = CollCount (&L->JumpFrom);
828     for (I = 0; I < Count; ++I) {
829         /* Get the insn referencing this label */
830         CodeEntry* E = CollAt (&L->JumpFrom, I);
831         /* Remove the reference */
832         E->JumpTo = 0;
833     }
834     CollDeleteAll (&L->JumpFrom);
835
836     /* Remove the reference to the owning instruction if it has one. The
837      * function may be called for a label without an owner when deleting
838      * unfinished parts of the code. This is unfortunate since it allows
839      * errors to slip through.
840      */
841     if (L->Owner) {
842         CollDeleteItem (&L->Owner->Labels, L);
843     }
844
845     /* All references removed, delete the label itself */
846     FreeCodeLabel (L);
847 }
848
849
850
851 void CS_MergeLabels (CodeSeg* S)
852 /* Merge code labels. That means: For each instruction, remove all labels but
853  * one and adjust references accordingly.
854  */
855 {
856     unsigned I;
857     unsigned J;
858
859     /* First, remove all labels from the label symbol table that don't have an
860      * owner (this means that they are actually external labels but we didn't
861      * know that previously since they may have also been forward references).
862      */
863     for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) {
864
865         /* Get the first label in this hash chain */
866         CodeLabel** L = &S->LabelHash[I];
867         while (*L) {
868             if ((*L)->Owner == 0) {
869
870                 /* The label does not have an owner, remove it from the chain */
871                 CodeLabel* X = *L;
872                 *L = X->Next;
873
874                 /* Cleanup any entries jumping to this label */
875                 for (J = 0; J < CL_GetRefCount (X); ++J) {
876                     /* Get the entry referencing this label */
877                     CodeEntry* E = CL_GetRef (X, J);
878                     /* And remove the reference */
879                     E->JumpTo = 0;
880                 }
881
882                 /* Print some debugging output */
883                 if (Debug) {
884                     printf ("Removing unused global label `%s'", X->Name);
885                 }
886
887                 /* And free the label */
888                 FreeCodeLabel (X);
889             } else {
890                 /* Label is owned, point to next code label pointer */
891                 L = &((*L)->Next);
892             }
893         }
894     }
895
896     /* Walk over all code entries */
897     for (I = 0; I < CS_GetEntryCount (S); ++I) {
898
899         CodeLabel* RefLab;
900         unsigned   J;
901
902         /* Get a pointer to the next entry */
903         CodeEntry* E = CS_GetEntry (S, I);
904
905         /* If this entry has zero labels, continue with the next one */
906         unsigned LabelCount = CE_GetLabelCount (E);
907         if (LabelCount == 0) {
908             continue;
909         }
910
911         /* We have at least one label. Use the first one as reference label. */
912         RefLab = CE_GetLabel (E, 0);
913
914         /* Walk through the remaining labels and change references to these
915          * labels to a reference to the one and only label. Delete the labels
916          * that are no longer used. To increase performance, walk backwards
917          * through the list.
918          */
919         for (J = LabelCount-1; J >= 1; --J) {
920
921             /* Get the next label */
922             CodeLabel* L = CE_GetLabel (E, J);
923
924             /* Move all references from this label to the reference label */
925             CL_MoveRefs (L, RefLab);
926
927             /* Remove the label completely. */
928             CS_DelLabel (S, L);
929         }
930
931         /* The reference label is the only remaining label. Check if there
932          * are any references to this label, and delete it if this is not
933          * the case.
934          */
935         if (CollCount (&RefLab->JumpFrom) == 0) {
936             /* Delete the label */
937             CS_DelLabel (S, RefLab);
938         }
939     }
940 }
941
942
943
944 void CS_MoveLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
945 /* Move all labels from Old to New. The routine will move the labels itself
946  * if New does not have any labels, and move references if there is at least
947  * a label for new. If references are moved, the old label is deleted
948  * afterwards.
949  */
950 {
951     /* Get the number of labels to move */
952     unsigned OldLabelCount = CE_GetLabelCount (Old);
953
954     /* Does the new entry have itself a label? */
955     if (CE_HasLabel (New)) {
956
957         /* The new entry does already have a label - move references */
958         CodeLabel* NewLabel = CE_GetLabel (New, 0);
959         while (OldLabelCount--) {
960
961             /* Get the next label */
962             CodeLabel* OldLabel = CE_GetLabel (Old, OldLabelCount);
963
964             /* Move references */
965             CL_MoveRefs (OldLabel, NewLabel);
966
967             /* Delete the label */
968             CS_DelLabel (S, OldLabel);
969
970         }
971
972     } else {
973
974         /* The new entry does not have a label, just move them */
975         while (OldLabelCount--) {
976
977             /* Move the label to the new entry */
978             CE_MoveLabel (CE_GetLabel (Old, OldLabelCount), New);
979
980         }
981
982     }
983 }
984
985
986
987 void CS_RemoveLabelRef (CodeSeg* S, struct CodeEntry* E)
988 /* Remove the reference between E and the label it jumps to. The reference
989  * will be removed on both sides and E->JumpTo will be 0 after that. If
990  * the reference was the only one for the label, the label will get
991  * deleted.
992  */
993 {
994     /* Get a pointer to the label and make sure it exists */
995     CodeLabel* L = E->JumpTo;
996     CHECK (L != 0);
997
998     /* Delete the entry from the label */
999     CollDeleteItem (&L->JumpFrom, E);
1000
1001     /* The entry jumps no longer to L */
1002     E->JumpTo = 0;
1003
1004     /* If there are no more references, delete the label */
1005     if (CollCount (&L->JumpFrom) == 0) {
1006         CS_DelLabel (S, L);
1007     }
1008 }
1009
1010
1011
1012 void CS_MoveLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
1013 /* Change the reference of E to L instead of the current one. If this
1014  * was the only reference to the old label, the old label will get
1015  * deleted.
1016  */
1017 {
1018     /* Get the old label */
1019     CodeLabel* OldLabel = E->JumpTo;
1020
1021     /* Be sure that code entry references a label */
1022     PRECONDITION (OldLabel != 0);
1023
1024     /* Remove the reference to our label */
1025     CS_RemoveLabelRef (S, E);
1026
1027     /* Use the new label */
1028     CL_AddRef (L, E);
1029 }
1030
1031
1032
1033 void CS_DelCodeAfter (CodeSeg* S, unsigned Last)
1034 /* Delete all entries including the given one */
1035 {
1036     /* Get the number of entries in this segment */
1037     unsigned Count = CS_GetEntryCount (S);
1038
1039     /* First pass: Delete all references to labels. If the reference count
1040      * for a label drops to zero, delete it.
1041      */
1042     unsigned C = Count;
1043     while (Last < C--) {
1044
1045         /* Get the next entry */
1046         CodeEntry* E = CS_GetEntry (S, C);
1047
1048         /* Check if this entry has a label reference */
1049         if (E->JumpTo) {
1050             /* If the label is a label in the label pool and this is the last
1051              * reference to the label, remove the label from the pool.
1052              */
1053             CodeLabel* L = E->JumpTo;
1054             int Index = CollIndex (&S->Labels, L);
1055             if (Index >= 0 && CollCount (&L->JumpFrom) == 1) {
1056                 /* Delete it from the pool */
1057                 CollDelete (&S->Labels, Index);
1058             }
1059
1060             /* Remove the reference to the label */
1061             CS_RemoveLabelRef (S, E);
1062         }
1063
1064     }
1065
1066     /* Second pass: Delete the instructions. If a label attached to an
1067      * instruction still has references, it must be references from outside
1068      * the deleted area. Don't delete the label in this case, just make it
1069      * ownerless and move it to the label pool.
1070      */
1071     C = Count;
1072     while (Last < C--) {
1073
1074         /* Get the next entry */
1075         CodeEntry* E = CS_GetEntry (S, C);
1076
1077         /* Check if this entry has a label attached */
1078         if (CE_HasLabel (E)) {
1079             /* Move the labels to the pool and clear the owner pointer */
1080             CS_MoveLabelsToPool (S, E);
1081         }
1082
1083         /* Delete the pointer to the entry */
1084         CollDelete (&S->Entries, C);
1085
1086         /* Delete the entry itself */
1087         FreeCodeEntry (E);
1088     }
1089 }
1090
1091
1092
1093 void CS_ResetMarks (CodeSeg* S, unsigned First, unsigned Last)
1094 /* Remove all user marks from the entries in the given range */
1095 {
1096     while (First <= Last) {
1097         CE_ResetMark (CS_GetEntry (S, First++));
1098     }
1099 }
1100
1101
1102
1103 int CS_IsBasicBlock (CodeSeg* S, unsigned First, unsigned Last)
1104 /* Check if the given code segment range is a basic block. That is, check if
1105  * First is the only entrance and Last is the only exit. This means that no
1106  * jump/branch inside the block may jump to an insn below First or after(!)
1107  * Last, and that no insn may jump into this block from the outside.
1108  */
1109 {
1110     unsigned I;
1111
1112     /* Don't accept invalid ranges */
1113     CHECK (First <= Last);
1114
1115     /* First pass: Walk over the range and remove all marks from the entries */
1116     CS_ResetMarks (S, First, Last);
1117
1118     /* Second pass: Walk over the range checking all labels. Note: There may be
1119      * label on the first insn which is ok.
1120      */
1121     I = First + 1;
1122     while (I <= Last) {
1123
1124         /* Get the next entry */
1125         CodeEntry* E = CS_GetEntry (S, I);
1126
1127         /* Check if this entry has one or more labels, if so, check which
1128          * entries jump to this label.
1129          */
1130         unsigned LabelCount = CE_GetLabelCount (E);
1131         unsigned LabelIndex;
1132         for (LabelIndex = 0; LabelIndex < LabelCount; ++LabelIndex) {
1133
1134             /* Get this label */
1135             CodeLabel* L = CE_GetLabel (E, LabelIndex);
1136
1137             /* Walk over all entries that jump to this label. Check for each
1138              * of the entries if it is out of the range.
1139              */
1140             unsigned RefCount = CL_GetRefCount (L);
1141             unsigned RefIndex;
1142             for (RefIndex = 0; RefIndex < RefCount; ++RefIndex) {
1143
1144                 /* Get the code entry that jumps here */
1145                 CodeEntry* Ref = CL_GetRef (L, RefIndex);
1146
1147                 /* Walk over out complete range and check if we find the
1148                  * refering entry. This is cheaper than using CS_GetEntryIndex,
1149                  * because CS_GetEntryIndex will search the complete code
1150                  * segment and not just our range.
1151                  */
1152                 unsigned J;
1153                 for (J = First; J <= Last; ++J) {
1154                     if (Ref == CS_GetEntry (S, J)) {
1155                         break;
1156                     }
1157                 }
1158                 if (J > Last) {
1159                     /* We did not find the entry. This means that the jump to
1160                      * out code segment entry E came from outside the range,
1161                      * which in turn means that the given range is not a basic
1162                      * block.
1163                      */
1164                     CS_ResetMarks (S, First, Last);
1165                     return 0;
1166                 }
1167
1168                 /* If we come here, we found the entry. Mark it, so we know
1169                  * that the branch to the label is in range.
1170                  */
1171                 CE_SetMark (Ref);
1172             }
1173         }
1174
1175         /* Next entry */
1176         ++I;
1177     }
1178
1179     /* Third pass: Walk again over the range and check all branches. If we
1180      * find a branch that is not marked, its target is not inside the range
1181      * (since we checked all the labels in the range before).
1182      */
1183     I = First;
1184     while (I <= Last) {
1185
1186         /* Get the next entry */
1187         CodeEntry* E = CS_GetEntry (S, I);
1188
1189         /* Check if this is a branch and if so, if it has a mark */
1190         if (E->Info & (OF_UBRA | OF_CBRA)) {
1191             if (!CE_HasMark (E)) {
1192                 /* No mark means not a basic block. Before bailing out, be sure
1193                  * to remove the marks from the remaining entries.
1194                  */
1195                 CS_ResetMarks (S, I+1, Last);
1196                 return 0;
1197             }
1198
1199             /* Remove the mark */
1200             CE_ResetMark (E);
1201         }
1202
1203         /* Next entry */
1204         ++I;
1205     }
1206
1207     /* Done - this is a basic block */
1208     return 1;
1209 }
1210
1211
1212
1213 void CS_OutputPrologue (const CodeSeg* S, FILE* F)
1214 /* If the given code segment is a code segment for a function, output the
1215  * assembler prologue into the file. That is: Output a comment header, switch
1216  * to the correct segment and enter the local function scope. If the code
1217  * segment is global, do nothing.
1218  */
1219 {
1220     /* Get the function associated with the code segment */
1221     SymEntry* Func = S->Func;
1222
1223     /* If the code segment is associated with a function, print a function
1224      * header and enter a local scope. Be sure to switch to the correct
1225      * segment before outputing the function label.
1226      */
1227     if (Func) {
1228         /* Get the function descriptor */
1229         const FuncDesc* D = GetFuncDesc (Func->Type);
1230         CS_PrintFunctionHeader (S, F);
1231         fprintf (F, ".segment\t\"%s\"\n\n.proc\t_%s", S->SegName, Func->Name);
1232         if (D->Flags & FD_NEAR) {
1233             fputs (": near", F);
1234         } else if (D->Flags & FD_FAR) {
1235             fputs (": far", F);
1236         }
1237         fputs ("\n\n", F);
1238     }
1239
1240 }
1241
1242
1243
1244 void CS_OutputEpilogue (const CodeSeg* S, FILE* F)
1245 /* If the given code segment is a code segment for a function, output the
1246  * assembler epilogue into the file. That is: Close the local function scope.
1247  */
1248 {
1249     if (S->Func) {
1250         fputs ("\n.endproc\n\n", F);
1251     }
1252 }
1253
1254
1255
1256 void CS_Output (CodeSeg* S, FILE* F)
1257 /* Output the code segment data to a file */
1258 {
1259     unsigned I;
1260     const LineInfo* LI;
1261
1262     /* Get the number of entries in this segment */
1263     unsigned Count = CS_GetEntryCount (S);
1264
1265     /* If the code segment is empty, bail out here */
1266     if (Count == 0) {
1267         return;
1268     }
1269
1270     /* Generate register info */
1271     CS_GenRegInfo (S);
1272
1273     /* Output the segment directive */
1274     fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
1275
1276     /* Output all entries, prepended by the line information if it has changed */
1277     LI = 0;
1278     for (I = 0; I < Count; ++I) {
1279         /* Get the next entry */
1280         const CodeEntry* E = CollConstAt (&S->Entries, I);
1281         /* Check if the line info has changed. If so, output the source line
1282          * if the option is enabled and output debug line info if the debug
1283          * option is enabled.
1284          */
1285         if (E->LI != LI) {
1286             /* Line info has changed, remember the new line info */
1287             LI = E->LI;
1288
1289             /* Add the source line as a comment. Beware: When line continuation
1290              * was used, the line may contain newlines.
1291              */
1292             if (AddSource) {
1293                 const char* L = LI->Line;
1294                 fputs (";\n; ", F);
1295                 while (*L) {
1296                     if (*L == '\n') {
1297                         fputs ("\n; ", F);
1298                     } else {
1299                         fputc (*L, F);
1300                     }
1301                     ++L;
1302                 }
1303                 fputs ("\n;\n", F);
1304             }
1305
1306             /* Add line debug info */
1307             if (DebugInfo) {
1308                 fprintf (F, "\t.dbg\tline, \"%s\", %u\n",
1309                          GetInputName (LI), GetInputLine (LI));
1310             }
1311         }
1312         /* Output the code */
1313         CE_Output (E, F);
1314     }
1315
1316     /* If debug info is enabled, terminate the last line number information */
1317     if (DebugInfo) {
1318         fputs ("\t.dbg\tline\n", F);
1319     }
1320
1321     /* Free register info */
1322     CS_FreeRegInfo (S);
1323 }
1324
1325
1326
1327 void CS_FreeRegInfo (CodeSeg* S)
1328 /* Free register infos for all instructions */
1329 {
1330     unsigned I;
1331     for (I = 0; I < CS_GetEntryCount (S); ++I) {
1332         CE_FreeRegInfo (CS_GetEntry(S, I));
1333     }
1334 }
1335
1336
1337
1338 void CS_GenRegInfo (CodeSeg* S)
1339 /* Generate register infos for all instructions */
1340 {
1341     unsigned I;
1342     RegContents Regs;           /* Initial register contents */
1343     RegContents* CurrentRegs;   /* Current register contents */
1344     int WasJump;                /* True if last insn was a jump */
1345     int Done;                   /* All runs done flag */
1346
1347     /* Be sure to delete all register infos */
1348     CS_FreeRegInfo (S);
1349
1350     /* We may need two runs to get back references right */
1351     do {
1352
1353         /* Assume we're done after this run */
1354         Done = 1;
1355
1356         /* On entry, the register contents are unknown */
1357         RC_Invalidate (&Regs);
1358         CurrentRegs = &Regs;
1359
1360         /* Walk over all insns and note just the changes from one insn to the
1361          * next one.
1362          */
1363         WasJump = 0;
1364         for (I = 0; I < CS_GetEntryCount (S); ++I) {
1365
1366             CodeEntry* P;
1367
1368             /* Get the next instruction */
1369             CodeEntry* E = CollAtUnchecked (&S->Entries, I);
1370
1371             /* If the instruction has a label, we need some special handling */
1372             unsigned LabelCount = CE_GetLabelCount (E);
1373             if (LabelCount > 0) {
1374
1375                 /* Loop over all entry points that jump here. If these entry
1376                  * points already have register info, check if all values are
1377                  * known and identical. If all values are identical, and the
1378                  * preceeding instruction was not an unconditional branch, check
1379                  * if the register value on exit of the preceeding instruction
1380                  * is also identical. If all these values are identical, the
1381                  * value of a register is known, otherwise it is unknown.
1382                  */
1383                 CodeLabel* Label = CE_GetLabel (E, 0);
1384                 unsigned Entry;
1385                 if (WasJump) {
1386                     /* Preceeding insn was an unconditional branch */
1387                     CodeEntry* J = CL_GetRef(Label, 0);
1388                     if (J->RI) {
1389                         Regs = J->RI->Out2;
1390                     } else {
1391                         RC_Invalidate (&Regs);
1392                     }
1393                     Entry = 1;
1394                 } else {
1395                     Regs = *CurrentRegs;
1396                     Entry = 0;
1397                 }
1398
1399                 while (Entry < CL_GetRefCount (Label)) {
1400                     /* Get this entry */
1401                     CodeEntry* J = CL_GetRef (Label, Entry);
1402                     if (J->RI == 0) {
1403                         /* No register info for this entry. This means that the
1404                          * instruction that jumps here is at higher addresses and
1405                          * the jump is a backward jump. We need a second run to
1406                          * get the register info right in this case. Until then,
1407                          * assume unknown register contents.
1408                          */
1409                         Done = 0;
1410                         RC_Invalidate (&Regs);
1411                         break;
1412                     }
1413                     if (J->RI->Out2.RegA != Regs.RegA) {
1414                         Regs.RegA = UNKNOWN_REGVAL;
1415                     }
1416                     if (J->RI->Out2.RegX != Regs.RegX) {
1417                         Regs.RegX = UNKNOWN_REGVAL;
1418                     }
1419                     if (J->RI->Out2.RegY != Regs.RegY) {
1420                         Regs.RegY = UNKNOWN_REGVAL;
1421                     }
1422                     if (J->RI->Out2.SRegLo != Regs.SRegLo) {
1423                         Regs.SRegLo = UNKNOWN_REGVAL;
1424                     }
1425                     if (J->RI->Out2.SRegHi != Regs.SRegHi) {
1426                         Regs.SRegHi = UNKNOWN_REGVAL;
1427                     }
1428                     if (J->RI->Out2.Tmp1 != Regs.Tmp1) {
1429                         Regs.Tmp1 = UNKNOWN_REGVAL;
1430                     }
1431                     ++Entry;
1432                 }
1433
1434                 /* Use this register info */
1435                 CurrentRegs = &Regs;
1436
1437             }
1438
1439             /* Generate register info for this instruction */
1440             CE_GenRegInfo (E, CurrentRegs);
1441
1442             /* Remember for the next insn if this insn was an uncondition branch */
1443             WasJump = (E->Info & OF_UBRA) != 0;
1444
1445             /* Output registers for this insn are input for the next */
1446             CurrentRegs = &E->RI->Out;
1447
1448             /* If this insn is a branch on zero flag, we may have more info on
1449              * register contents for one of both flow directions, but only if
1450              * there is a previous instruction.
1451              */
1452             if ((E->Info & OF_ZBRA) != 0 && (P = CS_GetPrevEntry (S, I)) != 0) {
1453
1454                 /* Get the branch condition */
1455                 bc_t BC = GetBranchCond (E->OPC);
1456
1457                 /* Check the previous instruction */
1458                 switch (P->OPC) {
1459
1460                     case OP65_ADC:
1461                     case OP65_AND:
1462                     case OP65_DEA:
1463                     case OP65_EOR:
1464                     case OP65_INA:
1465                     case OP65_LDA:
1466                     case OP65_ORA:
1467                     case OP65_PLA:
1468                     case OP65_SBC:
1469                         /* A is zero in one execution flow direction */
1470                         if (BC == BC_EQ) {
1471                             E->RI->Out2.RegA = 0;
1472                         } else {
1473                             E->RI->Out.RegA = 0;
1474                         }
1475                         break;
1476
1477                     case OP65_CMP:
1478                         /* If this is an immidiate compare, the A register has
1479                          * the value of the compare later.
1480                          */
1481                         if (CE_KnownImm (P)) {
1482                             if (BC == BC_EQ) {
1483                                 E->RI->Out2.RegA = (unsigned char)P->Num;
1484                             } else {
1485                                 E->RI->Out.RegA = (unsigned char)P->Num;
1486                             }
1487                         }
1488                         break;
1489
1490                     case OP65_CPX:
1491                         /* If this is an immidiate compare, the X register has
1492                          * the value of the compare later.
1493                          */
1494                         if (CE_KnownImm (P)) {
1495                             if (BC == BC_EQ) {
1496                                 E->RI->Out2.RegX = (unsigned char)P->Num;
1497                             } else {
1498                                 E->RI->Out.RegX = (unsigned char)P->Num;
1499                             }
1500                         }
1501                         break;
1502
1503                     case OP65_CPY:
1504                         /* If this is an immidiate compare, the Y register has
1505                          * the value of the compare later.
1506                          */
1507                         if (CE_KnownImm (P)) {
1508                             if (BC == BC_EQ) {
1509                                 E->RI->Out2.RegY = (unsigned char)P->Num;
1510                             } else {
1511                                 E->RI->Out.RegY = (unsigned char)P->Num;
1512                             }
1513                         }
1514                         break;
1515
1516                     case OP65_DEX:
1517                     case OP65_INX:
1518                     case OP65_LDX:
1519                     case OP65_PLX:
1520                         /* X is zero in one execution flow direction */
1521                         if (BC == BC_EQ) {
1522                             E->RI->Out2.RegX = 0;
1523                         } else {
1524                             E->RI->Out.RegX = 0;
1525                         }
1526                         break;
1527
1528                     case OP65_DEY:
1529                     case OP65_INY:
1530                     case OP65_LDY:
1531                     case OP65_PLY:
1532                         /* X is zero in one execution flow direction */
1533                         if (BC == BC_EQ) {
1534                             E->RI->Out2.RegY = 0;
1535                         } else {
1536                             E->RI->Out.RegY = 0;
1537                         }
1538                         break;
1539
1540                     case OP65_TAX:
1541                     case OP65_TXA:
1542                         /* If the branch is a beq, both A and X are zero at the
1543                          * branch target, otherwise they are zero at the next
1544                          * insn.
1545                          */
1546                         if (BC == BC_EQ) {
1547                             E->RI->Out2.RegA = E->RI->Out2.RegX = 0;
1548                         } else {
1549                             E->RI->Out.RegA = E->RI->Out.RegX = 0;
1550                         }
1551                         break;
1552
1553                     case OP65_TAY:
1554                     case OP65_TYA:
1555                         /* If the branch is a beq, both A and Y are zero at the
1556                          * branch target, otherwise they are zero at the next
1557                          * insn.
1558                          */
1559                         if (BC == BC_EQ) {
1560                             E->RI->Out2.RegA = E->RI->Out2.RegY = 0;
1561                         } else {
1562                             E->RI->Out.RegA = E->RI->Out.RegY = 0;
1563                         }
1564                         break;
1565
1566                     default:
1567                         break;
1568
1569                 }
1570             }
1571         }
1572     } while (!Done);
1573
1574 }
1575
1576
1577