]> git.sur5r.net Git - cc65/blob - src/cc65/codeopt.c
More optimizations
[cc65] / src / cc65 / codeopt.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 codeopt.c                                 */
4 /*                                                                           */
5 /*                           Optimizer subroutines                           */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001      Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <string.h>
37
38 /* common */
39 #include "abend.h"
40 #include "print.h"
41
42 /* cc65 */
43 #include "asmlabel.h"
44 #include "codeent.h"
45 #include "codeinfo.h"
46 #include "coptind.h"
47 #include "error.h"
48 #include "global.h"
49 #include "codeopt.h"
50
51
52
53 /*****************************************************************************/
54 /*                                   Data                                    */
55 /*****************************************************************************/
56
57
58
59 /* Defines for the conditions in a compare */
60 typedef enum {
61     CMP_INV = -1,
62     CMP_EQ,
63     CMP_NE,
64     CMP_GT,
65     CMP_GE,
66     CMP_LT,
67     CMP_LE,
68     CMP_UGT,
69     CMP_UGE,
70     CMP_ULT,
71     CMP_ULE
72 } cmp_t;
73
74 /* Table with the compare suffixes */
75 static const char CmpSuffixTab [][4] = {
76     "eq", "ne", "gt", "ge", "lt", "le", "ugt", "uge", "ult", "ule"
77 };
78
79 /* Table used to invert a condition, indexed by condition */
80 static const unsigned char CmpInvertTab [] = {
81     CMP_NE, CMP_EQ,
82     CMP_LE, CMP_LT, CMP_GE, CMP_GT,
83     CMP_ULE, CMP_ULT, CMP_UGE, CMP_UGT
84 };
85
86 /* Table to show which compares are signed (use the N flag) */
87 static const char CmpSignedTab [] = {
88     0, 0, 1, 1, 1, 1, 0, 0, 0, 0
89 };
90
91
92
93 /*****************************************************************************/
94 /*                             Helper functions                              */
95 /*****************************************************************************/
96
97
98
99 static cmp_t FindCmpCond (const char* Code, unsigned CodeLen)
100 /* Search for a compare condition by the given code using the given length */
101 {
102     unsigned I;
103
104     /* Linear search */
105     for (I = 0; I < sizeof (CmpSuffixTab) / sizeof (CmpSuffixTab [0]); ++I) {
106         if (strncmp (Code, CmpSuffixTab [I], CodeLen) == 0) {
107             /* Found */
108             return I;
109         }
110     }
111
112     /* Not found */
113     return CMP_INV;
114 }
115
116
117
118 static cmp_t FindBoolCmpCond (const char* Name)
119 /* Map a condition suffix to a code. Return the code or CMP_INV on failure */
120 {
121     /* Check for the correct subroutine name */
122     if (strncmp (Name, "bool", 4) == 0) {
123         /* Name is ok, search for the code in the table */
124         return FindCmpCond (Name+4, strlen(Name)-4);
125     } else {
126         /* Not found */
127         return CMP_INV;
128     }
129 }
130
131
132
133 static cmp_t FindTosCmpCond (const char* Name)
134 /* Check if this is a call to one of the TOS compare functions (tosgtax).
135  * Return the condition code or CMP_INV on failure.
136  */
137 {
138     unsigned Len = strlen (Name);
139
140     /* Check for the correct subroutine name */
141     if (strncmp (Name, "tos", 3) == 0 && strcmp (Name+Len-2, "ax") == 0) {
142         /* Name is ok, search for the code in the table */
143         return FindCmpCond (Name+3, Len-3-2);
144     } else {
145         /* Not found */
146         return CMP_INV;
147     }
148 }
149
150
151
152 static void ReplaceCmp (CodeSeg* S, unsigned I, cmp_t Cond)
153 /* Helper function for the replacement of routines that return a boolean
154  * followed by a conditional jump. Instead of the boolean value, the condition
155  * codes are evaluated directly.
156  * I is the index of the conditional branch, the sequence is already checked
157  * to be correct.
158  */
159 {
160     CodeEntry* N;
161     CodeLabel* L;
162
163     /* Get the entry */
164     CodeEntry* E = CS_GetEntry (S, I);
165
166     /* Replace the conditional branch */
167     switch (Cond) {
168
169         case CMP_EQ:
170             CE_ReplaceOPC (E, OP65_JEQ);
171             break;
172
173         case CMP_NE:
174             CE_ReplaceOPC (E, OP65_JNE);
175             break;
176
177         case CMP_GT:
178             /* Replace by
179              *     beq @L
180              *     jpl Target
181              * @L: ...
182              */
183             if ((N = CS_GetNextEntry (S, I)) == 0) {
184                 /* No such entry */
185                 Internal ("Invalid program flow");
186             }
187             L = CS_GenLabel (S, N);
188             N = NewCodeEntry (OP65_BEQ, AM65_BRA, L->Name, L, E->LI);
189             CS_InsertEntry (S, N, I);
190             CE_ReplaceOPC (E, OP65_JPL);
191             break;
192
193         case CMP_GE:
194             CE_ReplaceOPC (E, OP65_JPL);
195             break;
196
197         case CMP_LT:
198             CE_ReplaceOPC (E, OP65_JMI);
199             break;
200
201         case CMP_LE:
202             /* Replace by
203              *     jmi Target
204              *     jeq Target
205              */
206             CE_ReplaceOPC (E, OP65_JMI);
207             L = E->JumpTo;
208             N = NewCodeEntry (OP65_JEQ, AM65_BRA, L->Name, L, E->LI);
209             CS_InsertEntry (S, N, I+1);
210             break;
211
212         case CMP_UGT:
213             /* Replace by
214              *     beq @L
215              *     jcs Target
216              * @L: ...
217              */
218             if ((N = CS_GetNextEntry (S, I)) == 0) {
219                 /* No such entry */
220                 Internal ("Invalid program flow");
221             }
222             L = CS_GenLabel (S, N);
223             N = NewCodeEntry (OP65_BEQ, AM65_BRA, L->Name, L, E->LI);
224             CS_InsertEntry (S, N, I);
225             CE_ReplaceOPC (E, OP65_JCS);
226             break;
227
228         case CMP_UGE:
229             CE_ReplaceOPC (E, OP65_JCS);
230             break;
231
232         case CMP_ULT:
233             CE_ReplaceOPC (E, OP65_JCC);
234             break;
235
236         case CMP_ULE:
237             /* Replace by
238              *     jcc Target
239              *     jeq Target
240              */
241             CE_ReplaceOPC (E, OP65_JCC);
242             L = E->JumpTo;
243             N = NewCodeEntry (OP65_JEQ, AM65_BRA, L->Name, L, E->LI);
244             CS_InsertEntry (S, N, I+1);
245             break;
246
247         default:
248             Internal ("Unknown jump condition: %d", Cond);
249
250     }
251
252 }
253
254
255
256 static int IsCmpToZero (const CodeEntry* E)
257 /* Check if the given instrcuction is a compare to zero instruction */
258 {
259     return (E->OPC == OP65_CMP            &&
260             E->AM  == AM65_IMM            &&
261             (E->Flags & CEF_NUMARG) != 0  &&
262             E->Num == 0);
263 }
264
265
266
267 static int IsSpLoad (const CodeEntry* E)
268 /* Return true if this is the load of A from the stack */
269 {
270     return E->OPC == OP65_LDA && E->AM == AM65_ZP_INDY && strcmp (E->Arg, "sp") == 0;
271 }
272
273
274
275 static int IsLocalLoad16 (CodeSeg* S, unsigned Index,
276                           CodeEntry** L, unsigned Count)
277 /* Check if a 16 bit load of a local variable follows:
278  *
279  *      ldy     #$xx
280  *      lda     (sp),y
281  *      tax
282  *      dey
283  *      lda     (sp),y
284  *
285  * If so, read Count entries following the first ldy into L and return true
286  * if this is possible. Otherwise return false.
287  */
288 {
289     /* Be sure we read enough entries for the check */
290     CHECK (Count >= 5);
291
292     /* Read the first entry */
293     L[0] = CS_GetEntry (S, Index);
294
295     /* Check for the sequence */
296     return (L[0]->OPC == OP65_LDY                        &&
297             L[0]->AM == AM65_IMM                         &&
298             (L[0]->Flags & CEF_NUMARG) != 0              &&
299             CS_GetEntries (S, L+1, Index+1, Count-1)     &&
300             IsSpLoad (L[1])                              &&
301             !CE_HasLabel (L[1])                          &&
302             L[2]->OPC == OP65_TAX                        &&
303             !CE_HasLabel (L[2])                          &&
304             L[3]->OPC == OP65_DEY                        &&
305             !CE_HasLabel (L[3])                          &&
306             IsSpLoad (L[4])                              &&
307             !CE_HasLabel (L[4]));
308 }
309
310
311
312 static int IsImmCmp16 (CodeSeg* S, CodeEntry** L)
313 /* Check if the instructions at L are an immidiate compare of a/x:
314  *
315  *
316  */
317 {
318     return (L[0]->OPC == OP65_CPX                              &&
319             L[0]->AM == AM65_IMM                               &&
320             (L[0]->Flags & CEF_NUMARG) != 0                    &&
321             !CE_HasLabel (L[0])                                &&
322             (L[1]->OPC == OP65_JNE || L[1]->OPC == OP65_BNE)   &&
323             L[1]->JumpTo != 0                                  &&
324             !CE_HasLabel (L[1])                                &&
325             L[2]->OPC == OP65_CMP                              &&
326             L[2]->AM == AM65_IMM                               &&
327             (L[2]->Flags & CEF_NUMARG) != 0                    &&
328             (L[3]->Info & OF_ZBRA) != 0                        &&
329             L[3]->JumpTo != 0                                  &&
330             (L[1]->JumpTo->Owner == L[3] || L[1]->JumpTo == L[3]->JumpTo));
331 }
332
333
334
335 /*****************************************************************************/
336 /*             Remove calls to the bool transformer subroutines              */
337 /*****************************************************************************/
338
339
340
341 static unsigned OptBoolTransforms (CodeSeg* S)
342 /* Try to remove the call to boolean transformer routines where the call is
343  * not really needed.
344  */
345 {
346     unsigned Changes = 0;
347
348     /* Walk over the entries */
349     unsigned I = 0;
350     while (I < CS_GetEntryCount (S)) {
351
352         CodeEntry* N;
353         cmp_t Cond;
354
355         /* Get next entry */
356         CodeEntry* E = CS_GetEntry (S, I);
357
358         /* Check for a boolean transformer */
359         if (E->OPC == OP65_JSR                           &&
360             (Cond = FindBoolCmpCond (E->Arg)) != CMP_INV &&
361             (N = CS_GetNextEntry (S, I)) != 0        &&
362             (N->Info & OF_ZBRA) != 0) {
363
364             /* Make the boolean transformer unnecessary by changing the
365              * the conditional jump to evaluate the condition flags that
366              * are set after the compare directly. Note: jeq jumps if
367              * the condition is not met, jne jumps if the condition is met.
368              * Invert the code if we jump on condition not met.
369              */
370             if (GetBranchCond (N->OPC) == BC_EQ) {
371                 /* Jumps if condition false, invert condition */
372                 Cond = CmpInvertTab [Cond];
373             }
374
375             /* Check if we can replace the code by something better */
376             ReplaceCmp (S, I+1, Cond);
377
378             /* Remove the call to the bool transformer */
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     /* Return the number of changes made */
392     return Changes;
393 }
394
395
396
397 /*****************************************************************************/
398 /*                           Optimize subtractions                           */
399 /*****************************************************************************/
400
401
402
403 static unsigned OptSub1 (CodeSeg* S)
404 /* Search for the sequence
405  *
406  *      sbc     ...
407  *      bcs     L
408  *      dex
409  * L:
410  *
411  * and remove the handling of the high byte if X is not used later.
412  */
413 {
414     unsigned Changes = 0;
415
416     /* Walk over the entries */
417     unsigned I = 0;
418     while (I < CS_GetEntryCount (S)) {
419
420         CodeEntry* L[3];
421
422         /* Get next entry */
423         CodeEntry* E = CS_GetEntry (S, I);
424
425         /* Check for the sequence */
426         if (E->OPC == OP65_SBC                               &&
427             CS_GetEntries (S, L, I+1, 3)                     &&
428             (L[0]->OPC == OP65_BCS || L[0]->OPC == OP65_JCS) &&
429             L[0]->JumpTo != 0                                &&
430             !CE_HasLabel (L[0])                              &&
431             L[1]->OPC == OP65_DEX                            &&
432             !CE_HasLabel (L[1])                              &&
433             L[0]->JumpTo->Owner == L[2]                      &&
434             !RegXUsed (S, I+3)) {
435
436             /* Remove the bcs/dex */
437             CS_DelEntries (S, I+1, 2);
438
439             /* Remember, we had changes */
440             ++Changes;
441
442         }
443
444         /* Next entry */
445         ++I;
446
447     }
448
449     /* Return the number of changes made */
450     return Changes;
451 }
452
453
454
455 static unsigned OptSub2 (CodeSeg* S)
456 /* Search for the sequence
457  *
458  *      lda     xx
459  *      sec
460  *      sta     tmp1
461  *      lda     yy
462  *      sbc     tmp1
463  *      sta     yy
464  *
465  * and replace it by
466  *
467  *      sec
468  *      lda     yy
469  *      sbc     xx
470  *      sta     yy
471  */
472 {
473     unsigned Changes = 0;
474
475     /* Walk over the entries */
476     unsigned I = 0;
477     while (I < CS_GetEntryCount (S)) {
478
479         CodeEntry* L[5];
480
481         /* Get next entry */
482         CodeEntry* E = CS_GetEntry (S, I);
483
484         /* Check for the sequence */
485         if (E->OPC == OP65_LDA                             &&
486             CS_GetEntries (S, L, I+1, 5)                   &&
487             L[0]->OPC == OP65_SEC                          &&
488             !CE_HasLabel (L[0])                            &&
489             L[1]->OPC == OP65_STA                          &&
490             strcmp (L[1]->Arg, "tmp1") == 0                &&
491             !CE_HasLabel (L[1])                            &&
492             L[2]->OPC == OP65_LDA                          &&
493             !CE_HasLabel (L[2])                            &&
494             L[3]->OPC == OP65_SBC                          &&
495             strcmp (L[3]->Arg, "tmp1") == 0                &&
496             !CE_HasLabel (L[3])                            &&
497             L[4]->OPC == OP65_STA                          &&
498             strcmp (L[4]->Arg, L[2]->Arg) == 0             &&
499             !CE_HasLabel (L[4])) {
500
501             /* Remove the store to tmp1 */
502             CS_DelEntry (S, I+2);
503
504             /* Remove the subtraction */
505             CS_DelEntry (S, I+3);
506
507             /* Move the lda to the position of the subtraction and change the
508              * op to SBC.
509              */
510             CS_MoveEntry (S, I, I+3);
511             CE_ReplaceOPC (E, OP65_SBC);
512
513             /* If the sequence head had a label, move this label back to the
514              * head.
515              */
516             if (CE_HasLabel (E)) {
517                 CS_MoveLabels (S, E, L[0]);
518             }
519
520             /* Remember, we had changes */
521             ++Changes;
522
523         }
524
525         /* Next entry */
526         ++I;
527
528     }
529
530     /* Return the number of changes made */
531     return Changes;
532 }
533
534
535
536 /*****************************************************************************/
537 /*                            Optimize additions                             */
538 /*****************************************************************************/
539
540
541
542 static unsigned OptAdd1 (CodeSeg* S)
543 /* Search for the sequence
544  *
545  *      jsr     pushax
546  *      ldy     xxx
547  *      ldx     #$00
548  *      lda     (sp),y
549  *      jsr     tosaddax
550  *
551  * and replace it by:
552  *
553  *      ldy     xxx
554  *      clc
555  *      adc     (sp),y
556  *      bcc     L
557  *      inx
558  * L:
559  */
560 {
561     unsigned Changes = 0;
562
563     /* Walk over the entries */
564     unsigned I = 0;
565     while (I < CS_GetEntryCount (S)) {
566
567         CodeEntry* L[5];
568
569         /* Get next entry */
570         CodeEntry* E = CS_GetEntry (S, I);
571
572         /* Check for the sequence */
573         if (E->OPC == OP65_JSR                               &&
574             strcmp (E->Arg, "pushax") == 0                   &&
575             CS_GetEntries (S, L, I+1, 5)                     &&
576             L[0]->OPC == OP65_LDY                            &&
577             !CE_HasLabel (L[0])                              &&
578             L[1]->OPC == OP65_LDX                            &&
579             CE_KnownImm (L[1])                               &&
580             L[1]->Num == 0                                   &&
581             !CE_HasLabel (L[1])                              &&
582             L[2]->OPC == OP65_LDA                            &&
583             !CE_HasLabel (L[2])                              &&
584             L[3]->OPC == OP65_JSR                            &&
585             strcmp (L[3]->Arg, "tosaddax") == 0              &&
586             !CE_HasLabel (L[3])) {
587
588             CodeEntry* X;
589             CodeLabel* Label;
590
591             /* Remove the call to pushax */
592             CS_DelEntry (S, I);
593
594             /* Add the clc . */
595             X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, L[3]->LI);
596             CS_InsertEntry (S, X, I+1);
597
598             /* Remove the load */
599             CS_DelEntry (S, I+3);      /* lda */
600             CS_DelEntry (S, I+2);      /* ldx */
601
602             /* Add the adc */
603             X = NewCodeEntry (OP65_ADC, AM65_ZP_INDY, "sp", 0, L[3]->LI);
604             CS_InsertEntry (S, X, I+2);
605
606             /* Generate the branch label and the branch */
607             Label = CS_GenLabel (S, L[4]);
608             X = NewCodeEntry (OP65_BCC, AM65_BRA, Label->Name, Label, L[3]->LI);
609             CS_InsertEntry (S, X, I+3);
610
611             /* Generate the increment of the high byte */
612             X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, L[3]->LI);
613             CS_InsertEntry (S, X, I+4);
614
615             /* Delete the call to tosaddax */
616             CS_DelEntry (S, I+5);
617
618             /* Remember, we had changes */
619             ++Changes;
620
621         }
622
623         /* Next entry */
624         ++I;
625
626     }
627
628     /* Return the number of changes made */
629     return Changes;
630 }
631
632
633
634 static unsigned OptAdd2 (CodeSeg* S)
635 /* Search for the sequence
636  *
637  *      adc     ...
638  *      bcc     L
639  *      inx
640  * L:
641  *
642  * and remove the handling of the high byte if X is not used later.
643  */
644 {
645     unsigned Changes = 0;
646
647     /* Walk over the entries */
648     unsigned I = 0;
649     while (I < CS_GetEntryCount (S)) {
650
651         CodeEntry* L[3];
652
653         /* Get next entry */
654         CodeEntry* E = CS_GetEntry (S, I);
655
656         /* Check for the sequence */
657         if (E->OPC == OP65_ADC                               &&
658             CS_GetEntries (S, L, I+1, 3)                     &&
659             (L[0]->OPC == OP65_BCC || L[0]->OPC == OP65_JCC) &&
660             L[0]->JumpTo != 0                                &&
661             !CE_HasLabel (L[0])                              &&
662             L[1]->OPC == OP65_INX                            &&
663             !CE_HasLabel (L[1])                              &&
664             L[0]->JumpTo->Owner == L[2]                      &&
665             !RegXUsed (S, I+3)) {
666
667             /* Remove the bcs/dex */
668             CS_DelEntries (S, I+1, 2);
669
670             /* Remember, we had changes */
671             ++Changes;
672
673         }
674
675         /* Next entry */
676         ++I;
677
678     }
679
680     /* Return the number of changes made */
681     return Changes;
682 }
683
684
685
686 /*****************************************************************************/
687 /*                        Optimizations for compares                         */
688 /*****************************************************************************/
689
690
691
692 static unsigned OptCmp1 (CodeSeg* S)
693 /* Search for the sequence
694  *
695  *      stx     xx
696  *      stx     tmp1
697  *      ora     tmp1
698  *
699  * and replace it by
700  *
701  *      stx     xx
702  *      ora     xx
703  */
704 {
705     unsigned Changes = 0;
706
707     /* Walk over the entries */
708     unsigned I = 0;
709     while (I < CS_GetEntryCount (S)) {
710
711         CodeEntry* L[2];
712
713         /* Get next entry */
714         CodeEntry* E = CS_GetEntry (S, I);
715
716         /* Check for the sequence */
717         if (E->OPC == OP65_STX                  &&
718             CS_GetEntries (S, L, I+1, 2)        &&
719             L[0]->OPC == OP65_STX               &&
720             strcmp (L[0]->Arg, "tmp1") == 0     &&
721             !CE_HasLabel (L[0])                 &&
722             L[1]->OPC == OP65_ORA               &&
723             strcmp (L[1]->Arg, "tmp1") == 0     &&
724             !CE_HasLabel (L[1])) {
725
726             /* Remove the remaining instructions */
727             CS_DelEntries (S, I+1, 2);
728
729             /* Insert the ora instead */
730             CS_InsertEntry (S, NewCodeEntry (OP65_ORA, E->AM, E->Arg, 0, E->LI), I+1);
731
732             /* Remember, we had changes */
733             ++Changes;
734
735         }
736
737         /* Next entry */
738         ++I;
739
740     }
741
742     /* Return the number of changes made */
743     return Changes;
744 }
745
746
747
748 static unsigned OptCmp2 (CodeSeg* S)
749 /* Search for
750  *
751  *      lda/and/ora/eor ...
752  *      cmp #$00
753  *      jeq/jne
754  *
755  * and remove the cmp.
756  */
757 {
758     unsigned Changes = 0;
759
760     /* Walk over the entries */
761     unsigned I = 0;
762     while (I < CS_GetEntryCount (S)) {
763
764         CodeEntry* L[2];
765
766         /* Get next entry */
767         CodeEntry* E = CS_GetEntry (S, I);
768
769         /* Check for the sequence */
770         if ((E->OPC == OP65_ADC ||
771              E->OPC == OP65_AND ||
772              E->OPC == OP65_DEA ||
773              E->OPC == OP65_EOR ||
774              E->OPC == OP65_INA ||
775              E->OPC == OP65_LDA ||
776              E->OPC == OP65_ORA ||
777              E->OPC == OP65_PLA ||
778              E->OPC == OP65_SBC ||
779              E->OPC == OP65_TXA ||
780              E->OPC == OP65_TYA)                  &&
781             CS_GetEntries (S, L, I+1, 2)          &&
782             IsCmpToZero (L[0])                    &&
783             !CE_HasLabel (L[0])                   &&
784             (L[1]->Info & OF_FBRA) != 0           &&
785             !CE_HasLabel (L[1])) {
786
787             /* Remove the compare */
788             CS_DelEntry (S, I+1);
789
790             /* Remember, we had changes */
791             ++Changes;
792
793         }
794
795         /* Next entry */
796         ++I;
797
798     }
799
800     /* Return the number of changes made */
801     return Changes;
802 }
803
804
805
806 static unsigned OptCmp3 (CodeSeg* S)
807 /* Search for
808  *
809  *      lda     x
810  *      ldx     y
811  *      cpx     #a
812  *      bne     L1
813  *      cmp     #b
814  *      jne/jeq L2
815  *
816  * If a is zero, we may remove the compare. If a and b are both zero, we may
817  * replace it by the sequence
818  *
819  *      lda     x
820  *      ora     x+1
821  *      jne/jeq ...
822  *
823  * L1 may be either the label at the branch instruction, or the target label
824  * of this instruction.
825  */
826 {
827     unsigned Changes = 0;
828
829     /* Walk over the entries */
830     unsigned I = 0;
831     while (I < CS_GetEntryCount (S)) {
832
833         CodeEntry* L[5];
834
835         /* Get next entry */
836         CodeEntry* E = CS_GetEntry (S, I);
837
838         /* Check for the sequence */
839         if (E->OPC == OP65_LDA               &&
840             CS_GetEntries (S, L, I+1, 5) &&
841             L[0]->OPC == OP65_LDX            &&
842             !CE_HasLabel (L[0])              &&
843             IsImmCmp16 (S, L+1)) {
844
845             if (L[1]->Num == 0 && L[3]->Num == 0) {
846                 /* The value is zero, we may use the simple code version. */
847                 CE_ReplaceOPC (L[0], OP65_ORA);
848                 CS_DelEntries (S, I+2, 3);
849             } else {
850                 /* Move the lda instruction after the first branch. This will
851                  * improve speed, since the load is delayed after the first
852                  * test.
853                  */
854                 CS_MoveEntry (S, I, I+4);
855
856                 /* We will replace the ldx/cpx by lda/cmp */
857                 CE_ReplaceOPC (L[0], OP65_LDA);
858                 CE_ReplaceOPC (L[1], OP65_CMP);
859
860                 /* Beware: If the first LDA instruction had a label, we have
861                  * to move this label to the top of the sequence again.
862                  */
863                 if (CE_HasLabel (E)) {
864                     CS_MoveLabels (S, E, L[0]);
865                 }
866
867             }
868
869             ++Changes;
870         }
871
872         /* Next entry */
873         ++I;
874
875     }
876
877     /* Return the number of changes made */
878     return Changes;
879 }
880
881
882
883 static unsigned OptCmp4 (CodeSeg* S)
884 /* Optimize compares of local variables:
885  *
886  *      ldy     #o
887  *      lda     (sp),y
888  *      tax
889  *      dey
890  *      lda     (sp),y
891  *      cpx     #a
892  *      bne     L1
893  *      cmp     #b
894  *      jne/jeq L2
895  */
896 {
897     unsigned Changes = 0;
898
899     /* Walk over the entries */
900     unsigned I = 0;
901     while (I < CS_GetEntryCount (S)) {
902
903         CodeEntry* L[9];
904
905         /* Check for the sequence */
906         if (IsLocalLoad16 (S, I, L, 9) && IsImmCmp16 (S, L+5)) {
907
908             if (L[5]->Num == 0 && L[7]->Num == 0) {
909
910                 /* The value is zero, we may use the simple code version:
911                  *      ldy     #o
912                  *      lda     (sp),y
913                  *      dey
914                  *      ora     (sp),y
915                  *      jne/jeq ...
916                  */
917                 CE_ReplaceOPC (L[4], OP65_ORA);
918                 CS_DelEntries (S, I+5, 3);   /* cpx/bne/cmp */
919                 CS_DelEntry (S, I+2);        /* tax */
920
921             } else {
922
923                 /* Change the code to just use the A register. Move the load
924                  * of the low byte after the first branch if possible:
925                  *
926                  *      ldy     #o
927                  *      lda     (sp),y
928                  *      cmp     #a
929                  *      bne     L1
930                  *      dey
931                  *      lda     (sp),y
932                  *      cmp     #b
933                  *      jne/jeq ...
934                  */
935                 CS_DelEntry (S, I+2);             /* tax */
936                 CE_ReplaceOPC (L[5], OP65_CMP);   /* cpx -> cmp */
937                 CS_MoveEntry (S, I+4, I+2);       /* cmp */
938                 CS_MoveEntry (S, I+5, I+3);       /* bne */
939
940             }
941
942             ++Changes;
943         }
944
945         /* Next entry */
946         ++I;
947
948     }
949
950     /* Return the number of changes made */
951     return Changes;
952 }
953
954
955
956 static unsigned OptCmp5 (CodeSeg* S)
957 /* Search for calls to compare subroutines followed by a conditional branch
958  * and replace them by cheaper versions, since the branch means that the
959  * boolean value returned by these routines is not needed (we may also check
960  * that explicitly, but for the current code generator it is always true).
961  */
962 {
963     unsigned Changes = 0;
964
965     /* Walk over the entries */
966     unsigned I = 0;
967     while (I < CS_GetEntryCount (S)) {
968
969         CodeEntry* N;
970         cmp_t Cond;
971
972         /* Get next entry */
973         CodeEntry* E = CS_GetEntry (S, I);
974
975         /* Check for the sequence */
976         if (E->OPC == OP65_JSR                          &&
977             (Cond = FindTosCmpCond (E->Arg)) != CMP_INV &&
978             (N = CS_GetNextEntry (S, I)) != 0           &&
979             (N->Info & OF_ZBRA) != 0                    &&
980             !CE_HasLabel (N)) {
981
982             /* The tos... functions will return a boolean value in a/x and
983              * the Z flag says if this value is zero or not. We will call
984              * a cheaper subroutine instead, one that does not return a
985              * boolean value but only valid flags. Note: jeq jumps if
986              * the condition is not met, jne jumps if the condition is met.
987              * Invert the code if we jump on condition not met.
988              */
989             if (GetBranchCond (N->OPC) == BC_EQ) {
990                 /* Jumps if condition false, invert condition */
991                 Cond = CmpInvertTab [Cond];
992             }
993
994             /* Replace the subroutine call. */
995             E = NewCodeEntry (OP65_JSR, AM65_ABS, "tosicmp", 0, E->LI);
996             CS_InsertEntry (S, E, I+1);
997             CS_DelEntry (S, I);
998
999             /* Replace the conditional branch */
1000             ReplaceCmp (S, I+1, Cond);
1001
1002             /* Remember, we had changes */
1003             ++Changes;
1004
1005         }
1006
1007         /* Next entry */
1008         ++I;
1009
1010     }
1011
1012     /* Return the number of changes made */
1013     return Changes;
1014 }
1015
1016
1017
1018 static unsigned OptCmp6 (CodeSeg* S)
1019 /* Search for a sequence ldx/txa/branch and remove the txa if A is not
1020  * used later.
1021  */
1022 {
1023     unsigned Changes = 0;
1024
1025     /* Walk over the entries */
1026     unsigned I = 0;
1027     while (I < CS_GetEntryCount (S)) {
1028
1029         CodeEntry* L[2];
1030
1031         /* Get next entry */
1032         CodeEntry* E = CS_GetEntry (S, I);
1033
1034         /* Check for the sequence */
1035         if ((E->OPC == OP65_LDX || E->OPC == OP65_TAX)  &&
1036             CS_GetEntries (S, L, I+1, 2)                &&
1037             L[0]->OPC == OP65_TXA                       &&
1038             !CE_HasLabel (L[0])                         &&
1039             (L[1]->Info & OF_FBRA) != 0                 &&
1040             !CE_HasLabel (L[1])                         &&
1041             !RegAUsed (S, I+3)) {
1042
1043             /* Remove the txa */
1044             CS_DelEntry (S, I+1);
1045
1046             /* Remember, we had changes */
1047             ++Changes;
1048
1049         }
1050
1051         /* Next entry */
1052         ++I;
1053
1054     }
1055
1056     /* Return the number of changes made */
1057     return Changes;
1058 }
1059
1060
1061
1062 /*****************************************************************************/
1063 /*                              Optimize tests                               */
1064 /*****************************************************************************/
1065
1066
1067
1068 static unsigned OptTest1 (CodeSeg* S)
1069 /* On a sequence
1070  *
1071  *     stx     xxx
1072  *     ora     xxx
1073  *     beq/bne ...
1074  *
1075  * if X is zero, the sequence may be changed
1076  *
1077  *     cmp     #$00
1078  *     beq/bne ...
1079  *
1080  * which may be optimized further by another step.
1081  */
1082 {
1083     unsigned Changes = 0;
1084     unsigned I;
1085
1086     /* Generate register info for this step */
1087     CS_GenRegInfo (S);
1088
1089     /* Walk over the entries */
1090     I = 0;
1091     while (I < CS_GetEntryCount (S)) {
1092
1093         CodeEntry* L[3];
1094
1095         /* Get next entry */
1096         L[0] = CS_GetEntry (S, I);
1097
1098         /* Check if it's the sequence we're searching for */
1099         if (L[0]->OPC == OP65_STX              &&
1100             L[0]->RI->In.RegX == 0             &&
1101             CS_GetEntries (S, L+1, I+1, 2)     &&
1102             !CE_HasLabel (L[1])                &&
1103             L[1]->OPC == OP65_ORA              &&
1104             strcmp (L[0]->Arg, L[1]->Arg) == 0 &&
1105             !CE_HasLabel (L[2])                &&
1106             (L[2]->Info & OF_ZBRA) != 0) {
1107
1108             /* Insert the compare */
1109             CodeEntry* N = NewCodeEntry (OP65_CMP, AM65_IMM, "$00", 0, L[0]->LI);
1110             CS_InsertEntry (S, N, I+2);
1111
1112             /* Remove the two other insns */
1113             CS_DelEntry (S, I+1);
1114             CS_DelEntry (S, I);
1115
1116             /* We had changes */
1117             ++Changes;
1118         }
1119
1120         /* Next entry */
1121         ++I;
1122
1123     }
1124
1125     /* Free register info */
1126     CS_FreeRegInfo (S);
1127
1128     /* Return the number of changes made */
1129     return Changes;
1130 }
1131
1132
1133
1134
1135
1136
1137
1138 /*****************************************************************************/
1139 /*                            nega optimizations                             */
1140 /*****************************************************************************/
1141
1142
1143
1144 static unsigned OptNegA1 (CodeSeg* S)
1145 /* Check for
1146  *
1147  *      ldx     #$00
1148  *      lda     ..
1149  *      jsr     bnega
1150  *
1151  * Remove the ldx if the lda does not use it.
1152  */
1153 {
1154     unsigned Changes = 0;
1155
1156     /* Walk over the entries */
1157     unsigned I = 0;
1158     while (I < CS_GetEntryCount (S)) {
1159
1160         CodeEntry* L[2];
1161
1162         /* Get next entry */
1163         CodeEntry* E = CS_GetEntry (S, I);
1164
1165         /* Check for a ldx */
1166         if (E->OPC == OP65_LDX                  &&
1167             E->AM == AM65_IMM                   &&
1168             (E->Flags & CEF_NUMARG) != 0        &&
1169             E->Num == 0                         &&
1170             CS_GetEntries (S, L, I+1, 2)        &&
1171             L[0]->OPC == OP65_LDA               &&
1172             (L[0]->Use & REG_X) == 0            &&
1173             !CE_HasLabel (L[0])                 &&
1174             L[1]->OPC == OP65_JSR               &&
1175             strcmp (L[1]->Arg, "bnega") == 0    &&
1176             !CE_HasLabel (L[1])) {
1177
1178             /* Remove the ldx instruction */
1179             CS_DelEntry (S, I);
1180
1181             /* Remember, we had changes */
1182             ++Changes;
1183
1184         }
1185
1186         /* Next entry */
1187         ++I;
1188
1189     }
1190
1191     /* Return the number of changes made */
1192     return Changes;
1193 }
1194
1195
1196
1197 static unsigned OptNegA2 (CodeSeg* S)
1198 /* Check for
1199  *
1200  *      lda     ..
1201  *      jsr     bnega
1202  *      jeq/jne ..
1203  *
1204  * Adjust the conditional branch and remove the call to the subroutine.
1205  */
1206 {
1207     unsigned Changes = 0;
1208
1209     /* Walk over the entries */
1210     unsigned I = 0;
1211     while (I < CS_GetEntryCount (S)) {
1212
1213         CodeEntry* L[2];
1214
1215         /* Get next entry */
1216         CodeEntry* E = CS_GetEntry (S, I);
1217
1218         /* Check for the sequence */
1219         if ((E->OPC == OP65_ADC ||
1220              E->OPC == OP65_AND ||
1221              E->OPC == OP65_DEA ||
1222              E->OPC == OP65_EOR ||
1223              E->OPC == OP65_INA ||
1224              E->OPC == OP65_LDA ||
1225              E->OPC == OP65_ORA ||
1226              E->OPC == OP65_PLA ||
1227              E->OPC == OP65_SBC ||
1228              E->OPC == OP65_TXA ||
1229              E->OPC == OP65_TYA)                &&
1230             CS_GetEntries (S, L, I+1, 2)        &&
1231             L[0]->OPC == OP65_JSR               &&
1232             strcmp (L[0]->Arg, "bnega") == 0    &&
1233             !CE_HasLabel (L[0])                 &&
1234             (L[1]->Info & OF_ZBRA) != 0         &&
1235             !CE_HasLabel (L[1])) {
1236
1237             /* Invert the branch */
1238             CE_ReplaceOPC (L[1], GetInverseBranch (L[1]->OPC));
1239
1240             /* Delete the subroutine call */
1241             CS_DelEntry (S, I+1);
1242
1243             /* Remember, we had changes */
1244             ++Changes;
1245
1246         }
1247
1248         /* Next entry */
1249         ++I;
1250
1251     }
1252
1253     /* Return the number of changes made */
1254     return Changes;
1255 }
1256
1257
1258
1259 /*****************************************************************************/
1260 /*                            negax optimizations                            */
1261 /*****************************************************************************/
1262
1263
1264
1265 static unsigned OptNegAX1 (CodeSeg* S)
1266 /* On a call to bnegax, if X is zero, the result depends only on the value in
1267  * A, so change the call to a call to bnega. This will get further optimized
1268  * later if possible.
1269  */
1270 {
1271     unsigned Changes = 0;
1272     unsigned I;
1273
1274     /* Generate register info for this step */
1275     CS_GenRegInfo (S);
1276
1277     /* Walk over the entries */
1278     I = 0;
1279     while (I < CS_GetEntryCount (S)) {
1280
1281         /* Get next entry */
1282         CodeEntry* E = CS_GetEntry (S, I);
1283
1284         /* Check if this is a call to bnegax, and if X is known and zero */
1285         if (E->OPC == OP65_JSR              &&
1286             E->RI->In.RegX == 0             &&
1287             strcmp (E->Arg, "bnegax") == 0) {
1288
1289             /* We're cheating somewhat here ... */
1290             E->Arg[5] = '\0';
1291             E->Use &= ~REG_X;
1292
1293             /* We had changes */
1294             ++Changes;
1295         }
1296
1297         /* Next entry */
1298         ++I;
1299
1300     }
1301
1302     /* Free register info */
1303     CS_FreeRegInfo (S);
1304
1305     /* Return the number of changes made */
1306     return Changes;
1307 }
1308
1309
1310
1311 static unsigned OptNegAX2 (CodeSeg* S)
1312 /* Search for the sequence:
1313  *
1314  *      lda     (xx),y
1315  *      tax
1316  *      dey
1317  *      lda     (xx),y
1318  *      jsr     bnegax
1319  *      jne/jeq ...
1320  *
1321  * and replace it by
1322  *
1323  *      lda     (xx),y
1324  *      dey
1325  *      ora     (xx),y
1326  *      jeq/jne ...
1327  */
1328 {
1329     unsigned Changes = 0;
1330
1331     /* Walk over the entries */
1332     unsigned I = 0;
1333     while (I < CS_GetEntryCount (S)) {
1334
1335         CodeEntry* L[5];
1336
1337         /* Get next entry */
1338         CodeEntry* E = CS_GetEntry (S, I);
1339
1340         /* Check for the sequence */
1341         if (E->OPC == OP65_LDA                  &&
1342             E->AM == AM65_ZP_INDY               &&
1343             CS_GetEntries (S, L, I+1, 5)        &&
1344             L[0]->OPC == OP65_TAX               &&
1345             L[1]->OPC == OP65_DEY               &&
1346             L[2]->OPC == OP65_LDA               &&
1347             L[2]->AM == AM65_ZP_INDY            &&
1348             strcmp (L[2]->Arg, E->Arg) == 0     &&
1349             !CE_HasLabel (L[2])                 &&
1350             L[3]->OPC == OP65_JSR               &&
1351             strcmp (L[3]->Arg, "bnegax") == 0   &&
1352             !CE_HasLabel (L[3])                 &&
1353             (L[4]->Info & OF_ZBRA) != 0         &&
1354             !CE_HasLabel (L[4])) {
1355
1356             /* lda --> ora */
1357             CE_ReplaceOPC (L[2], OP65_ORA);
1358
1359             /* Invert the branch */
1360             CE_ReplaceOPC (L[4], GetInverseBranch (L[4]->OPC));
1361
1362             /* Delete the entries no longer needed. Beware: Deleting entries
1363              * will change the indices.
1364              */
1365             CS_DelEntry (S, I+4);               /* jsr bnegax */
1366             CS_DelEntry (S, I+1);               /* tax */
1367
1368             /* Remember, we had changes */
1369             ++Changes;
1370
1371         }
1372
1373         /* Next entry */
1374         ++I;
1375
1376     }
1377
1378     /* Return the number of changes made */
1379     return Changes;
1380 }
1381
1382
1383
1384 static unsigned OptNegAX3 (CodeSeg* S)
1385 /* Search for the sequence:
1386  *
1387  *      lda     xx
1388  *      ldx     yy
1389  *      jsr     bnegax
1390  *      jne/jeq ...
1391  *
1392  * and replace it by
1393  *
1394  *      lda     xx
1395  *      ora     xx+1
1396  *      jeq/jne ...
1397  */
1398 {
1399     unsigned Changes = 0;
1400
1401     /* Walk over the entries */
1402     unsigned I = 0;
1403     while (I < CS_GetEntryCount (S)) {
1404
1405         CodeEntry* L[3];
1406
1407         /* Get next entry */
1408         CodeEntry* E = CS_GetEntry (S, I);
1409
1410         /* Check for the sequence */
1411         if (E->OPC == OP65_LDA                  &&
1412             CS_GetEntries (S, L, I+1, 3)        &&
1413             L[0]->OPC == OP65_LDX               &&
1414             !CE_HasLabel (L[0])                 &&
1415             L[1]->OPC == OP65_JSR               &&
1416             strcmp (L[1]->Arg, "bnegax") == 0   &&
1417             !CE_HasLabel (L[1])                 &&
1418             (L[2]->Info & OF_ZBRA) != 0         &&
1419             !CE_HasLabel (L[2])) {
1420
1421             /* ldx --> ora */
1422             CE_ReplaceOPC (L[0], OP65_ORA);
1423
1424             /* Invert the branch */
1425             CE_ReplaceOPC (L[2], GetInverseBranch (L[2]->OPC));
1426
1427             /* Delete the subroutine call */
1428             CS_DelEntry (S, I+2);
1429
1430             /* Remember, we had changes */
1431             ++Changes;
1432
1433         }
1434
1435         /* Next entry */
1436         ++I;
1437
1438     }
1439
1440     /* Return the number of changes made */
1441     return Changes;
1442 }
1443
1444
1445
1446 static unsigned OptNegAX4 (CodeSeg* S)
1447 /* Search for the sequence:
1448  *
1449  *      jsr     xxx
1450  *      jsr     bnega(x)
1451  *      jeq/jne ...
1452  *
1453  * and replace it by:
1454  *
1455  *      jsr     xxx
1456  *      <boolean test>
1457  *      jne/jeq ...
1458  */
1459 {
1460     unsigned Changes = 0;
1461
1462     /* Walk over the entries */
1463     unsigned I = 0;
1464     while (I < CS_GetEntryCount (S)) {
1465
1466         CodeEntry* L[2];
1467
1468         /* Get next entry */
1469         CodeEntry* E = CS_GetEntry (S, I);
1470
1471         /* Check for the sequence */
1472         if (E->OPC == OP65_JSR                  &&
1473             CS_GetEntries (S, L, I+1, 2)        &&
1474             L[0]->OPC == OP65_JSR               &&
1475             strncmp (L[0]->Arg,"bnega",5) == 0  &&
1476             !CE_HasLabel (L[0])                 &&
1477             (L[1]->Info & OF_ZBRA) != 0         &&
1478             !CE_HasLabel (L[1])) {
1479
1480             CodeEntry* X;
1481
1482             /* Check if we're calling bnega or bnegax */
1483             int ByteSized = (strcmp (L[0]->Arg, "bnega") == 0);
1484
1485             /* Insert apropriate test code */
1486             if (ByteSized) {
1487                 /* Test bytes */
1488                 X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[0]->LI);
1489                 CS_InsertEntry (S, X, I+2);
1490             } else {
1491                 /* Test words */
1492                 X = NewCodeEntry (OP65_STX, AM65_ZP, "tmp1", 0, L[0]->LI);
1493                 CS_InsertEntry (S, X, I+2);
1494                 X = NewCodeEntry (OP65_ORA, AM65_ZP, "tmp1", 0, L[0]->LI);
1495                 CS_InsertEntry (S, X, I+3);
1496             }
1497
1498             /* Delete the subroutine call */
1499             CS_DelEntry (S, I+1);
1500
1501             /* Invert the branch */
1502             CE_ReplaceOPC (L[1], GetInverseBranch (L[1]->OPC));
1503
1504             /* Remember, we had changes */
1505             ++Changes;
1506
1507         }
1508
1509         /* Next entry */
1510         ++I;
1511
1512     }
1513
1514     /* Return the number of changes made */
1515     return Changes;
1516 }
1517
1518
1519
1520 /*****************************************************************************/
1521 /*                     Optimize stores through pointers                      */
1522 /*****************************************************************************/
1523
1524
1525
1526 static unsigned OptPtrStore1Sub (CodeSeg* S, unsigned I, CodeEntry** const L)
1527 /* Check if this is one of the allowed suboperation for OptPtrStore1 */
1528 {
1529     /* Check for a label attached to the entry */
1530     if (CE_HasLabel (L[0])) {
1531         return 0;
1532     }
1533
1534     /* Check for single insn sub ops */
1535     if (L[0]->OPC == OP65_AND                                           ||
1536         L[0]->OPC == OP65_EOR                                           ||
1537         L[0]->OPC == OP65_ORA                                           ||
1538         (L[0]->OPC == OP65_JSR && strncmp (L[0]->Arg, "shlax", 5) == 0) ||
1539         (L[0]->OPC == OP65_JSR && strncmp (L[0]->Arg, "shrax", 5) == 0)) {
1540
1541         /* One insn */
1542         return 1;
1543
1544     } else if (L[0]->OPC == OP65_CLC                      &&
1545                (L[1] = CS_GetNextEntry (S, I)) != 0       &&
1546                L[1]->OPC == OP65_ADC                      &&
1547                !CE_HasLabel (L[1])) {
1548         return 2;
1549     } else if (L[0]->OPC == OP65_SEC                      &&
1550                (L[1] = CS_GetNextEntry (S, I)) != 0       &&
1551                L[1]->OPC == OP65_SBC                      &&
1552                !CE_HasLabel (L[1])) {
1553         return 2;
1554     }
1555
1556
1557
1558     /* Not found */
1559     return 0;
1560 }
1561
1562
1563
1564 static unsigned OptPtrStore1 (CodeSeg* S)
1565 /* Search for the sequence:
1566  *
1567  *      jsr     pushax
1568  *      ldy     xxx
1569  *      jsr     ldauidx
1570  *      subop
1571  *      ldy     yyy
1572  *      jsr     staspidx
1573  *
1574  * and replace it by:
1575  *
1576  *      sta     ptr1
1577  *      stx     ptr1+1
1578  *      ldy     xxx
1579  *      ldx     #$00
1580  *      lda     (ptr1),y
1581  *      subop
1582  *      ldy     yyy
1583  *      sta     (ptr1),y
1584  */
1585 {
1586     unsigned Changes = 0;
1587
1588     /* Walk over the entries */
1589     unsigned I = 0;
1590     while (I < CS_GetEntryCount (S)) {
1591
1592         unsigned K;
1593         CodeEntry* L[10];
1594
1595         /* Get next entry */
1596         L[0] = CS_GetEntry (S, I);
1597
1598         /* Check for the sequence */
1599         if (L[0]->OPC == OP65_JSR                   &&
1600             strcmp (L[0]->Arg, "pushax") == 0       &&
1601             CS_GetEntries (S, L+1, I+1, 3)          &&
1602             L[1]->OPC == OP65_LDY                   &&
1603             CE_KnownImm (L[1])                      &&
1604             !CE_HasLabel (L[1])                     &&
1605             L[2]->OPC == OP65_JSR                   &&
1606             strcmp (L[2]->Arg, "ldauidx") == 0      &&
1607             !CE_HasLabel (L[2])                     &&
1608             (K = OptPtrStore1Sub (S, I+3, L+3)) > 0 &&
1609             CS_GetEntries (S, L+3+K, I+3+K, 2)      &&
1610             L[3+K]->OPC == OP65_LDY                 &&
1611             CE_KnownImm (L[3+K])                    &&
1612             !CE_HasLabel (L[3+K])                   &&
1613             L[4+K]->OPC == OP65_JSR                 &&
1614             strcmp (L[4+K]->Arg, "staspidx") == 0   &&
1615             !CE_HasLabel (L[4+K])) {
1616
1617             CodeEntry* X;
1618
1619             /* Create and insert the stores */
1620             X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI);
1621             CS_InsertEntry (S, X, I+1);
1622
1623             X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI);
1624             CS_InsertEntry (S, X, I+2);
1625
1626             /* Delete the call to pushax */
1627             CS_DelEntry (S, I);
1628
1629             /* Delete the call to ldauidx */
1630             CS_DelEntry (S, I+3);
1631
1632             /* Insert the load from ptr1 */
1633             X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[3]->LI);
1634             CS_InsertEntry (S, X, I+3);
1635             X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[2]->LI);
1636             CS_InsertEntry (S, X, I+4);
1637
1638             /* Insert the store through ptr1 */
1639             X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, "ptr1", 0, L[3]->LI);
1640             CS_InsertEntry (S, X, I+6+K);
1641
1642             /* Delete the call to staspidx */
1643             CS_DelEntry (S, I+7+K);
1644
1645             /* Remember, we had changes */
1646             ++Changes;
1647
1648         }
1649
1650         /* Next entry */
1651         ++I;
1652
1653     }
1654
1655     /* Return the number of changes made */
1656     return Changes;
1657 }
1658
1659
1660
1661 static unsigned OptPtrStore2 (CodeSeg* S)
1662 /* Search for the sequence:
1663  *
1664  *      jsr     pushax
1665  *      lda     xxx
1666  *      ldy     yyy
1667  *      jsr     staspidx
1668  *
1669  * and replace it by:
1670  *
1671  *      sta     ptr1
1672  *      stx     ptr1+1
1673  *      lda     xxx
1674  *      ldy     yyy
1675  *      sta     (ptr1),y
1676  */
1677 {
1678     unsigned Changes = 0;
1679
1680     /* Walk over the entries */
1681     unsigned I = 0;
1682     while (I < CS_GetEntryCount (S)) {
1683
1684         CodeEntry* L[4];
1685
1686         /* Get next entry */
1687         L[0] = CS_GetEntry (S, I);
1688
1689         /* Check for the sequence */
1690         if (L[0]->OPC == OP65_JSR               &&
1691             strcmp (L[0]->Arg, "pushax") == 0   &&
1692             CS_GetEntries (S, L+1, I+1, 3)      &&
1693             L[1]->OPC == OP65_LDA               &&
1694             !CE_HasLabel (L[1])                 &&
1695             L[2]->OPC == OP65_LDY               &&
1696             !CE_HasLabel (L[2])                 &&
1697             L[3]->OPC == OP65_JSR               &&
1698             strcmp (L[3]->Arg, "staspidx") == 0 &&
1699             !CE_HasLabel (L[3])) {
1700
1701             CodeEntry* X;
1702
1703             /* Create and insert the stores */
1704             X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI);
1705             CS_InsertEntry (S, X, I+1);
1706
1707             X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI);
1708             CS_InsertEntry (S, X, I+2);
1709
1710             /* Delete the call to pushax */
1711             CS_DelEntry (S, I);
1712
1713             /* Insert the store through ptr1 */
1714             X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, "ptr1", 0, L[3]->LI);
1715             CS_InsertEntry (S, X, I+4);
1716
1717             /* Delete the call to staspidx */
1718             CS_DelEntry (S, I+5);
1719
1720             /* Remember, we had changes */
1721             ++Changes;
1722
1723         }
1724
1725         /* Next entry */
1726         ++I;
1727
1728     }
1729
1730     /* Return the number of changes made */
1731     return Changes;
1732 }
1733
1734
1735
1736 /*****************************************************************************/
1737 /*                      Optimize loads through pointers                      */
1738 /*****************************************************************************/
1739
1740
1741
1742 static unsigned OptPtrLoad1 (CodeSeg* S)
1743 /* Search for the sequence:
1744  *
1745  *      tax
1746  *      dey
1747  *      lda     (sp),y             # May be any destination
1748  *      ldy     ...
1749  *      jsr     ldauidx
1750  *
1751  * and replace it by:
1752  *
1753  *      sta     ptr1+1
1754  *      dey
1755  *      lda     (sp),y
1756  *      sta     ptr1
1757  *      ldy     ...
1758  *      ldx     #$00
1759  *      lda     (ptr1),y
1760  */
1761 {
1762     unsigned Changes = 0;
1763
1764     /* Walk over the entries */
1765     unsigned I = 0;
1766     while (I < CS_GetEntryCount (S)) {
1767
1768         CodeEntry* L[5];
1769
1770         /* Get next entry */
1771         L[0] = CS_GetEntry (S, I);
1772
1773         /* Check for the sequence */
1774         if (L[0]->OPC == OP65_TAX               &&
1775             CS_GetEntries (S, L+1, I+1, 4)      &&
1776             L[1]->OPC == OP65_DEY               &&
1777             !CE_HasLabel (L[1])                 &&
1778             L[2]->OPC == OP65_LDA               &&
1779             !CE_HasLabel (L[2])                 &&
1780             L[3]->OPC == OP65_LDY               &&
1781             !CE_HasLabel (L[3])                 &&
1782             L[4]->OPC == OP65_JSR               &&
1783             strcmp (L[4]->Arg, "ldauidx") == 0  &&
1784             !CE_HasLabel (L[4])) {
1785
1786             CodeEntry* X;
1787
1788             /* Store the high byte and remove the TAX instead */
1789             X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1+1", 0, L[0]->LI);
1790             CS_InsertEntry (S, X, I+1);
1791             CS_DelEntry (S, I);
1792
1793             /* Store the low byte */
1794             X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[2]->LI);
1795             CS_InsertEntry (S, X, I+3);
1796
1797             /* Delete the call to ldauidx */
1798             CS_DelEntry (S, I+5);
1799
1800             /* Load high and low byte */
1801             X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[3]->LI);
1802             CS_InsertEntry (S, X, I+5);
1803             X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[3]->LI);
1804             CS_InsertEntry (S, X, I+6);
1805
1806             /* Remember, we had changes */
1807             ++Changes;
1808
1809         }
1810
1811         /* Next entry */
1812         ++I;
1813
1814     }
1815
1816     /* Return the number of changes made */
1817     return Changes;
1818 }
1819
1820
1821
1822 static unsigned OptPtrLoad2 (CodeSeg* S)
1823 /* Search for the sequence
1824  *
1825  *      ldy     ...
1826  *      jsr     ldauidx
1827  *
1828  * and replace it by:
1829  *
1830  *      ldy     ...
1831  *      stx     ptr1+1
1832  *      sta     ptr1
1833  *      ldx     #$00
1834  *      lda     (ptr1),y
1835  *
1836  * This step must be execute *after* OptPtrLoad1!
1837  */
1838 {
1839     unsigned Changes = 0;
1840
1841     /* Walk over the entries */
1842     unsigned I = 0;
1843     while (I < CS_GetEntryCount (S)) {
1844
1845         CodeEntry* L[2];
1846
1847         /* Get next entry */
1848         L[0] = CS_GetEntry (S, I);
1849
1850         /* Check for the sequence */
1851         if (L[0]->OPC == OP65_LDY               &&
1852             CS_GetEntries (S, L+1, I+1, 1)      &&
1853             L[1]->OPC == OP65_JSR               &&
1854             strcmp (L[1]->Arg, "ldauidx") == 0  &&
1855             !CE_HasLabel (L[1])) {
1856
1857             CodeEntry* X;
1858
1859             /* Store the high byte */
1860             X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI);
1861             CS_InsertEntry (S, X, I+1);
1862
1863             /* Store the low byte */
1864             X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI);
1865             CS_InsertEntry (S, X, I+2);
1866
1867             /* Delete the call to ldauidx */
1868             CS_DelEntry (S, I+3);
1869
1870             /* Load the high and low byte */
1871             X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[0]->LI);
1872             CS_InsertEntry (S, X, I+3);
1873             X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[0]->LI);
1874             CS_InsertEntry (S, X, I+4);
1875
1876             /* Remember, we had changes */
1877             ++Changes;
1878
1879         }
1880
1881         /* Next entry */
1882         ++I;
1883
1884     }
1885
1886     /* Return the number of changes made */
1887     return Changes;
1888 }
1889
1890
1891
1892 /*****************************************************************************/
1893 /*                                   Code                                    */
1894 /*****************************************************************************/
1895
1896
1897
1898 /* Types of optimization steps */
1899 enum {
1900     optPre,                     /* Repeated once */
1901     optPreMain,                 /* Repeated more than once */
1902     optMain,                    /* dito */
1903     optPostMain,                /* dito */
1904     optPost                     /* Repeated once */
1905 };
1906
1907 /* Table with all the optimization functions */
1908 typedef struct OptFunc OptFunc;
1909 struct OptFunc {
1910     unsigned        (*Func) (CodeSeg*); /* Optimizer function */
1911     const char*     Name;               /* Name of optimizer step */
1912     unsigned char   Type;               /* Type of this step */
1913     char            Disabled;           /* True if pass disabled */
1914 };
1915
1916 /* Macro that builds a table entry */
1917 #define OptEntry(func,type)     { func, #func, type, 0 }
1918
1919 /* Table with optimizer steps */
1920 static OptFunc OptFuncs [] = {
1921     /* Optimizes stores through pointers */
1922     OptEntry (OptPtrStore1, optPre),
1923     OptEntry (OptPtrStore2, optPre),
1924     /* Optimize loads through pointers */
1925     OptEntry (OptPtrLoad1, optMain),
1926     OptEntry (OptPtrLoad2, optMain),
1927     /* Optimize calls to nega */
1928     OptEntry (OptNegA1, optMain),
1929     OptEntry (OptNegA2, optMain),
1930     /* Optimize calls to negax */
1931     OptEntry (OptNegAX1, optPre),
1932     OptEntry (OptNegAX2, optPre),
1933     OptEntry (OptNegAX3, optPre),
1934     OptEntry (OptNegAX4, optPre),
1935     /* Optimize subtractions */
1936     OptEntry (OptSub1, optMain),
1937     OptEntry (OptSub2, optMain),
1938     /* Optimize additions */
1939     OptEntry (OptAdd1, optPre),
1940     OptEntry (OptAdd2, optMain),
1941     /* Optimize jump cascades */
1942     OptEntry (OptJumpCascades, optMain),
1943     /* Remove dead jumps */
1944     OptEntry (OptDeadJumps, optMain),
1945     /* Change jsr/rts to jmp */
1946     OptEntry (OptRTS, optMain),
1947     /* Remove dead code */
1948     OptEntry (OptDeadCode, optMain),
1949     /* Optimize jump targets */
1950     OptEntry (OptJumpTarget, optMain),
1951     /* Optimize conditional branches */
1952     OptEntry (OptCondBranches, optMain),
1953     /* Replace jumps to RTS by RTS */
1954     OptEntry (OptRTSJumps, optMain),
1955     /* Remove calls to the bool transformer subroutines */
1956     OptEntry (OptBoolTransforms, optMain),
1957     /* Optimize compares */
1958     OptEntry (OptCmp1, optMain),
1959     OptEntry (OptCmp2, optMain),
1960     OptEntry (OptCmp3, optMain),
1961     OptEntry (OptCmp4, optMain),
1962     OptEntry (OptCmp5, optMain),
1963     OptEntry (OptCmp6, optMain),
1964     /* Optimize tests */
1965     OptEntry (OptTest1, optMain),
1966     /* Remove unused loads */
1967     OptEntry (OptUnusedLoads, optMain),
1968     OptEntry (OptDuplicateLoads, optMain),
1969     OptEntry (OptStoreLoad, optMain),
1970     /* Optimize branch distance */
1971     OptEntry (OptBranchDist, optMain),
1972 };
1973
1974
1975
1976 static OptFunc* FindOptStep (const char* Name)
1977 /* Find an optimizer step by name in the table and return a pointer. Print an
1978  * error and call AbEnd if not found.
1979  */
1980 {
1981     unsigned I;
1982
1983     /* Run all optimization steps */
1984     for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
1985         if (strcmp (OptFuncs[I].Name, Name) == 0) {
1986             /* Found */
1987             return OptFuncs+I;
1988         }
1989     }
1990
1991     /* Not found */
1992     AbEnd ("Optimization step `%s' not found", Name);
1993     return 0;
1994 }
1995
1996
1997
1998 void DisableOpt (const char* Name)
1999 /* Disable the optimization with the given name */
2000 {
2001     if (strcmp (Name, "any") == 0) {
2002         unsigned I;
2003         for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
2004             OptFuncs[I].Disabled = 1;
2005         }
2006     } else {
2007         OptFunc* F = FindOptStep (Name);
2008         F->Disabled = 1;
2009     }
2010 }
2011
2012
2013
2014 void EnableOpt (const char* Name)
2015 /* Enable the optimization with the given name */
2016 {
2017     if (strcmp (Name, "any") == 0) {
2018         unsigned I;
2019         for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
2020             OptFuncs[I].Disabled = 0;
2021         }
2022     } else {
2023         OptFunc* F = FindOptStep (Name);
2024         F->Disabled = 0;
2025     }
2026 }
2027
2028
2029
2030 void ListOptSteps (FILE* F)
2031 /* List all optimization steps */
2032 {
2033     unsigned I;
2034     for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
2035         fprintf (F, "%s\n", OptFuncs[I].Name);
2036     }
2037 }
2038
2039
2040
2041 static void RepeatOptStep (CodeSeg* S, unsigned char Type, unsigned Max)
2042 /* Repeat the optimizer step of type Type at may Max times */
2043 {
2044     unsigned I;
2045     unsigned Pass = 0;
2046     unsigned OptChanges;
2047
2048     /* Repeat max times of until there are no more changes */
2049     do {
2050         /* Reset the number of changes */
2051         OptChanges = 0;
2052
2053         /* Keep the user hapy */
2054         Print (stdout, 1, "  Optimizer pass %u:\n", ++Pass);
2055
2056         /* Run all optimization steps */
2057         for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
2058
2059             /* Get the table entry */
2060             const OptFunc* F = OptFuncs + I;
2061
2062             /* Check if the type matches */
2063             if (F->Type != Type) {
2064                 /* Skip it */
2065                 continue;
2066             }
2067
2068             /* Print the name of the following optimizer step */
2069             Print (stdout, 1, "    %s:%*s", F->Name, (int) (30-strlen(F->Name)), "");
2070
2071             /* Check if the step is disabled */
2072             if (F->Disabled) {
2073                 Print (stdout, 1, "Disabled\n");
2074             } else {
2075                 unsigned Changes = F->Func (S);
2076                 OptChanges += Changes;
2077                 Print (stdout, 1, "%u Changes\n", Changes);
2078             }
2079         }
2080
2081     } while (--Max > 0 && OptChanges > 0);
2082 }
2083
2084
2085
2086 void RunOpt (CodeSeg* S)
2087 /* Run the optimizer */
2088 {
2089
2090     /* If we shouldn't run the optimizer, bail out */
2091     if (!Optimize) {
2092         return;
2093     }
2094
2095     /* Print the name of the function we are working on */
2096     if (S->Func) {
2097         Print (stdout, 1, "Running optimizer for function `%s'\n", S->Func->Name);
2098     } else {
2099         Print (stdout, 1, "Running optimizer for global code segment\n");
2100     }
2101
2102     /* Repeat all steps until there are no more changes */
2103     RepeatOptStep (S, optPre, 1);
2104     RepeatOptStep (S, optPreMain, 0xFFFF);
2105     RepeatOptStep (S, optMain, 0xFFFF);
2106     RepeatOptStep (S, optPostMain, 0xFFFF);
2107     RepeatOptStep (S, optPost, 1);
2108 }
2109
2110
2111