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