1 /*****************************************************************************/
5 /* Code segment structure */
9 /* (C) 2001 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@musoftware.de */
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 /*****************************************************************************/
57 /*****************************************************************************/
59 /*****************************************************************************/
63 /* Pointer to current code segment */
68 /*****************************************************************************/
69 /* Functions for parsing instructions */
70 /*****************************************************************************/
74 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
75 /* Create a new label and insert it into the label hash table */
77 /* Not found - create a new one */
78 CodeLabel* L = NewCodeLabel (Name, Hash);
80 /* Enter the label into the hash table */
81 L->Next = S->LabelHash[L->Hash];
82 S->LabelHash[L->Hash] = L;
84 /* Return the new label */
90 static const char* SkipSpace (const char* S)
91 /* Skip white space and return an updated pointer */
93 while (IsSpace (*S)) {
101 static const char* ReadToken (const char* L, const char* Term,
102 char* Buf, unsigned BufSize)
103 /* Read the next token into Buf, return the updated line pointer. The
104 * token is terminated by one of the characters given in term.
107 /* Read/copy the token */
109 unsigned ParenCount = 0;
110 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
116 } else if (*L == '(') {
122 /* Terminate the buffer contents */
125 /* Return the updated line pointer */
131 static CodeEntry* ParseInsn (CodeSeg* S, const char* L)
132 /* Parse an instruction nnd generate a code entry from it. If the line contains
133 * errors, output an error message and return NULL.
134 * For simplicity, we don't accept the broad range of input a "real" assembler
135 * does. The instruction and the argument are expected to be separated by
136 * white space, for example.
141 am_t AM = 0; /* Initialize to keep gcc silent */
148 L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
150 /* Try to find the opcode description for the mnemonic */
151 OPC = FindOpcode (Mnemo);
153 /* If we didn't find the opcode, print an error and bail out */
155 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
159 /* Skip separator white space */
162 /* Get the addressing mode */
173 StrCopy (Arg, sizeof (Arg), L+1);
179 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
181 /* Check for errors */
183 Error ("ASM code error: syntax error");
187 /* Check the different indirect modes */
189 /* Expect zp x indirect */
191 if (toupper (*L) != 'X') {
192 Error ("ASM code error: `X' expected");
197 Error ("ASM code error: `)' expected");
202 Error ("ASM code error: syntax error");
206 } else if (*L == ')') {
207 /* zp indirect or zp indirect, y */
211 if (toupper (*L) != 'Y') {
212 Error ("ASM code error: `Y' expected");
217 Error ("ASM code error: syntax error");
221 } else if (*L == '\0') {
224 Error ("ASM code error: syntax error");
240 /* Absolute, maybe indexed */
241 L = ReadToken (L, ",", Arg, sizeof (Arg));
243 /* Assume absolute */
245 } else if (*L == ',') {
249 Error ("ASM code error: syntax error");
256 } else if (Reg == 'Y') {
259 Error ("ASM code error: syntax error");
263 Error ("ASM code error: syntax error");
272 /* If the instruction is a branch, check for the label and generate it
273 * if it does not exist. Ignore anything but local labels here.
276 if ((OPC->Info & CI_MASK_BRA) == CI_BRA && Arg[0] == 'L') {
280 /* Addressing mode must be alsobute or something is really wrong */
281 CHECK (AM == AM_ABS);
283 /* Addressing mode is a branch/jump */
286 /* Generate the hash over the label, then search for the label */
287 Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
288 Label = FindCodeLabel (S, Arg, Hash);
290 /* If we don't have the label, it's a forward ref - create it */
292 /* Generate a new label */
293 Label = NewCodeSegLabel (S, Arg, Hash);
297 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
298 * structure and initialize it.
300 E = NewCodeEntry (OPC, AM, Arg, Label);
302 /* Return the new code entry */
308 /*****************************************************************************/
310 /*****************************************************************************/
314 CodeSeg* NewCodeSeg (const char* SegName, const char* FuncName)
315 /* Create a new code segment, initialize and return it */
319 /* Allocate memory */
320 CodeSeg* S = xmalloc (sizeof (CodeSeg));
322 /* Initialize the fields */
324 S->SegName = xstrdup (SegName);
325 S->FuncName = xstrdup (FuncName);
326 InitCollection (&S->Entries);
327 InitCollection (&S->Labels);
328 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
332 /* Return the new struct */
338 void FreeCodeSeg (CodeSeg* S)
339 /* Free a code segment including all code entries */
341 FAIL ("Not implemented");
346 void PushCodeSeg (CodeSeg* S)
347 /* Push the given code segment onto the stack */
355 CodeSeg* PopCodeSeg (void)
356 /* Remove the current code segment from the stack and return it */
358 /* Remember the current code segment */
361 /* Cannot pop on empty stack */
362 PRECONDITION (S != 0);
367 /* Return the popped code segment */
373 void AddCodeSegLine (CodeSeg* S, const char* Format, ...)
374 /* Add a line to the given code segment */
380 /* Format the line */
383 va_start (ap, Format);
384 xvsprintf (Buf, sizeof (Buf), Format, ap);
387 /* Skip whitespace */
390 /* Check which type of instruction we have */
391 E = 0; /* Assume no insn created */
395 /* Empty line, just ignore it */
399 /* Comment or hint, ignore it for now */
403 /* Control instruction */
404 ReadToken (L, " \t", Token, sizeof (Token));
405 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
409 E = ParseInsn (S, L);
413 /* If we have a code entry, transfer the labels and insert it */
416 /* Transfer the labels if we have any */
418 unsigned LabelCount = CollCount (&S->Labels);
419 for (I = 0; I < LabelCount; ++I) {
421 CodeLabel* L = CollAt (&S->Labels, I);
422 /* Mark it as defined */
424 /* Move it to the code entry */
425 CollAppend (&E->Labels, L);
426 /* Tell the label about it's owner */
430 /* Delete the transfered labels */
431 CollDeleteAll (&S->Labels);
433 /* Add the entry to the list of code entries in this segment */
434 CollAppend (&S->Entries, E);
441 void DelCodeSegLine (CodeSeg* S, unsigned Index)
442 /* Delete an entry from the code segment. This includes deleting any associated
443 * labels, removing references to labels and even removing the referenced labels
444 * if the reference count drops to zero.
447 /* Get the code entry for the given index */
448 CodeEntry* E = CollAt (&S->Entries, Index);
450 /* Remove any labels associated with this entry */
452 while ((Count = CollCount (&E->Labels)) > 0) {
453 DelCodeLabel (S, CollAt (&E->Labels, Count-1));
456 /* If this insn references a label, remove the reference. And, if the
457 * the reference count for this label drops to zero, remove this label.
461 /* Remove the reference */
462 if (RemoveLabelRef (E->JumpTo, E) == 0) {
463 /* No references remaining, remove the label */
464 DelCodeLabel (S, E->JumpTo);
467 /* Reset the label pointer to avoid problems later */
471 /* Delete the pointer to the insn */
472 CollDelete (&S->Entries, Index);
474 /* Delete the instruction itself */
480 void AddCodeLabel (CodeSeg* S, const char* Name)
481 /* Add a code label for the next instruction to follow */
483 /* Calculate the hash from the name */
484 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
486 /* Try to find the code label if it does already exist */
487 CodeLabel* L = FindCodeLabel (S, Name, Hash);
489 /* Did we find it? */
491 /* We found it - be sure it does not already have an owner */
492 CHECK (L->Owner == 0);
494 /* Not found - create a new one */
495 L = NewCodeSegLabel (S, Name, Hash);
498 /* We do now have a valid label. Remember it for later */
499 CollAppend (&S->Labels, L);
504 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
505 /* Remove references from this label and delete it. */
509 /* Get the first entry in the hash chain */
510 CodeLabel* List = S->LabelHash[L->Hash];
512 /* First, remove the label from the hash chain */
514 /* First entry in hash chain */
515 S->LabelHash[L->Hash] = L->Next;
517 /* Must search through the chain */
518 while (List->Next != L) {
519 /* If we've reached the end of the chain, something is *really* wrong */
520 CHECK (List->Next != 0);
524 /* The next entry is the one, we have been searching for */
525 List->Next = L->Next;
528 /* Remove references from insns jumping to this label */
529 Count = CollCount (&L->JumpFrom);
530 for (I = 0; I < Count; ++I) {
531 /* Get the insn referencing this label */
532 CodeEntry* E = CollAt (&L->JumpFrom, I);
533 /* Remove the reference */
536 CollDeleteAll (&L->JumpFrom);
538 /* Remove the reference to the owning instruction */
539 CollDeleteItem (&L->Owner->Labels, L);
541 /* All references removed, delete the label itself */
547 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
548 /* Add a hint for the preceeding instruction */
552 /* Get the number of entries in this segment */
553 unsigned EntryCount = CollCount (&S->Entries);
555 /* Must have at least one entry */
556 CHECK (EntryCount > 0);
558 /* Get the last entry */
559 E = CollAt (&S->Entries, EntryCount-1);
567 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
568 /* Delete all entries including the given one */
570 /* Get the number of entries in this segment */
571 unsigned Count = CollCount (&S->Entries);
573 /* Remove all entries after the given one */
574 while (Last < Count) {
576 /* Get the next entry */
577 CodeEntry* E = CollAt (&S->Entries, Count-1);
579 /* We have to transfer all labels to the code segment label pool */
580 unsigned LabelCount = CollCount (&E->Labels);
581 while (LabelCount--) {
582 CodeLabel* L = CollAt (&E->Labels, LabelCount);
584 CollAppend (&S->Labels, L);
586 CollDeleteAll (&E->Labels);
588 /* Remove the code entry */
589 FreeCodeEntry (CollAt (&S->Entries, Count-1));
590 CollDelete (&S->Entries, Count-1);
597 void OutputCodeSeg (FILE* F, const CodeSeg* S)
598 /* Output the code segment data to a file */
602 /* Get the number of entries in this segment */
603 unsigned Count = CollCount (&S->Entries);
605 fprintf (F, "; Labels: ");
606 for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) {
607 const CodeLabel* L = S->LabelHash[I];
609 fprintf (F, "%s ", L->Name);
615 /* Output the segment directive */
616 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
618 /* If this is a segment for a function, enter a function */
619 if (S->FuncName[0] != '\0') {
620 fprintf (F, ".proc\t_%s\n\n", S->FuncName);
623 /* Output all entries */
624 for (I = 0; I < Count; ++I) {
625 OutputCodeEntry (F, CollConstAt (&S->Entries, I));
628 /* If this is a segment for a function, leave the function */
629 if (S->FuncName[0] != '\0') {
630 fprintf (F, "\n.endproc\n\n");
636 CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
637 /* Find the label with the given name. Return the label or NULL if not found */
639 /* Get the first hash chain entry */
640 CodeLabel* L = S->LabelHash[Hash];
642 /* Search the list */
644 if (strcmp (Name, L->Name) == 0) {
655 void MergeCodeLabels (CodeSeg* S)
656 /* Merge code labels. That means: For each instruction, remove all labels but
657 * one and adjust the code entries accordingly.
662 /* Walk over all code entries */
663 unsigned EntryCount = CollCount (&S->Entries);
664 for (I = 0; I < EntryCount; ++I) {
669 /* Get a pointer to the next entry */
670 CodeEntry* E = CollAt (&S->Entries, I);
672 /* If this entry has zero labels, continue with the next one */
673 unsigned LabelCount = CollCount (&E->Labels);
674 if (LabelCount == 0) {
678 /* We have at least one label. Use the first one as reference label. */
679 RefLab = CollAt (&E->Labels, 0);
681 /* Walk through the remaining labels and change references to these
682 * labels to a reference to the one and only label. Delete the labels
683 * that are no longer used. To increase performance, walk backwards
686 for (J = LabelCount-1; J >= 1; --J) {
690 /* Get the next label */
691 CodeLabel* L = CollAt (&E->Labels, J);
693 /* Walk through all instructions referencing this label */
694 unsigned RefCount = CollCount (&L->JumpFrom);
695 for (K = 0; K < RefCount; ++K) {
697 /* Get the next instruction that references this label */
698 CodeEntry* E = CollAt (&L->JumpFrom, K);
700 /* Change the reference */
701 CHECK (E->JumpTo == L);
702 AddLabelRef (RefLab, E);
706 /* There are no more instructions jumping to this label now */
707 CollDeleteAll (&L->JumpFrom);
709 /* Remove the label completely. */
713 /* The reference label is the only remaining label. Check if there
714 * are any references to this label, and delete it if this is not
717 if (CollCount (&RefLab->JumpFrom) == 0) {
718 /* Delete the label */
719 DelCodeLabel (S, RefLab);
726 unsigned GetCodeSegEntries (const CodeSeg* S)
727 /* Return the number of entries for the given code segment */
729 return CollCount (&S->Entries);