]> git.sur5r.net Git - cc65/blob - src/cc65/codeopt.c
The CodeEntry buffer array was one entry to small.
[cc65] / src / cc65 / codeopt.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 codeopt.c                                 */
4 /*                                                                           */
5 /*                           Optimizer subroutines                           */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001-2009 Ullrich von Bassewitz                                       */
10 /*               Roemerstrasse 52                                            */
11 /*               D-70794 Filderstadt                                         */
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 <stdlib.h>
37 #include <string.h>
38
39 /* common */
40 #include "abend.h"
41 #include "chartype.h"
42 #include "cpu.h"
43 #include "print.h"
44 #include "xmalloc.h"
45 #include "xsprintf.h"
46
47 /* cc65 */
48 #include "asmlabel.h"
49 #include "codeent.h"
50 #include "codeinfo.h"
51 #include "coptadd.h"
52 #include "coptc02.h"
53 #include "coptcmp.h"
54 #include "coptind.h"
55 #include "coptneg.h"
56 #include "coptptrload.h"
57 #include "coptpush.h"
58 #include "coptsize.h"
59 #include "coptstop.h"
60 #include "coptstore.h"
61 #include "coptsub.h"
62 #include "copttest.h"
63 #include "error.h"
64 #include "global.h"
65 #include "codeopt.h"
66
67
68
69 /*****************************************************************************/
70 /*                                     Data                                  */
71 /*****************************************************************************/
72
73
74
75 /* Shift types */
76 enum {
77     SHIFT_NONE,
78     SHIFT_ASR_1,
79     SHIFT_ASL_1,
80     SHIFT_LSR_1,
81     SHIFT_LSL_1
82 };
83
84
85
86 /*****************************************************************************/
87 /*                              Optimize shifts                              */
88 /*****************************************************************************/
89
90
91
92 static unsigned OptShift1 (CodeSeg* S)
93 /* A call to the shlaxN routine may get replaced by one or more asl insns
94  * if the value of X is not used later. If X is used later, but it is zero
95  * on entry and it's a shift by one, it may get replaced by:
96  *
97  *      asl     a
98  *      bcc     L1
99  *      inx
100  *  L1:
101  *
102  */
103 {
104     unsigned Changes = 0;
105     unsigned I;
106
107     /* Generate register info */
108     CS_GenRegInfo (S);
109
110     /* Walk over the entries */
111     I = 0;
112     while (I < CS_GetEntryCount (S)) {
113
114         CodeEntry* N;
115         CodeEntry* X;
116         CodeLabel* L;
117
118         /* Get next entry */
119         CodeEntry* E = CS_GetEntry (S, I);
120
121         /* Check for the sequence */
122         if (E->OPC == OP65_JSR                       &&
123             (strncmp (E->Arg, "shlax", 5) == 0 ||
124              strncmp (E->Arg, "aslax", 5) == 0)      &&
125             strlen (E->Arg) == 6                     &&
126             IsDigit (E->Arg[5])) {
127
128             if (!RegXUsed (S, I+1)) {
129
130                 /* Insert shift insns */
131                 unsigned Count = E->Arg[5] - '0';
132                 while (Count--) {
133                     X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI);
134                     CS_InsertEntry (S, X, I+1);
135                 }
136
137                 /* Delete the call to shlax */
138                 CS_DelEntry (S, I);
139
140                 /* Remember, we had changes */
141                 ++Changes;
142
143             } else if (E->RI->In.RegX == 0              &&
144                        E->Arg[5] == '1'                 &&
145                        (N = CS_GetNextEntry (S, I)) != 0) {
146
147                 /* asl a */
148                 X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI);
149                 CS_InsertEntry (S, X, I+1);
150
151                 /* bcc L1 */
152                 L = CS_GenLabel (S, N);
153                 X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, E->LI);
154                 CS_InsertEntry (S, X, I+2);
155
156                 /* inx */
157                 X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, E->LI);
158                 CS_InsertEntry (S, X, I+3);
159
160                 /* Delete the call to shlax */
161                 CS_DelEntry (S, I);
162
163                 /* Remember, we had changes */
164                 ++Changes;
165             }
166
167         }
168
169         /* Next entry */
170         ++I;
171
172     }
173
174     /* Free the register info */
175     CS_FreeRegInfo (S);
176
177     /* Return the number of changes made */
178     return Changes;
179 }
180
181
182
183 static unsigned OptShift2 (CodeSeg* S)
184 /* A call to the shraxN routine may get replaced by one or more lsr insns
185  * if the value of X is zero.
186  */
187 {
188     unsigned Changes = 0;
189     unsigned I;
190
191     /* Generate register info */
192     CS_GenRegInfo (S);
193
194     /* Walk over the entries */
195     I = 0;
196     while (I < CS_GetEntryCount (S)) {
197
198         /* Get next entry */
199         CodeEntry* E = CS_GetEntry (S, I);
200
201         /* Check for the sequence */
202         if (E->OPC == OP65_JSR                       &&
203             strncmp (E->Arg, "shrax", 5) == 0        &&
204             strlen (E->Arg) == 6                     &&
205             IsDigit (E->Arg[5])                      &&
206             E->RI->In.RegX == 0) {
207
208             /* Insert shift insns */
209             unsigned Count = E->Arg[5] - '0';
210             while (Count--) {
211                 CodeEntry* X = NewCodeEntry (OP65_LSR, AM65_ACC, "a", 0, E->LI);
212                 CS_InsertEntry (S, X, I+1);
213             }
214
215             /* Delete the call to shrax */
216             CS_DelEntry (S, I);
217
218             /* Remember, we had changes */
219             ++Changes;
220
221         }
222
223         /* Next entry */
224         ++I;
225
226     }
227
228     /* Free the register info */
229     CS_FreeRegInfo (S);
230
231     /* Return the number of changes made */
232     return Changes;
233 }
234
235
236
237 static unsigned GetShiftType (const char* Sub)
238 /* Helper function for OptShift3 */
239 {
240     if (*Sub == 'a') {
241         if (strcmp (Sub+1, "slax1") == 0) {
242             return SHIFT_ASL_1;
243         } else if (strcmp (Sub+1, "srax1") == 0) {
244             return SHIFT_ASR_1;
245         }
246     } else if (*Sub == 's') {
247         if (strcmp (Sub+1, "hlax1") == 0) {
248             return SHIFT_LSL_1;
249         } else if (strcmp (Sub+1, "hrax1") == 0) {
250             return SHIFT_LSR_1;
251         }
252     }
253     return SHIFT_NONE;
254 }
255
256
257
258 static unsigned OptShift3 (CodeSeg* S)
259 /* Search for the sequence
260  *
261  *      lda     xxx
262  *      ldx     yyy
263  *      jsr     aslax1/asrax1/shlax1/shrax1
264  *      sta     aaa
265  *      stx     bbb
266  *
267  * and replace it by
268  *
269  *      lda     xxx
270  *      asl     a
271  *      sta     aaa
272  *      lda     yyy
273  *      rol     a
274  *      sta     bbb
275  *
276  * or similar, provided that a/x is not used later
277  */
278 {
279     unsigned Changes = 0;
280
281     /* Walk over the entries */
282     unsigned I = 0;
283     while (I < CS_GetEntryCount (S)) {
284
285         unsigned ShiftType;
286         CodeEntry* L[5];
287
288         /* Get next entry */
289         L[0] = CS_GetEntry (S, I);
290
291         /* Check for the sequence */
292         if (L[0]->OPC == OP65_LDA                               &&
293             (L[0]->AM == AM65_ABS || L[0]->AM == AM65_ZP)       &&
294             CS_GetEntries (S, L+1, I+1, 4)                      &&
295             !CS_RangeHasLabel (S, I+1, 4)                       &&
296             L[1]->OPC == OP65_LDX                               &&
297             (L[1]->AM == AM65_ABS || L[1]->AM == AM65_ZP)       &&
298             L[2]->OPC == OP65_JSR                               &&
299             (ShiftType = GetShiftType (L[2]->Arg)) != SHIFT_NONE&&
300             L[3]->OPC == OP65_STA                               &&
301             (L[3]->AM == AM65_ABS || L[3]->AM == AM65_ZP)       &&
302             L[4]->OPC == OP65_STX                               &&
303             (L[4]->AM == AM65_ABS || L[4]->AM == AM65_ZP)       &&
304             !RegAXUsed (S, I+5)) {
305
306             CodeEntry* X;
307
308             /* Handle the four shift types differently */
309             switch (ShiftType) {
310
311                 case SHIFT_ASR_1:
312                     X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI);
313                     CS_InsertEntry (S, X, I+5);
314                     X = NewCodeEntry (OP65_CMP, AM65_IMM, "$80", 0, L[2]->LI);
315                     CS_InsertEntry (S, X, I+6);
316                     X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI);
317                     CS_InsertEntry (S, X, I+7);
318                     X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI);
319                     CS_InsertEntry (S, X, I+8);
320                     X = NewCodeEntry (OP65_LDA, L[0]->AM, L[0]->Arg, 0, L[0]->LI);
321                     CS_InsertEntry (S, X, I+9);
322                     X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI);
323                     CS_InsertEntry (S, X, I+10);
324                     X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI);
325                     CS_InsertEntry (S, X, I+11);
326                     CS_DelEntries (S, I, 5);
327                     break;
328
329                 case SHIFT_LSR_1:
330                     X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI);
331                     CS_InsertEntry (S, X, I+5);
332                     X = NewCodeEntry (OP65_LSR, AM65_ACC, "a", 0, L[2]->LI);
333                     CS_InsertEntry (S, X, I+6);
334                     X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI);
335                     CS_InsertEntry (S, X, I+7);
336                     X = NewCodeEntry (OP65_LDA, L[0]->AM, L[0]->Arg, 0, L[0]->LI);
337                     CS_InsertEntry (S, X, I+8);
338                     X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI);
339                     CS_InsertEntry (S, X, I+9);
340                     X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI);
341                     CS_InsertEntry (S, X, I+10);
342                     CS_DelEntries (S, I, 5);
343                     break;
344
345                 case SHIFT_LSL_1:
346                 case SHIFT_ASL_1:
347                     /* These two are identical */
348                     X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, L[2]->LI);
349                     CS_InsertEntry (S, X, I+1);
350                     X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI);
351                     CS_InsertEntry (S, X, I+2);
352                     X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI);
353                     CS_InsertEntry (S, X, I+3);
354                     X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, L[2]->LI);
355                     CS_InsertEntry (S, X, I+4);
356                     X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI);
357                     CS_InsertEntry (S, X, I+5);
358                     CS_DelEntries (S, I+6, 4);
359                     break;
360
361             }
362
363             /* Remember, we had changes */
364             ++Changes;
365
366         }
367
368         /* Next entry */
369         ++I;
370
371     }
372
373     /* Return the number of changes made */
374     return Changes;
375 }
376
377
378
379 static unsigned OptShift4 (CodeSeg* S)
380 /* Inline the shift subroutines. */
381 {
382     unsigned Changes = 0;
383
384     /* Walk over the entries */
385     unsigned I = 0;
386     while (I < CS_GetEntryCount (S)) {
387
388         CodeEntry* X;
389         unsigned   IP;
390
391         /* Get next entry */
392         CodeEntry* E = CS_GetEntry (S, I);
393
394         /* Check for a call to one of the shift routine */
395         if (E->OPC == OP65_JSR                          &&
396             (strncmp (E->Arg, "shlax", 5) == 0  ||
397              strncmp (E->Arg, "aslax", 5) == 0)         &&
398             strlen (E->Arg) == 6                        &&
399             IsDigit (E->Arg[5])) {
400
401             /* Get number of shifts */
402             unsigned ShiftCount = (E->Arg[5] - '0');
403
404             /* Code is:
405              *
406              *      stx     tmp1
407              *      asl     a
408              *      rol     tmp1
409              *      (repeat ShiftCount-1 times)
410              *      ldx     tmp1
411              *
412              * which makes 4 + 3 * ShiftCount bytes, compared to the original
413              * 3 bytes for the subroutine call. However, in most cases, the
414              * final load of the X register gets merged with some other insn
415              * and replaces a txa, so for a shift count of 1, we get a factor
416              * of 200, which matches nicely the CodeSizeFactor enabled with -Oi
417              */
418             if (ShiftCount > 1 || S->CodeSizeFactor > 200) {
419                 unsigned Size = 4 + 3 * ShiftCount;
420                 if ((Size * 100 / 3) > S->CodeSizeFactor) {
421                     /* Not acceptable */
422                     goto NextEntry;
423                 }
424             }
425
426             /* Inline the code. Insertion point is behind the subroutine call */
427             IP = (I + 1);
428
429             /* stx tmp1 */
430             X = NewCodeEntry (OP65_STX, AM65_ZP, "tmp1", 0, E->LI);
431             CS_InsertEntry (S, X, IP++);
432
433             while (ShiftCount--) {
434                 /* asl a */
435                 X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI);
436                 CS_InsertEntry (S, X, IP++);
437
438                 /* rol tmp1 */
439                 X = NewCodeEntry (OP65_ROL, AM65_ZP, "tmp1", 0, E->LI);
440                 CS_InsertEntry (S, X, IP++);
441             }
442
443             /* ldx tmp1 */
444             X = NewCodeEntry (OP65_LDX, AM65_ZP, "tmp1", 0, E->LI);
445             CS_InsertEntry (S, X, IP++);
446
447             /* Remove the subroutine call */
448             CS_DelEntry (S, I);
449
450             /* Remember, we had changes */
451             ++Changes;
452         }
453
454 NextEntry:
455         /* Next entry */
456         ++I;
457
458     }
459
460     /* Return the number of changes made */
461     return Changes;
462 }
463
464
465
466 /*****************************************************************************/
467 /*                              Optimize loads                               */
468 /*****************************************************************************/
469
470
471
472 static unsigned OptLoad1 (CodeSeg* S)
473 /* Search for a call to ldaxysp where X is not used later and replace it by
474  * a load of just the A register.
475  */
476 {
477     unsigned I;
478     unsigned Changes = 0;
479
480     /* Generate register info */
481     CS_GenRegInfo (S);
482
483     /* Walk over the entries */
484     I = 0;
485     while (I < CS_GetEntryCount (S)) {
486
487         CodeEntry* E;
488
489         /* Get next entry */
490         E = CS_GetEntry (S, I);
491
492         /* Check for the sequence */
493         if (CE_IsCallTo (E, "ldaxysp")          &&
494             RegValIsKnown (E->RI->In.RegY)      &&
495             !RegXUsed (S, I+1)) {
496
497             CodeEntry* X;
498
499             /* Reload the Y register */
500             const char* Arg = MakeHexArg (E->RI->In.RegY - 1);
501             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
502             CS_InsertEntry (S, X, I+1);
503
504             /* Load from stack */
505             X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, E->LI);
506             CS_InsertEntry (S, X, I+2);
507
508             /* Now remove the call to the subroutine */
509             CS_DelEntry (S, I);
510
511             /* Remember, we had changes */
512             ++Changes;
513
514         }
515
516         /* Next entry */
517         ++I;
518
519     }
520
521     /* Free the register info */
522     CS_FreeRegInfo (S);
523
524     /* Return the number of changes made */
525     return Changes;
526 }
527
528
529
530 /*****************************************************************************/
531 /*                     Optimize stores through pointers                      */
532 /*****************************************************************************/
533
534
535
536 static unsigned OptPtrStore1Sub (CodeSeg* S, unsigned I, CodeEntry** const L)
537 /* Check if this is one of the allowed suboperation for OptPtrStore1 */
538 {
539     /* Check for a label attached to the entry */
540     if (CE_HasLabel (L[0])) {
541         return 0;
542     }
543
544     /* Check for single insn sub ops */
545     if (L[0]->OPC == OP65_AND                                           ||
546         L[0]->OPC == OP65_EOR                                           ||
547         L[0]->OPC == OP65_ORA                                           ||
548         (L[0]->OPC == OP65_JSR && strncmp (L[0]->Arg, "shlax", 5) == 0) ||
549         (L[0]->OPC == OP65_JSR && strncmp (L[0]->Arg, "shrax", 5) == 0)) {
550
551         /* One insn */
552         return 1;
553
554     } else if (L[0]->OPC == OP65_CLC                      &&
555                (L[1] = CS_GetNextEntry (S, I)) != 0       &&
556                L[1]->OPC == OP65_ADC                      &&
557                !CE_HasLabel (L[1])) {
558         return 2;
559     } else if (L[0]->OPC == OP65_SEC                      &&
560                (L[1] = CS_GetNextEntry (S, I)) != 0       &&
561                L[1]->OPC == OP65_SBC                      &&
562                !CE_HasLabel (L[1])) {
563         return 2;
564     }
565
566
567
568     /* Not found */
569     return 0;
570 }
571
572
573
574 static unsigned OptPtrStore1 (CodeSeg* S)
575 /* Search for the sequence:
576  *
577  *      jsr     pushax
578  *      ldy     xxx
579  *      jsr     ldauidx
580  *      subop
581  *      ldy     yyy
582  *      jsr     staspidx
583  *
584  * and replace it by:
585  *
586  *      sta     ptr1
587  *      stx     ptr1+1
588  *      ldy     xxx
589  *      ldx     #$00
590  *      lda     (ptr1),y
591  *      subop
592  *      ldy     yyy
593  *      sta     (ptr1),y
594  *
595  * In case a/x is loaded from the register bank before the pushax, we can even
596  * use the register bank instead of ptr1.
597  */
598 /*
599  *      jsr     pushax
600  *      ldy     xxx
601  *      jsr     ldauidx
602  *      ldx     #$00
603  *      lda     (zp),y
604  *      subop
605  *      ldy     yyy
606  *      sta     (zp),y
607  *      jsr     staspidx
608  */
609 {
610     unsigned Changes = 0;
611
612     /* Walk over the entries */
613     unsigned I = 0;
614     while (I < CS_GetEntryCount (S)) {
615
616         unsigned K;
617         CodeEntry* L[10];
618
619         /* Get next entry */
620         L[0] = CS_GetEntry (S, I);
621
622         /* Check for the sequence */
623         if (CE_IsCallTo (L[0], "pushax")            &&
624             CS_GetEntries (S, L+1, I+1, 3)          &&
625             L[1]->OPC == OP65_LDY                   &&
626             CE_IsConstImm (L[1])                    &&
627             !CE_HasLabel (L[1])                     &&
628             CE_IsCallTo (L[2], "ldauidx")           &&
629             !CE_HasLabel (L[2])                     &&
630             (K = OptPtrStore1Sub (S, I+3, L+3)) > 0 &&
631             CS_GetEntries (S, L+3+K, I+3+K, 2)      &&
632             L[3+K]->OPC == OP65_LDY                 &&
633             CE_IsConstImm (L[3+K])                  &&
634             !CE_HasLabel (L[3+K])                   &&
635             CE_IsCallTo (L[4+K], "staspidx")        &&
636             !CE_HasLabel (L[4+K])) {
637
638
639             const char* RegBank = 0;
640             const char* ZPLoc   = "ptr1";
641             CodeEntry* X;
642
643
644             /* Get the preceeding two instructions and check them. We check
645              * for:
646              *          lda     regbank+n
647              *          ldx     regbank+n+1
648              */
649             if (I > 1) {
650                 CodeEntry* P[2];
651                 P[0] = CS_GetEntry (S, I-2);
652                 P[1] = CS_GetEntry (S, I-1);
653                 if (P[0]->OPC == OP65_LDA &&
654                     P[0]->AM  == AM65_ZP  &&
655                     P[1]->OPC == OP65_LDX &&
656                     P[1]->AM  == AM65_ZP  &&
657                     !CE_HasLabel (P[1])   &&
658                     strncmp (P[0]->Arg, "regbank+", 8) == 0) {
659
660                     unsigned Len = strlen (P[0]->Arg);
661
662                     if (strncmp (P[0]->Arg, P[1]->Arg, Len) == 0 &&
663                         P[1]->Arg[Len+0] == '+'                  &&
664                         P[1]->Arg[Len+1] == '1'                  &&
665                         P[1]->Arg[Len+2] == '\0') {
666
667                         /* Ok, found. Use the name of the register bank */
668                         RegBank = ZPLoc = P[0]->Arg;
669                     }
670                 }
671             }
672
673             /* Insert the load via the zp pointer */
674             X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[3]->LI);
675             CS_InsertEntry (S, X, I+3);
676             X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, ZPLoc, 0, L[2]->LI);
677             CS_InsertEntry (S, X, I+4);
678
679             /* Insert the store through the zp pointer */
680             X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLoc, 0, L[3]->LI);
681             CS_InsertEntry (S, X, I+6+K);
682
683             /* Delete the old code */
684             CS_DelEntry (S, I+7+K);     /* jsr spaspidx */
685             CS_DelEntry (S, I+2);       /* jsr ldauidx */
686
687             /* Create and insert the stores into the zp pointer if needed */
688             if (RegBank == 0) {
689                 X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI);
690                 CS_InsertEntry (S, X, I+1);
691                 X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI);
692                 CS_InsertEntry (S, X, I+2);
693             }
694
695             /* Delete more old code. Do it here to keep a label attached to
696              * entry I in place.
697              */
698             CS_DelEntry (S, I);         /* jsr pushax */
699
700             /* Remember, we had changes */
701             ++Changes;
702
703         }
704
705         /* Next entry */
706         ++I;
707
708     }
709
710     /* Return the number of changes made */
711     return Changes;
712 }
713
714
715
716 static unsigned OptPtrStore2 (CodeSeg* S)
717 /* Search for the sequence:
718  *
719  *      lda     #<(label+0)
720  *      ldx     #>(label+0)
721  *      clc
722  *      adc     xxx
723  *      bcc     L
724  *      inx
725  * L:   jsr     pushax
726  *      ldx     #$00
727  *      lda     yyy
728  *      ldy     #$00
729  *      jsr     staspidx
730  *
731  * and replace it by:
732  *
733  *      ldy     xxx
734  *      ldx     #$00
735  *      lda     yyy
736  *      sta     label,y
737  */
738 {
739     unsigned Changes = 0;
740
741     /* Walk over the entries */
742     unsigned I = 0;
743     while (I < CS_GetEntryCount (S)) {
744
745         CodeEntry* L[11];
746         unsigned Len;
747
748         /* Get next entry */
749         L[0] = CS_GetEntry (S, I);
750
751         /* Check for the sequence */
752         if (L[0]->OPC == OP65_LDA                            &&
753             L[0]->AM == AM65_IMM                             &&
754             CS_GetEntries (S, L+1, I+1, 10)                  &&
755             L[1]->OPC == OP65_LDX                            &&
756             L[1]->AM == AM65_IMM                             &&
757             L[2]->OPC == OP65_CLC                            &&
758             L[3]->OPC == OP65_ADC                            &&
759             (L[3]->AM == AM65_ABS || L[3]->AM == AM65_ZP)    &&
760             (L[4]->OPC == OP65_BCC || L[4]->OPC == OP65_JCC) &&
761             L[4]->JumpTo != 0                                &&
762             L[4]->JumpTo->Owner == L[6]                      &&
763             L[5]->OPC == OP65_INX                            &&
764             CE_IsCallTo (L[6], "pushax")                     &&
765             L[7]->OPC == OP65_LDX                            &&
766             L[8]->OPC == OP65_LDA                            &&
767             L[9]->OPC == OP65_LDY                            &&
768             CE_IsKnownImm (L[9], 0)                          &&
769             CE_IsCallTo (L[10], "staspidx")                  &&
770             !CS_RangeHasLabel (S, I+1, 5)                    &&
771             !CS_RangeHasLabel (S, I+7, 4)                    &&
772             /* Check the label last because this is quite costly */
773             (Len = strlen (L[0]->Arg)) > 3                   &&
774             L[0]->Arg[0] == '<'                              &&
775             L[0]->Arg[1] == '('                              &&
776             strlen (L[1]->Arg) == Len                        &&
777             L[1]->Arg[0] == '>'                              &&
778             memcmp (L[0]->Arg+1, L[1]->Arg+1, Len-1) == 0) {
779
780             CodeEntry* X;
781             char* Label;
782
783             /* We will create all the new stuff behind the current one so
784              * we keep the line references.
785              */
786             X = NewCodeEntry (OP65_LDY, L[3]->AM, L[3]->Arg, 0, L[0]->LI);
787             CS_InsertEntry (S, X, I+11);
788
789             X = NewCodeEntry (OP65_LDX, L[7]->AM, L[7]->Arg, 0, L[7]->LI);
790             CS_InsertEntry (S, X, I+12);
791
792             X = NewCodeEntry (OP65_LDA, L[8]->AM, L[8]->Arg, 0, L[8]->LI);
793             CS_InsertEntry (S, X, I+13);
794
795             Label = memcpy (xmalloc (Len-2), L[0]->Arg+2, Len-3);
796             Label[Len-3] = '\0';
797             X = NewCodeEntry (OP65_STA, AM65_ABSY, Label, 0, L[10]->LI);
798             CS_InsertEntry (S, X, I+14);
799             xfree (Label);
800
801             /* Remove the old code */
802             CS_DelEntries (S, I, 11);
803
804             /* Remember, we had changes */
805             ++Changes;
806
807         }
808
809         /* Next entry */
810         ++I;
811
812     }
813
814     /* Return the number of changes made */
815     return Changes;
816 }
817
818
819
820 static unsigned OptPtrStore3 (CodeSeg* S)
821 /* Search for the sequence:
822  *
823  *      lda     #<(label+0)
824  *      ldx     #>(label+0)
825  *      ldy     aaa
826  *      clc
827  *      adc     (sp),y
828  *      bcc     L
829  *      inx
830  * L:   jsr     pushax
831  *      ldx     #$00
832  *      lda     yyy
833  *      ldy     #$00
834  *      jsr     staspidx
835  *
836  * and replace it by:
837  *
838  *      ldy     aaa
839  *      ldx     #$00
840  *      lda     (sp),y
841  *      tay
842  *      lda     yyy
843  *      sta     label,y
844  */
845 {
846     unsigned Changes = 0;
847
848     /* Walk over the entries */
849     unsigned I = 0;
850     while (I < CS_GetEntryCount (S)) {
851
852         CodeEntry* L[12];
853         unsigned Len;
854
855         /* Get next entry */
856         L[0] = CS_GetEntry (S, I);
857
858         /* Check for the sequence */
859         if (L[0]->OPC == OP65_LDA                            &&
860             L[0]->AM == AM65_IMM                             &&
861             CS_GetEntries (S, L+1, I+1, 11)                  &&
862             L[1]->OPC == OP65_LDX                            &&
863             L[1]->AM == AM65_IMM                             &&
864             L[2]->OPC == OP65_LDY                            &&
865             L[3]->OPC == OP65_CLC                            &&
866             L[4]->OPC == OP65_ADC                            &&
867             L[4]->AM == AM65_ZP_INDY                         &&
868             strcmp (L[4]->Arg, "sp") == 0                    &&
869             (L[5]->OPC == OP65_BCC || L[5]->OPC == OP65_JCC) &&
870             L[5]->JumpTo != 0                                &&
871             L[5]->JumpTo->Owner == L[7]                      &&
872             L[6]->OPC == OP65_INX                            &&
873             CE_IsCallTo (L[7], "pushax")                     &&
874             L[8]->OPC == OP65_LDX                            &&
875             L[9]->OPC == OP65_LDA                            &&
876             L[10]->OPC == OP65_LDY                           &&
877             CE_IsKnownImm (L[10], 0)                         &&
878             CE_IsCallTo (L[11], "staspidx")                  &&
879             !CS_RangeHasLabel (S, I+1, 6)                    &&
880             !CS_RangeHasLabel (S, I+8, 4)                    &&
881             /* Check the label last because this is quite costly */
882             (Len = strlen (L[0]->Arg)) > 3                   &&
883             L[0]->Arg[0] == '<'                              &&
884             L[0]->Arg[1] == '('                              &&
885             strlen (L[1]->Arg) == Len                        &&
886             L[1]->Arg[0] == '>'                              &&
887             memcmp (L[0]->Arg+1, L[1]->Arg+1, Len-1) == 0) {
888
889             CodeEntry* X;
890             char* Label;
891
892             /* We will create all the new stuff behind the current one so
893              * we keep the line references.
894              */
895             X = NewCodeEntry (OP65_LDY, L[2]->AM, L[2]->Arg, 0, L[2]->LI);
896             CS_InsertEntry (S, X, I+12);
897
898             X = NewCodeEntry (OP65_LDX, L[8]->AM, L[8]->Arg, 0, L[8]->LI);
899             CS_InsertEntry (S, X, I+13);
900
901             X = NewCodeEntry (OP65_LDA, L[4]->AM, L[4]->Arg, 0, L[4]->LI);
902             CS_InsertEntry (S, X, I+14);
903
904             X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, L[4]->LI);
905             CS_InsertEntry (S, X, I+15);
906
907             X = NewCodeEntry (OP65_LDA, L[8]->AM, L[8]->Arg, 0, L[8]->LI);
908             CS_InsertEntry (S, X, I+16);
909
910             Label = memcpy (xmalloc (Len-2), L[0]->Arg+2, Len-3);
911             Label[Len-3] = '\0';
912             X = NewCodeEntry (OP65_STA, AM65_ABSY, Label, 0, L[11]->LI);
913             CS_InsertEntry (S, X, I+17);
914             xfree (Label);
915
916             /* Remove the old code */
917             CS_DelEntries (S, I, 12);
918
919             /* Remember, we had changes */
920             ++Changes;
921
922         }
923
924         /* Next entry */
925         ++I;
926
927     }
928
929     /* Return the number of changes made */
930     return Changes;
931 }
932
933
934
935 /*****************************************************************************/
936 /*                            Decouple operations                            */
937 /*****************************************************************************/
938
939
940
941 static unsigned OptDecouple (CodeSeg* S)
942 /* Decouple operations, that is, do the following replacements:
943  *
944  *   dex        -> ldx #imm
945  *   inx        -> ldx #imm
946  *   dey        -> ldy #imm
947  *   iny        -> ldy #imm
948  *   tax        -> ldx #imm
949  *   txa        -> lda #imm
950  *   tay        -> ldy #imm
951  *   tya        -> lda #imm
952  *   lda zp     -> lda #imm
953  *   ldx zp     -> ldx #imm
954  *   ldy zp     -> ldy #imm
955  *
956  * Provided that the register values are known of course.
957  */
958 {
959     unsigned Changes = 0;
960     unsigned I;
961
962     /* Generate register info for the following step */
963     CS_GenRegInfo (S);
964
965     /* Walk over the entries */
966     I = 0;
967     while (I < CS_GetEntryCount (S)) {
968
969         const char* Arg;
970
971         /* Get next entry and it's input register values */
972         CodeEntry* E = CS_GetEntry (S, I);
973         const RegContents* In = &E->RI->In;
974
975         /* Assume we have no replacement */
976         CodeEntry* X = 0;
977
978         /* Check the instruction */
979         switch (E->OPC) {
980
981             case OP65_DEA:
982                 if (RegValIsKnown (In->RegA)) {
983                     Arg = MakeHexArg ((In->RegA - 1) & 0xFF);
984                     X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
985                 }
986                 break;
987
988             case OP65_DEX:
989                 if (RegValIsKnown (In->RegX)) {
990                     Arg = MakeHexArg ((In->RegX - 1) & 0xFF);
991                     X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
992                 }
993                 break;
994
995             case OP65_DEY:
996                 if (RegValIsKnown (In->RegY)) {
997                     Arg = MakeHexArg ((In->RegY - 1) & 0xFF);
998                     X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
999                 }
1000                 break;
1001
1002             case OP65_INA:
1003                 if (RegValIsKnown (In->RegA)) {
1004                     Arg = MakeHexArg ((In->RegA + 1) & 0xFF);
1005                     X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1006                 }
1007                 break;
1008
1009             case OP65_INX:
1010                 if (RegValIsKnown (In->RegX)) {
1011                     Arg = MakeHexArg ((In->RegX + 1) & 0xFF);
1012                     X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
1013                 }
1014                 break;
1015
1016             case OP65_INY:
1017                 if (RegValIsKnown (In->RegY)) {
1018                     Arg = MakeHexArg ((In->RegY + 1) & 0xFF);
1019                     X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
1020                 }
1021                 break;
1022
1023             case OP65_LDA:
1024                 if (E->AM == AM65_ZP) {
1025                     switch (GetKnownReg (E->Use & REG_ZP, In)) {
1026                         case REG_TMP1:
1027                             Arg = MakeHexArg (In->Tmp1);
1028                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1029                             break;
1030
1031                         case REG_PTR1_LO:
1032                             Arg = MakeHexArg (In->Ptr1Lo);
1033                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1034                             break;
1035
1036                         case REG_PTR1_HI:
1037                             Arg = MakeHexArg (In->Ptr1Hi);
1038                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1039                             break;
1040
1041                         case REG_SREG_LO:
1042                             Arg = MakeHexArg (In->SRegLo);
1043                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1044                             break;
1045
1046                         case REG_SREG_HI:
1047                             Arg = MakeHexArg (In->SRegHi);
1048                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1049                             break;
1050                     }
1051                 }
1052                 break;
1053
1054             case OP65_LDX:
1055                 if (E->AM == AM65_ZP) {
1056                     switch (GetKnownReg (E->Use & REG_ZP, In)) {
1057                         case REG_TMP1:
1058                             Arg = MakeHexArg (In->Tmp1);
1059                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
1060                             break;
1061
1062                         case REG_PTR1_LO:
1063                             Arg = MakeHexArg (In->Ptr1Lo);
1064                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
1065                             break;
1066
1067                         case REG_PTR1_HI:
1068                             Arg = MakeHexArg (In->Ptr1Hi);
1069                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
1070                             break;
1071
1072                         case REG_SREG_LO:
1073                             Arg = MakeHexArg (In->SRegLo);
1074                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
1075                             break;
1076
1077                         case REG_SREG_HI:
1078                             Arg = MakeHexArg (In->SRegHi);
1079                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
1080                             break;
1081                     }
1082                 }
1083                 break;
1084
1085             case OP65_LDY:
1086                 if (E->AM == AM65_ZP) {
1087                     switch (GetKnownReg (E->Use, In)) {
1088                         case REG_TMP1:
1089                             Arg = MakeHexArg (In->Tmp1);
1090                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
1091                             break;
1092
1093                         case REG_PTR1_LO:
1094                             Arg = MakeHexArg (In->Ptr1Lo);
1095                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
1096                             break;
1097
1098                         case REG_PTR1_HI:
1099                             Arg = MakeHexArg (In->Ptr1Hi);
1100                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
1101                             break;
1102
1103                         case REG_SREG_LO:
1104                             Arg = MakeHexArg (In->SRegLo);
1105                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
1106                             break;
1107
1108                         case REG_SREG_HI:
1109                             Arg = MakeHexArg (In->SRegHi);
1110                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
1111                             break;
1112                     }
1113                 }
1114                 break;
1115
1116             case OP65_TAX:
1117                 if (E->RI->In.RegA >= 0) {
1118                     Arg = MakeHexArg (In->RegA);
1119                     X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
1120                 }
1121                 break;
1122
1123             case OP65_TAY:
1124                 if (E->RI->In.RegA >= 0) {
1125                     Arg = MakeHexArg (In->RegA);
1126                     X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
1127                 }
1128                 break;
1129
1130             case OP65_TXA:
1131                 if (E->RI->In.RegX >= 0) {
1132                     Arg = MakeHexArg (In->RegX);
1133                     X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1134                 }
1135                 break;
1136
1137             case OP65_TYA:
1138                 if (E->RI->In.RegY >= 0) {
1139                     Arg = MakeHexArg (In->RegY);
1140                     X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1141                 }
1142                 break;
1143
1144             default:
1145                 /* Avoid gcc warnings */
1146                 break;
1147
1148         }
1149
1150         /* Insert the replacement if we have one */
1151         if (X) {
1152             CS_InsertEntry (S, X, I+1);
1153             CS_DelEntry (S, I);
1154             ++Changes;
1155         }
1156
1157         /* Next entry */
1158         ++I;
1159
1160     }
1161
1162     /* Free register info */
1163     CS_FreeRegInfo (S);
1164
1165     /* Return the number of changes made */
1166     return Changes;
1167 }
1168
1169
1170
1171 /*****************************************************************************/
1172 /*                        Optimize stack pointer ops                         */
1173 /*****************************************************************************/
1174
1175
1176
1177 static unsigned IsDecSP (const CodeEntry* E)
1178 /* Check if this is an insn that decrements the stack pointer. If so, return
1179  * the decrement. If not, return zero.
1180  * The function expects E to be a subroutine call.
1181  */
1182 {
1183     if (strncmp (E->Arg, "decsp", 5) == 0) {
1184         if (E->Arg[5] >= '1' && E->Arg[5] <= '8') {
1185             return (E->Arg[5] - '0');
1186         }
1187     } else if (strcmp (E->Arg, "subysp") == 0 && RegValIsKnown (E->RI->In.RegY)) {
1188         return E->RI->In.RegY;
1189     }
1190
1191     /* If we come here, it's not a decsp op */
1192     return 0;
1193 }
1194
1195
1196
1197 static unsigned OptStackPtrOps (CodeSeg* S)
1198 /* Merge adjacent calls to decsp into one. NOTE: This function won't merge all
1199  * known cases!
1200  */
1201 {
1202     unsigned Changes = 0;
1203     unsigned I;
1204
1205     /* Generate register info for the following step */
1206     CS_GenRegInfo (S);
1207
1208     /* Walk over the entries */
1209     I = 0;
1210     while (I < CS_GetEntryCount (S)) {
1211
1212         unsigned Dec1;
1213         unsigned Dec2;
1214         const CodeEntry* N;
1215
1216         /* Get the next entry */
1217         const CodeEntry* E = CS_GetEntry (S, I);
1218
1219         /* Check for decspn or subysp */
1220         if (E->OPC == OP65_JSR                          &&
1221             (Dec1 = IsDecSP (E)) > 0                    &&
1222             (N = CS_GetNextEntry (S, I)) != 0           &&
1223             (Dec2 = IsDecSP (N)) > 0                    &&
1224             (Dec1 += Dec2) <= 255                       &&
1225             !CE_HasLabel (N)) {
1226
1227             CodeEntry* X;
1228             char Buf[20];
1229
1230             /* We can combine the two */
1231             if (Dec1 <= 8) {
1232                 /* Insert a call to decsp */
1233                 xsprintf (Buf, sizeof (Buf), "decsp%u", Dec1);
1234                 X = NewCodeEntry (OP65_JSR, AM65_ABS, Buf, 0, N->LI);
1235                 CS_InsertEntry (S, X, I+2);
1236             } else {
1237                 /* Insert a call to subysp */
1238                 const char* Arg = MakeHexArg (Dec1);
1239                 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, N->LI);
1240                 CS_InsertEntry (S, X, I+2);
1241                 X = NewCodeEntry (OP65_JSR, AM65_ABS, "subysp", 0, N->LI);
1242                 CS_InsertEntry (S, X, I+3);
1243             }
1244
1245             /* Delete the old code */
1246             CS_DelEntries (S, I, 2);
1247
1248             /* Regenerate register info */
1249             CS_GenRegInfo (S);
1250
1251             /* Remember we had changes */
1252             ++Changes;
1253
1254         } else {
1255
1256             /* Next entry */
1257             ++I;
1258         }
1259
1260     }
1261
1262     /* Free register info */
1263     CS_FreeRegInfo (S);
1264
1265     /* Return the number of changes made */
1266     return Changes;
1267 }
1268
1269
1270
1271 /*****************************************************************************/
1272 /*                              struct OptFunc                               */
1273 /*****************************************************************************/
1274
1275
1276
1277 typedef struct OptFunc OptFunc;
1278 struct OptFunc {
1279     unsigned       (*Func) (CodeSeg*);  /* Optimizer function */
1280     const char*    Name;                /* Name of the function/group */
1281     unsigned       CodeSizeFactor;      /* Code size factor for this opt func */
1282     unsigned long  TotalRuns;           /* Total number of runs */
1283     unsigned long  LastRuns;            /* Last number of runs */
1284     unsigned long  TotalChanges;        /* Total number of changes */
1285     unsigned long  LastChanges;         /* Last number of changes */
1286     char           Disabled;            /* True if function disabled */
1287 };
1288
1289
1290
1291 /*****************************************************************************/
1292 /*                                   Code                                    */
1293 /*****************************************************************************/
1294
1295
1296
1297 /* A list of all the function descriptions */
1298 static OptFunc DOpt65C02BitOps  = { Opt65C02BitOps,  "Opt65C02BitOps",   66, 0, 0, 0, 0, 0 };
1299 static OptFunc DOpt65C02Ind     = { Opt65C02Ind,     "Opt65C02Ind",     100, 0, 0, 0, 0, 0 };
1300 static OptFunc DOpt65C02Stores  = { Opt65C02Stores,  "Opt65C02Stores",  100, 0, 0, 0, 0, 0 };
1301 static OptFunc DOptAdd1         = { OptAdd1,         "OptAdd1",         125, 0, 0, 0, 0, 0 };
1302 static OptFunc DOptAdd2         = { OptAdd2,         "OptAdd2",         200, 0, 0, 0, 0, 0 };
1303 static OptFunc DOptAdd3         = { OptAdd3,         "OptAdd3",          65, 0, 0, 0, 0, 0 };
1304 static OptFunc DOptAdd4         = { OptAdd4,         "OptAdd4",          90, 0, 0, 0, 0, 0 };
1305 static OptFunc DOptAdd5         = { OptAdd5,         "OptAdd5",         100, 0, 0, 0, 0, 0 };
1306 static OptFunc DOptAdd6         = { OptAdd6,         "OptAdd6",          40, 0, 0, 0, 0, 0 };
1307 static OptFunc DOptBoolTrans    = { OptBoolTrans,    "OptBoolTrans",    100, 0, 0, 0, 0, 0 };
1308 static OptFunc DOptBranchDist   = { OptBranchDist,   "OptBranchDist",     0, 0, 0, 0, 0, 0 };
1309 static OptFunc DOptCmp1         = { OptCmp1,         "OptCmp1",          42, 0, 0, 0, 0, 0 };
1310 static OptFunc DOptCmp2         = { OptCmp2,         "OptCmp2",          85, 0, 0, 0, 0, 0 };
1311 static OptFunc DOptCmp3         = { OptCmp3,         "OptCmp3",          75, 0, 0, 0, 0, 0 };
1312 static OptFunc DOptCmp4         = { OptCmp4,         "OptCmp4",          75, 0, 0, 0, 0, 0 };
1313 static OptFunc DOptCmp5         = { OptCmp5,         "OptCmp5",         100, 0, 0, 0, 0, 0 };
1314 static OptFunc DOptCmp6         = { OptCmp6,         "OptCmp6",         100, 0, 0, 0, 0, 0 };
1315 static OptFunc DOptCmp7         = { OptCmp7,         "OptCmp7",          85, 0, 0, 0, 0, 0 };
1316 static OptFunc DOptCmp8         = { OptCmp8,         "OptCmp8",          50, 0, 0, 0, 0, 0 };
1317 static OptFunc DOptCmp9         = { OptCmp9,         "OptCmp9",          85, 0, 0, 0, 0, 0 };
1318 static OptFunc DOptCondBranches1= { OptCondBranches1,"OptCondBranches1", 80, 0, 0, 0, 0, 0 };
1319 static OptFunc DOptCondBranches2= { OptCondBranches2,"OptCondBranches2",  0, 0, 0, 0, 0, 0 };
1320 static OptFunc DOptDeadCode     = { OptDeadCode,     "OptDeadCode",     100, 0, 0, 0, 0, 0 };
1321 static OptFunc DOptDeadJumps    = { OptDeadJumps,    "OptDeadJumps",    100, 0, 0, 0, 0, 0 };
1322 static OptFunc DOptDecouple     = { OptDecouple,     "OptDecouple",     100, 0, 0, 0, 0, 0 };
1323 static OptFunc DOptDupLoads     = { OptDupLoads,     "OptDupLoads",       0, 0, 0, 0, 0, 0 };
1324 static OptFunc DOptIndLoads1    = { OptIndLoads1,    "OptIndLoads1",      0, 0, 0, 0, 0, 0 };
1325 static OptFunc DOptIndLoads2    = { OptIndLoads2,    "OptIndLoads2",      0, 0, 0, 0, 0, 0 };
1326 static OptFunc DOptJumpCascades = { OptJumpCascades, "OptJumpCascades", 100, 0, 0, 0, 0, 0 };
1327 static OptFunc DOptJumpTarget1  = { OptJumpTarget1,  "OptJumpTarget1",  100, 0, 0, 0, 0, 0 };
1328 static OptFunc DOptJumpTarget2  = { OptJumpTarget2,  "OptJumpTarget2",  100, 0, 0, 0, 0, 0 };
1329 static OptFunc DOptJumpTarget3  = { OptJumpTarget3,  "OptJumpTarget3",  100, 0, 0, 0, 0, 0 };
1330 static OptFunc DOptLoad1        = { OptLoad1,        "OptLoad1",        100, 0, 0, 0, 0, 0 };
1331 static OptFunc DOptRTS          = { OptRTS,          "OptRTS",          100, 0, 0, 0, 0, 0 };
1332 static OptFunc DOptRTSJumps1    = { OptRTSJumps1,    "OptRTSJumps1",    100, 0, 0, 0, 0, 0 };
1333 static OptFunc DOptRTSJumps2    = { OptRTSJumps2,    "OptRTSJumps2",    100, 0, 0, 0, 0, 0 };
1334 static OptFunc DOptNegA1        = { OptNegA1,        "OptNegA1",        100, 0, 0, 0, 0, 0 };
1335 static OptFunc DOptNegA2        = { OptNegA2,        "OptNegA2",        100, 0, 0, 0, 0, 0 };
1336 static OptFunc DOptNegAX1       = { OptNegAX1,       "OptNegAX1",       100, 0, 0, 0, 0, 0 };
1337 static OptFunc DOptNegAX2       = { OptNegAX2,       "OptNegAX2",       100, 0, 0, 0, 0, 0 };
1338 static OptFunc DOptNegAX3       = { OptNegAX3,       "OptNegAX3",       100, 0, 0, 0, 0, 0 };
1339 static OptFunc DOptNegAX4       = { OptNegAX4,       "OptNegAX4",       100, 0, 0, 0, 0, 0 };
1340 static OptFunc DOptPrecalc      = { OptPrecalc,      "OptPrecalc",      100, 0, 0, 0, 0, 0 };
1341 static OptFunc DOptPtrLoad1     = { OptPtrLoad1,     "OptPtrLoad1",     100, 0, 0, 0, 0, 0 };
1342 static OptFunc DOptPtrLoad2     = { OptPtrLoad2,     "OptPtrLoad2",     100, 0, 0, 0, 0, 0 };
1343 static OptFunc DOptPtrLoad3     = { OptPtrLoad3,     "OptPtrLoad3",     100, 0, 0, 0, 0, 0 };
1344 static OptFunc DOptPtrLoad4     = { OptPtrLoad4,     "OptPtrLoad4",     100, 0, 0, 0, 0, 0 };
1345 static OptFunc DOptPtrLoad5     = { OptPtrLoad5,     "OptPtrLoad5",      50, 0, 0, 0, 0, 0 };
1346 static OptFunc DOptPtrLoad6     = { OptPtrLoad6,     "OptPtrLoad6",      60, 0, 0, 0, 0, 0 };
1347 static OptFunc DOptPtrLoad7     = { OptPtrLoad7,     "OptPtrLoad7",     140, 0, 0, 0, 0, 0 };
1348 static OptFunc DOptPtrLoad11    = { OptPtrLoad11,    "OptPtrLoad11",     92, 0, 0, 0, 0, 0 };
1349 static OptFunc DOptPtrLoad12    = { OptPtrLoad12,    "OptPtrLoad12",    50, 0, 0, 0, 0, 0 };
1350 static OptFunc DOptPtrLoad13    = { OptPtrLoad13,    "OptPtrLoad13",    65, 0, 0, 0, 0, 0 };
1351 static OptFunc DOptPtrLoad14    = { OptPtrLoad14,    "OptPtrLoad14",    108, 0, 0, 0, 0, 0 };
1352 static OptFunc DOptPtrLoad15    = { OptPtrLoad15,    "OptPtrLoad15",     86, 0, 0, 0, 0, 0 };
1353 static OptFunc DOptPtrLoad16    = { OptPtrLoad16,    "OptPtrLoad16",    100, 0, 0, 0, 0, 0 };
1354 static OptFunc DOptPtrLoad17    = { OptPtrLoad17,    "OptPtrLoad17",    190, 0, 0, 0, 0, 0 };
1355 static OptFunc DOptPtrStore1    = { OptPtrStore1,    "OptPtrStore1",    100, 0, 0, 0, 0, 0 };
1356 static OptFunc DOptPtrStore2    = { OptPtrStore2,    "OptPtrStore2",     40, 0, 0, 0, 0, 0 };
1357 static OptFunc DOptPtrStore3    = { OptPtrStore3,    "OptPtrStore3",     50, 0, 0, 0, 0, 0 };
1358 static OptFunc DOptPush1        = { OptPush1,        "OptPush1",         65, 0, 0, 0, 0, 0 };
1359 static OptFunc DOptPush2        = { OptPush2,        "OptPush2",         50, 0, 0, 0, 0, 0 };
1360 static OptFunc DOptPushPop      = { OptPushPop,      "OptPushPop",        0, 0, 0, 0, 0, 0 };
1361 static OptFunc DOptShift1       = { OptShift1,       "OptShift1",       100, 0, 0, 0, 0, 0 };
1362 static OptFunc DOptShift2       = { OptShift2,       "OptShift2",       100, 0, 0, 0, 0, 0 };
1363 static OptFunc DOptShift3       = { OptShift3,       "OptShift3",       110, 0, 0, 0, 0, 0 };
1364 static OptFunc DOptShift4       = { OptShift4,       "OptShift4",       200, 0, 0, 0, 0, 0 };
1365 static OptFunc DOptSize1        = { OptSize1,        "OptSize1",        100, 0, 0, 0, 0, 0 };
1366 static OptFunc DOptSize2        = { OptSize2,        "OptSize2",        100, 0, 0, 0, 0, 0 };
1367 static OptFunc DOptStackOps     = { OptStackOps,     "OptStackOps",     100, 0, 0, 0, 0, 0 };
1368 static OptFunc DOptStackPtrOps  = { OptStackPtrOps,  "OptStackPtrOps",   50, 0, 0, 0, 0, 0 };
1369 static OptFunc DOptStore1       = { OptStore1,       "OptStore1",        70, 0, 0, 0, 0, 0 };
1370 static OptFunc DOptStore2       = { OptStore2,       "OptStore2",       220, 0, 0, 0, 0, 0 };
1371 static OptFunc DOptStore3       = { OptStore3,       "OptStore3",       120, 0, 0, 0, 0, 0 };
1372 static OptFunc DOptStore4       = { OptStore4,       "OptStore4",        50, 0, 0, 0, 0, 0 };
1373 static OptFunc DOptStore5       = { OptStore5,       "OptStore5",       100, 0, 0, 0, 0, 0 };
1374 static OptFunc DOptStoreLoad    = { OptStoreLoad,    "OptStoreLoad",      0, 0, 0, 0, 0, 0 };
1375 static OptFunc DOptSub1         = { OptSub1,         "OptSub1",         100, 0, 0, 0, 0, 0 };
1376 static OptFunc DOptSub2         = { OptSub2,         "OptSub2",         100, 0, 0, 0, 0, 0 };
1377 static OptFunc DOptSub3         = { OptSub3,         "OptSub3",         100, 0, 0, 0, 0, 0 };
1378 static OptFunc DOptTest1        = { OptTest1,        "OptTest1",        100, 0, 0, 0, 0, 0 };
1379 static OptFunc DOptTransfers1   = { OptTransfers1,   "OptTransfers1",     0, 0, 0, 0, 0, 0 };
1380 static OptFunc DOptTransfers2   = { OptTransfers2,   "OptTransfers2",    60, 0, 0, 0, 0, 0 };
1381 static OptFunc DOptTransfers3   = { OptTransfers3,   "OptTransfers3",    65, 0, 0, 0, 0, 0 };
1382 static OptFunc DOptTransfers4   = { OptTransfers4,   "OptTransfers4",    65, 0, 0, 0, 0, 0 };
1383 static OptFunc DOptUnusedLoads  = { OptUnusedLoads,  "OptUnusedLoads",    0, 0, 0, 0, 0, 0 };
1384 static OptFunc DOptUnusedStores = { OptUnusedStores, "OptUnusedStores",   0, 0, 0, 0, 0, 0 };
1385
1386
1387 /* Table containing all the steps in alphabetical order */
1388 static OptFunc* OptFuncs[] = {
1389     &DOpt65C02BitOps,
1390     &DOpt65C02Ind,
1391     &DOpt65C02Stores,
1392     &DOptAdd1,
1393     &DOptAdd2,
1394     &DOptAdd3,
1395     &DOptAdd4,
1396     &DOptAdd5,
1397     &DOptAdd6,
1398     &DOptBoolTrans,
1399     &DOptBranchDist,
1400     &DOptCmp1,
1401     &DOptCmp2,
1402     &DOptCmp3,
1403     &DOptCmp4,
1404     &DOptCmp5,
1405     &DOptCmp6,
1406     &DOptCmp7,
1407     &DOptCmp8,
1408     &DOptCmp9,
1409     &DOptCondBranches1,
1410     &DOptCondBranches2,
1411     &DOptDeadCode,
1412     &DOptDeadJumps,
1413     &DOptDecouple,
1414     &DOptDupLoads,
1415     &DOptIndLoads1,
1416     &DOptIndLoads2,
1417     &DOptJumpCascades,
1418     &DOptJumpTarget1,
1419     &DOptJumpTarget2,
1420     &DOptJumpTarget3,
1421     &DOptLoad1,
1422     &DOptNegA1,
1423     &DOptNegA2,
1424     &DOptNegAX1,
1425     &DOptNegAX2,
1426     &DOptNegAX3,
1427     &DOptNegAX4,
1428     &DOptPrecalc,
1429     &DOptPtrLoad1,
1430     &DOptPtrLoad11,
1431     &DOptPtrLoad12,
1432     &DOptPtrLoad13,
1433     &DOptPtrLoad14,
1434     &DOptPtrLoad15,
1435     &DOptPtrLoad16,
1436     &DOptPtrLoad17,
1437     &DOptPtrLoad2,
1438     &DOptPtrLoad3,
1439     &DOptPtrLoad4,
1440     &DOptPtrLoad5,
1441     &DOptPtrLoad6,
1442     &DOptPtrLoad7,
1443     &DOptPtrStore1,
1444     &DOptPtrStore2,
1445     &DOptPtrStore3,
1446     &DOptPush1,
1447     &DOptPush2,
1448     &DOptPushPop,
1449     &DOptRTS,
1450     &DOptRTSJumps1,
1451     &DOptRTSJumps2,
1452     &DOptShift1,
1453     &DOptShift2,
1454     &DOptShift3,
1455     &DOptShift4,
1456     &DOptSize1,
1457     &DOptSize2,
1458     &DOptStackOps,
1459     &DOptStackPtrOps,
1460     &DOptStore1,
1461     &DOptStore2,
1462     &DOptStore3,
1463     &DOptStore4,
1464     &DOptStore5,
1465     &DOptStoreLoad,
1466     &DOptSub1,
1467     &DOptSub2,
1468     &DOptSub3,
1469     &DOptTest1,
1470     &DOptTransfers1,
1471     &DOptTransfers2,
1472     &DOptTransfers3,
1473     &DOptTransfers4,
1474     &DOptUnusedLoads,
1475     &DOptUnusedStores,
1476 };
1477 #define OPTFUNC_COUNT  (sizeof(OptFuncs) / sizeof(OptFuncs[0]))
1478
1479
1480
1481 static int CmpOptStep (const void* Key, const void* Func)
1482 /* Compare function for bsearch */
1483 {
1484     return strcmp (Key, (*(const OptFunc**)Func)->Name);
1485 }
1486
1487
1488
1489 static OptFunc* FindOptFunc (const char* Name)
1490 /* Find an optimizer step by name in the table and return a pointer. Return
1491  * NULL if no such step is found.
1492  */
1493 {
1494     /* Search for the function in the list */
1495     OptFunc** O = bsearch (Name, OptFuncs, OPTFUNC_COUNT, sizeof (OptFuncs[0]), CmpOptStep);
1496     return O? *O : 0;
1497 }
1498
1499
1500
1501 static OptFunc* GetOptFunc (const char* Name)
1502 /* Find an optimizer step by name in the table and return a pointer. Print an
1503  * error and call AbEnd if not found.
1504  */
1505 {
1506     /* Search for the function in the list */
1507     OptFunc* F = FindOptFunc (Name);
1508     if (F == 0) {
1509         /* Not found */
1510         AbEnd ("Optimization step `%s' not found", Name);
1511     }
1512     return F;
1513 }
1514
1515
1516
1517 void DisableOpt (const char* Name)
1518 /* Disable the optimization with the given name */
1519 {
1520     if (strcmp (Name, "any") == 0) {
1521         unsigned I;
1522         for (I = 0; I < OPTFUNC_COUNT; ++I) {
1523             OptFuncs[I]->Disabled = 1;
1524         }
1525     } else {
1526         GetOptFunc(Name)->Disabled = 1;
1527     }
1528 }
1529
1530
1531
1532 void EnableOpt (const char* Name)
1533 /* Enable the optimization with the given name */
1534 {
1535     if (strcmp (Name, "any") == 0) {
1536         unsigned I;
1537         for (I = 0; I < OPTFUNC_COUNT; ++I) {
1538             OptFuncs[I]->Disabled = 0;
1539         }
1540     } else {
1541         GetOptFunc(Name)->Disabled = 0;
1542     }
1543 }
1544
1545
1546
1547 void ListOptSteps (FILE* F)
1548 /* List all optimization steps */
1549 {
1550     unsigned I;
1551     for (I = 0; I < OPTFUNC_COUNT; ++I) {
1552         fprintf (F, "%s\n", OptFuncs[I]->Name);
1553     }
1554 }
1555
1556
1557
1558 static void ReadOptStats (const char* Name)
1559 /* Read the optimizer statistics file */
1560 {
1561     char Buf [256];
1562     unsigned Lines;
1563
1564     /* Try to open the file */
1565     FILE* F = fopen (Name, "r");
1566     if (F == 0) {
1567         /* Ignore the error */
1568         return;
1569     }
1570
1571     /* Read and parse the lines */
1572     Lines = 0;
1573     while (fgets (Buf, sizeof (Buf), F) != 0) {
1574
1575         char* B;
1576         unsigned Len;
1577         OptFunc* Func;
1578
1579         /* Fields */
1580         char Name[32];
1581         unsigned long  TotalRuns;
1582         unsigned long  TotalChanges;
1583
1584         /* Count lines */
1585         ++Lines;
1586
1587         /* Remove trailing white space including the line terminator */
1588         B = Buf;
1589         Len = strlen (B);
1590         while (Len > 0 && IsSpace (B[Len-1])) {
1591             --Len;
1592         }
1593         B[Len] = '\0';
1594
1595         /* Remove leading whitespace */
1596         while (IsSpace (*B)) {
1597             ++B;
1598         }
1599
1600         /* Check for empty and comment lines */
1601         if (*B == '\0' || *B == ';' || *B == '#') {
1602             continue;
1603         }
1604
1605         /* Parse the line */
1606         if (sscanf (B, "%31s %lu %*u %lu %*u", Name, &TotalRuns, &TotalChanges) != 3) {
1607             /* Syntax error */
1608             continue;
1609         }
1610
1611         /* Search for the optimizer step. */
1612         Func = FindOptFunc (Name);
1613         if (Func == 0) {
1614             /* Not found */
1615             continue;
1616         }
1617
1618         /* Found the step, set the fields */
1619         Func->TotalRuns    = TotalRuns;
1620         Func->TotalChanges = TotalChanges;
1621
1622     }
1623
1624     /* Close the file, ignore errors here. */
1625     fclose (F);
1626 }
1627
1628
1629
1630 static void WriteOptStats (const char* Name)
1631 /* Write the optimizer statistics file */
1632 {
1633     unsigned I;
1634
1635     /* Try to open the file */
1636     FILE* F = fopen (Name, "w");
1637     if (F == 0) {
1638         /* Ignore the error */
1639         return;
1640     }
1641
1642     /* Write a header */
1643     fprintf (F,
1644              "; Optimizer               Total      Last       Total      Last\n"
1645              ";   Step                  Runs       Runs        Chg       Chg\n");
1646
1647
1648     /* Write the data */
1649     for (I = 0; I < OPTFUNC_COUNT; ++I) {
1650         const OptFunc* O = OptFuncs[I];
1651         fprintf (F,
1652                  "%-20s %10lu %10lu %10lu %10lu\n",
1653                  O->Name,
1654                  O->TotalRuns,
1655                  O->LastRuns,
1656                  O->TotalChanges,
1657                  O->LastChanges);
1658     }
1659
1660     /* Close the file, ignore errors here. */
1661     fclose (F);
1662 }
1663
1664
1665
1666 static unsigned RunOptFunc (CodeSeg* S, OptFunc* F, unsigned Max)
1667 /* Run one optimizer function Max times or until there are no more changes */
1668 {
1669     unsigned Changes, C;
1670
1671     /* Don't run the function if it is disabled or if it is prohibited by the
1672      * code size factor
1673      */
1674     if (F->Disabled || F->CodeSizeFactor > S->CodeSizeFactor) {
1675         return 0;
1676     }
1677
1678     /* Run this until there are no more changes */
1679     Changes = 0;
1680     do {
1681
1682         /* Run the function */
1683         C = F->Func (S);
1684         Changes += C;
1685
1686         /* Do statistics */
1687         ++F->TotalRuns;
1688         ++F->LastRuns;
1689         F->TotalChanges += C;
1690         F->LastChanges  += C;
1691
1692     } while (--Max && C > 0);
1693
1694     /* Return the number of changes */
1695     return Changes;
1696 }
1697
1698
1699
1700 static unsigned RunOptGroup1 (CodeSeg* S)
1701 /* Run the first group of optimization steps. These steps translate known
1702  * patterns emitted by the code generator into more optimal patterns. Order
1703  * of the steps is important, because some of the steps done earlier cover
1704  * the same patterns as later steps as subpatterns.
1705  */
1706 {
1707     unsigned Changes = 0;
1708
1709     Changes += RunOptFunc (S, &DOptStackPtrOps, 5);
1710     Changes += RunOptFunc (S, &DOptPtrStore1, 1);
1711     Changes += RunOptFunc (S, &DOptPtrStore2, 1);
1712     Changes += RunOptFunc (S, &DOptPtrStore3, 1);
1713     Changes += RunOptFunc (S, &DOptAdd3, 1);    /* Before OptPtrLoad5! */
1714     Changes += RunOptFunc (S, &DOptPtrLoad1, 1);
1715     Changes += RunOptFunc (S, &DOptPtrLoad2, 1);
1716     Changes += RunOptFunc (S, &DOptPtrLoad3, 1);
1717     Changes += RunOptFunc (S, &DOptPtrLoad4, 1);
1718     Changes += RunOptFunc (S, &DOptPtrLoad5, 1);
1719     Changes += RunOptFunc (S, &DOptPtrLoad6, 1);
1720     Changes += RunOptFunc (S, &DOptPtrLoad7, 1);
1721     Changes += RunOptFunc (S, &DOptPtrLoad11, 1);
1722     Changes += RunOptFunc (S, &DOptPtrLoad12, 1);
1723     Changes += RunOptFunc (S, &DOptPtrLoad13, 1);
1724     Changes += RunOptFunc (S, &DOptPtrLoad14, 1);
1725     Changes += RunOptFunc (S, &DOptPtrLoad15, 1);
1726     Changes += RunOptFunc (S, &DOptPtrLoad16, 1);
1727     Changes += RunOptFunc (S, &DOptPtrLoad17, 1);
1728     Changes += RunOptFunc (S, &DOptNegAX1, 1);
1729     Changes += RunOptFunc (S, &DOptNegAX2, 1);
1730     Changes += RunOptFunc (S, &DOptNegAX3, 1);
1731     Changes += RunOptFunc (S, &DOptNegAX4, 1);
1732     Changes += RunOptFunc (S, &DOptAdd1, 1);
1733     Changes += RunOptFunc (S, &DOptAdd2, 1);
1734     Changes += RunOptFunc (S, &DOptAdd4, 1);
1735     Changes += RunOptFunc (S, &DOptStore4, 1);
1736     Changes += RunOptFunc (S, &DOptStore5, 1);
1737     Changes += RunOptFunc (S, &DOptShift1, 1);
1738     Changes += RunOptFunc (S, &DOptShift2, 1);
1739     Changes += RunOptFunc (S, &DOptShift3, 1);
1740     Changes += RunOptFunc (S, &DOptShift4, 1);
1741     Changes += RunOptFunc (S, &DOptStore1, 1);
1742     Changes += RunOptFunc (S, &DOptStore2, 5);
1743     Changes += RunOptFunc (S, &DOptStore3, 5);
1744
1745     /* Return the number of changes */
1746     return Changes;
1747 }
1748
1749
1750
1751 static unsigned RunOptGroup2 (CodeSeg* S)
1752 /* Run one group of optimization steps. This step involves just decoupling
1753  * instructions by replacing them by instructions that do not depend on
1754  * previous instructions. This makes it easier to find instructions that
1755  * aren't used.
1756  */
1757 {
1758     unsigned Changes = 0;
1759
1760     Changes += RunOptFunc (S, &DOptDecouple, 1);
1761
1762     /* Return the number of changes */
1763     return Changes;
1764 }
1765
1766
1767
1768 static unsigned RunOptGroup3 (CodeSeg* S)
1769 /* Run one group of optimization steps. These steps depend on each other,
1770  * that means that one step may allow another step to do additional work,
1771  * so we will repeat the steps as long as we see any changes.
1772  */
1773 {
1774     unsigned Changes, C;
1775
1776     Changes = 0;
1777     do {
1778         C = 0;
1779
1780         C += RunOptFunc (S, &DOptNegA1, 1);
1781         C += RunOptFunc (S, &DOptNegA2, 1);
1782         C += RunOptFunc (S, &DOptSub1, 1);
1783         C += RunOptFunc (S, &DOptSub2, 1);
1784         C += RunOptFunc (S, &DOptSub3, 1);
1785         C += RunOptFunc (S, &DOptAdd5, 1);
1786         C += RunOptFunc (S, &DOptAdd6, 1);
1787         C += RunOptFunc (S, &DOptStackOps, 1);
1788         C += RunOptFunc (S, &DOptJumpCascades, 1);
1789         C += RunOptFunc (S, &DOptDeadJumps, 1);
1790         C += RunOptFunc (S, &DOptRTS, 1);
1791         C += RunOptFunc (S, &DOptDeadCode, 1);
1792         C += RunOptFunc (S, &DOptBoolTrans, 1);
1793         C += RunOptFunc (S, &DOptJumpTarget1, 1);
1794         C += RunOptFunc (S, &DOptJumpTarget2, 1);
1795         C += RunOptFunc (S, &DOptCondBranches1, 1);
1796         C += RunOptFunc (S, &DOptCondBranches2, 1);
1797         C += RunOptFunc (S, &DOptRTSJumps1, 1);
1798         C += RunOptFunc (S, &DOptCmp1, 1);
1799         C += RunOptFunc (S, &DOptCmp2, 1);
1800         C += RunOptFunc (S, &DOptCmp3, 1);
1801         C += RunOptFunc (S, &DOptCmp4, 1);
1802         C += RunOptFunc (S, &DOptCmp5, 1);
1803         C += RunOptFunc (S, &DOptCmp6, 1);
1804         C += RunOptFunc (S, &DOptCmp7, 1);
1805         C += RunOptFunc (S, &DOptCmp8, 1);
1806         C += RunOptFunc (S, &DOptCmp9, 1);
1807         C += RunOptFunc (S, &DOptTest1, 1);
1808         C += RunOptFunc (S, &DOptLoad1, 1);
1809         C += RunOptFunc (S, &DOptJumpTarget3, 1);       /* After OptCondBranches2 */
1810         C += RunOptFunc (S, &DOptUnusedLoads, 1);
1811         C += RunOptFunc (S, &DOptUnusedStores, 1);
1812         C += RunOptFunc (S, &DOptDupLoads, 1);
1813         C += RunOptFunc (S, &DOptStoreLoad, 1);
1814         C += RunOptFunc (S, &DOptTransfers1, 1);
1815         C += RunOptFunc (S, &DOptTransfers3, 1);
1816         C += RunOptFunc (S, &DOptTransfers4, 1);
1817         C += RunOptFunc (S, &DOptStore1, 1);
1818         C += RunOptFunc (S, &DOptStore5, 1);
1819         C += RunOptFunc (S, &DOptPushPop, 1);
1820         C += RunOptFunc (S, &DOptPrecalc, 1);
1821
1822         Changes += C;
1823
1824     } while (C);
1825
1826     /* Return the number of changes */
1827     return Changes;
1828 }
1829
1830
1831
1832 static unsigned RunOptGroup4 (CodeSeg* S)
1833 /* 65C02 specific optimizations. */
1834 {
1835     unsigned Changes = 0;
1836
1837     if (CPUIsets[CPU] & CPU_ISET_65SC02) {
1838         Changes += RunOptFunc (S, &DOpt65C02BitOps, 1);
1839         Changes += RunOptFunc (S, &DOpt65C02Ind, 1);
1840         Changes += RunOptFunc (S, &DOpt65C02Stores, 1);
1841         if (Changes) {
1842             /* The 65C02 replacement codes do often make the use of a register
1843              * value unnecessary, so if we have changes, run another load
1844              * removal pass.
1845              */
1846             Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1847         }
1848     }
1849
1850     /* Return the number of changes */
1851     return Changes;
1852 }
1853
1854
1855
1856 static unsigned RunOptGroup5 (CodeSeg* S)
1857 /* Run another round of pattern replacements. These are done late, since there
1858  * may be better replacements before.
1859  */
1860 {
1861     unsigned Changes = 0;
1862
1863     Changes += RunOptFunc (S, &DOptPush1, 1);
1864     Changes += RunOptFunc (S, &DOptPush2, 1);
1865     /* Repeat some of the other optimizations now */
1866     Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1867     Changes += RunOptFunc (S, &DOptTransfers2, 1);
1868
1869     /* Return the number of changes */
1870     return Changes;
1871 }
1872
1873
1874
1875 static unsigned RunOptGroup6 (CodeSeg* S)
1876 /* This one is quite special. It tries to replace "lda (sp),y" by "lda (sp,x)".
1877  * The latter is ony cycle slower, but if we're able to remove the necessary
1878  * load of the Y register, because X is zero anyway, we gain 1 cycle and
1879  * shorten the code by one (transfer) or two bytes (load). So what we do is
1880  * to replace the insns, remove unused loads, and then change back all insns
1881  * where Y is still zero (meaning that the load has not been removed).
1882  */
1883 {
1884     unsigned Changes = 0;
1885
1886     /* This group will only run for a standard 6502, because the 65C02 has a
1887      * better addressing mode that covers this case.
1888      */
1889     if ((CPUIsets[CPU] & CPU_ISET_65SC02) == 0) {
1890         Changes += RunOptFunc (S, &DOptIndLoads1, 1);
1891         Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1892         Changes += RunOptFunc (S, &DOptIndLoads2, 1);
1893     }
1894
1895     /* Return the number of changes */
1896     return Changes;
1897 }
1898
1899
1900
1901 static unsigned RunOptGroup7 (CodeSeg* S)
1902 /* The last group of optimization steps. Adjust branches, do size optimizations.
1903  */
1904 {
1905     unsigned Changes = 0;
1906     unsigned C;
1907
1908     /* Optimize for size, that is replace operations by shorter ones, even
1909      * if this does hinder further optimizations (no problem since we're
1910      * done soon).
1911      */
1912     C = RunOptFunc (S, &DOptSize1, 1);
1913     if (C) {
1914         Changes += C;
1915         /* Run some optimization passes again, since the size optimizations
1916          * may have opened new oportunities.
1917          */
1918         Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1919         Changes += RunOptFunc (S, &DOptUnusedStores, 1);
1920         Changes += RunOptFunc (S, &DOptJumpTarget1, 5);
1921         Changes += RunOptFunc (S, &DOptStore5, 1);
1922     }
1923
1924     C = RunOptFunc (S, &DOptSize2, 1);
1925     if (C) {
1926         Changes += C;
1927         /* Run some optimization passes again, since the size optimizations
1928          * may have opened new oportunities.
1929          */
1930         Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1931         Changes += RunOptFunc (S, &DOptJumpTarget1, 5);
1932         Changes += RunOptFunc (S, &DOptStore5, 1);
1933         Changes += RunOptFunc (S, &DOptTransfers3, 1);
1934     }
1935
1936     /* Adjust branch distances */
1937     Changes += RunOptFunc (S, &DOptBranchDist, 3);
1938
1939     /* Replace conditional branches to RTS. If we had changes, we must run dead
1940      * code elimination again, since the change may have introduced dead code.
1941      */
1942     C = RunOptFunc (S, &DOptRTSJumps2, 1);
1943     Changes += C;
1944     if (C) {
1945         Changes += RunOptFunc (S, &DOptDeadCode, 1);
1946     }
1947
1948     /* Return the number of changes */
1949     return Changes;
1950 }
1951
1952
1953
1954 void RunOpt (CodeSeg* S)
1955 /* Run the optimizer */
1956 {
1957     const char* StatFileName;
1958
1959     /* If we shouldn't run the optimizer, bail out */
1960     if (!S->Optimize) {
1961         return;
1962     }
1963
1964     /* Check if we are requested to write optimizer statistics */
1965     StatFileName = getenv ("CC65_OPTSTATS");
1966     if (StatFileName) {
1967         ReadOptStats (StatFileName);
1968     }
1969
1970     /* Print the name of the function we are working on */
1971     if (S->Func) {
1972         Print (stdout, 1, "Running optimizer for function `%s'\n", S->Func->Name);
1973     } else {
1974         Print (stdout, 1, "Running optimizer for global code segment\n");
1975     }
1976
1977     /* Run groups of optimizations */
1978     RunOptGroup1 (S);
1979     RunOptGroup2 (S);
1980     RunOptGroup3 (S);
1981     RunOptGroup4 (S);
1982     RunOptGroup5 (S);
1983     RunOptGroup6 (S);
1984     RunOptGroup7 (S);
1985
1986     /* Write statistics */
1987     if (StatFileName) {
1988         WriteOptStats (StatFileName);
1989     }
1990 }
1991
1992
1993