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