1 /*****************************************************************************/
5 /* Code segment structure */
9 /* (C) 2001 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
56 /*****************************************************************************/
57 /* Helper functions */
58 /*****************************************************************************/
62 static void MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
63 /* Move the labels of the code entry E to the label pool of the code segment */
65 unsigned LabelCount = GetCodeLabelCount (E);
66 while (LabelCount--) {
67 CodeLabel* L = GetCodeLabel (E, LabelCount);
70 CollAppend (&S->Labels, L);
72 CollDeleteAll (&E->Labels);
77 static CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
78 /* Find the label with the given name. Return the label or NULL if not found */
80 /* Get the first hash chain entry */
81 CodeLabel* L = S->LabelHash[Hash];
85 if (strcmp (Name, L->Name) == 0) {
96 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
97 /* Create a new label and insert it into the label hash table */
99 /* Not found - create a new one */
100 CodeLabel* L = NewCodeLabel (Name, Hash);
102 /* Enter the label into the hash table */
103 L->Next = S->LabelHash[L->Hash];
104 S->LabelHash[L->Hash] = L;
106 /* Return the new label */
112 static void RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
113 /* Remove the given code label from the hash list */
115 /* Get the first entry in the hash chain */
116 CodeLabel* List = S->LabelHash[L->Hash];
119 /* First, remove the label from the hash chain */
121 /* First entry in hash chain */
122 S->LabelHash[L->Hash] = L->Next;
124 /* Must search through the chain */
125 while (List->Next != L) {
126 /* If we've reached the end of the chain, something is *really* wrong */
127 CHECK (List->Next != 0);
131 /* The next entry is the one, we have been searching for */
132 List->Next = L->Next;
138 /*****************************************************************************/
139 /* Functions for parsing instructions */
140 /*****************************************************************************/
144 static const char* SkipSpace (const char* S)
145 /* Skip white space and return an updated pointer */
147 while (IsSpace (*S)) {
155 static const char* ReadToken (const char* L, const char* Term,
156 char* Buf, unsigned BufSize)
157 /* Read the next token into Buf, return the updated line pointer. The
158 * token is terminated by one of the characters given in term.
161 /* Read/copy the token */
163 unsigned ParenCount = 0;
164 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
170 } else if (*L == '(') {
176 /* Terminate the buffer contents */
179 /* Return the updated line pointer */
185 static CodeEntry* ParseInsn (CodeSeg* S, const char* L)
186 /* Parse an instruction nnd generate a code entry from it. If the line contains
187 * errors, output an error message and return NULL.
188 * For simplicity, we don't accept the broad range of input a "real" assembler
189 * does. The instruction and the argument are expected to be separated by
190 * white space, for example.
195 am_t AM = 0; /* Initialize to keep gcc silent */
202 L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
204 /* Try to find the opcode description for the mnemonic */
205 OPC = FindOpcode (Mnemo);
207 /* If we didn't find the opcode, print an error and bail out */
209 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
213 /* Skip separator white space */
216 /* Get the addressing mode */
227 StrCopy (Arg, sizeof (Arg), L+1);
233 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
235 /* Check for errors */
237 Error ("ASM code error: syntax error");
241 /* Check the different indirect modes */
243 /* Expect zp x indirect */
245 if (toupper (*L) != 'X') {
246 Error ("ASM code error: `X' expected");
251 Error ("ASM code error: `)' expected");
256 Error ("ASM code error: syntax error");
260 } else if (*L == ')') {
261 /* zp indirect or zp indirect, y */
265 if (toupper (*L) != 'Y') {
266 Error ("ASM code error: `Y' expected");
271 Error ("ASM code error: syntax error");
275 } else if (*L == '\0') {
278 Error ("ASM code error: syntax error");
294 /* Absolute, maybe indexed */
295 L = ReadToken (L, ",", Arg, sizeof (Arg));
297 /* Assume absolute */
299 } else if (*L == ',') {
303 Error ("ASM code error: syntax error");
310 } else if (Reg == 'Y') {
313 Error ("ASM code error: syntax error");
317 Error ("ASM code error: syntax error");
326 /* If the instruction is a branch, check for the label and generate it
327 * if it does not exist. Ignore anything but local labels here.
330 if ((OPC->Info & OF_BRA) != 0 && Arg[0] == 'L') {
334 /* Addressing mode must be alsobute or something is really wrong */
335 CHECK (AM == AM_ABS);
337 /* Addressing mode is a branch/jump */
340 /* Generate the hash over the label, then search for the label */
341 Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
342 Label = FindCodeLabel (S, Arg, Hash);
344 /* If we don't have the label, it's a forward ref - create it */
346 /* Generate a new label */
347 Label = NewCodeSegLabel (S, Arg, Hash);
351 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
352 * structure and initialize it.
354 E = NewCodeEntry (OPC, AM, Arg, Label);
356 /* Return the new code entry */
362 /*****************************************************************************/
364 /*****************************************************************************/
368 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
369 /* Create a new code segment, initialize and return it */
373 /* Allocate memory */
374 CodeSeg* S = xmalloc (sizeof (CodeSeg));
376 /* Initialize the fields */
377 S->SegName = xstrdup (SegName);
379 InitCollection (&S->Entries);
380 InitCollection (&S->Labels);
381 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
385 /* Return the new struct */
391 void AddCodeEntry (CodeSeg* S, const char* Format, va_list ap)
392 /* Add a line to the given code segment */
398 /* Format the line */
400 xvsprintf (Buf, sizeof (Buf), Format, ap);
402 /* Skip whitespace */
405 /* Check which type of instruction we have */
406 E = 0; /* Assume no insn created */
410 /* Empty line, just ignore it */
414 /* Comment or hint, ignore it for now */
418 /* Control instruction */
419 ReadToken (L, " \t", Token, sizeof (Token));
420 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
424 E = ParseInsn (S, L);
428 /* If we have a code entry, transfer the labels and insert it */
431 /* Transfer the labels if we have any */
433 unsigned LabelCount = CollCount (&S->Labels);
434 for (I = 0; I < LabelCount; ++I) {
437 CodeLabel* L = CollAt (&S->Labels, I);
439 /* Attach it to the entry */
440 AttachCodeLabel (E, L);
443 /* Delete the transfered labels */
444 CollDeleteAll (&S->Labels);
446 /* Add the entry to the list of code entries in this segment */
447 CollAppend (&S->Entries, E);
454 void InsertCodeEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
455 /* Insert the code entry at the index given. Following code entries will be
456 * moved to slots with higher indices.
459 /* Insert the entry into the collection */
460 CollInsert (&S->Entries, E, Index);
465 void DelCodeEntry (CodeSeg* S, unsigned Index)
466 /* Delete an entry from the code segment. This includes moving any associated
467 * labels, removing references to labels and even removing the referenced labels
468 * if the reference count drops to zero.
471 /* Get the code entry for the given index */
472 CodeEntry* E = GetCodeEntry (S, Index);
474 /* If the entry has a labels, we have to move this label to the next insn.
475 * If there is no next insn, move the label into the code segement label
476 * pool. The operation is further complicated by the fact that the next
477 * insn may already have a label. In that case change all reference to
478 * this label and delete the label instead of moving it.
480 unsigned Count = GetCodeLabelCount (E);
483 /* The instruction has labels attached. Check if there is a next
486 if (Index == GetCodeEntryCount (S)-1) {
488 /* No next instruction, move to the codeseg label pool */
489 MoveLabelsToPool (S, E);
493 /* There is a next insn, get it */
494 CodeEntry* N = GetCodeEntry (S, Index+1);
496 /* Move labels to the next entry */
497 MoveCodeLabels (S, E, N);
502 /* If this insn references a label, remove the reference. And, if the
503 * the reference count for this label drops to zero, remove this label.
506 /* Remove the reference */
507 RemoveCodeLabelRef (S, E);
510 /* Delete the pointer to the insn */
511 CollDelete (&S->Entries, Index);
513 /* Delete the instruction itself */
519 struct CodeEntry* GetCodeEntry (CodeSeg* S, unsigned Index)
520 /* Get an entry from the given code segment */
522 return CollAt (&S->Entries, Index);
527 struct CodeEntry* GetNextCodeEntry (CodeSeg* S, unsigned Index)
528 /* Get the code entry following the one with the index Index. If there is no
529 * following code entry, return NULL.
532 if (Index >= CollCount (&S->Entries)-1) {
533 /* This is the last entry */
536 /* Code entries left */
537 return CollAt (&S->Entries, Index+1);
543 unsigned GetCodeEntryIndex (CodeSeg* S, struct CodeEntry* E)
544 /* Return the index of a code entry */
546 int Index = CollIndex (&S->Entries, E);
553 void AddCodeLabel (CodeSeg* S, const char* Name)
554 /* Add a code label for the next instruction to follow */
556 /* Calculate the hash from the name */
557 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
559 /* Try to find the code label if it does already exist */
560 CodeLabel* L = FindCodeLabel (S, Name, Hash);
562 /* Did we find it? */
564 /* We found it - be sure it does not already have an owner */
565 CHECK (L->Owner == 0);
567 /* Not found - create a new one */
568 L = NewCodeSegLabel (S, Name, Hash);
571 /* Safety. This call is quite costly, but safety is better */
572 if (CollIndex (&S->Labels, L) >= 0) {
573 Internal ("AddCodeLabel: Label `%s' already defined", Name);
576 /* We do now have a valid label. Remember it for later */
577 CollAppend (&S->Labels, L);
582 CodeLabel* GenCodeLabel (CodeSeg* S, struct CodeEntry* E)
583 /* If the code entry E does already have a label, return it. Otherwise
584 * create a new label, attach it to E and return it.
589 if (CodeEntryHasLabel (E)) {
591 /* Get the label from this entry */
592 L = GetCodeLabel (E, 0);
597 const char* Name = LocalLabelName (GetLocalLabel ());
599 /* Generate the hash over the name */
600 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
602 /* Create a new label */
603 L = NewCodeSegLabel (S, Name, Hash);
605 /* Attach this label to the code entry */
606 AttachCodeLabel (E, L);
610 /* Return the label */
616 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
617 /* Remove references from this label and delete it. */
621 /* First, remove the label from the hash chain */
622 RemoveLabelFromHash (S, L);
624 /* Remove references from insns jumping to this label */
625 Count = CollCount (&L->JumpFrom);
626 for (I = 0; I < Count; ++I) {
627 /* Get the insn referencing this label */
628 CodeEntry* E = CollAt (&L->JumpFrom, I);
629 /* Remove the reference */
632 CollDeleteAll (&L->JumpFrom);
634 /* Remove the reference to the owning instruction if it has one. The
635 * function may be called for a label without an owner when deleting
636 * unfinished parts of the code. This is unfortunate since it allows
637 * errors to slip through.
640 CollDeleteItem (&L->Owner->Labels, L);
643 /* All references removed, delete the label itself */
649 void MergeCodeLabels (CodeSeg* S)
650 /* Merge code labels. That means: For each instruction, remove all labels but
651 * one and adjust references accordingly.
656 /* Walk over all code entries */
657 unsigned EntryCount = GetCodeEntryCount (S);
658 for (I = 0; I < EntryCount; ++I) {
663 /* Get a pointer to the next entry */
664 CodeEntry* E = GetCodeEntry (S, I);
666 /* If this entry has zero labels, continue with the next one */
667 unsigned LabelCount = GetCodeLabelCount (E);
668 if (LabelCount == 0) {
672 /* We have at least one label. Use the first one as reference label. */
673 RefLab = GetCodeLabel (E, 0);
675 /* Walk through the remaining labels and change references to these
676 * labels to a reference to the one and only label. Delete the labels
677 * that are no longer used. To increase performance, walk backwards
680 for (J = LabelCount-1; J >= 1; --J) {
682 /* Get the next label */
683 CodeLabel* L = GetCodeLabel (E, J);
685 /* Move all references from this label to the reference label */
686 MoveLabelRefs (L, RefLab);
688 /* Remove the label completely. */
692 /* The reference label is the only remaining label. Check if there
693 * are any references to this label, and delete it if this is not
696 if (CollCount (&RefLab->JumpFrom) == 0) {
697 /* Delete the label */
698 DelCodeLabel (S, RefLab);
705 void MoveCodeLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
706 /* Move all labels from Old to New. The routine will move the labels itself
707 * if New does not have any labels, and move references if there is at least
708 * a label for new. If references are moved, the old label is deleted
712 /* Get the number of labels to move */
713 unsigned OldLabelCount = GetCodeLabelCount (Old);
715 /* Does the new entry have itself a label? */
716 if (CodeEntryHasLabel (New)) {
718 /* The new entry does already have a label - move references */
719 CodeLabel* NewLabel = GetCodeLabel (New, 0);
720 while (OldLabelCount--) {
722 /* Get the next label */
723 CodeLabel* OldLabel = GetCodeLabel (Old, OldLabelCount);
725 /* Move references */
726 MoveLabelRefs (OldLabel, NewLabel);
728 /* Delete the label */
729 DelCodeLabel (S, OldLabel);
735 /* The new entry does not have a label, just move them */
736 while (OldLabelCount--) {
738 /* Move the label to the new entry */
739 MoveCodeLabel (GetCodeLabel (Old, OldLabelCount), New);
748 void RemoveCodeLabelRef (CodeSeg* S, struct CodeEntry* E)
749 /* Remove the reference between E and the label it jumps to. The reference
750 * will be removed on both sides and E->JumpTo will be 0 after that. If
751 * the reference was the only one for the label, the label will get
755 /* Get a pointer to the label and make sure it exists */
756 CodeLabel* L = E->JumpTo;
759 /* Delete the entry from the label */
760 CollDeleteItem (&L->JumpFrom, E);
762 /* The entry jumps no longer to L */
765 /* If there are no more references, delete the label */
766 if (CollCount (&L->JumpFrom) == 0) {
773 void MoveCodeLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
774 /* Change the reference of E to L instead of the current one. If this
775 * was the only reference to the old label, the old label will get
779 /* Get the old label */
780 CodeLabel* OldLabel = E->JumpTo;
782 /* Be sure that code entry references a label */
783 PRECONDITION (OldLabel != 0);
785 /* Remove the reference to our label */
786 RemoveCodeLabelRef (S, E);
788 /* Use the new label */
794 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
795 /* Add a hint for the preceeding instruction */
799 /* Get the number of entries in this segment */
800 unsigned EntryCount = GetCodeEntryCount (S);
802 /* Must have at least one entry */
803 CHECK (EntryCount > 0);
805 /* Get the last entry */
806 E = GetCodeEntry (S, EntryCount-1);
814 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
815 /* Delete all entries including the given one */
817 /* Get the number of entries in this segment */
818 unsigned Count = GetCodeEntryCount (S);
820 /* First pass: Delete all references to labels. If the reference count
821 * for a label drops to zero, delete it.
826 /* Get the next entry */
827 CodeEntry* E = GetCodeEntry (S, C);
829 /* Check if this entry has a label reference */
831 /* Remove the reference to the label */
832 RemoveCodeLabelRef (S, E);
837 /* Second pass: Delete the instructions. If a label attached to an
838 * instruction still has references, it must be references from outside
839 * the deleted area. Don't delete the label in this case, just make it
840 * ownerless and move it to the label pool.
845 /* Get the next entry */
846 CodeEntry* E = GetCodeEntry (S, C);
848 /* Check if this entry has a label attached */
849 if (CodeEntryHasLabel (E)) {
850 /* Move the labels to the pool and clear the owner pointer */
851 MoveLabelsToPool (S, E);
854 /* Delete the pointer to the entry */
855 CollDelete (&S->Entries, C);
857 /* Delete the entry itself */
864 void OutputCodeSeg (const CodeSeg* S, FILE* F)
865 /* Output the code segment data to a file */
869 /* Get the number of entries in this segment */
870 unsigned Count = GetCodeEntryCount (S);
872 /* If the code segment is empty, bail out here */
877 /* Output the segment directive */
878 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
880 /* If this is a segment for a function, enter a function */
882 fprintf (F, ".proc\t_%s\n\n", S->Func->Name);
885 /* Output all entries */
886 for (I = 0; I < Count; ++I) {
890 OutputCodeEntry (CollConstAt (&S->Entries, I), F);
892 /* Print usage info */
893 Use = GetRegInfo ((CodeSeg*) S, I+1);
896 (Use & REG_A)? 'A' : '_',
897 (Use & REG_X)? 'X' : '_',
898 (Use & REG_Y)? 'Y' : '_');
901 /* If this is a segment for a function, leave the function */
903 fprintf (F, "\n.endproc\n\n");
909 unsigned GetCodeEntryCount (const CodeSeg* S)
910 /* Return the number of entries for the given code segment */
912 return CollCount (&S->Entries);