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