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 /*****************************************************************************/
59 /*****************************************************************************/
60 /* Helper functions */
61 /*****************************************************************************/
65 static void MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
66 /* Move the labels of the code entry E to the label pool of the code segment */
68 unsigned LabelCount = GetCodeLabelCount (E);
69 while (LabelCount--) {
70 CodeLabel* L = GetCodeLabel (E, LabelCount);
72 CollAppend (&S->Labels, L);
74 CollDeleteAll (&E->Labels);
79 static CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
80 /* Find the label with the given name. Return the label or NULL if not found */
82 /* Get the first hash chain entry */
83 CodeLabel* L = S->LabelHash[Hash];
87 if (strcmp (Name, L->Name) == 0) {
98 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
99 /* Create a new label and insert it into the label hash table */
101 /* Not found - create a new one */
102 CodeLabel* L = NewCodeLabel (Name, Hash);
104 /* Enter the label into the hash table */
105 L->Next = S->LabelHash[L->Hash];
106 S->LabelHash[L->Hash] = L;
108 /* Return the new label */
114 static void RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
115 /* Remove the given code label from the hash list */
117 /* Get the first entry in the hash chain */
118 CodeLabel* List = S->LabelHash[L->Hash];
121 /* First, remove the label from the hash chain */
123 /* First entry in hash chain */
124 S->LabelHash[L->Hash] = L->Next;
126 /* Must search through the chain */
127 while (List->Next != L) {
128 /* If we've reached the end of the chain, something is *really* wrong */
129 CHECK (List->Next != 0);
133 /* The next entry is the one, we have been searching for */
134 List->Next = L->Next;
140 /*****************************************************************************/
141 /* Functions for parsing instructions */
142 /*****************************************************************************/
146 static const char* SkipSpace (const char* S)
147 /* Skip white space and return an updated pointer */
149 while (IsSpace (*S)) {
157 static const char* ReadToken (const char* L, const char* Term,
158 char* Buf, unsigned BufSize)
159 /* Read the next token into Buf, return the updated line pointer. The
160 * token is terminated by one of the characters given in term.
163 /* Read/copy the token */
165 unsigned ParenCount = 0;
166 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
172 } else if (*L == '(') {
178 /* Terminate the buffer contents */
181 /* Return the updated line pointer */
187 static CodeEntry* ParseInsn (CodeSeg* S, LineInfo* LI, const char* L)
188 /* Parse an instruction nnd generate a code entry from it. If the line contains
189 * errors, output an error message and return NULL.
190 * For simplicity, we don't accept the broad range of input a "real" assembler
191 * does. The instruction and the argument are expected to be separated by
192 * white space, for example.
197 am_t AM = 0; /* Initialize to keep gcc silent */
204 L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
206 /* Try to find the opcode description for the mnemonic */
207 OPC = FindOpcode (Mnemo);
209 /* If we didn't find the opcode, print an error and bail out */
211 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
215 /* Skip separator white space */
218 /* Get the addressing mode */
229 StrCopy (Arg, sizeof (Arg), L+1);
235 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
237 /* Check for errors */
239 Error ("ASM code error: syntax error");
243 /* Check the different indirect modes */
245 /* Expect zp x indirect */
247 if (toupper (*L) != 'X') {
248 Error ("ASM code error: `X' expected");
253 Error ("ASM code error: `)' expected");
258 Error ("ASM code error: syntax error");
262 } else if (*L == ')') {
263 /* zp indirect or zp indirect, y */
267 if (toupper (*L) != 'Y') {
268 Error ("ASM code error: `Y' expected");
273 Error ("ASM code error: syntax error");
277 } else if (*L == '\0') {
280 Error ("ASM code error: syntax error");
296 /* Absolute, maybe indexed */
297 L = ReadToken (L, ",", Arg, sizeof (Arg));
299 /* Absolute, zeropage or branch */
300 if ((OPC->Info & OF_BRA) != 0) {
303 } else if (IsZPName (Arg)) {
308 } else if (*L == ',') {
312 Error ("ASM code error: syntax error");
318 if (IsZPName (Arg)) {
323 } else if (Reg == 'Y') {
326 Error ("ASM code error: syntax error");
330 Error ("ASM code error: syntax error");
339 /* If the instruction is a branch, check for the label and generate it
340 * if it does not exist. Ignore anything but local labels here.
343 if (AM == AM_BRA && Arg[0] == 'L') {
345 /* Generate the hash over the label, then search for the label */
346 unsigned Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
347 Label = FindCodeLabel (S, Arg, Hash);
349 /* If we don't have the label, it's a forward ref - create it */
351 /* Generate a new label */
352 Label = NewCodeSegLabel (S, Arg, Hash);
356 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
357 * structure and initialize it.
359 E = NewCodeEntry (OPC->OPC, AM, Arg, Label, LI);
361 /* Return the new code entry */
367 /*****************************************************************************/
369 /*****************************************************************************/
373 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
374 /* Create a new code segment, initialize and return it */
378 /* Allocate memory */
379 CodeSeg* S = xmalloc (sizeof (CodeSeg));
381 /* Initialize the fields */
382 S->SegName = xstrdup (SegName);
384 InitCollection (&S->Entries);
385 InitCollection (&S->Labels);
386 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
390 /* If we have a function given, get the return type of the function.
391 * Assume ANY return type besides void will use the A and X registers.
393 if (S->Func && !IsTypeVoid (GetFuncReturn (Func->Type))) {
394 S->ExitRegs = REG_AX;
396 S->ExitRegs = REG_NONE;
399 /* Return the new struct */
405 void AddCodeEntry (CodeSeg* S, LineInfo* LI, const char* Format, va_list ap)
406 /* Add a line to the given code segment */
412 /* Format the line */
414 xvsprintf (Buf, sizeof (Buf), Format, ap);
416 /* Skip whitespace */
419 /* Check which type of instruction we have */
420 E = 0; /* Assume no insn created */
424 /* Empty line, just ignore it */
428 /* Comment or hint, ignore it for now */
432 /* Control instruction */
433 ReadToken (L, " \t", Token, sizeof (Token));
434 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
438 E = ParseInsn (S, LI, L);
442 /* If we have a code entry, transfer the labels and insert it */
445 /* Transfer the labels if we have any */
447 unsigned LabelCount = CollCount (&S->Labels);
448 for (I = 0; I < LabelCount; ++I) {
451 CodeLabel* L = CollAt (&S->Labels, I);
453 /* Attach it to the entry */
454 AttachCodeLabel (E, L);
457 /* Delete the transfered labels */
458 CollDeleteAll (&S->Labels);
460 /* Add the entry to the list of code entries in this segment */
461 CollAppend (&S->Entries, E);
468 void InsertCodeEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
469 /* Insert the code entry at the index given. Following code entries will be
470 * moved to slots with higher indices.
473 /* Insert the entry into the collection */
474 CollInsert (&S->Entries, E, Index);
479 void DelCodeEntry (CodeSeg* S, unsigned Index)
480 /* Delete an entry from the code segment. This includes moving any associated
481 * labels, removing references to labels and even removing the referenced labels
482 * if the reference count drops to zero.
485 /* Get the code entry for the given index */
486 CodeEntry* E = GetCodeEntry (S, Index);
488 /* If the entry has a labels, we have to move this label to the next insn.
489 * If there is no next insn, move the label into the code segement label
490 * pool. The operation is further complicated by the fact that the next
491 * insn may already have a label. In that case change all reference to
492 * this label and delete the label instead of moving it.
494 unsigned Count = GetCodeLabelCount (E);
497 /* The instruction has labels attached. Check if there is a next
500 if (Index == GetCodeEntryCount (S)-1) {
502 /* No next instruction, move to the codeseg label pool */
503 MoveLabelsToPool (S, E);
507 /* There is a next insn, get it */
508 CodeEntry* N = GetCodeEntry (S, Index+1);
510 /* Move labels to the next entry */
511 MoveCodeLabels (S, E, N);
516 /* If this insn references a label, remove the reference. And, if the
517 * the reference count for this label drops to zero, remove this label.
520 /* Remove the reference */
521 RemoveCodeLabelRef (S, E);
524 /* Delete the pointer to the insn */
525 CollDelete (&S->Entries, Index);
527 /* Delete the instruction itself */
533 void DelCodeEntries (CodeSeg* S, unsigned Start, unsigned Count)
534 /* Delete a range of code entries. This includes removing references to labels,
535 * labels attached to the entries and so on.
538 /* Start deleting the entries from the rear, because this involves less
542 DelCodeEntry (S, Start + Count);
548 void MoveCodeEntry (CodeSeg* S, unsigned OldPos, unsigned NewPos)
549 /* Move an entry from one position to another. OldPos is the current position
550 * of the entry, NewPos is the new position of the entry.
553 /* Get the code entry and remove it from the collection */
554 CodeEntry* E = GetCodeEntry (S, OldPos);
555 CollDelete (&S->Entries, OldPos);
557 /* Correct NewPos if needed */
558 if (NewPos >= OldPos) {
559 /* Position has changed with removal */
563 /* Now insert it at the new position */
564 CollInsert (&S->Entries, E, NewPos);
569 struct CodeEntry* GetNextCodeEntry (CodeSeg* S, unsigned Index)
570 /* Get the code entry following the one with the index Index. If there is no
571 * following code entry, return NULL.
574 if (Index >= CollCount (&S->Entries)-1) {
575 /* This is the last entry */
578 /* Code entries left */
579 return CollAtUnchecked (&S->Entries, Index+1);
585 int GetCodeEntries (CodeSeg* S, struct CodeEntry** List,
586 unsigned Start, unsigned Count)
587 /* Get Count code entries into List starting at index start. Return true if
588 * we got the lines, return false if not enough lines were available.
591 /* Check if enough entries are available */
592 if (Start + Count > CollCount (&S->Entries)) {
596 /* Copy the entries */
598 *List++ = CollAtUnchecked (&S->Entries, Start++);
601 /* We have the entries */
607 unsigned GetCodeEntryIndex (CodeSeg* S, struct CodeEntry* E)
608 /* Return the index of a code entry */
610 int Index = CollIndex (&S->Entries, E);
617 void AddCodeLabel (CodeSeg* S, const char* Name)
618 /* Add a code label for the next instruction to follow */
620 /* Calculate the hash from the name */
621 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
623 /* Try to find the code label if it does already exist */
624 CodeLabel* L = FindCodeLabel (S, Name, Hash);
626 /* Did we find it? */
628 /* We found it - be sure it does not already have an owner */
629 CHECK (L->Owner == 0);
631 /* Not found - create a new one */
632 L = NewCodeSegLabel (S, Name, Hash);
635 /* Safety. This call is quite costly, but safety is better */
636 if (CollIndex (&S->Labels, L) >= 0) {
637 Internal ("AddCodeLabel: Label `%s' already defined", Name);
640 /* We do now have a valid label. Remember it for later */
641 CollAppend (&S->Labels, L);
646 CodeLabel* GenCodeLabel (CodeSeg* S, struct CodeEntry* E)
647 /* If the code entry E does already have a label, return it. Otherwise
648 * create a new label, attach it to E and return it.
653 if (CodeEntryHasLabel (E)) {
655 /* Get the label from this entry */
656 L = GetCodeLabel (E, 0);
661 const char* Name = LocalLabelName (GetLocalLabel ());
663 /* Generate the hash over the name */
664 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
666 /* Create a new label */
667 L = NewCodeSegLabel (S, Name, Hash);
669 /* Attach this label to the code entry */
670 AttachCodeLabel (E, L);
674 /* Return the label */
680 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
681 /* Remove references from this label and delete it. */
685 /* First, remove the label from the hash chain */
686 RemoveLabelFromHash (S, L);
688 /* Remove references from insns jumping to this label */
689 Count = CollCount (&L->JumpFrom);
690 for (I = 0; I < Count; ++I) {
691 /* Get the insn referencing this label */
692 CodeEntry* E = CollAt (&L->JumpFrom, I);
693 /* Remove the reference */
696 CollDeleteAll (&L->JumpFrom);
698 /* Remove the reference to the owning instruction if it has one. The
699 * function may be called for a label without an owner when deleting
700 * unfinished parts of the code. This is unfortunate since it allows
701 * errors to slip through.
704 CollDeleteItem (&L->Owner->Labels, L);
707 /* All references removed, delete the label itself */
713 void MergeCodeLabels (CodeSeg* S)
714 /* Merge code labels. That means: For each instruction, remove all labels but
715 * one and adjust references accordingly.
720 /* Walk over all code entries */
721 unsigned EntryCount = GetCodeEntryCount (S);
722 for (I = 0; I < EntryCount; ++I) {
727 /* Get a pointer to the next entry */
728 CodeEntry* E = GetCodeEntry (S, I);
730 /* If this entry has zero labels, continue with the next one */
731 unsigned LabelCount = GetCodeLabelCount (E);
732 if (LabelCount == 0) {
736 /* We have at least one label. Use the first one as reference label. */
737 RefLab = GetCodeLabel (E, 0);
739 /* Walk through the remaining labels and change references to these
740 * labels to a reference to the one and only label. Delete the labels
741 * that are no longer used. To increase performance, walk backwards
744 for (J = LabelCount-1; J >= 1; --J) {
746 /* Get the next label */
747 CodeLabel* L = GetCodeLabel (E, J);
749 /* Move all references from this label to the reference label */
750 MoveLabelRefs (L, RefLab);
752 /* Remove the label completely. */
756 /* The reference label is the only remaining label. Check if there
757 * are any references to this label, and delete it if this is not
760 if (CollCount (&RefLab->JumpFrom) == 0) {
761 /* Delete the label */
762 DelCodeLabel (S, RefLab);
769 void MoveCodeLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
770 /* Move all labels from Old to New. The routine will move the labels itself
771 * if New does not have any labels, and move references if there is at least
772 * a label for new. If references are moved, the old label is deleted
776 /* Get the number of labels to move */
777 unsigned OldLabelCount = GetCodeLabelCount (Old);
779 /* Does the new entry have itself a label? */
780 if (CodeEntryHasLabel (New)) {
782 /* The new entry does already have a label - move references */
783 CodeLabel* NewLabel = GetCodeLabel (New, 0);
784 while (OldLabelCount--) {
786 /* Get the next label */
787 CodeLabel* OldLabel = GetCodeLabel (Old, OldLabelCount);
789 /* Move references */
790 MoveLabelRefs (OldLabel, NewLabel);
792 /* Delete the label */
793 DelCodeLabel (S, OldLabel);
799 /* The new entry does not have a label, just move them */
800 while (OldLabelCount--) {
802 /* Move the label to the new entry */
803 MoveCodeLabel (GetCodeLabel (Old, OldLabelCount), New);
812 void RemoveCodeLabelRef (CodeSeg* S, struct CodeEntry* E)
813 /* Remove the reference between E and the label it jumps to. The reference
814 * will be removed on both sides and E->JumpTo will be 0 after that. If
815 * the reference was the only one for the label, the label will get
819 /* Get a pointer to the label and make sure it exists */
820 CodeLabel* L = E->JumpTo;
823 /* Delete the entry from the label */
824 CollDeleteItem (&L->JumpFrom, E);
826 /* The entry jumps no longer to L */
829 /* If there are no more references, delete the label */
830 if (CollCount (&L->JumpFrom) == 0) {
837 void MoveCodeLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
838 /* Change the reference of E to L instead of the current one. If this
839 * was the only reference to the old label, the old label will get
843 /* Get the old label */
844 CodeLabel* OldLabel = E->JumpTo;
846 /* Be sure that code entry references a label */
847 PRECONDITION (OldLabel != 0);
849 /* Remove the reference to our label */
850 RemoveCodeLabelRef (S, E);
852 /* Use the new label */
858 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
859 /* Delete all entries including the given one */
861 /* Get the number of entries in this segment */
862 unsigned Count = GetCodeEntryCount (S);
864 /* First pass: Delete all references to labels. If the reference count
865 * for a label drops to zero, delete it.
870 /* Get the next entry */
871 CodeEntry* E = GetCodeEntry (S, C);
873 /* Check if this entry has a label reference */
875 /* If the label is a label in the label pool and this is the last
876 * reference to the label, remove the label from the pool.
878 CodeLabel* L = E->JumpTo;
879 int Index = CollIndex (&S->Labels, L);
880 if (Index >= 0 && CollCount (&L->JumpFrom) == 1) {
881 /* Delete it from the pool */
882 CollDelete (&S->Labels, Index);
885 /* Remove the reference to the label */
886 RemoveCodeLabelRef (S, E);
891 /* Second pass: Delete the instructions. If a label attached to an
892 * instruction still has references, it must be references from outside
893 * the deleted area. Don't delete the label in this case, just make it
894 * ownerless and move it to the label pool.
899 /* Get the next entry */
900 CodeEntry* E = GetCodeEntry (S, C);
902 /* Check if this entry has a label attached */
903 if (CodeEntryHasLabel (E)) {
904 /* Move the labels to the pool and clear the owner pointer */
905 MoveLabelsToPool (S, E);
908 /* Delete the pointer to the entry */
909 CollDelete (&S->Entries, C);
911 /* Delete the entry itself */
918 void OutputCodeSeg (const CodeSeg* S, FILE* F)
919 /* Output the code segment data to a file */
924 /* Get the number of entries in this segment */
925 unsigned Count = GetCodeEntryCount (S);
927 /* If the code segment is empty, bail out here */
932 /* Output the segment directive */
933 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
935 /* If this is a segment for a function, enter a function */
937 fprintf (F, ".proc\t_%s\n\n", S->Func->Name);
940 /* Output all entries, prepended by the line information if it has changed */
942 for (I = 0; I < Count; ++I) {
943 /* Get the next entry */
944 const CodeEntry* E = CollConstAt (&S->Entries, I);
945 /* Check if the line info has changed. If so, output the source line
946 * if the option is enabled and output debug line info if the debug
950 /* Line info has changed, remember the new line info */
953 /* Add the source line as a comment */
955 fprintf (F, ";\n; %s\n;\n", LI->Line);
958 /* Add line debug info */
960 fprintf (F, "\t.dbg\tline, \"%s\", %u\n",
961 GetInputName (LI), GetInputLine (LI));
964 /* Output the code */
965 OutputCodeEntry (E, F);
968 /* If debug info is enabled, terminate the last line number information */
970 fprintf (F, "\t.dbg\tline\n");
973 /* If this is a segment for a function, leave the function */
975 fprintf (F, "\n.endproc\n\n");