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 /*****************************************************************************/
55 /*****************************************************************************/
56 /* Functions for parsing instructions */
57 /*****************************************************************************/
61 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
62 /* Create a new label and insert it into the label hash table */
64 /* Not found - create a new one */
65 CodeLabel* L = NewCodeLabel (Name, Hash);
67 /* Enter the label into the hash table */
68 L->Next = S->LabelHash[L->Hash];
69 S->LabelHash[L->Hash] = L;
71 /* Return the new label */
77 static const char* SkipSpace (const char* S)
78 /* Skip white space and return an updated pointer */
80 while (IsSpace (*S)) {
88 static const char* ReadToken (const char* L, const char* Term,
89 char* Buf, unsigned BufSize)
90 /* Read the next token into Buf, return the updated line pointer. The
91 * token is terminated by one of the characters given in term.
94 /* Read/copy the token */
96 unsigned ParenCount = 0;
97 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
103 } else if (*L == '(') {
109 /* Terminate the buffer contents */
112 /* Return the updated line pointer */
118 static CodeEntry* ParseInsn (CodeSeg* S, const char* L)
119 /* Parse an instruction nnd generate a code entry from it. If the line contains
120 * errors, output an error message and return NULL.
121 * For simplicity, we don't accept the broad range of input a "real" assembler
122 * does. The instruction and the argument are expected to be separated by
123 * white space, for example.
128 am_t AM = 0; /* Initialize to keep gcc silent */
135 L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
137 /* Try to find the opcode description for the mnemonic */
138 OPC = FindOpcode (Mnemo);
140 /* If we didn't find the opcode, print an error and bail out */
142 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
146 /* Skip separator white space */
149 /* Get the addressing mode */
160 StrCopy (Arg, sizeof (Arg), L+1);
166 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
168 /* Check for errors */
170 Error ("ASM code error: syntax error");
174 /* Check the different indirect modes */
176 /* Expect zp x indirect */
178 if (toupper (*L) != 'X') {
179 Error ("ASM code error: `X' expected");
184 Error ("ASM code error: `)' expected");
189 Error ("ASM code error: syntax error");
193 } else if (*L == ')') {
194 /* zp indirect or zp indirect, y */
198 if (toupper (*L) != 'Y') {
199 Error ("ASM code error: `Y' expected");
204 Error ("ASM code error: syntax error");
208 } else if (*L == '\0') {
211 Error ("ASM code error: syntax error");
227 /* Absolute, maybe indexed */
228 L = ReadToken (L, ",", Arg, sizeof (Arg));
230 /* Assume absolute */
232 } else if (*L == ',') {
236 Error ("ASM code error: syntax error");
243 } else if (Reg == 'Y') {
246 Error ("ASM code error: syntax error");
250 Error ("ASM code error: syntax error");
259 /* If the instruction is a branch, check for the label and generate it
260 * if it does not exist. Ignore anything but local labels here.
263 if ((OPC->Info & CI_MASK_BRA) == CI_BRA && Arg[0] == 'L') {
267 /* Addressing mode must be alsobute or something is really wrong */
268 CHECK (AM == AM_ABS);
270 /* Addressing mode is a branch/jump */
273 /* Generate the hash over the label, then search for the label */
274 Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
275 Label = FindCodeLabel (S, Arg, Hash);
277 /* If we don't have the label, it's a forward ref - create it */
279 /* Generate a new label */
280 Label = NewCodeSegLabel (S, Arg, Hash);
284 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
285 * structure and initialize it.
287 E = NewCodeEntry (OPC, AM, Arg, Label);
289 /* Return the new code entry */
295 /*****************************************************************************/
297 /*****************************************************************************/
301 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
302 /* Create a new code segment, initialize and return it */
306 /* Allocate memory */
307 CodeSeg* S = xmalloc (sizeof (CodeSeg));
309 /* Initialize the fields */
310 S->SegName = xstrdup (SegName);
312 InitCollection (&S->Entries);
313 InitCollection (&S->Labels);
314 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
318 /* Return the new struct */
324 void AddCodeEntry (CodeSeg* S, const char* Format, va_list ap)
325 /* Add a line to the given code segment */
331 /* Format the line */
333 xvsprintf (Buf, sizeof (Buf), Format, ap);
335 /* Skip whitespace */
338 /* Check which type of instruction we have */
339 E = 0; /* Assume no insn created */
343 /* Empty line, just ignore it */
347 /* Comment or hint, ignore it for now */
351 /* Control instruction */
352 ReadToken (L, " \t", Token, sizeof (Token));
353 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
357 E = ParseInsn (S, L);
361 /* If we have a code entry, transfer the labels and insert it */
364 /* Transfer the labels if we have any */
366 unsigned LabelCount = CollCount (&S->Labels);
367 for (I = 0; I < LabelCount; ++I) {
369 CodeLabel* L = CollAt (&S->Labels, I);
370 /* Mark it as defined */
372 /* Move it to the code entry */
373 CollAppend (&E->Labels, L);
374 /* Tell the label about it's owner */
378 /* Delete the transfered labels */
379 CollDeleteAll (&S->Labels);
381 /* Add the entry to the list of code entries in this segment */
382 CollAppend (&S->Entries, E);
389 void DelCodeEntry (CodeSeg* S, unsigned Index)
390 /* Delete an entry from the code segment. This includes deleting any associated
391 * labels, removing references to labels and even removing the referenced labels
392 * if the reference count drops to zero.
395 /* Get the code entry for the given index */
396 CodeEntry* E = CollAt (&S->Entries, Index);
398 /* Remove any labels associated with this entry */
400 while ((Count = CollCount (&E->Labels)) > 0) {
401 DelCodeLabel (S, CollAt (&E->Labels, Count-1));
404 /* If this insn references a label, remove the reference. And, if the
405 * the reference count for this label drops to zero, remove this label.
409 /* Remove the reference */
410 if (RemoveLabelRef (E->JumpTo, E) == 0) {
411 /* No references remaining, remove the label */
412 DelCodeLabel (S, E->JumpTo);
415 /* Reset the label pointer to avoid problems later */
419 /* Delete the pointer to the insn */
420 CollDelete (&S->Entries, Index);
422 /* Delete the instruction itself */
428 void AddCodeLabel (CodeSeg* S, const char* Name)
429 /* Add a code label for the next instruction to follow */
431 /* Calculate the hash from the name */
432 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
434 /* Try to find the code label if it does already exist */
435 CodeLabel* L = FindCodeLabel (S, Name, Hash);
437 /* Did we find it? */
439 /* We found it - be sure it does not already have an owner */
440 CHECK (L->Owner == 0);
442 /* Not found - create a new one */
443 L = NewCodeSegLabel (S, Name, Hash);
446 /* We do now have a valid label. Remember it for later */
447 CollAppend (&S->Labels, L);
452 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
453 /* Remove references from this label and delete it. */
457 /* Get the first entry in the hash chain */
458 CodeLabel* List = S->LabelHash[L->Hash];
460 /* First, remove the label from the hash chain */
462 /* First entry in hash chain */
463 S->LabelHash[L->Hash] = L->Next;
465 /* Must search through the chain */
466 while (List->Next != L) {
467 /* If we've reached the end of the chain, something is *really* wrong */
468 CHECK (List->Next != 0);
472 /* The next entry is the one, we have been searching for */
473 List->Next = L->Next;
476 /* Remove references from insns jumping to this label */
477 Count = CollCount (&L->JumpFrom);
478 for (I = 0; I < Count; ++I) {
479 /* Get the insn referencing this label */
480 CodeEntry* E = CollAt (&L->JumpFrom, I);
481 /* Remove the reference */
484 CollDeleteAll (&L->JumpFrom);
486 /* Remove the reference to the owning instruction */
487 CollDeleteItem (&L->Owner->Labels, L);
489 /* All references removed, delete the label itself */
495 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
496 /* Add a hint for the preceeding instruction */
500 /* Get the number of entries in this segment */
501 unsigned EntryCount = CollCount (&S->Entries);
503 /* Must have at least one entry */
504 CHECK (EntryCount > 0);
506 /* Get the last entry */
507 E = CollAt (&S->Entries, EntryCount-1);
515 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
516 /* Delete all entries including the given one */
518 /* Get the number of entries in this segment */
519 unsigned Count = CollCount (&S->Entries);
521 /* Remove all entries after the given one */
522 while (Last < Count) {
524 /* Get the next entry */
525 CodeEntry* E = CollAt (&S->Entries, Count-1);
527 /* We have to transfer all labels to the code segment label pool */
528 unsigned LabelCount = CollCount (&E->Labels);
529 while (LabelCount--) {
530 CodeLabel* L = CollAt (&E->Labels, LabelCount);
532 CollAppend (&S->Labels, L);
534 CollDeleteAll (&E->Labels);
536 /* Remove the code entry */
537 FreeCodeEntry (CollAt (&S->Entries, Count-1));
538 CollDelete (&S->Entries, Count-1);
545 void OutputCodeSeg (const CodeSeg* S, FILE* F)
546 /* Output the code segment data to a file */
550 /* Get the number of entries in this segment */
551 unsigned Count = CollCount (&S->Entries);
553 /* If the code segment is empty, bail out here */
558 /* Output the segment directive */
559 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
561 /* If this is a segment for a function, enter a function */
563 fprintf (F, ".proc\t_%s\n\n", S->Func->Name);
566 /* Output all entries */
567 for (I = 0; I < Count; ++I) {
568 OutputCodeEntry (CollConstAt (&S->Entries, I), F);
571 /* If this is a segment for a function, leave the function */
573 fprintf (F, "\n.endproc\n\n");
579 CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
580 /* Find the label with the given name. Return the label or NULL if not found */
582 /* Get the first hash chain entry */
583 CodeLabel* L = S->LabelHash[Hash];
585 /* Search the list */
587 if (strcmp (Name, L->Name) == 0) {
598 void MergeCodeLabels (CodeSeg* S)
599 /* Merge code labels. That means: For each instruction, remove all labels but
600 * one and adjust the code entries accordingly.
605 /* Walk over all code entries */
606 unsigned EntryCount = CollCount (&S->Entries);
607 for (I = 0; I < EntryCount; ++I) {
612 /* Get a pointer to the next entry */
613 CodeEntry* E = CollAt (&S->Entries, I);
615 /* If this entry has zero labels, continue with the next one */
616 unsigned LabelCount = CollCount (&E->Labels);
617 if (LabelCount == 0) {
621 /* We have at least one label. Use the first one as reference label. */
622 RefLab = CollAt (&E->Labels, 0);
624 /* Walk through the remaining labels and change references to these
625 * labels to a reference to the one and only label. Delete the labels
626 * that are no longer used. To increase performance, walk backwards
629 for (J = LabelCount-1; J >= 1; --J) {
633 /* Get the next label */
634 CodeLabel* L = CollAt (&E->Labels, J);
636 /* Walk through all instructions referencing this label */
637 unsigned RefCount = CollCount (&L->JumpFrom);
638 for (K = 0; K < RefCount; ++K) {
640 /* Get the next instruction that references this label */
641 CodeEntry* E = CollAt (&L->JumpFrom, K);
643 /* Change the reference */
644 CHECK (E->JumpTo == L);
645 AddLabelRef (RefLab, E);
649 /* There are no more instructions jumping to this label now */
650 CollDeleteAll (&L->JumpFrom);
652 /* Remove the label completely. */
656 /* The reference label is the only remaining label. Check if there
657 * are any references to this label, and delete it if this is not
660 if (CollCount (&RefLab->JumpFrom) == 0) {
661 /* Delete the label */
662 DelCodeLabel (S, RefLab);
669 unsigned GetCodeSegEntries (const CodeSeg* S)
670 /* Return the number of entries for the given code segment */
672 return CollCount (&S->Entries);