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