1 /*****************************************************************************/
5 /* Code segment structure */
9 /* (C) 2001-2009, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
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 /*****************************************************************************/
42 #include "debugflag.h"
63 /*****************************************************************************/
64 /* Helper functions */
65 /*****************************************************************************/
69 static void CS_PrintFunctionHeader (const CodeSeg* S)
70 /* Print a comment with the function signature to the output file */
72 /* Get the associated function */
73 const SymEntry* Func = S->Func;
75 /* If this is a global code segment, do nothing */
77 WriteOutput ("; ---------------------------------------------------------------\n"
79 PrintFuncSig (OutputFile, Func->Name, Func->Type);
81 "; ---------------------------------------------------------------\n"
88 static void CS_MoveLabelsToEntry (CodeSeg* S, CodeEntry* E)
89 /* Move all labels from the label pool to the given entry and remove them
93 /* Transfer the labels if we have any */
95 unsigned LabelCount = CollCount (&S->Labels);
96 for (I = 0; I < LabelCount; ++I) {
99 CodeLabel* L = CollAt (&S->Labels, I);
101 /* Attach it to the entry */
102 CE_AttachLabel (E, L);
105 /* Delete the transfered labels */
106 CollDeleteAll (&S->Labels);
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 */
114 unsigned LabelCount = CE_GetLabelCount (E);
115 while (LabelCount--) {
116 CodeLabel* L = CE_GetLabel (E, LabelCount);
118 CollAppend (&S->Labels, L);
120 CollDeleteAll (&E->Labels);
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 */
128 /* Get the first hash chain entry */
129 CodeLabel* L = S->LabelHash[Hash];
131 /* Search the list */
133 if (strcmp (Name, L->Name) == 0) {
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 */
147 /* Create a new label */
148 CodeLabel* L = NewCodeLabel (Name, Hash);
150 /* Enter the label into the hash table */
151 L->Next = S->LabelHash[L->Hash];
152 S->LabelHash[L->Hash] = L;
154 /* Return the new label */
160 static void CS_RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
161 /* Remove the given code label from the hash list */
163 /* Get the first entry in the hash chain */
164 CodeLabel* List = S->LabelHash[L->Hash];
167 /* First, remove the label from the hash chain */
169 /* First entry in hash chain */
170 S->LabelHash[L->Hash] = L->Next;
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);
179 /* The next entry is the one, we have been searching for */
180 List->Next = L->Next;
186 /*****************************************************************************/
187 /* Functions for parsing instructions */
188 /*****************************************************************************/
192 static const char* SkipSpace (const char* S)
193 /* Skip white space and return an updated pointer */
195 while (IsSpace (*S)) {
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.
209 /* Read/copy the token */
211 unsigned ParenCount = 0;
212 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
215 } else if (I == BufSize-1) {
216 /* Cannot store this character, this is an input error (maybe
217 * identifier too long or similar).
219 Error ("ASM code error: syntax error");
224 } else if (*L == '(') {
230 /* Terminate the buffer contents */
233 /* Return the updated line pointer */
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.
247 char Mnemo[IDENTSIZE+10];
249 am_t AM = 0; /* Initialize to keep gcc silent */
250 char Arg[IDENTSIZE+10];
255 /* Read the first token and skip white space after it */
256 L = SkipSpace (ReadToken (L, " \t:", Mnemo, sizeof (Mnemo)));
258 /* Check if we have a label */
261 /* Skip the colon and following white space */
265 CS_AddLabel (S, Mnemo);
267 /* If we have reached end of line, bail out, otherwise a mnemonic
274 L = SkipSpace (ReadToken (L, " \t", Mnemo, sizeof (Mnemo)));
277 /* Try to find the opcode description for the mnemonic */
278 OPC = FindOP65 (Mnemo);
280 /* If we didn't find the opcode, print an error and bail out */
282 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
286 /* Get the addressing mode */
291 /* Implicit or accu */
292 if (OPC->Info & OF_NOIMP) {
301 StrCopy (Arg, sizeof (Arg), L+1);
307 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
309 /* Check for errors */
311 Error ("ASM code error: syntax error");
315 /* Check the different indirect modes */
317 /* Expect zp x indirect */
319 if (toupper (*L) != 'X') {
320 Error ("ASM code error: `X' expected");
325 Error ("ASM code error: `)' expected");
330 Error ("ASM code error: syntax error");
334 } else if (*L == ')') {
335 /* zp indirect or zp indirect, y */
339 if (toupper (*L) != 'Y') {
340 Error ("ASM code error: `Y' expected");
345 Error ("ASM code error: syntax error");
349 } else if (*L == '\0') {
352 Error ("ASM code error: syntax error");
368 /* Absolute, maybe indexed */
369 L = ReadToken (L, ",", Arg, sizeof (Arg));
371 /* Absolute, zeropage or branch */
372 if ((OPC->Info & OF_BRA) != 0) {
375 } else if (GetZPInfo(Arg) != 0) {
378 /* Check for subroutine call to local label */
379 if ((OPC->Info & OF_CALL) && IsLocalLabelName (Arg)) {
380 Error ("ASM code error: "
381 "Cannot use local label `%s' in subroutine call",
386 } else if (*L == ',') {
390 Error ("ASM code error: syntax error");
396 if (GetZPInfo(Arg) != 0) {
401 } else if (Reg == 'Y') {
404 Error ("ASM code error: syntax error");
408 Error ("ASM code error: syntax error");
417 /* If the instruction is a branch, check for the label and generate it
418 * if it does not exist. This may lead to unused labels (if the label
419 * is actually an external one) which are removed by the CS_MergeLabels
423 if (AM == AM65_BRA) {
425 /* Generate the hash over the label, then search for the label */
426 unsigned Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
427 Label = CS_FindLabel (S, Arg, Hash);
429 /* If we don't have the label, it's a forward ref - create it */
431 /* Generate a new label */
432 Label = CS_NewCodeLabel (S, Arg, Hash);
436 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
437 * structure and initialize it.
439 E = NewCodeEntry (OPC->OPC, AM, Arg, Label, LI);
441 /* Return the new code entry */
447 /*****************************************************************************/
449 /*****************************************************************************/
453 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
454 /* Create a new code segment, initialize and return it */
459 /* Allocate memory */
460 CodeSeg* S = xmalloc (sizeof (CodeSeg));
462 /* Initialize the fields */
463 S->SegName = xstrdup (SegName);
465 InitCollection (&S->Entries);
466 InitCollection (&S->Labels);
467 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
471 /* If we have a function given, get the return type of the function.
472 * Assume ANY return type besides void will use the A and X registers.
474 if (S->Func && !IsTypeVoid ((RetType = GetFuncReturn (Func->Type)))) {
475 if (SizeOf (RetType) == SizeOf (type_long)) {
476 S->ExitRegs = REG_EAX;
478 S->ExitRegs = REG_AX;
481 S->ExitRegs = REG_NONE;
484 /* Copy the global optimization settings */
485 S->Optimize = (unsigned char) IS_Get (&Optimize);
486 S->CodeSizeFactor = (unsigned) IS_Get (&CodeSizeFactor);
488 /* Return the new struct */
494 void CS_AddEntry (CodeSeg* S, struct CodeEntry* E)
495 /* Add an entry to the given code segment */
497 /* Transfer the labels if we have any */
498 CS_MoveLabelsToEntry (S, E);
500 /* Add the entry to the list of code entries in this segment */
501 CollAppend (&S->Entries, E);
506 void CS_AddVLine (CodeSeg* S, LineInfo* LI, const char* Format, va_list ap)
507 /* Add a line to the given code segment */
511 char Token[IDENTSIZE+10];
513 /* Format the line */
514 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
515 SB_VPrintf (&Buf, Format, ap);
517 /* Skip whitespace */
518 L = SkipSpace (SB_GetConstBuf (&Buf));
520 /* Check which type of instruction we have */
521 E = 0; /* Assume no insn created */
525 /* Empty line, just ignore it */
529 /* Comment or hint, ignore it for now */
533 /* Control instruction */
534 ReadToken (L, " \t", Token, sizeof (Token));
535 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
539 E = ParseInsn (S, LI, L);
543 /* If we have a code entry, transfer the labels and insert it */
548 /* Cleanup the string buffer */
554 void CS_AddLine (CodeSeg* S, LineInfo* LI, const char* Format, ...)
555 /* Add a line to the given code segment */
558 va_start (ap, Format);
559 CS_AddVLine (S, LI, Format, ap);
565 void CS_InsertEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
566 /* Insert the code entry at the index given. Following code entries will be
567 * moved to slots with higher indices.
570 /* Insert the entry into the collection */
571 CollInsert (&S->Entries, E, Index);
576 void CS_DelEntry (CodeSeg* S, unsigned Index)
577 /* Delete an entry from the code segment. This includes moving any associated
578 * labels, removing references to labels and even removing the referenced labels
579 * if the reference count drops to zero.
580 * Note: Labels are moved forward if possible, that is, they are moved to the
581 * next insn (not the preceeding one).
584 /* Get the code entry for the given index */
585 CodeEntry* E = CS_GetEntry (S, Index);
587 /* If the entry has a labels, we have to move this label to the next insn.
588 * If there is no next insn, move the label into the code segement label
589 * pool. The operation is further complicated by the fact that the next
590 * insn may already have a label. In that case change all reference to
591 * this label and delete the label instead of moving it.
593 unsigned Count = CE_GetLabelCount (E);
596 /* The instruction has labels attached. Check if there is a next
599 if (Index == CS_GetEntryCount (S)-1) {
601 /* No next instruction, move to the codeseg label pool */
602 CS_MoveLabelsToPool (S, E);
606 /* There is a next insn, get it */
607 CodeEntry* N = CS_GetEntry (S, Index+1);
609 /* Move labels to the next entry */
610 CS_MoveLabels (S, E, N);
615 /* If this insn references a label, remove the reference. And, if the
616 * the reference count for this label drops to zero, remove this label.
619 /* Remove the reference */
620 CS_RemoveLabelRef (S, E);
623 /* Delete the pointer to the insn */
624 CollDelete (&S->Entries, Index);
626 /* Delete the instruction itself */
632 void CS_DelEntries (CodeSeg* S, unsigned Start, unsigned Count)
633 /* Delete a range of code entries. This includes removing references to labels,
634 * labels attached to the entries and so on.
637 /* Start deleting the entries from the rear, because this involves less
641 CS_DelEntry (S, Start + Count);
647 void CS_MoveEntries (CodeSeg* S, unsigned Start, unsigned Count, unsigned NewPos)
648 /* Move a range of entries from one position to another. Start is the index
649 * of the first entry to move, Count is the number of entries and NewPos is
650 * the index of the target entry. The entry with the index Start will later
651 * have the index NewPos. All entries with indices NewPos and above are
652 * moved to higher indices. If the code block is moved to the end of the
653 * current code, and if pending labels exist, these labels will get attached
654 * to the first instruction of the moved block (the first one after the
658 /* If NewPos is at the end of the code segment, move any labels from the
659 * label pool to the first instruction of the moved range.
661 if (NewPos == CS_GetEntryCount (S)) {
662 CS_MoveLabelsToEntry (S, CS_GetEntry (S, Start));
665 /* Move the code block to the destination */
666 CollMoveMultiple (&S->Entries, Start, Count, NewPos);
671 struct CodeEntry* CS_GetPrevEntry (CodeSeg* S, unsigned Index)
672 /* Get the code entry preceeding the one with the index Index. If there is no
673 * preceeding code entry, return NULL.
677 /* This is the first entry */
680 /* Previous entry available */
681 return CollAtUnchecked (&S->Entries, Index-1);
687 struct CodeEntry* CS_GetNextEntry (CodeSeg* S, unsigned Index)
688 /* Get the code entry following the one with the index Index. If there is no
689 * following code entry, return NULL.
692 if (Index >= CollCount (&S->Entries)-1) {
693 /* This is the last entry */
696 /* Code entries left */
697 return CollAtUnchecked (&S->Entries, Index+1);
703 int CS_GetEntries (CodeSeg* S, struct CodeEntry** List,
704 unsigned Start, unsigned Count)
705 /* Get Count code entries into List starting at index start. Return true if
706 * we got the lines, return false if not enough lines were available.
709 /* Check if enough entries are available */
710 if (Start + Count > CollCount (&S->Entries)) {
714 /* Copy the entries */
716 *List++ = CollAtUnchecked (&S->Entries, Start++);
719 /* We have the entries */
725 unsigned CS_GetEntryIndex (CodeSeg* S, struct CodeEntry* E)
726 /* Return the index of a code entry */
728 int Index = CollIndex (&S->Entries, E);
735 int CS_RangeHasLabel (CodeSeg* S, unsigned Start, unsigned Count)
736 /* Return true if any of the code entries in the given range has a label
737 * attached. If the code segment does not span the given range, check the
738 * possible span instead.
741 unsigned EntryCount = CS_GetEntryCount(S);
743 /* Adjust count. We expect at least Start to be valid. */
744 CHECK (Start < EntryCount);
745 if (Start + Count > EntryCount) {
746 Count = EntryCount - Start;
749 /* Check each entry. Since we have validated the index above, we may
750 * use the unchecked access function in the loop which is faster.
753 const CodeEntry* E = CollAtUnchecked (&S->Entries, Start++);
754 if (CE_HasLabel (E)) {
759 /* No label in the complete range */
765 CodeLabel* CS_AddLabel (CodeSeg* S, const char* Name)
766 /* Add a code label for the next instruction to follow */
768 /* Calculate the hash from the name */
769 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
771 /* Try to find the code label if it does already exist */
772 CodeLabel* L = CS_FindLabel (S, Name, Hash);
774 /* Did we find it? */
776 /* We found it - be sure it does not already have an owner */
778 Error ("ASM label `%s' is already defined", Name);
782 /* Not found - create a new one */
783 L = CS_NewCodeLabel (S, Name, Hash);
786 /* Safety. This call is quite costly, but safety is better */
787 if (CollIndex (&S->Labels, L) >= 0) {
788 Error ("ASM label `%s' is already defined", Name);
792 /* We do now have a valid label. Remember it for later */
793 CollAppend (&S->Labels, L);
795 /* Return the label */
801 CodeLabel* CS_GenLabel (CodeSeg* S, struct CodeEntry* E)
802 /* If the code entry E does already have a label, return it. Otherwise
803 * create a new label, attach it to E and return it.
808 if (CE_HasLabel (E)) {
810 /* Get the label from this entry */
811 L = CE_GetLabel (E, 0);
816 const char* Name = LocalLabelName (GetLocalLabel ());
818 /* Generate the hash over the name */
819 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
821 /* Create a new label */
822 L = CS_NewCodeLabel (S, Name, Hash);
824 /* Attach this label to the code entry */
825 CE_AttachLabel (E, L);
829 /* Return the label */
835 void CS_DelLabel (CodeSeg* S, CodeLabel* L)
836 /* Remove references from this label and delete it. */
840 /* First, remove the label from the hash chain */
841 CS_RemoveLabelFromHash (S, L);
843 /* Remove references from insns jumping to this label */
844 Count = CollCount (&L->JumpFrom);
845 for (I = 0; I < Count; ++I) {
846 /* Get the insn referencing this label */
847 CodeEntry* E = CollAt (&L->JumpFrom, I);
848 /* Remove the reference */
851 CollDeleteAll (&L->JumpFrom);
853 /* Remove the reference to the owning instruction if it has one. The
854 * function may be called for a label without an owner when deleting
855 * unfinished parts of the code. This is unfortunate since it allows
856 * errors to slip through.
859 CollDeleteItem (&L->Owner->Labels, L);
862 /* All references removed, delete the label itself */
868 void CS_MergeLabels (CodeSeg* S)
869 /* Merge code labels. That means: For each instruction, remove all labels but
870 * one and adjust references accordingly.
876 /* First, remove all labels from the label symbol table that don't have an
877 * owner (this means that they are actually external labels but we didn't
878 * know that previously since they may have also been forward references).
880 for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) {
882 /* Get the first label in this hash chain */
883 CodeLabel** L = &S->LabelHash[I];
885 if ((*L)->Owner == 0) {
887 /* The label does not have an owner, remove it from the chain */
891 /* Cleanup any entries jumping to this label */
892 for (J = 0; J < CL_GetRefCount (X); ++J) {
893 /* Get the entry referencing this label */
894 CodeEntry* E = CL_GetRef (X, J);
895 /* And remove the reference. Do NOT call CE_ClearJumpTo
896 * here, because this will also clear the label name,
897 * which is not what we want.
902 /* Print some debugging output */
904 printf ("Removing unused global label `%s'", X->Name);
907 /* And free the label */
910 /* Label is owned, point to next code label pointer */
916 /* Walk over all code entries */
917 for (I = 0; I < CS_GetEntryCount (S); ++I) {
922 /* Get a pointer to the next entry */
923 CodeEntry* E = CS_GetEntry (S, I);
925 /* If this entry has zero labels, continue with the next one */
926 unsigned LabelCount = CE_GetLabelCount (E);
927 if (LabelCount == 0) {
931 /* We have at least one label. Use the first one as reference label. */
932 RefLab = CE_GetLabel (E, 0);
934 /* Walk through the remaining labels and change references to these
935 * labels to a reference to the one and only label. Delete the labels
936 * that are no longer used. To increase performance, walk backwards
939 for (J = LabelCount-1; J >= 1; --J) {
941 /* Get the next label */
942 CodeLabel* L = CE_GetLabel (E, J);
944 /* Move all references from this label to the reference label */
945 CL_MoveRefs (L, RefLab);
947 /* Remove the label completely. */
951 /* The reference label is the only remaining label. Check if there
952 * are any references to this label, and delete it if this is not
955 if (CollCount (&RefLab->JumpFrom) == 0) {
956 /* Delete the label */
957 CS_DelLabel (S, RefLab);
964 void CS_MoveLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
965 /* Move all labels from Old to New. The routine will move the labels itself
966 * if New does not have any labels, and move references if there is at least
967 * a label for new. If references are moved, the old label is deleted
971 /* Get the number of labels to move */
972 unsigned OldLabelCount = CE_GetLabelCount (Old);
974 /* Does the new entry have itself a label? */
975 if (CE_HasLabel (New)) {
977 /* The new entry does already have a label - move references */
978 CodeLabel* NewLabel = CE_GetLabel (New, 0);
979 while (OldLabelCount--) {
981 /* Get the next label */
982 CodeLabel* OldLabel = CE_GetLabel (Old, OldLabelCount);
984 /* Move references */
985 CL_MoveRefs (OldLabel, NewLabel);
987 /* Delete the label */
988 CS_DelLabel (S, OldLabel);
994 /* The new entry does not have a label, just move them */
995 while (OldLabelCount--) {
997 /* Move the label to the new entry */
998 CE_MoveLabel (CE_GetLabel (Old, OldLabelCount), New);
1007 void CS_RemoveLabelRef (CodeSeg* S, struct CodeEntry* E)
1008 /* Remove the reference between E and the label it jumps to. The reference
1009 * will be removed on both sides and E->JumpTo will be 0 after that. If
1010 * the reference was the only one for the label, the label will get
1014 /* Get a pointer to the label and make sure it exists */
1015 CodeLabel* L = E->JumpTo;
1018 /* Delete the entry from the label */
1019 CollDeleteItem (&L->JumpFrom, E);
1021 /* The entry jumps no longer to L */
1024 /* If there are no more references, delete the label */
1025 if (CollCount (&L->JumpFrom) == 0) {
1032 void CS_MoveLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
1033 /* Change the reference of E to L instead of the current one. If this
1034 * was the only reference to the old label, the old label will get
1038 /* Get the old label */
1039 CodeLabel* OldLabel = E->JumpTo;
1041 /* Be sure that code entry references a label */
1042 PRECONDITION (OldLabel != 0);
1044 /* Remove the reference to our label */
1045 CS_RemoveLabelRef (S, E);
1047 /* Use the new label */
1053 void CS_DelCodeRange (CodeSeg* S, unsigned First, unsigned Last)
1054 /* Delete all entries between first and last, both inclusive. The function
1055 * can only handle basic blocks (First is the only entry, Last the only exit)
1056 * and no open labels. It will call FAIL if any of these preconditions are
1061 CodeEntry* FirstEntry;
1063 /* Do some sanity checks */
1064 CHECK (First <= Last && Last < CS_GetEntryCount (S));
1066 /* If Last is actually the last insn, call CS_DelCodeAfter instead, which
1067 * is more flexible in this case.
1069 if (Last == CS_GetEntryCount (S) - 1) {
1070 CS_DelCodeAfter (S, First);
1074 /* Get the first entry and check if it has any labels. If it has, move
1075 * them to the insn following Last. If Last is the last insn of the code
1076 * segment, make them ownerless and move them to the label pool.
1078 FirstEntry = CS_GetEntry (S, First);
1079 if (CE_HasLabel (FirstEntry)) {
1080 /* Get the entry following last */
1081 CodeEntry* FollowingEntry = CS_GetNextEntry (S, Last);
1082 if (FollowingEntry) {
1083 /* There is an entry after Last - move the labels */
1084 CS_MoveLabels (S, FirstEntry, FollowingEntry);
1086 /* Move the labels to the pool and clear the owner pointer */
1087 CS_MoveLabelsToPool (S, FirstEntry);
1091 /* First pass: Delete all references to labels. If the reference count
1092 * for a label drops to zero, delete it.
1094 for (I = Last; I >= First; --I) {
1096 /* Get the next entry */
1097 CodeEntry* E = CS_GetEntry (S, I);
1099 /* Check if this entry has a label reference */
1102 /* If the label is a label in the label pool, this is an error */
1103 CodeLabel* L = E->JumpTo;
1104 CHECK (CollIndex (&S->Labels, L) < 0);
1106 /* Remove the reference to the label */
1107 CS_RemoveLabelRef (S, E);
1111 /* Second pass: Delete the instructions. If a label attached to an
1112 * instruction still has references, it must be references from outside
1113 * the deleted area, which is an error.
1115 for (I = Last; I >= First; --I) {
1117 /* Get the next entry */
1118 CodeEntry* E = CS_GetEntry (S, I);
1120 /* Check if this entry has a label attached */
1121 CHECK (!CE_HasLabel (E));
1123 /* Delete the pointer to the entry */
1124 CollDelete (&S->Entries, I);
1126 /* Delete the entry itself */
1133 void CS_DelCodeAfter (CodeSeg* S, unsigned Last)
1134 /* Delete all entries including the given one */
1136 /* Get the number of entries in this segment */
1137 unsigned Count = CS_GetEntryCount (S);
1139 /* First pass: Delete all references to labels. If the reference count
1140 * for a label drops to zero, delete it.
1143 while (Last < C--) {
1145 /* Get the next entry */
1146 CodeEntry* E = CS_GetEntry (S, C);
1148 /* Check if this entry has a label reference */
1150 /* If the label is a label in the label pool and this is the last
1151 * reference to the label, remove the label from the pool.
1153 CodeLabel* L = E->JumpTo;
1154 int Index = CollIndex (&S->Labels, L);
1155 if (Index >= 0 && CollCount (&L->JumpFrom) == 1) {
1156 /* Delete it from the pool */
1157 CollDelete (&S->Labels, Index);
1160 /* Remove the reference to the label */
1161 CS_RemoveLabelRef (S, E);
1166 /* Second pass: Delete the instructions. If a label attached to an
1167 * instruction still has references, it must be references from outside
1168 * the deleted area. Don't delete the label in this case, just make it
1169 * ownerless and move it to the label pool.
1172 while (Last < C--) {
1174 /* Get the next entry */
1175 CodeEntry* E = CS_GetEntry (S, C);
1177 /* Check if this entry has a label attached */
1178 if (CE_HasLabel (E)) {
1179 /* Move the labels to the pool and clear the owner pointer */
1180 CS_MoveLabelsToPool (S, E);
1183 /* Delete the pointer to the entry */
1184 CollDelete (&S->Entries, C);
1186 /* Delete the entry itself */
1193 void CS_ResetMarks (CodeSeg* S, unsigned First, unsigned Last)
1194 /* Remove all user marks from the entries in the given range */
1196 while (First <= Last) {
1197 CE_ResetMark (CS_GetEntry (S, First++));
1203 int CS_IsBasicBlock (CodeSeg* S, unsigned First, unsigned Last)
1204 /* Check if the given code segment range is a basic block. That is, check if
1205 * First is the only entrance and Last is the only exit. This means that no
1206 * jump/branch inside the block may jump to an insn below First or after(!)
1207 * Last, and that no insn may jump into this block from the outside.
1212 /* Don't accept invalid ranges */
1213 CHECK (First <= Last);
1215 /* First pass: Walk over the range and remove all marks from the entries */
1216 CS_ResetMarks (S, First, Last);
1218 /* Second pass: Walk over the range checking all labels. Note: There may be
1219 * label on the first insn which is ok.
1224 /* Get the next entry */
1225 CodeEntry* E = CS_GetEntry (S, I);
1227 /* Check if this entry has one or more labels, if so, check which
1228 * entries jump to this label.
1230 unsigned LabelCount = CE_GetLabelCount (E);
1231 unsigned LabelIndex;
1232 for (LabelIndex = 0; LabelIndex < LabelCount; ++LabelIndex) {
1234 /* Get this label */
1235 CodeLabel* L = CE_GetLabel (E, LabelIndex);
1237 /* Walk over all entries that jump to this label. Check for each
1238 * of the entries if it is out of the range.
1240 unsigned RefCount = CL_GetRefCount (L);
1242 for (RefIndex = 0; RefIndex < RefCount; ++RefIndex) {
1244 /* Get the code entry that jumps here */
1245 CodeEntry* Ref = CL_GetRef (L, RefIndex);
1247 /* Walk over out complete range and check if we find the
1248 * refering entry. This is cheaper than using CS_GetEntryIndex,
1249 * because CS_GetEntryIndex will search the complete code
1250 * segment and not just our range.
1253 for (J = First; J <= Last; ++J) {
1254 if (Ref == CS_GetEntry (S, J)) {
1259 /* We did not find the entry. This means that the jump to
1260 * out code segment entry E came from outside the range,
1261 * which in turn means that the given range is not a basic
1264 CS_ResetMarks (S, First, Last);
1268 /* If we come here, we found the entry. Mark it, so we know
1269 * that the branch to the label is in range.
1279 /* Third pass: Walk again over the range and check all branches. If we
1280 * find a branch that is not marked, its target is not inside the range
1281 * (since we checked all the labels in the range before).
1286 /* Get the next entry */
1287 CodeEntry* E = CS_GetEntry (S, I);
1289 /* Check if this is a branch and if so, if it has a mark */
1290 if (E->Info & (OF_UBRA | OF_CBRA)) {
1291 if (!CE_HasMark (E)) {
1292 /* No mark means not a basic block. Before bailing out, be sure
1293 * to remove the marks from the remaining entries.
1295 CS_ResetMarks (S, I+1, Last);
1299 /* Remove the mark */
1307 /* Done - this is a basic block */
1313 void CS_OutputPrologue (const CodeSeg* S)
1314 /* If the given code segment is a code segment for a function, output the
1315 * assembler prologue into the file. That is: Output a comment header, switch
1316 * to the correct segment and enter the local function scope. If the code
1317 * segment is global, do nothing.
1320 /* Get the function associated with the code segment */
1321 SymEntry* Func = S->Func;
1323 /* If the code segment is associated with a function, print a function
1324 * header and enter a local scope. Be sure to switch to the correct
1325 * segment before outputing the function label.
1328 /* Get the function descriptor */
1329 CS_PrintFunctionHeader (S);
1330 WriteOutput (".segment\t\"%s\"\n\n.proc\t_%s", S->SegName, Func->Name);
1331 if (IsQualNear (Func->Type)) {
1332 WriteOutput (": near");
1333 } else if (IsQualFar (Func->Type)) {
1334 WriteOutput (": far");
1336 WriteOutput ("\n\n");
1343 void CS_OutputEpilogue (const CodeSeg* S)
1344 /* If the given code segment is a code segment for a function, output the
1345 * assembler epilogue into the file. That is: Close the local function scope.
1349 WriteOutput ("\n.endproc\n\n");
1355 void CS_Output (CodeSeg* S)
1356 /* Output the code segment data to the output file */
1361 /* Get the number of entries in this segment */
1362 unsigned Count = CS_GetEntryCount (S);
1364 /* If the code segment is empty, bail out here */
1369 /* Generate register info */
1372 /* Output the segment directive */
1373 WriteOutput (".segment\t\"%s\"\n\n", S->SegName);
1375 /* Output all entries, prepended by the line information if it has changed */
1377 for (I = 0; I < Count; ++I) {
1378 /* Get the next entry */
1379 const CodeEntry* E = CollConstAt (&S->Entries, I);
1380 /* Check if the line info has changed. If so, output the source line
1381 * if the option is enabled and output debug line info if the debug
1382 * option is enabled.
1385 /* Line info has changed, remember the new line info */
1388 /* Add the source line as a comment. Beware: When line continuation
1389 * was used, the line may contain newlines.
1392 const char* L = LI->Line;
1393 WriteOutput (";\n; ");
1395 const char* N = strchr (L, '\n');
1397 /* We have a newline, just write the first part */
1398 WriteOutput ("%.*s\n; ", (int) (N - L), L);
1401 /* No Newline, write as is */
1402 WriteOutput ("%s\n", L);
1406 WriteOutput (";\n");
1409 /* Add line debug info */
1411 WriteOutput ("\t.dbg\tline, \"%s\", %u\n",
1412 GetInputName (LI), GetInputLine (LI));
1415 /* Output the code */
1419 /* If debug info is enabled, terminate the last line number information */
1421 WriteOutput ("\t.dbg\tline\n");
1424 /* Free register info */
1430 void CS_FreeRegInfo (CodeSeg* S)
1431 /* Free register infos for all instructions */
1434 for (I = 0; I < CS_GetEntryCount (S); ++I) {
1435 CE_FreeRegInfo (CS_GetEntry(S, I));
1441 void CS_GenRegInfo (CodeSeg* S)
1442 /* Generate register infos for all instructions */
1445 RegContents Regs; /* Initial register contents */
1446 RegContents* CurrentRegs; /* Current register contents */
1447 int WasJump; /* True if last insn was a jump */
1448 int Done; /* All runs done flag */
1450 /* Be sure to delete all register infos */
1453 /* We may need two runs to get back references right */
1456 /* Assume we're done after this run */
1459 /* On entry, the register contents are unknown */
1460 RC_Invalidate (&Regs);
1461 CurrentRegs = &Regs;
1463 /* Walk over all insns and note just the changes from one insn to the
1467 for (I = 0; I < CS_GetEntryCount (S); ++I) {
1471 /* Get the next instruction */
1472 CodeEntry* E = CollAtUnchecked (&S->Entries, I);
1474 /* If the instruction has a label, we need some special handling */
1475 unsigned LabelCount = CE_GetLabelCount (E);
1476 if (LabelCount > 0) {
1478 /* Loop over all entry points that jump here. If these entry
1479 * points already have register info, check if all values are
1480 * known and identical. If all values are identical, and the
1481 * preceeding instruction was not an unconditional branch, check
1482 * if the register value on exit of the preceeding instruction
1483 * is also identical. If all these values are identical, the
1484 * value of a register is known, otherwise it is unknown.
1486 CodeLabel* Label = CE_GetLabel (E, 0);
1489 /* Preceeding insn was an unconditional branch */
1490 CodeEntry* J = CL_GetRef(Label, 0);
1494 RC_Invalidate (&Regs);
1498 Regs = *CurrentRegs;
1502 while (Entry < CL_GetRefCount (Label)) {
1503 /* Get this entry */
1504 CodeEntry* J = CL_GetRef (Label, Entry);
1506 /* No register info for this entry. This means that the
1507 * instruction that jumps here is at higher addresses and
1508 * the jump is a backward jump. We need a second run to
1509 * get the register info right in this case. Until then,
1510 * assume unknown register contents.
1513 RC_Invalidate (&Regs);
1516 if (J->RI->Out2.RegA != Regs.RegA) {
1517 Regs.RegA = UNKNOWN_REGVAL;
1519 if (J->RI->Out2.RegX != Regs.RegX) {
1520 Regs.RegX = UNKNOWN_REGVAL;
1522 if (J->RI->Out2.RegY != Regs.RegY) {
1523 Regs.RegY = UNKNOWN_REGVAL;
1525 if (J->RI->Out2.SRegLo != Regs.SRegLo) {
1526 Regs.SRegLo = UNKNOWN_REGVAL;
1528 if (J->RI->Out2.SRegHi != Regs.SRegHi) {
1529 Regs.SRegHi = UNKNOWN_REGVAL;
1531 if (J->RI->Out2.Tmp1 != Regs.Tmp1) {
1532 Regs.Tmp1 = UNKNOWN_REGVAL;
1537 /* Use this register info */
1538 CurrentRegs = &Regs;
1542 /* Generate register info for this instruction */
1543 CE_GenRegInfo (E, CurrentRegs);
1545 /* Remember for the next insn if this insn was an uncondition branch */
1546 WasJump = (E->Info & OF_UBRA) != 0;
1548 /* Output registers for this insn are input for the next */
1549 CurrentRegs = &E->RI->Out;
1551 /* If this insn is a branch on zero flag, we may have more info on
1552 * register contents for one of both flow directions, but only if
1553 * there is a previous instruction.
1555 if ((E->Info & OF_ZBRA) != 0 && (P = CS_GetPrevEntry (S, I)) != 0) {
1557 /* Get the branch condition */
1558 bc_t BC = GetBranchCond (E->OPC);
1560 /* Check the previous instruction */
1572 /* A is zero in one execution flow direction */
1574 E->RI->Out2.RegA = 0;
1576 E->RI->Out.RegA = 0;
1581 /* If this is an immidiate compare, the A register has
1582 * the value of the compare later.
1584 if (CE_IsConstImm (P)) {
1586 E->RI->Out2.RegA = (unsigned char)P->Num;
1588 E->RI->Out.RegA = (unsigned char)P->Num;
1594 /* If this is an immidiate compare, the X register has
1595 * the value of the compare later.
1597 if (CE_IsConstImm (P)) {
1599 E->RI->Out2.RegX = (unsigned char)P->Num;
1601 E->RI->Out.RegX = (unsigned char)P->Num;
1607 /* If this is an immidiate compare, the Y register has
1608 * the value of the compare later.
1610 if (CE_IsConstImm (P)) {
1612 E->RI->Out2.RegY = (unsigned char)P->Num;
1614 E->RI->Out.RegY = (unsigned char)P->Num;
1623 /* X is zero in one execution flow direction */
1625 E->RI->Out2.RegX = 0;
1627 E->RI->Out.RegX = 0;
1635 /* X is zero in one execution flow direction */
1637 E->RI->Out2.RegY = 0;
1639 E->RI->Out.RegY = 0;
1645 /* If the branch is a beq, both A and X are zero at the
1646 * branch target, otherwise they are zero at the next
1650 E->RI->Out2.RegA = E->RI->Out2.RegX = 0;
1652 E->RI->Out.RegA = E->RI->Out.RegX = 0;
1658 /* If the branch is a beq, both A and Y are zero at the
1659 * branch target, otherwise they are zero at the next
1663 E->RI->Out2.RegA = E->RI->Out2.RegY = 0;
1665 E->RI->Out.RegA = E->RI->Out.RegY = 0;