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