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 (Expr, sizeof (Expr), L+1);
179 L = ReadToken (L+1, ",)", Expr, sizeof (Expr));
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, ",", Expr, sizeof (Expr));
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 && Expr[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 (Expr) % CS_LABEL_HASH_SIZE;
288 Label = FindCodeLabel (S, Expr, 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, Expr, 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, Label);
301 if (Expr[0] != '\0') {
302 /* We have an additional expression */
303 E->Arg.Expr = xstrdup (Expr);
306 /* Return the new code entry */
312 /*****************************************************************************/
314 /*****************************************************************************/
318 CodeSeg* NewCodeSeg (const char* SegName, const char* FuncName)
319 /* Create a new code segment, initialize and return it */
323 /* Allocate memory */
324 CodeSeg* S = xmalloc (sizeof (CodeSeg));
326 /* Initialize the fields */
328 S->SegName = xstrdup (SegName);
329 S->FuncName = xstrdup (FuncName);
330 InitCollection (&S->Entries);
331 InitCollection (&S->Labels);
332 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
336 /* Return the new struct */
342 void FreeCodeSeg (CodeSeg* S)
343 /* Free a code segment including all code entries */
351 /* Free the entries */
352 Count = CollCount (&S->Entries);
353 for (I = 0; I < Count; ++I) {
354 FreeCodeEntry (CollAt (&S->Entries, I));
357 /* Free the collections */
358 DoneCollection (&S->Entries);
359 DoneCollection (&S->Labels);
361 /* Free all labels */
362 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
363 CodeLabel* L = S->LabelHash[I];
371 /* Free the struct */
377 void PushCodeSeg (CodeSeg* S)
378 /* Push the given code segment onto the stack */
386 CodeSeg* PopCodeSeg (void)
387 /* Remove the current code segment from the stack and return it */
389 /* Remember the current code segment */
392 /* Cannot pop on empty stack */
393 PRECONDITION (S != 0);
398 /* Return the popped code segment */
404 void AddCodeSegLine (CodeSeg* S, const char* Format, ...)
405 /* Add a line to the given code segment */
411 /* Format the line */
414 va_start (ap, Format);
415 xvsprintf (Buf, sizeof (Buf), Format, ap);
418 /* Skip whitespace */
421 /* Check which type of instruction we have */
422 E = 0; /* Assume no insn created */
426 /* Empty line, just ignore it */
430 /* Comment or hint, ignore it for now */
434 /* Control instruction */
435 ReadToken (L, " \t", Token, sizeof (Token));
436 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
440 E = ParseInsn (S, L);
444 /* If we have a code entry, transfer the labels and insert it */
447 /* Transfer the labels if we have any */
449 unsigned LabelCount = CollCount (&S->Labels);
450 for (I = 0; I < LabelCount; ++I) {
452 CodeLabel* L = CollAt (&S->Labels, I);
453 /* Mark it as defined */
455 /* Move it to the code entry */
456 CollAppend (&E->Labels, L);
457 /* Tell the label about it's owner */
461 /* Delete the transfered labels */
462 CollDeleteAll (&S->Labels);
464 /* Add the entry to the list of code entries in this segment */
465 CollAppend (&S->Entries, E);
472 void AddCodeLabel (CodeSeg* S, const char* Name)
473 /* Add a code label for the next instruction to follow */
475 /* Calculate the hash from the name */
476 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
478 /* Try to find the code label if it does already exist */
479 CodeLabel* L = FindCodeLabel (S, Name, Hash);
481 /* Did we find it? */
483 /* We found it - be sure it does not already have an owner */
484 CHECK (L->Owner == 0);
486 /* Not found - create a new one */
487 L = NewCodeSegLabel (S, Name, Hash);
490 /* We do now have a valid label. Remember it for later */
491 CollAppend (&S->Labels, L);
496 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
497 /* Add a hint for the preceeding instruction */
501 /* Get the number of entries in this segment */
502 unsigned EntryCount = CollCount (&S->Entries);
504 /* Must have at least one entry */
505 CHECK (EntryCount > 0);
507 /* Get the last entry */
508 E = CollAt (&S->Entries, EntryCount-1);
516 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
517 /* Delete all entries including the given one */
519 /* Get the number of entries in this segment */
520 unsigned Count = CollCount (&S->Entries);
522 /* Remove all entries after the given one */
523 while (Last < Count) {
525 /* Get the next entry */
526 CodeEntry* E = CollAt (&S->Entries, Count-1);
528 /* We have to transfer all labels to the code segment label pool */
529 unsigned LabelCount = CollCount (&E->Labels);
530 while (LabelCount--) {
531 CodeLabel* L = CollAt (&E->Labels, LabelCount);
533 CollAppend (&S->Labels, L);
535 CollDeleteAll (&E->Labels);
537 /* Remove the code entry */
538 FreeCodeEntry (CollAt (&S->Entries, Count-1));
539 CollDelete (&S->Entries, Count-1);
546 void OutputCodeSeg (FILE* F, const CodeSeg* S)
547 /* Output the code segment data to a file */
551 /* Get the number of entries in this segment */
552 unsigned Count = CollCount (&S->Entries);
554 /* Output the segment directive */
555 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
557 /* If this is a segment for a function, enter a function */
558 if (S->FuncName[0] != '\0') {
559 fprintf (F, ".proc\t_%s\n\n", S->FuncName);
562 /* Output all entries */
563 for (I = 0; I < Count; ++I) {
564 OutputCodeEntry (F, CollConstAt (&S->Entries, I));
567 /* If this is a segment for a function, leave the function */
568 if (S->FuncName[0] != '\0') {
569 fprintf (F, "\n.endproc\n\n");
575 CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
576 /* Find the label with the given name. Return the label or NULL if not found */
578 /* Get the first hash chain entry */
579 CodeLabel* L = S->LabelHash[Hash];
581 /* Search the list */
583 if (strcmp (Name, L->Name) == 0) {
594 void MergeCodeLabels (CodeSeg* S)
595 /* Merge code labels. That means: For each instruction, remove all labels but
596 * one and adjust the code entries accordingly.
601 /* Walk over all code entries */
602 unsigned EntryCount = CollCount (&S->Entries);
603 for (I = 0; I < EntryCount; ++I) {
608 /* Get a pointer to the next entry */
609 CodeEntry* E = CollAt (&S->Entries, I);
611 /* If this entry has zero labels, continue with the next one */
612 unsigned LabelCount = CollCount (&E->Labels);
613 if (LabelCount == 0) {
617 /* We have at least one label. Use the first one as reference label. */
618 RefLab = CollAt (&E->Labels, 0);
620 /* Walk through the remaining labels and change references to these
621 * labels to a reference to the one and only label. Delete the labels
622 * that are no longer used. To increase performance, walk backwards
625 for (J = LabelCount-1; J >= 1; --J) {
629 /* Get the next label */
630 CodeLabel* L = CollAt (&E->Labels, J);
632 /* Walk through all instructions referencing this label */
633 unsigned RefCount = CollCount (&L->JumpFrom);
634 for (K = 0; K < RefCount; ++K) {
636 /* Get the next instrcuction that references this label */
637 CodeEntry* E = CollAt (&L->JumpFrom, K);
639 /* Change the reference */
640 CHECK (E->JumpTo == L);
642 CollAppend (&RefLab->JumpFrom, E);
646 /* Remove the label completely. */
648 CollDelete (&E->Labels, J);
651 /* The reference label is the only remaining label. Check if there
652 * are any references to this label, and delete it if this is not
655 if (CollCount (&RefLab->JumpFrom) == 0) {
656 /* Delete the label */
657 FreeCodeLabel (RefLab);
658 /* Remove it from the list */
659 CollDelete (&E->Labels, 0);
666 unsigned GetCodeSegEntries (const CodeSeg* S)
667 /* Return the number of entries for the given code segment */
669 return CollCount (&S->Entries);