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