]> git.sur5r.net Git - cc65/blob - src/cc65/codeseg.c
Working on the new backend
[cc65] / src / cc65 / codeseg.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 codeseg.c                                 */
4 /*                                                                           */
5 /*                          Code segment structure                           */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001      Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <string.h>
37 #include <ctype.h>
38
39 /* common */
40 #include "chartype.h"
41 #include "check.h"
42 #include "hashstr.h"
43 #include "strutil.h"
44 #include "xmalloc.h"
45 #include "xsprintf.h"
46
47 /* cc65 */
48 #include "codeent.h"
49 #include "codeinfo.h"
50 #include "error.h"
51 #include "codeseg.h"
52
53
54
55 /*****************************************************************************/
56 /*                    Functions for parsing instructions                     */
57 /*****************************************************************************/
58
59
60
61 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
62 /* Create a new label and insert it into the label hash table */
63 {
64     /* Not found - create a new one */
65     CodeLabel* L = NewCodeLabel (Name, Hash);
66
67     /* Enter the label into the hash table */
68     L->Next = S->LabelHash[L->Hash];
69     S->LabelHash[L->Hash] = L;
70
71     /* Return the new label */
72     return L;
73 }
74
75
76
77 static const char* SkipSpace (const char* S)
78 /* Skip white space and return an updated pointer */
79 {
80     while (IsSpace (*S)) {
81         ++S;
82     }
83     return S;
84 }
85
86
87
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.
92  */
93 {
94     /* Read/copy the token */
95     unsigned I = 0;
96     unsigned ParenCount = 0;
97     while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
98         if (I < BufSize-1) {
99             Buf[I++] = *L;
100         }
101         if (*L == ')') {
102             --ParenCount;
103         } else if (*L == '(') {
104             ++ParenCount;
105         }
106         ++L;
107     }
108
109     /* Terminate the buffer contents */
110     Buf[I] = '\0';
111
112     /* Return the updated line pointer */
113     return L;
114 }
115
116
117
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.
124  */
125 {
126     char                Mnemo[16];
127     const OPCDesc*      OPC;
128     am_t                AM = 0;         /* Initialize to keep gcc silent */
129     char                Arg[64];
130     char                Reg;
131     CodeEntry*          E;
132     CodeLabel*          Label;
133
134     /* Mnemonic */
135     L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
136
137     /* Try to find the opcode description for the mnemonic */
138     OPC = FindOpcode (Mnemo);
139
140     /* If we didn't find the opcode, print an error and bail out */
141     if (OPC == 0) {
142         Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
143         return 0;
144     }
145
146     /* Skip separator white space */
147     L = SkipSpace (L);
148
149     /* Get the addressing mode */
150     Arg[0] = '\0';
151     switch (*L) {
152
153         case '\0':
154             /* Implicit */
155             AM = AM_IMP;
156             break;
157
158         case '#':
159             /* Immidiate */
160             StrCopy (Arg, sizeof (Arg), L+1);
161             AM = AM_IMM;
162             break;
163
164         case '(':
165             /* Indirect */
166             L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
167
168             /* Check for errors */
169             if (*L == '\0') {
170                 Error ("ASM code error: syntax error");
171                 return 0;
172             }
173
174             /* Check the different indirect modes */
175             if (*L == ',') {
176                 /* Expect zp x indirect */
177                 L = SkipSpace (L+1);
178                 if (toupper (*L) != 'X') {
179                     Error ("ASM code error: `X' expected");
180                     return 0;
181                 }
182                 L = SkipSpace (L+1);
183                 if (*L != ')') {
184                     Error ("ASM code error: `)' expected");
185                     return 0;
186                 }
187                 L = SkipSpace (L+1);
188                 if (*L != '\0') {
189                     Error ("ASM code error: syntax error");
190                     return 0;
191                 }
192                 AM = AM_ZPX_IND;
193             } else if (*L == ')') {
194                 /* zp indirect or zp indirect, y */
195                 L = SkipSpace (L+1);
196                 if (*L == ',') {
197                     L = SkipSpace (L+1);
198                     if (toupper (*L) != 'Y') {
199                         Error ("ASM code error: `Y' expected");
200                         return 0;
201                     }
202                     L = SkipSpace (L+1);
203                     if (*L != '\0') {
204                         Error ("ASM code error: syntax error");
205                         return 0;
206                     }
207                     AM = AM_ZP_INDY;
208                 } else if (*L == '\0') {
209                     AM = AM_ZP_IND;
210                 } else {
211                     Error ("ASM code error: syntax error");
212                     return 0;
213                 }
214             }
215             break;
216
217         case 'a':
218         case 'A':
219             /* Accumulator? */
220             if (L[1] == '\0') {
221                 AM = AM_ACC;
222                 break;
223             }
224             /* FALLTHROUGH */
225
226         default:
227             /* Absolute, maybe indexed */
228             L = ReadToken (L, ",", Arg, sizeof (Arg));
229             if (*L == '\0') {
230                 /* Assume absolute */
231                 AM = AM_ABS;
232             } else if (*L == ',') {
233                 /* Indexed */
234                 L = SkipSpace (L+1);
235                 if (*L == '\0') {
236                     Error ("ASM code error: syntax error");
237                     return 0;
238                 } else {
239                     Reg = toupper (*L);
240                     L = SkipSpace (L+1);
241                     if (Reg == 'X') {
242                         AM = AM_ABSX;
243                     } else if (Reg == 'Y') {
244                         AM = AM_ABSY;
245                     } else {
246                         Error ("ASM code error: syntax error");
247                         return 0;
248                     }
249                     if (*L != '\0') {
250                         Error ("ASM code error: syntax error");
251                         return 0;
252                     }
253                 }
254             }
255             break;
256
257     }
258
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.
261      */
262     Label = 0;
263     if ((OPC->Info & OF_BRA) != 0 && Arg[0] == 'L') {
264
265         unsigned Hash;
266
267         /* Addressing mode must be alsobute or something is really wrong */
268         CHECK (AM == AM_ABS);
269
270         /* Addressing mode is a branch/jump */
271         AM = AM_BRA;
272
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);
276
277         /* If we don't have the label, it's a forward ref - create it */
278         if (Label == 0) {
279             /* Generate a new label */
280             Label = NewCodeSegLabel (S, Arg, Hash);
281         }
282     }
283
284     /* We do now have the addressing mode in AM. Allocate a new CodeEntry
285      * structure and initialize it.
286      */
287     E = NewCodeEntry (OPC, AM, Arg, Label);
288
289     /* Return the new code entry */
290     return E;
291 }
292
293
294
295 /*****************************************************************************/
296 /*                                   Code                                    */
297 /*****************************************************************************/
298
299
300
301 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
302 /* Create a new code segment, initialize and return it */
303 {
304     unsigned I;
305
306     /* Allocate memory */
307     CodeSeg* S = xmalloc (sizeof (CodeSeg));
308
309     /* Initialize the fields */
310     S->SegName  = xstrdup (SegName);
311     S->Func     = Func;
312     InitCollection (&S->Entries);
313     InitCollection (&S->Labels);
314     for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
315         S->LabelHash[I] = 0;
316     }
317
318     /* Return the new struct */
319     return S;
320 }
321
322
323
324 void AddCodeEntry (CodeSeg* S, const char* Format, va_list ap)
325 /* Add a line to the given code segment */
326 {
327     const char* L;
328     CodeEntry*  E;
329     char        Token[64];
330
331     /* Format the line */
332     char Buf [256];
333     xvsprintf (Buf, sizeof (Buf), Format, ap);
334
335     /* Skip whitespace */
336     L = SkipSpace (Buf);
337
338     /* Check which type of instruction we have */
339     E = 0;      /* Assume no insn created */
340     switch (*L) {
341
342         case '\0':
343             /* Empty line, just ignore it */
344             break;
345
346         case ';':
347             /* Comment or hint, ignore it for now */
348             break;
349
350         case '.':
351             /* Control instruction */
352             ReadToken (L, " \t", Token, sizeof (Token));
353             Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
354             break;
355
356         default:
357             E = ParseInsn (S, L);
358             break;
359     }
360
361     /* If we have a code entry, transfer the labels and insert it */
362     if (E) {
363
364         /* Transfer the labels if we have any */
365         unsigned I;
366         unsigned LabelCount = CollCount (&S->Labels);
367         for (I = 0; I < LabelCount; ++I) {
368             /* Get the label */
369             CodeLabel* L = CollAt (&S->Labels, I);
370             /* Mark it as defined */
371             L->Flags |= LF_DEF;
372             /* Move it to the code entry */
373             CollAppend (&E->Labels, L);
374             /* Tell the label about it's owner */
375             L->Owner = E;
376         }
377
378         /* Delete the transfered labels */
379         CollDeleteAll (&S->Labels);
380
381         /* Add the entry to the list of code entries in this segment */
382         CollAppend (&S->Entries, E);
383
384     }
385 }
386
387
388
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.
393  */
394 {
395     /* Get the code entry for the given index */
396     CodeEntry* E = CollAt (&S->Entries, Index);
397
398     /* Remove any labels associated with this entry */
399     unsigned Count;
400     while ((Count = CollCount (&E->Labels)) > 0) {
401         DelCodeLabel (S, CollAt (&E->Labels, Count-1));
402     }
403
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.
406      */
407     if (E->JumpTo) {
408
409         /* Remove the reference */
410         if (RemoveLabelRef (E->JumpTo, E) == 0) {
411             /* No references remaining, remove the label */
412             DelCodeLabel (S, E->JumpTo);
413         }
414
415         /* Reset the label pointer to avoid problems later */
416         E->JumpTo = 0;
417     }
418
419     /* Delete the pointer to the insn */
420     CollDelete (&S->Entries, Index);
421
422     /* Delete the instruction itself */
423     FreeCodeEntry (E);
424 }
425
426
427
428 void AddCodeLabel (CodeSeg* S, const char* Name)
429 /* Add a code label for the next instruction to follow */
430 {
431     /* Calculate the hash from the name */
432     unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
433
434     /* Try to find the code label if it does already exist */
435     CodeLabel* L = FindCodeLabel (S, Name, Hash);
436
437     /* Did we find it? */
438     if (L) {
439         /* We found it - be sure it does not already have an owner */
440         CHECK (L->Owner == 0);
441     } else {
442         /* Not found - create a new one */
443         L = NewCodeSegLabel (S, Name, Hash);
444     }
445
446     /* We do now have a valid label. Remember it for later */
447     CollAppend (&S->Labels, L);
448 }
449
450
451
452 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
453 /* Remove references from this label and delete it. */
454 {
455     unsigned Count, I;
456
457     /* Get the first entry in the hash chain */
458     CodeLabel* List = S->LabelHash[L->Hash];
459
460     /* First, remove the label from the hash chain */
461     if (List == L) {
462         /* First entry in hash chain */
463         S->LabelHash[L->Hash] = L->Next;
464     } else {
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);
469             /* Next entry */
470             List = List->Next;
471         }
472         /* The next entry is the one, we have been searching for */
473         List->Next = L->Next;
474     }
475
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 */
482         E->JumpTo = 0;
483     }
484     CollDeleteAll (&L->JumpFrom);
485
486     /* Remove the reference to the owning instruction */
487     CollDeleteItem (&L->Owner->Labels, L);
488
489     /* All references removed, delete the label itself */
490     FreeCodeLabel (L);
491 }
492
493
494
495 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
496 /* Add a hint for the preceeding instruction */
497 {
498     CodeEntry* E;
499
500     /* Get the number of entries in this segment */
501     unsigned EntryCount = CollCount (&S->Entries);
502
503     /* Must have at least one entry */
504     CHECK (EntryCount > 0);
505
506     /* Get the last entry */
507     E = CollAt (&S->Entries, EntryCount-1);
508
509     /* Add the hint */
510     E->Hints |= Hint;
511 }
512
513
514
515 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
516 /* Delete all entries including the given one */
517 {
518     /* Get the number of entries in this segment */
519     unsigned Count = CollCount (&S->Entries);
520
521     /* Remove all entries after the given one */
522     while (Last < Count) {
523
524         /* Get the next entry */
525         CodeEntry* E = CollAt (&S->Entries, Count-1);
526
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);
531             L->Flags &= ~LF_DEF;
532             CollAppend (&S->Labels, L);
533         }
534         CollDeleteAll (&E->Labels);
535
536         /* Remove the code entry */
537         FreeCodeEntry (CollAt (&S->Entries, Count-1));
538         CollDelete (&S->Entries, Count-1);
539         --Count;
540     }
541 }
542
543
544
545 void OutputCodeSeg (const CodeSeg* S, FILE* F)
546 /* Output the code segment data to a file */
547 {
548     unsigned I;
549
550     /* Get the number of entries in this segment */
551     unsigned Count = CollCount (&S->Entries);
552
553     /* If the code segment is empty, bail out here */
554     if (Count == 0) {
555         return;
556     }
557
558     /* Output the segment directive */
559     fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
560
561     /* If this is a segment for a function, enter a function */
562     if (S->Func) {
563         fprintf (F, ".proc\t_%s\n\n", S->Func->Name);
564     }
565
566     /* Output all entries */
567     for (I = 0; I < Count; ++I) {
568         OutputCodeEntry (CollConstAt (&S->Entries, I), F);
569     }
570
571     /* If this is a segment for a function, leave the function */
572     if (S->Func) {
573         fprintf (F, "\n.endproc\n\n");
574     }
575 }
576
577
578
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 */
581 {
582     /* Get the first hash chain entry */
583     CodeLabel* L = S->LabelHash[Hash];
584
585     /* Search the list */
586     while (L) {
587         if (strcmp (Name, L->Name) == 0) {
588             /* Found */
589             break;
590         }
591         L = L->Next;
592     }
593     return L;
594 }
595
596
597
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.
601  */
602 {
603     unsigned I;
604
605     /* Walk over all code entries */
606     unsigned EntryCount = CollCount (&S->Entries);
607     for (I = 0; I < EntryCount; ++I) {
608
609         CodeLabel* RefLab;
610         unsigned   J;
611
612         /* Get a pointer to the next entry */
613         CodeEntry* E = CollAt (&S->Entries, I);
614
615         /* If this entry has zero labels, continue with the next one */
616         unsigned LabelCount = CollCount (&E->Labels);
617         if (LabelCount == 0) {
618             continue;
619         }
620
621         /* We have at least one label. Use the first one as reference label. */
622         RefLab = CollAt (&E->Labels, 0);
623
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
627          * through the list.
628          */
629         for (J = LabelCount-1; J >= 1; --J) {
630
631             unsigned K;
632
633             /* Get the next label */
634             CodeLabel* L = CollAt (&E->Labels, J);
635
636             /* Walk through all instructions referencing this label */
637             unsigned RefCount = CollCount (&L->JumpFrom);
638             for (K = 0; K < RefCount; ++K) {
639
640                 /* Get the next instruction that references this label */
641                 CodeEntry* E = CollAt (&L->JumpFrom, K);
642
643                 /* Change the reference */
644                 CHECK (E->JumpTo == L);
645                 AddLabelRef (RefLab, E);
646
647             }
648
649             /* There are no more instructions jumping to this label now */
650             CollDeleteAll (&L->JumpFrom);
651
652             /* Remove the label completely. */
653             DelCodeLabel (S, L);
654         }
655
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
658          * the case.
659          */
660         if (CollCount (&RefLab->JumpFrom) == 0) {
661             /* Delete the label */
662             DelCodeLabel (S, RefLab);
663         }
664     }
665 }
666
667
668
669 unsigned GetCodeSegEntries (const CodeSeg* S)
670 /* Return the number of entries for the given code segment */
671 {
672     return CollCount (&S->Entries);
673 }
674
675
676
677