]> 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  *      adc     ...
546  *      bcc     L
547  *      inx
548  * L:
549  *
550  * and remove the handling of the high byte if X is not used later.
551  */
552 {
553     unsigned Changes = 0;
554
555     /* Walk over the entries */
556     unsigned I = 0;
557     while (I < CS_GetEntryCount (S)) {
558
559         CodeEntry* L[3];
560
561         /* Get next entry */
562         CodeEntry* E = CS_GetEntry (S, I);
563
564         /* Check for the sequence */
565         if (E->OPC == OP65_ADC                               &&
566             CS_GetEntries (S, L, I+1, 3)                     &&
567             (L[0]->OPC == OP65_BCC || L[0]->OPC == OP65_JCC) &&
568             L[0]->JumpTo != 0                                &&
569             !CE_HasLabel (L[0])                              &&
570             L[1]->OPC == OP65_INX                            &&
571             !CE_HasLabel (L[1])                              &&
572             L[0]->JumpTo->Owner == L[2]                      &&
573             !RegXUsed (S, I+3)) {
574
575             /* Remove the bcs/dex */
576             CS_DelEntries (S, I+1, 2);
577
578             /* Remember, we had changes */
579             ++Changes;
580
581         }
582
583         /* Next entry */
584         ++I;
585
586     }
587
588     /* Return the number of changes made */
589     return Changes;
590 }
591
592
593
594 /*****************************************************************************/
595 /*                        Optimizations for compares                         */
596 /*****************************************************************************/
597
598
599
600 static unsigned OptCmp1 (CodeSeg* S)
601 /* Search for the sequence
602  *
603  *      stx     xx
604  *      stx     tmp1
605  *      ora     tmp1
606  *
607  * and replace it by
608  *
609  *      stx     xx
610  *      ora     xx
611  */
612 {
613     unsigned Changes = 0;
614
615     /* Walk over the entries */
616     unsigned I = 0;
617     while (I < CS_GetEntryCount (S)) {
618
619         CodeEntry* L[2];
620
621         /* Get next entry */
622         CodeEntry* E = CS_GetEntry (S, I);
623
624         /* Check for the sequence */
625         if (E->OPC == OP65_STX                  &&
626             CS_GetEntries (S, L, I+1, 2)        &&
627             L[0]->OPC == OP65_STX               &&
628             strcmp (L[0]->Arg, "tmp1") == 0     &&
629             !CE_HasLabel (L[0])                 &&
630             L[1]->OPC == OP65_ORA               &&
631             strcmp (L[1]->Arg, "tmp1") == 0     &&
632             !CE_HasLabel (L[1])) {
633
634             /* Remove the remaining instructions */
635             CS_DelEntries (S, I+1, 2);
636
637             /* Insert the ora instead */
638             CS_InsertEntry (S, NewCodeEntry (OP65_ORA, E->AM, E->Arg, 0, E->LI), I+1);
639
640             /* Remember, we had changes */
641             ++Changes;
642
643         }
644
645         /* Next entry */
646         ++I;
647
648     }
649
650     /* Return the number of changes made */
651     return Changes;
652 }
653
654
655
656 static unsigned OptCmp2 (CodeSeg* S)
657 /* Search for
658  *
659  *      lda/and/ora/eor ...
660  *      cmp #$00
661  *      jeq/jne
662  *
663  * and remove the cmp.
664  */
665 {
666     unsigned Changes = 0;
667
668     /* Walk over the entries */
669     unsigned I = 0;
670     while (I < CS_GetEntryCount (S)) {
671
672         CodeEntry* L[2];
673
674         /* Get next entry */
675         CodeEntry* E = CS_GetEntry (S, I);
676
677         /* Check for the sequence */
678         if ((E->OPC == OP65_ADC ||
679              E->OPC == OP65_AND ||
680              E->OPC == OP65_DEA ||
681              E->OPC == OP65_EOR ||
682              E->OPC == OP65_INA ||
683              E->OPC == OP65_LDA ||
684              E->OPC == OP65_ORA ||
685              E->OPC == OP65_PLA ||
686              E->OPC == OP65_SBC ||
687              E->OPC == OP65_TXA ||
688              E->OPC == OP65_TYA)                  &&
689             CS_GetEntries (S, L, I+1, 2)          &&
690             IsCmpToZero (L[0])                    &&
691             !CE_HasLabel (L[0])                   &&
692             (L[1]->Info & OF_FBRA) != 0           &&
693             !CE_HasLabel (L[1])) {
694
695             /* Remove the compare */
696             CS_DelEntry (S, I+1);
697
698             /* Remember, we had changes */
699             ++Changes;
700
701         }
702
703         /* Next entry */
704         ++I;
705
706     }
707
708     /* Return the number of changes made */
709     return Changes;
710 }
711
712
713
714 static unsigned OptCmp3 (CodeSeg* S)
715 /* Search for
716  *
717  *      lda     x
718  *      ldx     y
719  *      cpx     #a
720  *      bne     L1
721  *      cmp     #b
722  *      jne/jeq L2
723  *
724  * If a is zero, we may remove the compare. If a and b are both zero, we may
725  * replace it by the sequence
726  *
727  *      lda     x
728  *      ora     x+1
729  *      jne/jeq ...
730  *
731  * L1 may be either the label at the branch instruction, or the target label
732  * of this instruction.
733  */
734 {
735     unsigned Changes = 0;
736
737     /* Walk over the entries */
738     unsigned I = 0;
739     while (I < CS_GetEntryCount (S)) {
740
741         CodeEntry* L[5];
742
743         /* Get next entry */
744         CodeEntry* E = CS_GetEntry (S, I);
745
746         /* Check for the sequence */
747         if (E->OPC == OP65_LDA               &&
748             CS_GetEntries (S, L, I+1, 5) &&
749             L[0]->OPC == OP65_LDX            &&
750             !CE_HasLabel (L[0])              &&
751             IsImmCmp16 (S, L+1)) {
752
753             if (L[1]->Num == 0 && L[3]->Num == 0) {
754                 /* The value is zero, we may use the simple code version. */
755                 CE_ReplaceOPC (L[0], OP65_ORA);
756                 CS_DelEntries (S, I+2, 3);
757             } else {
758                 /* Move the lda instruction after the first branch. This will
759                  * improve speed, since the load is delayed after the first
760                  * test.
761                  */
762                 CS_MoveEntry (S, I, I+4);
763
764                 /* We will replace the ldx/cpx by lda/cmp */
765                 CE_ReplaceOPC (L[0], OP65_LDA);
766                 CE_ReplaceOPC (L[1], OP65_CMP);
767
768                 /* Beware: If the first LDA instruction had a label, we have
769                  * to move this label to the top of the sequence again.
770                  */
771                 if (CE_HasLabel (E)) {
772                     CS_MoveLabels (S, E, L[0]);
773                 }
774
775             }
776
777             ++Changes;
778         }
779
780         /* Next entry */
781         ++I;
782
783     }
784
785     /* Return the number of changes made */
786     return Changes;
787 }
788
789
790
791 static unsigned OptCmp4 (CodeSeg* S)
792 /* Optimize compares of local variables:
793  *
794  *      ldy     #o
795  *      lda     (sp),y
796  *      tax
797  *      dey
798  *      lda     (sp),y
799  *      cpx     #a
800  *      bne     L1
801  *      cmp     #b
802  *      jne/jeq L2
803  */
804 {
805     unsigned Changes = 0;
806
807     /* Walk over the entries */
808     unsigned I = 0;
809     while (I < CS_GetEntryCount (S)) {
810
811         CodeEntry* L[9];
812
813         /* Check for the sequence */
814         if (IsLocalLoad16 (S, I, L, 9) && IsImmCmp16 (S, L+5)) {
815
816             if (L[5]->Num == 0 && L[7]->Num == 0) {
817
818                 /* The value is zero, we may use the simple code version:
819                  *      ldy     #o
820                  *      lda     (sp),y
821                  *      dey
822                  *      ora     (sp),y
823                  *      jne/jeq ...
824                  */
825                 CE_ReplaceOPC (L[4], OP65_ORA);
826                 CS_DelEntries (S, I+5, 3);   /* cpx/bne/cmp */
827                 CS_DelEntry (S, I+2);        /* tax */
828
829             } else {
830
831                 /* Change the code to just use the A register. Move the load
832                  * of the low byte after the first branch if possible:
833                  *
834                  *      ldy     #o
835                  *      lda     (sp),y
836                  *      cmp     #a
837                  *      bne     L1
838                  *      dey
839                  *      lda     (sp),y
840                  *      cmp     #b
841                  *      jne/jeq ...
842                  */
843                 CS_DelEntry (S, I+2);             /* tax */
844                 CE_ReplaceOPC (L[5], OP65_CMP);   /* cpx -> cmp */
845                 CS_MoveEntry (S, I+4, I+2);       /* cmp */
846                 CS_MoveEntry (S, I+5, I+3);       /* bne */
847
848             }
849
850             ++Changes;
851         }
852
853         /* Next entry */
854         ++I;
855
856     }
857
858     /* Return the number of changes made */
859     return Changes;
860 }
861
862
863
864 static unsigned OptCmp5 (CodeSeg* S)
865 /* Search for calls to compare subroutines followed by a conditional branch
866  * and replace them by cheaper versions, since the branch means that the
867  * boolean value returned by these routines is not needed (we may also check
868  * that explicitly, but for the current code generator it is always true).
869  */
870 {
871     unsigned Changes = 0;
872
873     /* Walk over the entries */
874     unsigned I = 0;
875     while (I < CS_GetEntryCount (S)) {
876
877         CodeEntry* N;
878         cmp_t Cond;
879
880         /* Get next entry */
881         CodeEntry* E = CS_GetEntry (S, I);
882
883         /* Check for the sequence */
884         if (E->OPC == OP65_JSR                          &&
885             (Cond = FindTosCmpCond (E->Arg)) != CMP_INV &&
886             (N = CS_GetNextEntry (S, I)) != 0           &&
887             (N->Info & OF_ZBRA) != 0                    &&
888             !CE_HasLabel (N)) {
889
890             /* The tos... functions will return a boolean value in a/x and
891              * the Z flag says if this value is zero or not. We will call
892              * a cheaper subroutine instead, one that does not return a
893              * boolean value but only valid flags. Note: jeq jumps if
894              * the condition is not met, jne jumps if the condition is met.
895              * Invert the code if we jump on condition not met.
896              */
897             if (GetBranchCond (N->OPC) == BC_EQ) {
898                 /* Jumps if condition false, invert condition */
899                 Cond = CmpInvertTab [Cond];
900             }
901
902             /* Replace the subroutine call. */
903             E = NewCodeEntry (OP65_JSR, AM65_ABS, "tosicmp", 0, E->LI);
904             CS_InsertEntry (S, E, I+1);
905             CS_DelEntry (S, I);
906
907             /* Replace the conditional branch */
908             ReplaceCmp (S, I+1, Cond);
909
910             /* Remember, we had changes */
911             ++Changes;
912
913         }
914
915         /* Next entry */
916         ++I;
917
918     }
919
920     /* Return the number of changes made */
921     return Changes;
922 }
923
924
925
926 /*****************************************************************************/
927 /*                              Optimize tests                               */
928 /*****************************************************************************/
929
930
931
932 static unsigned OptTest1 (CodeSeg* S)
933 /* On a sequence
934  *
935  *     stx     xxx
936  *     ora     xxx
937  *     beq/bne ...
938  *
939  * if X is zero, the sequence may be changed
940  *
941  *     cmp     #$00
942  *     beq/bne ...
943  *
944  * which may be optimized further by another step.
945  */
946 {
947     unsigned Changes = 0;
948     unsigned I;
949
950     /* Generate register info for this step */
951     CS_GenRegInfo (S);
952
953     /* Walk over the entries */
954     I = 0;
955     while (I < CS_GetEntryCount (S)) {
956
957         CodeEntry* L[3];
958
959         /* Get next entry */
960         L[0] = CS_GetEntry (S, I);
961
962         /* Check if it's the sequence we're searching for */
963         if (L[0]->OPC == OP65_STX              &&
964             L[0]->RI->In.RegX == 0             &&
965             CS_GetEntries (S, L+1, I+1, 2)     &&
966             !CE_HasLabel (L[1])                &&
967             L[1]->OPC == OP65_ORA              &&
968             strcmp (L[0]->Arg, L[1]->Arg) == 0 &&
969             !CE_HasLabel (L[2])                &&
970             (L[2]->Info & OF_ZBRA) != 0) {
971
972             /* Insert the compare */
973             CodeEntry* N = NewCodeEntry (OP65_CMP, AM65_IMM, "$00", 0, L[0]->LI);
974             CS_InsertEntry (S, N, I);
975
976             /* Remove the two other insns */
977             CS_DelEntry (S, I+2);
978             CS_DelEntry (S, I+1);
979
980             /* We had changes */
981             ++Changes;
982         }
983
984         /* Next entry */
985         ++I;
986
987     }
988
989     /* Free register info */
990     CS_FreeRegInfo (S);
991
992     /* Return the number of changes made */
993     return Changes;
994 }
995
996
997
998
999
1000
1001
1002 /*****************************************************************************/
1003 /*                            nega optimizations                             */
1004 /*****************************************************************************/
1005
1006
1007
1008 static unsigned OptNegA1 (CodeSeg* S)
1009 /* Check for
1010  *
1011  *      ldx     #$00
1012  *      lda     ..
1013  *      jsr     bnega
1014  *
1015  * Remove the ldx if the lda does not use it.
1016  */
1017 {
1018     unsigned Changes = 0;
1019
1020     /* Walk over the entries */
1021     unsigned I = 0;
1022     while (I < CS_GetEntryCount (S)) {
1023
1024         CodeEntry* L[2];
1025
1026         /* Get next entry */
1027         CodeEntry* E = CS_GetEntry (S, I);
1028
1029         /* Check for a ldx */
1030         if (E->OPC == OP65_LDX                  &&
1031             E->AM == AM65_IMM                   &&
1032             (E->Flags & CEF_NUMARG) != 0        &&
1033             E->Num == 0                         &&
1034             CS_GetEntries (S, L, I+1, 2)        &&
1035             L[0]->OPC == OP65_LDA               &&
1036             (L[0]->Use & REG_X) == 0            &&
1037             L[1]->OPC == OP65_JSR               &&
1038             strcmp (L[1]->Arg, "bnega") == 0) {
1039
1040             /* Remove the ldx instruction */
1041             CS_DelEntry (S, I);
1042
1043             /* Remember, we had changes */
1044             ++Changes;
1045
1046         }
1047
1048         /* Next entry */
1049         ++I;
1050
1051     }
1052
1053     /* Return the number of changes made */
1054     return Changes;
1055 }
1056
1057
1058
1059 static unsigned OptNegA2 (CodeSeg* S)
1060 /* Check for
1061  *
1062  *      lda     ..
1063  *      jsr     bnega
1064  *      jeq/jne ..
1065  *
1066  * Adjust the conditional branch and remove the call to the subroutine.
1067  */
1068 {
1069     unsigned Changes = 0;
1070
1071     /* Walk over the entries */
1072     unsigned I = 0;
1073     while (I < CS_GetEntryCount (S)) {
1074
1075         CodeEntry* L[2];
1076
1077         /* Get next entry */
1078         CodeEntry* E = CS_GetEntry (S, I);
1079
1080         /* Check for the sequence */
1081         if ((E->OPC == OP65_ADC ||
1082              E->OPC == OP65_AND ||
1083              E->OPC == OP65_DEA ||
1084              E->OPC == OP65_EOR ||
1085              E->OPC == OP65_INA ||
1086              E->OPC == OP65_LDA ||
1087              E->OPC == OP65_ORA ||
1088              E->OPC == OP65_PLA ||
1089              E->OPC == OP65_SBC ||
1090              E->OPC == OP65_TXA ||
1091              E->OPC == OP65_TYA)                &&
1092             CS_GetEntries (S, L, I+1, 2)        &&
1093             L[0]->OPC == OP65_JSR               &&
1094             strcmp (L[0]->Arg, "bnega") == 0    &&
1095             !CE_HasLabel (L[0])                 &&
1096             (L[1]->Info & OF_ZBRA) != 0) {
1097
1098             /* Invert the branch */
1099             CE_ReplaceOPC (L[1], GetInverseBranch (L[1]->OPC));
1100
1101             /* Delete the subroutine call */
1102             CS_DelEntry (S, I+1);
1103
1104             /* Remember, we had changes */
1105             ++Changes;
1106
1107         }
1108
1109         /* Next entry */
1110         ++I;
1111
1112     }
1113
1114     /* Return the number of changes made */
1115     return Changes;
1116 }
1117
1118
1119
1120 /*****************************************************************************/
1121 /*                            negax optimizations                            */
1122 /*****************************************************************************/
1123
1124
1125
1126 static unsigned OptNegAX1 (CodeSeg* S)
1127 /* On a call to bnegax, if X is zero, the result depends only on the value in
1128  * A, so change the call to a call to bnega. This will get further optimized
1129  * later if possible.
1130  */
1131 {
1132     unsigned Changes = 0;
1133     unsigned I;
1134
1135     /* Generate register info for this step */
1136     CS_GenRegInfo (S);
1137
1138     /* Walk over the entries */
1139     I = 0;
1140     while (I < CS_GetEntryCount (S)) {
1141
1142         /* Get next entry */
1143         CodeEntry* E = CS_GetEntry (S, I);
1144
1145         /* Check if this is a call to bnegax, and if X is known and zero */
1146         if (E->OPC == OP65_JSR              &&
1147             E->RI->In.RegX == 0             &&
1148             strcmp (E->Arg, "bnegax") == 0) {
1149
1150             /* We're cheating somewhat here ... */
1151             E->Arg[5] = '\0';
1152             E->Use &= ~REG_X;
1153
1154             /* We had changes */
1155             ++Changes;
1156         }
1157
1158         /* Next entry */
1159         ++I;
1160
1161     }
1162
1163     /* Free register info */
1164     CS_FreeRegInfo (S);
1165
1166     /* Return the number of changes made */
1167     return Changes;
1168 }
1169
1170
1171
1172 static unsigned OptNegAX2 (CodeSeg* S)
1173 /* Search for the sequence:
1174  *
1175  *      lda     (xx),y
1176  *      tax
1177  *      dey
1178  *      lda     (xx),y
1179  *      jsr     bnegax
1180  *      jne/jeq ...
1181  *
1182  * and replace it by
1183  *
1184  *      lda     (xx),y
1185  *      dey
1186  *      ora     (xx),y
1187  *      jeq/jne ...
1188  */
1189 {
1190     unsigned Changes = 0;
1191
1192     /* Walk over the entries */
1193     unsigned I = 0;
1194     while (I < CS_GetEntryCount (S)) {
1195
1196         CodeEntry* L[5];
1197
1198         /* Get next entry */
1199         CodeEntry* E = CS_GetEntry (S, I);
1200
1201         /* Check for the sequence */
1202         if (E->OPC == OP65_LDA                  &&
1203             E->AM == AM65_ZP_INDY               &&
1204             CS_GetEntries (S, L, I+1, 5)        &&
1205             L[0]->OPC == OP65_TAX               &&
1206             L[1]->OPC == OP65_DEY               &&
1207             L[2]->OPC == OP65_LDA               &&
1208             L[2]->AM == AM65_ZP_INDY            &&
1209             strcmp (L[2]->Arg, E->Arg) == 0     &&
1210             !CE_HasLabel (L[2])                 &&
1211             L[3]->OPC == OP65_JSR               &&
1212             strcmp (L[3]->Arg, "bnegax") == 0   &&
1213             !CE_HasLabel (L[3])                 &&
1214             (L[4]->Info & OF_ZBRA) != 0) {
1215
1216             /* lda --> ora */
1217             CE_ReplaceOPC (L[2], OP65_ORA);
1218
1219             /* Invert the branch */
1220             CE_ReplaceOPC (L[4], GetInverseBranch (L[4]->OPC));
1221
1222             /* Delete the entries no longer needed. Beware: Deleting entries
1223              * will change the indices.
1224              */
1225             CS_DelEntry (S, I+4);               /* jsr bnegax */
1226             CS_DelEntry (S, I+1);               /* tax */
1227
1228             /* Remember, we had changes */
1229             ++Changes;
1230
1231         }
1232
1233         /* Next entry */
1234         ++I;
1235
1236     }
1237
1238     /* Return the number of changes made */
1239     return Changes;
1240 }
1241
1242
1243
1244 static unsigned OptNegAX3 (CodeSeg* S)
1245 /* Search for the sequence:
1246  *
1247  *      lda     xx
1248  *      ldx     yy
1249  *      jsr     bnegax
1250  *      jne/jeq ...
1251  *
1252  * and replace it by
1253  *
1254  *      lda     xx
1255  *      ora     xx+1
1256  *      jeq/jne ...
1257  */
1258 {
1259     unsigned Changes = 0;
1260
1261     /* Walk over the entries */
1262     unsigned I = 0;
1263     while (I < CS_GetEntryCount (S)) {
1264
1265         CodeEntry* L[3];
1266
1267         /* Get next entry */
1268         CodeEntry* E = CS_GetEntry (S, I);
1269
1270         /* Check for the sequence */
1271         if (E->OPC == OP65_LDA                  &&
1272             CS_GetEntries (S, L, I+1, 3)        &&
1273             L[0]->OPC == OP65_LDX               &&
1274             !CE_HasLabel (L[0])                 &&
1275             L[1]->OPC == OP65_JSR               &&
1276             strcmp (L[1]->Arg, "bnegax") == 0   &&
1277             !CE_HasLabel (L[1])                 &&
1278             (L[2]->Info & OF_ZBRA) != 0) {
1279
1280             /* ldx --> ora */
1281             CE_ReplaceOPC (L[0], OP65_ORA);
1282
1283             /* Invert the branch */
1284             CE_ReplaceOPC (L[2], GetInverseBranch (L[2]->OPC));
1285
1286             /* Delete the subroutine call */
1287             CS_DelEntry (S, I+2);
1288
1289             /* Remember, we had changes */
1290             ++Changes;
1291
1292         }
1293
1294         /* Next entry */
1295         ++I;
1296
1297     }
1298
1299     /* Return the number of changes made */
1300     return Changes;
1301 }
1302
1303
1304
1305 static unsigned OptNegAX4 (CodeSeg* S)
1306 /* Search for the sequence:
1307  *
1308  *      jsr     xxx
1309  *      jsr     bnega(x)
1310  *      jeq/jne ...
1311  *
1312  * and replace it by:
1313  *
1314  *      jsr     xxx
1315  *      <boolean test>
1316  *      jne/jeq ...
1317  */
1318 {
1319     unsigned Changes = 0;
1320
1321     /* Walk over the entries */
1322     unsigned I = 0;
1323     while (I < CS_GetEntryCount (S)) {
1324
1325         CodeEntry* L[2];
1326
1327         /* Get next entry */
1328         CodeEntry* E = CS_GetEntry (S, I);
1329
1330         /* Check for the sequence */
1331         if (E->OPC == OP65_JSR                  &&
1332             CS_GetEntries (S, L, I+1, 2)        &&
1333             L[0]->OPC == OP65_JSR               &&
1334             strncmp (L[0]->Arg,"bnega",5) == 0  &&
1335             !CE_HasLabel (L[0])                 &&
1336             (L[1]->Info & OF_ZBRA) != 0) {
1337
1338             CodeEntry* X;
1339
1340             /* Check if we're calling bnega or bnegax */
1341             int ByteSized = (strcmp (L[0]->Arg, "bnega") == 0);
1342
1343             /* Insert apropriate test code */
1344             if (ByteSized) {
1345                 /* Test bytes */
1346                 X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[0]->LI);
1347                 CS_InsertEntry (S, X, I+2);
1348             } else {
1349                 /* Test words */
1350                 X = NewCodeEntry (OP65_STX, AM65_ZP, "tmp1", 0, L[0]->LI);
1351                 CS_InsertEntry (S, X, I+2);
1352                 X = NewCodeEntry (OP65_ORA, AM65_ZP, "tmp1", 0, L[0]->LI);
1353                 CS_InsertEntry (S, X, I+3);
1354             }
1355
1356             /* Delete the subroutine call */
1357             CS_DelEntry (S, I+1);
1358
1359             /* Invert the branch */
1360             CE_ReplaceOPC (L[1], GetInverseBranch (L[1]->OPC));
1361
1362             /* Remember, we had changes */
1363             ++Changes;
1364
1365         }
1366
1367         /* Next entry */
1368         ++I;
1369
1370     }
1371
1372     /* Return the number of changes made */
1373     return Changes;
1374 }
1375
1376
1377
1378 /*****************************************************************************/
1379 /*                                   Code                                    */
1380 /*****************************************************************************/
1381
1382
1383
1384 /* Table with all the optimization functions */
1385 typedef struct OptFunc OptFunc;
1386 struct OptFunc {
1387     unsigned (*Func) (CodeSeg*);/* Optimizer function */
1388     const char* Name;           /* Name of optimizer step */
1389     char        Disabled;       /* True if pass disabled */
1390 };
1391
1392
1393
1394 /* Table with optimizer steps -  are called in this order */
1395 static OptFunc OptFuncs [] = {
1396     /* Optimize subtractions */
1397     { OptSub1,              "OptSub1",                  0       },
1398     { OptSub2,              "OptSub2",                  0       },
1399     /* Optimize additions */
1400     { OptAdd1,              "OptAdd1",                  0       },
1401     /* Optimize jump cascades */
1402     { OptJumpCascades,      "OptJumpCascades",          0       },
1403     /* Remove dead jumps */
1404     { OptDeadJumps,         "OptDeadJumps",             0       },
1405     /* Change jsr/rts to jmp */
1406     { OptRTS,               "OptRTS",                   0       },
1407     /* Remove dead code */
1408     { OptDeadCode,          "OptDeadCode",              0       },
1409     /* Optimize jump targets */
1410     { OptJumpTarget,        "OptJumpTarget",            0       },
1411     /* Optimize conditional branches */
1412     { OptCondBranches,      "OptCondBranches",          0       },
1413     /* Replace jumps to RTS by RTS */
1414     { OptRTSJumps,          "OptRTSJumps",              0       },
1415     /* Remove calls to the bool transformer subroutines */
1416     { OptBoolTransforms,    "OptBoolTransforms",        0       },
1417     /* Optimize calls to nega */
1418     { OptNegA1,             "OptNegA1",                 0       },
1419     { OptNegA2,             "OptNegA2",                 0       },
1420     /* Optimize calls to negax */
1421     { OptNegAX1,            "OptNegAX1",                0       },
1422     { OptNegAX2,            "OptNegAX2",                0       },
1423     { OptNegAX3,            "OptNegAX3",                0       },
1424     { OptNegAX4,            "OptNegAX4",                0       },
1425     /* Optimize compares */
1426     { OptCmp1,              "OptCmp1",                  0       },
1427     { OptCmp2,              "OptCmp2",                  0       },
1428     { OptCmp3,              "OptCmp3",                  0       },
1429     { OptCmp4,              "OptCmp4",                  0       },
1430     { OptCmp5,              "OptCmp5",                  0       },
1431     /* Optimize tests */
1432     { OptTest1,             "OptTest1",                 0       },
1433     /* Remove unused loads */
1434     { OptUnusedLoads,       "OptUnusedLoads",           0       },
1435     { OptDuplicateLoads,    "OptDuplicateLoads",        0       },
1436     { OptStoreLoad,         "OptStoreLoad",             0       },
1437     /* Optimize branch distance */
1438     { OptBranchDist,        "OptBranchDist",            0       },
1439 };
1440
1441
1442
1443 static OptFunc* FindOptStep (const char* Name)
1444 /* Find an optimizer step by name in the table and return a pointer. Print an
1445  * error and call AbEnd if not found.
1446  */
1447 {
1448     unsigned I;
1449
1450     /* Run all optimization steps */
1451     for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
1452         if (strcmp (OptFuncs[I].Name, Name) == 0) {
1453             /* Found */
1454             return OptFuncs+I;
1455         }
1456     }
1457
1458     /* Not found */
1459     AbEnd ("Optimization step `%s' not found", Name);
1460     return 0;
1461 }
1462
1463
1464
1465 void DisableOpt (const char* Name)
1466 /* Disable the optimization with the given name */
1467 {
1468     if (strcmp (Name, "any") == 0) {
1469         unsigned I;
1470         for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
1471             OptFuncs[I].Disabled = 1;
1472         }
1473     } else {
1474         OptFunc* F = FindOptStep (Name);
1475         F->Disabled = 1;
1476     }
1477 }
1478
1479
1480
1481 void EnableOpt (const char* Name)
1482 /* Enable the optimization with the given name */
1483 {
1484     if (strcmp (Name, "any") == 0) {
1485         unsigned I;
1486         for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
1487             OptFuncs[I].Disabled = 0;
1488         }
1489     } else {
1490         OptFunc* F = FindOptStep (Name);
1491         F->Disabled = 0;
1492     }
1493 }
1494
1495
1496
1497 void RunOpt (CodeSeg* S)
1498 /* Run the optimizer */
1499 {
1500     unsigned I;
1501     unsigned Pass = 0;
1502     unsigned OptChanges;
1503
1504     /* If we shouldn't run the optimizer, bail out */
1505     if (!Optimize) {
1506         return;
1507     }
1508
1509     /* Print the name of the function we are working on */
1510     if (S->Func) {
1511         Print (stdout, 1, "Running optimizer for function `%s'\n", S->Func->Name);
1512     } else {
1513         Print (stdout, 1, "Running optimizer for global code segment\n");
1514     }
1515
1516     /* Repeat all steps until there are no more changes */
1517     do {
1518         /* Reset the number of changes */
1519         OptChanges = 0;
1520
1521         /* Keep the user hapy */
1522         Print (stdout, 1, "  Optimizer pass %u:\n", ++Pass);
1523
1524         /* Run all optimization steps */
1525         for (I = 0; I < sizeof(OptFuncs)/sizeof(OptFuncs[0]); ++I) {
1526
1527             /* Print the name of the following optimizer step */
1528             Print (stdout, 1, "    %s:%*s", OptFuncs[I].Name,
1529                    (int) (30-strlen(OptFuncs[I].Name)), "");
1530
1531             /* Check if the step is disabled */
1532             if (OptFuncs[I].Disabled) {
1533                 Print (stdout, 1, "Disabled\n");
1534             } else {
1535                 unsigned Changes = OptFuncs[I].Func (S);
1536                 OptChanges += Changes;
1537                 Print (stdout, 1, "%u Changes\n", Changes);
1538             }
1539         }
1540
1541     } while (OptChanges > 0);
1542 }
1543
1544
1545