]> git.sur5r.net Git - cc65/blob - src/cc65/coptind.c
Added an additional precondition check to OptJumpTarget3.
[cc65] / src / cc65 / coptind.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 coptind.c                                 */
4 /*                                                                           */
5 /*              Environment independent low level optimizations              */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001-2009, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 /* common */
37 #include "cpu.h"
38
39 /* cc65 */
40 #include "codeent.h"
41 #include "coptind.h"
42 #include "codeinfo.h"
43 #include "codeopt.h"
44 #include "error.h"
45
46
47
48 /*****************************************************************************/
49 /*                             Helper functions                              */
50 /*****************************************************************************/
51
52
53
54 static int MemAccess (CodeSeg* S, unsigned From, unsigned To, const CodeEntry* N)
55 /* Checks a range of code entries if there are any memory accesses to N->Arg */
56 {
57     /* Get the length of the argument */
58     unsigned NLen = strlen (N->Arg);
59
60     /* What to check for? */
61     enum {
62         None    = 0x00,
63         Base    = 0x01,         /* Check for location without "+1" */
64         Word    = 0x02,         /* Check for location with "+1" added */
65     } What = None;
66
67
68     /* If the argument of N is a zero page location that ends with "+1", we
69      * must also check for word accesses to the location without +1.
70      */
71     if (N->AM == AM65_ZP && NLen > 2 && strcmp (N->Arg + NLen - 2, "+1") == 0) {
72         What |= Base;
73     }
74
75     /* If the argument is zero page indirect, we must also check for accesses
76      * to "arg+1"
77      */
78     if (N->AM == AM65_ZP_INDY || N->AM == AM65_ZPX_IND || N->AM == AM65_ZP_IND) {
79         What |= Word;
80     }
81
82     /* Walk over all code entries */
83     while (From <= To) {
84
85         /* Get the next entry */
86         CodeEntry* E = CS_GetEntry (S, From);
87
88         /* Check if there is an argument and if this argument equals Arg in
89          * some variants.
90          */
91         if (E->Arg[0] != '\0') {
92
93             unsigned ELen;
94
95             if (strcmp (E->Arg, N->Arg) == 0) {
96                 /* Found an access */
97                 return 1;
98             }
99
100             ELen = strlen (E->Arg);
101             if ((What & Base) != 0) {
102                 if (ELen == NLen - 2 && strncmp (E->Arg, N->Arg, NLen-2) == 0) {
103                     /* Found an access */
104                     return 1;
105                 }
106             }
107
108             if ((What & Word) != 0) {
109                 if (ELen == NLen + 2 && strncmp (E->Arg, N->Arg, NLen) == 0 &&
110                     E->Arg[NLen] == '+' && E->Arg[NLen+1] == '1') {
111                     /* Found an access */
112                     return 1;
113                 }
114             }
115         }
116
117         /* Next entry */
118         ++From;
119     }
120
121     /* Nothing found */
122     return 0;
123 }
124
125
126
127 static int GetBranchDist (CodeSeg* S, unsigned From, CodeEntry* To)
128 /* Get the branch distance between the two entries and return it. The distance
129  * will be negative for backward jumps and positive for forward jumps.
130  */
131 {
132     /* Get the index of the branch target */
133     unsigned TI = CS_GetEntryIndex (S, To);
134
135     /* Determine the branch distance */
136     int Distance = 0;
137     if (TI >= From) {
138         /* Forward branch, do not count the current insn */
139         unsigned J = From+1;
140         while (J < TI) {
141             CodeEntry* N = CS_GetEntry (S, J++);
142             Distance += N->Size;
143         }
144     } else {
145         /* Backward branch */
146         unsigned J = TI;
147         while (J < From) {
148             CodeEntry* N = CS_GetEntry (S, J++);
149             Distance -= N->Size;
150         }
151     }
152
153     /* Return the calculated distance */
154     return Distance;
155 }
156
157
158
159 static int IsShortDist (int Distance)
160 /* Return true if the given distance is a short branch distance */
161 {
162     return (Distance >= -125 && Distance <= 125);
163 }
164
165
166
167 static short ZPRegVal (unsigned short Use, const RegContents* RC)
168 /* Return the contents of the given zeropage register */
169 {
170     if ((Use & REG_TMP1) != 0) {
171         return RC->Tmp1;
172     } else if ((Use & REG_PTR1_LO) != 0) {
173         return RC->Ptr1Lo;
174     } else if ((Use & REG_PTR1_HI) != 0) {
175         return RC->Ptr1Hi;
176     } else if ((Use & REG_SREG_LO) != 0) {
177         return RC->SRegLo;
178     } else if ((Use & REG_SREG_HI) != 0) {
179         return RC->SRegHi;
180     } else {
181         return UNKNOWN_REGVAL;
182     }
183 }
184
185
186
187 static short RegVal (unsigned short Use, const RegContents* RC)
188 /* Return the contents of the given register */
189 {
190     if ((Use & REG_A) != 0) {
191         return RC->RegA;
192     } else if ((Use & REG_X) != 0) {
193         return RC->RegX;
194     } else if ((Use & REG_Y) != 0) {
195         return RC->RegY;
196     } else {
197         return ZPRegVal (Use, RC);
198     }
199 }
200
201
202
203 /*****************************************************************************/
204 /*                        Replace jumps to RTS by RTS                        */
205 /*****************************************************************************/
206
207
208
209 unsigned OptRTSJumps1 (CodeSeg* S)
210 /* Replace jumps to RTS by RTS */
211 {
212     unsigned Changes = 0;
213
214     /* Walk over all entries minus the last one */
215     unsigned I = 0;
216     while (I < CS_GetEntryCount (S)) {
217
218         /* Get the next entry */
219         CodeEntry* E = CS_GetEntry (S, I);
220
221         /* Check if it's an unconditional branch to a local target */
222         if ((E->Info & OF_UBRA) != 0            &&
223             E->JumpTo != 0                      &&
224             E->JumpTo->Owner->OPC == OP65_RTS) {
225
226             /* Insert an RTS instruction */
227             CodeEntry* X = NewCodeEntry (OP65_RTS, AM65_IMP, 0, 0, E->LI);
228             CS_InsertEntry (S, X, I+1);
229
230             /* Delete the jump */
231             CS_DelEntry (S, I);
232
233             /* Remember, we had changes */
234             ++Changes;
235
236         }
237
238         /* Next entry */
239         ++I;
240
241     }
242
243     /* Return the number of changes made */
244     return Changes;
245 }
246
247
248
249 unsigned OptRTSJumps2 (CodeSeg* S)
250 /* Replace long conditional jumps to RTS */
251 {
252     unsigned Changes = 0;
253
254     /* Walk over all entries minus the last one */
255     unsigned I = 0;
256     while (I < CS_GetEntryCount (S)) {
257
258         CodeEntry* N;
259
260         /* Get the next entry */
261         CodeEntry* E = CS_GetEntry (S, I);
262
263         /* Check if it's an unconditional branch to a local target */
264         if ((E->Info & OF_CBRA) != 0            &&   /* Conditional branch */
265             (E->Info & OF_LBRA) != 0            &&   /* Long branch */
266             E->JumpTo != 0                      &&   /* Local label */
267             E->JumpTo->Owner->OPC == OP65_RTS   &&   /* Target is an RTS */
268             (N = CS_GetNextEntry (S, I)) != 0) {     /* There is a next entry */
269
270             CodeEntry* X;
271             CodeLabel* LN;
272             opc_t      NewBranch;
273
274             /* We will create a jump around an RTS instead of the long branch */
275             X = NewCodeEntry (OP65_RTS, AM65_IMP, 0, 0, E->JumpTo->Owner->LI);
276             CS_InsertEntry (S, X, I+1);
277
278             /* Get the new branch opcode */
279             NewBranch = MakeShortBranch (GetInverseBranch (E->OPC));
280
281             /* Get the label attached to N, create a new one if needed */
282             LN = CS_GenLabel (S, N);
283
284             /* Generate the branch */
285             X = NewCodeEntry (NewBranch, AM65_BRA, LN->Name, LN, E->LI);
286             CS_InsertEntry (S, X, I+1);
287
288             /* Delete the long branch */
289             CS_DelEntry (S, I);
290
291             /* Remember, we had changes */
292             ++Changes;
293
294         }
295
296         /* Next entry */
297         ++I;
298
299     }
300
301     /* Return the number of changes made */
302     return Changes;
303 }
304
305
306
307 /*****************************************************************************/
308 /*                             Remove dead jumps                             */
309 /*****************************************************************************/
310
311
312
313 unsigned OptDeadJumps (CodeSeg* S)
314 /* Remove dead jumps (jumps to the next instruction) */
315 {
316     unsigned Changes = 0;
317
318     /* Walk over all entries minus the last one */
319     unsigned I = 0;
320     while (I < CS_GetEntryCount (S)) {
321
322         /* Get the next entry */
323         CodeEntry* E = CS_GetEntry (S, I);
324
325         /* Check if it's a branch, if it has a local target, and if the target
326          * is the next instruction.
327          */
328         if (E->AM == AM65_BRA                               &&
329             E->JumpTo                                       &&
330             E->JumpTo->Owner == CS_GetNextEntry (S, I)) {
331
332             /* Delete the dead jump */
333             CS_DelEntry (S, I);
334
335             /* Remember, we had changes */
336             ++Changes;
337
338         } else {
339
340             /* Next entry */
341             ++I;
342
343         }
344     }
345
346     /* Return the number of changes made */
347     return Changes;
348 }
349
350
351
352 /*****************************************************************************/
353 /*                             Remove dead code                              */
354 /*****************************************************************************/
355
356
357
358 unsigned OptDeadCode (CodeSeg* S)
359 /* Remove dead code (code that follows an unconditional jump or an rts/rti
360  * and has no label)
361  */
362 {
363     unsigned Changes = 0;
364
365     /* Walk over all entries */
366     unsigned I = 0;
367     while (I < CS_GetEntryCount (S)) {
368
369         CodeEntry* N;
370         CodeLabel* LN;
371
372         /* Get this entry */
373         CodeEntry* E = CS_GetEntry (S, I);
374
375         /* Check if it's an unconditional branch, and if the next entry has
376          * no labels attached, or if the label is just used so that the insn
377          * can jump to itself.
378          */
379         if ((E->Info & OF_DEAD) != 0                     &&     /* Dead code follows */
380             (N = CS_GetNextEntry (S, I)) != 0            &&     /* Has next entry */
381             (!CE_HasLabel (N)                        ||         /* Don't has a label */
382              ((N->Info & OF_UBRA) != 0          &&              /* Uncond branch */
383               (LN = N->JumpTo) != 0             &&              /* Jumps to known label */
384               LN->Owner == N                    &&              /* Attached to insn */
385               CL_GetRefCount (LN) == 1))) {                     /* Only reference */
386
387             /* Delete the next entry */
388             CS_DelEntry (S, I+1);
389
390             /* Remember, we had changes */
391             ++Changes;
392
393         } else {
394
395             /* Next entry */
396             ++I;
397
398         }
399     }
400
401     /* Return the number of changes made */
402     return Changes;
403 }
404
405
406
407 /*****************************************************************************/
408 /*                          Optimize jump cascades                           */
409 /*****************************************************************************/
410
411
412
413 unsigned OptJumpCascades (CodeSeg* S)
414 /* Optimize jump cascades (jumps to jumps). In such a case, the jump is
415  * replaced by a jump to the final location. This will in some cases produce
416  * worse code, because some jump targets are no longer reachable by short
417  * branches, but this is quite rare, so there are more advantages than
418  * disadvantages.
419  */
420 {
421     unsigned Changes = 0;
422
423     /* Walk over all entries */
424     unsigned I = 0;
425     while (I < CS_GetEntryCount (S)) {
426
427         CodeEntry* N;
428         CodeLabel* OldLabel;
429
430         /* Get this entry */
431         CodeEntry* E = CS_GetEntry (S, I);
432
433         /* Check if it's a branch, if it has a jump label, if this jump
434          * label is not attached to the instruction itself, and if the
435          * target instruction is itself a branch.
436          */
437         if ((E->Info & OF_BRA) != 0        &&
438             (OldLabel = E->JumpTo) != 0    &&
439             (N = OldLabel->Owner) != E     &&
440             (N->Info & OF_BRA) != 0) {
441
442             /* Check if we can use the final target label. This is the case,
443              * if the target branch is an absolut branch, or if it is a
444              * conditional branch checking the same condition as the first one.
445              */
446             if ((N->Info & OF_UBRA) != 0 ||
447                 ((E->Info & OF_CBRA) != 0 &&
448                  GetBranchCond (E->OPC)  == GetBranchCond (N->OPC))) {
449
450                 /* This is a jump cascade and we may jump to the final target,
451                  * provided that the other insn does not jump to itself. If
452                  * this is the case, we can also jump to ourselves, otherwise
453                  * insert a jump to the new instruction and remove the old one.
454                  */
455                 CodeEntry* X;
456                 CodeLabel* LN = N->JumpTo;
457
458                 if (LN != 0 && LN->Owner == N) {
459
460                     /* We found a jump to a jump to itself. Replace our jump
461                      * by a jump to itself.
462                      */
463                     CodeLabel* LE = CS_GenLabel (S, E);
464                     X = NewCodeEntry (E->OPC, E->AM, LE->Name, LE, E->LI);
465
466                 } else {
467
468                     /* Jump to the final jump target */
469                     X = NewCodeEntry (E->OPC, E->AM, N->Arg, N->JumpTo, E->LI);
470
471                 }
472
473                 /* Insert it behind E */
474                 CS_InsertEntry (S, X, I+1);
475
476                 /* Remove E */
477                 CS_DelEntry (S, I);
478
479                 /* Remember, we had changes */
480                 ++Changes;
481
482             /* Check if both are conditional branches, and the condition of
483              * the second is the inverse of that of the first. In this case,
484              * the second branch will never be taken, and we may jump directly
485              * to the instruction behind this one.
486              */
487             } else if ((E->Info & OF_CBRA) != 0 && (N->Info & OF_CBRA) != 0) {
488
489                 CodeEntry* X;   /* Instruction behind N */
490                 CodeLabel* LX;  /* Label attached to X */
491
492                 /* Get the branch conditions of both branches */
493                 bc_t BC1 = GetBranchCond (E->OPC);
494                 bc_t BC2 = GetBranchCond (N->OPC);
495
496                 /* Check the branch conditions */
497                 if (BC1 != GetInverseCond (BC2)) {
498                     /* Condition not met */
499                     goto NextEntry;
500                 }
501
502                 /* We may jump behind this conditional branch. Get the
503                  * pointer to the next instruction
504                  */
505                 if ((X = CS_GetNextEntry (S, CS_GetEntryIndex (S, N))) == 0) {
506                     /* N is the last entry, bail out */
507                     goto NextEntry;
508                 }
509
510                 /* Get the label attached to X, create a new one if needed */
511                 LX = CS_GenLabel (S, X);
512
513                 /* Move the reference from E to the new label */
514                 CS_MoveLabelRef (S, E, LX);
515
516                 /* Remember, we had changes */
517                 ++Changes;
518             }
519         }
520
521 NextEntry:
522         /* Next entry */
523         ++I;
524
525     }
526
527     /* Return the number of changes made */
528     return Changes;
529 }
530
531
532
533 /*****************************************************************************/
534 /*                             Optimize jsr/rts                              */
535 /*****************************************************************************/
536
537
538
539 unsigned OptRTS (CodeSeg* S)
540 /* Optimize subroutine calls followed by an RTS. The subroutine call will get
541  * replaced by a jump. Don't bother to delete the RTS if it does not have a
542  * label, the dead code elimination should take care of it.
543  */
544 {
545     unsigned Changes = 0;
546
547     /* Walk over all entries minus the last one */
548     unsigned I = 0;
549     while (I < CS_GetEntryCount (S)) {
550
551         CodeEntry* N;
552
553         /* Get this entry */
554         CodeEntry* E = CS_GetEntry (S, I);
555
556         /* Check if it's a subroutine call and if the following insn is RTS */
557         if (E->OPC == OP65_JSR                    &&
558             (N = CS_GetNextEntry (S, I)) != 0 &&
559             N->OPC == OP65_RTS) {
560
561             /* Change the jsr to a jmp and use the additional info for a jump */
562             E->AM = AM65_BRA;
563             CE_ReplaceOPC (E, OP65_JMP);
564
565             /* Remember, we had changes */
566             ++Changes;
567
568         }
569
570         /* Next entry */
571         ++I;
572
573     }
574
575     /* Return the number of changes made */
576     return Changes;
577 }
578
579
580
581 /*****************************************************************************/
582 /*                           Optimize jump targets                           */
583 /*****************************************************************************/
584
585
586
587 unsigned OptJumpTarget1 (CodeSeg* S)
588 /* If the instruction preceeding an unconditional branch is the same as the
589  * instruction preceeding the jump target, the jump target may be moved
590  * one entry back. This is a size optimization, since the instruction before
591  * the branch gets removed.
592  */
593 {
594     unsigned Changes = 0;
595     CodeEntry* E1;              /* Entry 1 */
596     CodeEntry* E2;              /* Entry 2 */
597     CodeEntry* T1;              /* Jump target entry 1 */
598     CodeLabel* TL1;             /* Target label 1 */
599
600     /* Walk over the entries */
601     unsigned I = 0;
602     while (I < CS_GetEntryCount (S)) {
603
604         /* Get next entry */
605         E2 = CS_GetNextEntry (S, I);
606
607         /* Check if we have a jump or branch without a label attached, and
608          * a jump target, which is not attached to the jump itself
609          */
610         if (E2 != 0                     &&
611             (E2->Info & OF_UBRA) != 0   &&
612             !CE_HasLabel (E2)           &&
613             E2->JumpTo                  &&
614             E2->JumpTo->Owner != E2) {
615
616             /* Get the entry preceeding the branch target */
617             T1 = CS_GetPrevEntry (S, CS_GetEntryIndex (S, E2->JumpTo->Owner));
618             if (T1 == 0) {
619                 /* There is no such entry */
620                 goto NextEntry;
621             }
622
623             /* The entry preceeding the branch target may not be the branch
624              * insn.
625              */
626             if (T1 == E2) {
627                 goto NextEntry;
628             }
629
630             /* Get the entry preceeding the jump */
631             E1 = CS_GetEntry (S, I);
632
633             /* Check if both preceeding instructions are identical */
634             if (!CodeEntriesAreEqual (E1, T1)) {
635                 /* Not equal, try next */
636                 goto NextEntry;
637             }
638
639             /* Get the label for the instruction preceeding the jump target.
640              * This routine will create a new label if the instruction does
641              * not already have one.
642              */
643             TL1 = CS_GenLabel (S, T1);
644
645             /* Change the jump target to point to this new label */
646             CS_MoveLabelRef (S, E2, TL1);
647
648             /* If the instruction preceeding the jump has labels attached,
649              * move references to this label to the new label.
650              */
651             if (CE_HasLabel (E1)) {
652                 CS_MoveLabels (S, E1, T1);
653             }
654
655             /* Remove the entry preceeding the jump */
656             CS_DelEntry (S, I);
657
658             /* Remember, we had changes */
659             ++Changes;
660
661         } else {
662 NextEntry:
663             /* Next entry */
664             ++I;
665         }
666     }
667
668     /* Return the number of changes made */
669     return Changes;
670 }
671
672
673
674 unsigned OptJumpTarget2 (CodeSeg* S)
675 /* If a bcs jumps to a sec insn or a bcc jumps to clc, skip this insn, since
676  * it's job is already done.
677  */
678 {
679     unsigned Changes = 0;
680
681     /* Walk over the entries */
682     unsigned I = 0;
683     while (I < CS_GetEntryCount (S)) {
684
685         /* OP that may be skipped */
686         opc_t OPC;
687
688         /* Jump target insn, old and new */
689         CodeEntry* T;
690         CodeEntry* N;
691
692         /* New jump label */
693         CodeLabel* L;
694
695         /* Get next entry */
696         CodeEntry* E = CS_GetEntry (S, I);
697
698         /* Check if this is a bcc insn */
699         if (E->OPC == OP65_BCC || E->OPC == OP65_JCC) {
700             OPC = OP65_CLC;
701         } else if (E->OPC == OP65_BCS || E->OPC == OP65_JCS) {
702             OPC = OP65_SEC;
703         } else {
704             /* Not what we're looking for */
705             goto NextEntry;
706         }
707
708         /* Must have a jump target */
709         if (E->JumpTo == 0) {
710             goto NextEntry;
711         }
712
713         /* Get the owner insn of the jump target and check if it's the one, we
714          * will skip if present.
715          */
716         T = E->JumpTo->Owner;
717         if (T->OPC != OPC) {
718             goto NextEntry;
719         }
720
721         /* Get the entry following the branch target */
722         N = CS_GetNextEntry (S, CS_GetEntryIndex (S, T));
723         if (N == 0) {
724             /* There is no such entry */
725             goto NextEntry;
726         }
727
728         /* Get the label for the instruction following the jump target.
729          * This routine will create a new label if the instruction does
730          * not already have one.
731          */
732         L = CS_GenLabel (S, N);
733
734         /* Change the jump target to point to this new label */
735         CS_MoveLabelRef (S, E, L);
736
737         /* Remember that we had changes */
738         ++Changes;
739
740 NextEntry:
741         /* Next entry */
742         ++I;
743     }
744
745     /* Return the number of changes made */
746     return Changes;
747 }
748
749
750
751 unsigned OptJumpTarget3 (CodeSeg* S)
752 /* Jumps to load instructions of a register, that do already have the matching
753  * register contents may skip the load instruction, since it's job is already
754  * done.
755  */
756 {
757     unsigned Changes = 0;
758     unsigned I;
759
760     /* Generate register info for this step */
761     CS_GenRegInfo (S);
762
763     /* Walk over the entries */
764     I = 0;
765     while (I < CS_GetEntryCount (S)) {
766
767         unsigned J, K;
768         CodeEntry* N;
769
770         /* New jump label */
771         CodeLabel* LN = 0;
772
773         /* Get next entry */
774         CodeEntry* E = CS_GetEntry (S, I);
775
776         /* Check if this is a load insn with a label */
777         if ((E->Info & OF_LOAD) != 0            &&
778             CE_IsConstImm (E)                   &&
779             CE_HasLabel (E)                     &&
780             (N = CS_GetNextEntry (S, I)) != 0   &&
781             (N->Info & OF_FBRA) == 0)    {
782
783             /* Walk over all insn that jump here */
784             for (J = 0; J < CE_GetLabelCount (E); ++J) {
785
786                 /* Get the label */
787                 CodeLabel* L = CE_GetLabel (E, J);
788                 for (K = 0; K < CL_GetRefCount (L); ++K) {
789
790                     /* Get the entry that jumps here */
791                     CodeEntry* Jump = CL_GetRef (L, K);
792
793                     /* Get the register info from this insn */
794                     short Val = RegVal (E->Chg, &Jump->RI->Out2);
795
796                     /* Check if the outgoing value is the one thatr's loaded */
797                     if (Val == (unsigned char) E->Num) {
798
799                         /* Ok, skip the insn. First, generate a label */
800                         if (LN == 0) {
801                             LN = CS_GenLabel (S, N);
802                         }
803
804                         /* Change the jump target to point to this new label */
805                         CS_MoveLabelRef (S, Jump, LN);
806
807                         /* Remember that we had changes */
808                         ++Changes;
809                     }
810                 }
811             }
812
813         }
814
815         /* Next entry */
816         ++I;
817     }
818
819     /* Free register info */
820     CS_FreeRegInfo (S);
821
822     /* Return the number of changes made */
823     return Changes;
824 }
825
826
827
828 /*****************************************************************************/
829 /*                       Optimize conditional branches                       */
830 /*****************************************************************************/
831
832
833
834 unsigned OptCondBranches1 (CodeSeg* S)
835 /* Performs several optimization steps:
836  *
837  *  - If an immidiate load of a register is followed by a conditional jump that
838  *    is never taken because the load of the register sets the flags in such a
839  *    manner, remove the conditional branch.
840  *  - If the conditional branch is always taken because of the register load,
841  *    replace it by a jmp.
842  *  - If a conditional branch jumps around an unconditional branch, remove the
843  *    conditional branch and make the jump a conditional branch with the
844  *    inverse condition of the first one.
845  */
846 {
847     unsigned Changes = 0;
848
849     /* Walk over the entries */
850     unsigned I = 0;
851     while (I < CS_GetEntryCount (S)) {
852
853         CodeEntry* N;
854         CodeLabel* L;
855
856         /* Get next entry */
857         CodeEntry* E = CS_GetEntry (S, I);
858
859         /* Check if it's a register load */
860         if ((E->Info & OF_LOAD) != 0              &&  /* It's a load instruction */
861             E->AM == AM65_IMM                     &&  /* ..with immidiate addressing */
862             (E->Flags & CEF_NUMARG) != 0          &&  /* ..and a numeric argument. */
863             (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
864             (N->Info & OF_CBRA) != 0              &&  /* ..which is a conditional branch */
865             !CE_HasLabel (N)) {               /* ..and does not have a label */
866
867             /* Get the branch condition */
868             bc_t BC = GetBranchCond (N->OPC);
869
870             /* Check the argument against the branch condition */
871             if ((BC == BC_EQ && E->Num != 0)            ||
872                 (BC == BC_NE && E->Num == 0)            ||
873                 (BC == BC_PL && (E->Num & 0x80) != 0)   ||
874                 (BC == BC_MI && (E->Num & 0x80) == 0)) {
875
876                 /* Remove the conditional branch */
877                 CS_DelEntry (S, I+1);
878
879                 /* Remember, we had changes */
880                 ++Changes;
881
882             } else if ((BC == BC_EQ && E->Num == 0)             ||
883                        (BC == BC_NE && E->Num != 0)             ||
884                        (BC == BC_PL && (E->Num & 0x80) == 0)    ||
885                        (BC == BC_MI && (E->Num & 0x80) != 0)) {
886
887                 /* The branch is always taken, replace it by a jump */
888                 CE_ReplaceOPC (N, OP65_JMP);
889
890                 /* Remember, we had changes */
891                 ++Changes;
892             }
893
894         }
895
896         if ((E->Info & OF_CBRA) != 0              &&  /* It's a conditional branch */
897             (L = E->JumpTo) != 0                  &&  /* ..referencing a local label */
898             (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
899             (N->Info & OF_UBRA) != 0              &&  /* ..which is an uncond branch, */
900             !CE_HasLabel (N)                      &&  /* ..has no label attached */
901             L->Owner == CS_GetNextEntry (S, I+1)) {/* ..and jump target follows */
902
903             /* Replace the jump by a conditional branch with the inverse branch
904              * condition than the branch around it.
905              */
906             CE_ReplaceOPC (N, GetInverseBranch (E->OPC));
907
908             /* Remove the conditional branch */
909             CS_DelEntry (S, I);
910
911             /* Remember, we had changes */
912             ++Changes;
913
914         }
915
916         /* Next entry */
917         ++I;
918
919     }
920
921     /* Return the number of changes made */
922     return Changes;
923 }
924
925
926
927 unsigned OptCondBranches2 (CodeSeg* S)
928 /* If on entry to a "rol a" instruction the accu is zero, and a beq/bne follows,
929  * we can remove the rol and branch on the state of the carry flag.
930  */
931 {
932     unsigned Changes = 0;
933     unsigned I;
934
935     /* Generate register info for this step */
936     CS_GenRegInfo (S);
937
938     /* Walk over the entries */
939     I = 0;
940     while (I < CS_GetEntryCount (S)) {
941
942         CodeEntry* N;
943
944         /* Get next entry */
945         CodeEntry* E = CS_GetEntry (S, I);
946
947         /* Check if it's a rol insn with A in accu and a branch follows */
948         if (E->OPC == OP65_ROL                  &&
949             E->AM == AM65_ACC                   &&
950             E->RI->In.RegA == 0                 &&
951             !CE_HasLabel (E)                    &&
952             (N = CS_GetNextEntry (S, I)) != 0   &&
953             (N->Info & OF_ZBRA) != 0            &&
954             !RegAUsed (S, I+1)) {
955
956             /* Replace the branch condition */
957             switch (GetBranchCond (N->OPC)) {
958                 case BC_EQ:     CE_ReplaceOPC (N, OP65_JCC); break;
959                 case BC_NE:     CE_ReplaceOPC (N, OP65_JCS); break;
960                 default:        Internal ("Unknown branch condition in OptCondBranches2");
961             }
962
963             /* Delete the rol insn */
964             CS_DelEntry (S, I);
965
966             /* Remember, we had changes */
967             ++Changes;
968         }
969
970         /* Next entry */
971         ++I;
972     }
973
974     /* Free register info */
975     CS_FreeRegInfo (S);
976
977     /* Return the number of changes made */
978     return Changes;
979 }
980
981
982
983 /*****************************************************************************/
984 /*                      Remove unused loads and stores                       */
985 /*****************************************************************************/
986
987
988
989 unsigned OptUnusedLoads (CodeSeg* S)
990 /* Remove loads of registers where the value loaded is not used later. */
991 {
992     unsigned Changes = 0;
993
994     /* Walk over the entries */
995     unsigned I = 0;
996     while (I < CS_GetEntryCount (S)) {
997
998         CodeEntry* N;
999
1000         /* Get next entry */
1001         CodeEntry* E = CS_GetEntry (S, I);
1002
1003         /* Check if it's a register load or transfer insn */
1004         if ((E->Info & (OF_LOAD | OF_XFR | OF_REG_INCDEC)) != 0         &&
1005             (N = CS_GetNextEntry (S, I)) != 0                           &&
1006             !CE_UseLoadFlags (N)) {
1007
1008             /* Check which sort of load or transfer it is */
1009             unsigned R;
1010             switch (E->OPC) {
1011                 case OP65_DEA:
1012                 case OP65_INA:
1013                 case OP65_LDA:
1014                 case OP65_TXA:
1015                 case OP65_TYA:  R = REG_A;      break;
1016                 case OP65_DEX:
1017                 case OP65_INX:
1018                 case OP65_LDX:
1019                 case OP65_TAX:  R = REG_X;      break;
1020                 case OP65_DEY:
1021                 case OP65_INY:
1022                 case OP65_LDY:
1023                 case OP65_TAY:  R = REG_Y;      break;
1024                 default:        goto NextEntry;         /* OOPS */
1025             }
1026
1027             /* Get register usage and check if the register value is used later */
1028             if ((GetRegInfo (S, I+1, R) & R) == 0) {
1029
1030                 /* Register value is not used, remove the load */
1031                 CS_DelEntry (S, I);
1032
1033                 /* Remember, we had changes. Account the deleted entry in I. */
1034                 ++Changes;
1035                 --I;
1036
1037             }
1038         }
1039
1040 NextEntry:
1041         /* Next entry */
1042         ++I;
1043
1044     }
1045
1046     /* Return the number of changes made */
1047     return Changes;
1048 }
1049
1050
1051
1052 unsigned OptUnusedStores (CodeSeg* S)
1053 /* Remove stores into zero page registers that aren't used later */
1054 {
1055     unsigned Changes = 0;
1056
1057     /* Walk over the entries */
1058     unsigned I = 0;
1059     while (I < CS_GetEntryCount (S)) {
1060
1061         /* Get next entry */
1062         CodeEntry* E = CS_GetEntry (S, I);
1063
1064         /* Check if it's a register load or transfer insn */
1065         if ((E->Info & OF_STORE) != 0    &&
1066             E->AM == AM65_ZP             &&
1067             (E->Chg & REG_ZP) != 0) {
1068
1069             /* Check for the zero page location. We know that there cannot be
1070              * more than one zero page location involved in the store.
1071              */
1072             unsigned R = E->Chg & REG_ZP;
1073
1074             /* Get register usage and check if the register value is used later */
1075             if ((GetRegInfo (S, I+1, R) & R) == 0) {
1076
1077                 /* Register value is not used, remove the load */
1078                 CS_DelEntry (S, I);
1079
1080                 /* Remember, we had changes */
1081                 ++Changes;
1082
1083                 /* Continue with next insn */
1084                 continue;
1085             }
1086         }
1087
1088         /* Next entry */
1089         ++I;
1090
1091     }
1092
1093     /* Return the number of changes made */
1094     return Changes;
1095 }
1096
1097
1098
1099 unsigned OptDupLoads (CodeSeg* S)
1100 /* Remove loads of registers where the value loaded is already in the register. */
1101 {
1102     unsigned Changes = 0;
1103     unsigned I;
1104
1105     /* Generate register info for this step */
1106     CS_GenRegInfo (S);
1107
1108     /* Walk over the entries */
1109     I = 0;
1110     while (I < CS_GetEntryCount (S)) {
1111
1112         CodeEntry* N;
1113
1114         /* Get next entry */
1115         CodeEntry* E = CS_GetEntry (S, I);
1116
1117         /* Assume we won't delete the entry */
1118         int Delete = 0;
1119
1120         /* Get a pointer to the input registers of the insn */
1121         const RegContents* In  = &E->RI->In;
1122
1123         /* Handle the different instructions */
1124         switch (E->OPC) {
1125
1126             case OP65_LDA:
1127                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1128                     CE_IsKnownImm (E, In->RegA)       && /* Value to be loaded is known */
1129                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1130                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1131                     Delete = 1;
1132                 }
1133                 break;
1134
1135             case OP65_LDX:
1136                 if (RegValIsKnown (In->RegX)          && /* Value of X is known */
1137                     CE_IsKnownImm (E, In->RegX)       && /* Value to be loaded is known */
1138                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1139                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1140                     Delete = 1;
1141                 }
1142                 break;
1143
1144             case OP65_LDY:
1145                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1146                     CE_IsKnownImm (E, In->RegY)       && /* Value to be loaded is known */
1147                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1148                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1149                     Delete = 1;
1150                 }
1151                 break;
1152
1153             case OP65_STA:
1154                 /* If we store into a known zero page location, and this
1155                  * location does already contain the value to be stored,
1156                  * remove the store.
1157                  */
1158                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1159                     E->AM == AM65_ZP                  && /* Store into zp */
1160                     In->RegA == ZPRegVal (E->Chg, In)) { /* Value identical */
1161
1162                     Delete = 1;
1163                 }
1164                 break;
1165
1166             case OP65_STX:
1167                 /* If we store into a known zero page location, and this
1168                  * location does already contain the value to be stored,
1169                  * remove the store.
1170                  */
1171                 if (RegValIsKnown (In->RegX)          && /* Value of A is known */
1172                     E->AM == AM65_ZP                  && /* Store into zp */
1173                     In->RegX == ZPRegVal (E->Chg, In)) { /* Value identical */
1174
1175                     Delete = 1;
1176
1177                 /* If the value in the X register is known and the same as
1178                  * that in the A register, replace the store by a STA. The
1179                  * optimizer will then remove the load instruction for X
1180                  * later. STX does support the zeropage,y addressing mode,
1181                  * so be sure to check for that.
1182                  */
1183                 } else if (RegValIsKnown (In->RegX)   &&
1184                            In->RegX == In->RegA       &&
1185                            E->AM != AM65_ABSY         &&
1186                            E->AM != AM65_ZPY) {
1187                     /* Use the A register instead */
1188                     CE_ReplaceOPC (E, OP65_STA);
1189                 }
1190                 break;
1191
1192             case OP65_STY:
1193                 /* If we store into a known zero page location, and this
1194                  * location does already contain the value to be stored,
1195                  * remove the store.
1196                  */
1197                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1198                     E->AM == AM65_ZP                  && /* Store into zp */
1199                     In->RegY == ZPRegVal (E->Chg, In)) { /* Value identical */
1200
1201                     Delete = 1;
1202
1203                 /* If the value in the Y register is known and the same as
1204                  * that in the A register, replace the store by a STA. The
1205                  * optimizer will then remove the load instruction for Y
1206                  * later. If replacement by A is not possible try a
1207                  * replacement by X, but check for invalid addressing modes
1208                  * in this case.
1209                  */
1210                 } else if (RegValIsKnown (In->RegY)) {
1211                     if (In->RegY == In->RegA) {
1212                         CE_ReplaceOPC (E, OP65_STA);
1213                     } else if (In->RegY == In->RegX   &&
1214                                E->AM != AM65_ABSX     &&
1215                                E->AM != AM65_ZPX) {
1216                         CE_ReplaceOPC (E, OP65_STX);
1217                     }
1218                 }
1219                 break;
1220
1221             case OP65_STZ:
1222                 /* If we store into a known zero page location, and this
1223                  * location does already contain the value to be stored,
1224                  * remove the store.
1225                  */
1226                 if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && E->AM == AM65_ZP) {
1227                     if (ZPRegVal (E->Chg, In) == 0) {
1228                         Delete = 1;
1229                     }
1230                 }
1231                 break;
1232
1233             case OP65_TAX:
1234                 if (RegValIsKnown (In->RegA)          &&
1235                     In->RegA == In->RegX              &&
1236                     (N = CS_GetNextEntry (S, I)) != 0 &&
1237                     !CE_UseLoadFlags (N)) {
1238                     /* Value is identical and not followed by a branch */
1239                     Delete = 1;
1240                 }
1241                 break;
1242
1243             case OP65_TAY:
1244                 if (RegValIsKnown (In->RegA)            &&
1245                     In->RegA == In->RegY                &&
1246                     (N = CS_GetNextEntry (S, I)) != 0   &&
1247                     !CE_UseLoadFlags (N)) {
1248                     /* Value is identical and not followed by a branch */
1249                     Delete = 1;
1250                 }
1251                 break;
1252
1253             case OP65_TXA:
1254                 if (RegValIsKnown (In->RegX)            &&
1255                     In->RegX == In->RegA                &&
1256                     (N = CS_GetNextEntry (S, I)) != 0   &&
1257                     !CE_UseLoadFlags (N)) {
1258                     /* Value is identical and not followed by a branch */
1259                     Delete = 1;
1260                 }
1261                 break;
1262
1263             case OP65_TYA:
1264                 if (RegValIsKnown (In->RegY)            &&
1265                     In->RegY == In->RegA                &&
1266                     (N = CS_GetNextEntry (S, I)) != 0   &&
1267                     !CE_UseLoadFlags (N)) {
1268                     /* Value is identical and not followed by a branch */
1269                     Delete = 1;
1270                 }
1271                 break;
1272
1273             default:
1274                 break;
1275
1276         }
1277
1278         /* Delete the entry if requested */
1279         if (Delete) {
1280
1281             /* Register value is not used, remove the load */
1282             CS_DelEntry (S, I);
1283
1284             /* Remember, we had changes */
1285             ++Changes;
1286
1287         } else {
1288
1289             /* Next entry */
1290             ++I;
1291
1292         }
1293
1294     }
1295
1296     /* Free register info */
1297     CS_FreeRegInfo (S);
1298
1299     /* Return the number of changes made */
1300     return Changes;
1301 }
1302
1303
1304
1305 unsigned OptStoreLoad (CodeSeg* S)
1306 /* Remove a store followed by a load from the same location. */
1307 {
1308     unsigned Changes = 0;
1309
1310     /* Walk over the entries */
1311     unsigned I = 0;
1312     while (I < CS_GetEntryCount (S)) {
1313
1314         CodeEntry* N;
1315         CodeEntry* X;
1316
1317         /* Get next entry */
1318         CodeEntry* E = CS_GetEntry (S, I);
1319
1320         /* Check if it is a store instruction followed by a load from the
1321          * same address which is itself not followed by a conditional branch.
1322          */
1323         if ((E->Info & OF_STORE) != 0                       &&
1324             (N = CS_GetNextEntry (S, I)) != 0               &&
1325             !CE_HasLabel (N)                                &&
1326             E->AM == N->AM                                  &&
1327             ((E->OPC == OP65_STA && N->OPC == OP65_LDA) ||
1328              (E->OPC == OP65_STX && N->OPC == OP65_LDX) ||
1329              (E->OPC == OP65_STY && N->OPC == OP65_LDY))    &&
1330             strcmp (E->Arg, N->Arg) == 0                    &&
1331             (X = CS_GetNextEntry (S, I+1)) != 0             &&
1332             !CE_UseLoadFlags (X)) {
1333
1334             /* Register has already the correct value, remove the load */
1335             CS_DelEntry (S, I+1);
1336
1337             /* Remember, we had changes */
1338             ++Changes;
1339
1340         }
1341
1342         /* Next entry */
1343         ++I;
1344
1345     }
1346
1347     /* Return the number of changes made */
1348     return Changes;
1349 }
1350
1351
1352
1353 unsigned OptTransfers1 (CodeSeg* S)
1354 /* Remove transfers from one register to another and back */
1355 {
1356     unsigned Changes = 0;
1357
1358     /* Walk over the entries */
1359     unsigned I = 0;
1360     while (I < CS_GetEntryCount (S)) {
1361
1362         CodeEntry* N;
1363         CodeEntry* X;
1364         CodeEntry* P;
1365
1366         /* Get next entry */
1367         CodeEntry* E = CS_GetEntry (S, I);
1368
1369         /* Check if we have two transfer instructions */
1370         if ((E->Info & OF_XFR) != 0                 &&
1371             (N = CS_GetNextEntry (S, I)) != 0       &&
1372             !CE_HasLabel (N)                        &&
1373             (N->Info & OF_XFR) != 0) {
1374
1375             /* Check if it's a transfer and back */
1376             if ((E->OPC == OP65_TAX && N->OPC == OP65_TXA && !RegXUsed (S, I+2)) ||
1377                 (E->OPC == OP65_TAY && N->OPC == OP65_TYA && !RegYUsed (S, I+2)) ||
1378                 (E->OPC == OP65_TXA && N->OPC == OP65_TAX && !RegAUsed (S, I+2)) ||
1379                 (E->OPC == OP65_TYA && N->OPC == OP65_TAY && !RegAUsed (S, I+2))) {
1380
1381                 /* If the next insn is a conditional branch, check if the insn
1382                  * preceeding the first xfr will set the flags right, otherwise we
1383                  * may not remove the sequence.
1384                  */
1385                 if ((X = CS_GetNextEntry (S, I+1)) == 0) {
1386                     goto NextEntry;
1387                 }
1388                 if (CE_UseLoadFlags (X)) {
1389                     if (I == 0) {
1390                         /* No preceeding entry */
1391                         goto NextEntry;
1392                     }
1393                     P = CS_GetEntry (S, I-1);
1394                     if ((P->Info & OF_SETF) == 0) {
1395                         /* Does not set the flags */
1396                         goto NextEntry;
1397                     }
1398                 }
1399
1400                 /* Remove both transfers */
1401                 CS_DelEntry (S, I+1);
1402                 CS_DelEntry (S, I);
1403
1404                 /* Remember, we had changes */
1405                 ++Changes;
1406             }
1407         }
1408
1409 NextEntry:
1410         /* Next entry */
1411         ++I;
1412
1413     }
1414
1415     /* Return the number of changes made */
1416     return Changes;
1417 }
1418
1419
1420
1421 unsigned OptTransfers2 (CodeSeg* S)
1422 /* Replace loads followed by a register transfer by a load with the second
1423  * register if possible.
1424  */
1425 {
1426     unsigned Changes = 0;
1427
1428     /* Walk over the entries */
1429     unsigned I = 0;
1430     while (I < CS_GetEntryCount (S)) {
1431
1432         CodeEntry* N;
1433
1434         /* Get next entry */
1435         CodeEntry* E = CS_GetEntry (S, I);
1436
1437         /* Check if we have a load followed by a transfer where the loaded
1438          * register is not used later.
1439          */
1440         if ((E->Info & OF_LOAD) != 0                &&
1441             (N = CS_GetNextEntry (S, I)) != 0       &&
1442             !CE_HasLabel (N)                        &&
1443             (N->Info & OF_XFR) != 0                 &&
1444             GetRegInfo (S, I+2, E->Chg) != E->Chg) {
1445
1446             CodeEntry* X = 0;
1447
1448             if (E->OPC == OP65_LDA && N->OPC == OP65_TAX) {
1449                 /* LDA/TAX - check for the right addressing modes */
1450                 if (E->AM == AM65_IMM ||
1451                     E->AM == AM65_ZP  ||
1452                     E->AM == AM65_ABS ||
1453                     E->AM == AM65_ABSY) {
1454                     /* Replace */
1455                     X = NewCodeEntry (OP65_LDX, E->AM, E->Arg, 0, N->LI);
1456                 }
1457             } else if (E->OPC == OP65_LDA && N->OPC == OP65_TAY) {
1458                 /* LDA/TAY - check for the right addressing modes */
1459                 if (E->AM == AM65_IMM ||
1460                     E->AM == AM65_ZP  ||
1461                     E->AM == AM65_ZPX ||
1462                     E->AM == AM65_ABS ||
1463                     E->AM == AM65_ABSX) {
1464                     /* Replace */
1465                     X = NewCodeEntry (OP65_LDY, E->AM, E->Arg, 0, N->LI);
1466                 }
1467             } else if (E->OPC == OP65_LDY && N->OPC == OP65_TYA) {
1468                 /* LDY/TYA. LDA supports all addressing modes LDY does */
1469                 X = NewCodeEntry (OP65_LDA, E->AM, E->Arg, 0, N->LI);
1470             } else if (E->OPC == OP65_LDX && N->OPC == OP65_TXA) {
1471                 /* LDX/TXA. LDA doesn't support zp,y, so we must map it to
1472                  * abs,y instead.
1473                  */
1474                 am_t AM = (E->AM == AM65_ZPY)? AM65_ABSY : E->AM;
1475                 X = NewCodeEntry (OP65_LDA, AM, E->Arg, 0, N->LI);
1476             }
1477
1478             /* If we have a load entry, add it and remove the old stuff */
1479             if (X) {
1480                 CS_InsertEntry (S, X, I+2);
1481                 CS_DelEntries (S, I, 2);
1482                 ++Changes;
1483                 --I;    /* Correct for one entry less */
1484             }
1485         }
1486
1487         /* Next entry */
1488         ++I;
1489     }
1490
1491     /* Return the number of changes made */
1492     return Changes;
1493 }
1494
1495
1496
1497 unsigned OptTransfers3 (CodeSeg* S)
1498 /* Replace a register transfer followed by a store of the second register by a
1499  * store of the first register if this is possible.
1500  */
1501 {
1502     unsigned Changes      = 0;
1503     unsigned UsedRegs     = REG_NONE;   /* Track used registers */
1504     unsigned Xfer         = 0;          /* Index of transfer insn */
1505     unsigned Store        = 0;          /* Index of store insn */
1506     CodeEntry* XferEntry  = 0;          /* Pointer to xfer insn */
1507     CodeEntry* StoreEntry = 0;          /* Pointer to store insn */
1508
1509     enum {
1510         Initialize,
1511         Search,
1512         FoundXfer,
1513         FoundStore
1514     } State = Initialize;
1515
1516     /* Walk over the entries. Look for a xfer instruction that is followed by
1517      * a store later, where the value of the register is not used later.
1518      */
1519     unsigned I = 0;
1520     while (I < CS_GetEntryCount (S)) {
1521
1522         /* Get next entry */
1523         CodeEntry* E = CS_GetEntry (S, I);
1524
1525         switch (State) {
1526
1527             case Initialize:
1528                 /* Clear the list of used registers */
1529                 UsedRegs = REG_NONE;
1530                 /* FALLTHROUGH */
1531
1532             case Search:
1533                 if (E->Info & OF_XFR) {
1534                     /* Found start of sequence */
1535                     Xfer = I;
1536                     XferEntry = E;
1537                     State = FoundXfer;
1538                 }
1539                 break;
1540
1541             case FoundXfer:
1542                 /* If we find a conditional jump, abort the sequence, since
1543                  * handling them makes things really complicated.
1544                  */
1545                 if (E->Info & OF_CBRA) {
1546
1547                     /* Switch back to searching */
1548                     I = Xfer;
1549                     State = Initialize;
1550
1551                 /* Does this insn use the target register of the transfer? */
1552                 } else if ((E->Use & XferEntry->Chg) != 0) {
1553
1554                     /* It it's a store instruction, and the block is a basic
1555                      * block, proceed. Otherwise restart
1556                      */
1557                     if ((E->Info & OF_STORE) != 0       &&
1558                         CS_IsBasicBlock (S, Xfer, I)) {
1559                         Store = I;
1560                         StoreEntry = E;
1561                         State = FoundStore;
1562                     } else {
1563                         I = Xfer;
1564                         State = Initialize;
1565                     }
1566
1567                 /* Does this insn change the target register of the transfer? */
1568                 } else if (E->Chg & XferEntry->Chg) {
1569
1570                     /* We *may* add code here to remove the transfer, but I'm
1571                      * currently not sure about the consequences, so I won't
1572                      * do that and bail out instead.
1573                      */
1574                     I = Xfer;
1575                     State = Initialize;
1576
1577                 /* Does this insn have a label? */
1578                 } else if (CE_HasLabel (E)) {
1579
1580                     /* Too complex to handle - bail out */
1581                     I = Xfer;
1582                     State = Initialize;
1583
1584                 } else {
1585                     /* Track used registers */
1586                     UsedRegs |= E->Use;
1587                 }
1588                 break;
1589
1590             case FoundStore:
1591                 /* We are at the instruction behind the store. If the register
1592                  * isn't used later, and we have an address mode match, we can
1593                  * replace the transfer by a store and remove the store here.
1594                  */
1595                 if ((GetRegInfo (S, I, XferEntry->Chg) & XferEntry->Chg) == 0   &&
1596                     (StoreEntry->AM == AM65_ABS         ||
1597                      StoreEntry->AM == AM65_ZP)                                 &&
1598                     (StoreEntry->AM != AM65_ZP ||
1599                      (StoreEntry->Chg & UsedRegs) == 0)                         &&
1600                     !MemAccess (S, Xfer+1, Store-1, StoreEntry)) {
1601
1602                     /* Generate the replacement store insn */
1603                     CodeEntry* X = 0;
1604                     switch (XferEntry->OPC) {
1605
1606                         case OP65_TXA:
1607                             X = NewCodeEntry (OP65_STX,
1608                                               StoreEntry->AM,
1609                                               StoreEntry->Arg,
1610                                               0,
1611                                               StoreEntry->LI);
1612                             break;
1613
1614                         case OP65_TAX:
1615                             X = NewCodeEntry (OP65_STA,
1616                                               StoreEntry->AM,
1617                                               StoreEntry->Arg,
1618                                               0,
1619                                               StoreEntry->LI);
1620                             break;
1621
1622                         case OP65_TYA:
1623                             X = NewCodeEntry (OP65_STY,
1624                                               StoreEntry->AM,
1625                                               StoreEntry->Arg,
1626                                               0,
1627                                               StoreEntry->LI);
1628                             break;
1629
1630                         case OP65_TAY:
1631                             X = NewCodeEntry (OP65_STA,
1632                                               StoreEntry->AM,
1633                                               StoreEntry->Arg,
1634                                               0,
1635                                               StoreEntry->LI);
1636                             break;
1637
1638                         default:
1639                             break;
1640                     }
1641
1642                     /* If we have a replacement store, change the code */
1643                     if (X) {
1644                         /* Insert after the xfer insn */
1645                         CS_InsertEntry (S, X, Xfer+1);
1646
1647                         /* Remove the xfer instead */
1648                         CS_DelEntry (S, Xfer);
1649
1650                         /* Remove the final store */
1651                         CS_DelEntry (S, Store);
1652
1653                         /* Correct I so we continue with the next insn */
1654                         I -= 2;
1655
1656                         /* Remember we had changes */
1657                         ++Changes;
1658                     } else {
1659                         /* Restart after last xfer insn */
1660                         I = Xfer;
1661                     }
1662                 } else {
1663                     /* Restart after last xfer insn */
1664                     I = Xfer;
1665                 }
1666                 State = Initialize;
1667                 break;
1668
1669         }
1670
1671         /* Next entry */
1672         ++I;
1673     }
1674
1675     /* Return the number of changes made */
1676     return Changes;
1677 }
1678
1679
1680
1681 unsigned OptTransfers4 (CodeSeg* S)
1682 /* Replace a load of a register followed by a transfer insn of the same register
1683  * by a load of the second register if possible.
1684  */
1685 {
1686     unsigned Changes      = 0;
1687     unsigned Load         = 0;  /* Index of load insn */
1688     unsigned Xfer         = 0;  /* Index of transfer insn */
1689     CodeEntry* LoadEntry  = 0;  /* Pointer to load insn */
1690     CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
1691
1692     enum {
1693         Search,
1694         FoundLoad,
1695         FoundXfer
1696     } State = Search;
1697
1698     /* Walk over the entries. Look for a load instruction that is followed by
1699      * a load later.
1700      */
1701     unsigned I = 0;
1702     while (I < CS_GetEntryCount (S)) {
1703
1704         /* Get next entry */
1705         CodeEntry* E = CS_GetEntry (S, I);
1706
1707         switch (State) {
1708
1709             case Search:
1710                 if (E->Info & OF_LOAD) {
1711                     /* Found start of sequence */
1712                     Load = I;
1713                     LoadEntry = E;
1714                     State = FoundLoad;
1715                 }
1716                 break;
1717
1718             case FoundLoad:
1719                 /* If we find a conditional jump, abort the sequence, since
1720                  * handling them makes things really complicated.
1721                  */
1722                 if (E->Info & OF_CBRA) {
1723
1724                     /* Switch back to searching */
1725                     I = Load;
1726                     State = Search;
1727
1728                 /* Does this insn use the target register of the load? */
1729                 } else if ((E->Use & LoadEntry->Chg) != 0) {
1730
1731                     /* It it's a xfer instruction, and the block is a basic
1732                      * block, proceed. Otherwise restart
1733                      */
1734                     if ((E->Info & OF_XFR) != 0       &&
1735                         CS_IsBasicBlock (S, Load, I)) {
1736                         Xfer = I;
1737                         XferEntry = E;
1738                         State = FoundXfer;
1739                     } else {
1740                         I = Load;
1741                         State = Search;
1742                     }
1743
1744                 /* Does this insn change the target register of the load? */
1745                 } else if (E->Chg & LoadEntry->Chg) {
1746
1747                     /* We *may* add code here to remove the load, but I'm
1748                      * currently not sure about the consequences, so I won't
1749                      * do that and bail out instead.
1750                      */
1751                     I = Load;
1752                     State = Search;
1753                 }
1754                 break;
1755
1756             case FoundXfer:
1757                 /* We are at the instruction behind the xfer. If the register
1758                  * isn't used later, and we have an address mode match, we can
1759                  * replace the transfer by a load and remove the initial load.
1760                  */
1761                 if ((GetRegInfo (S, I, LoadEntry->Chg) & LoadEntry->Chg) == 0   &&
1762                     (LoadEntry->AM == AM65_ABS          ||
1763                      LoadEntry->AM == AM65_ZP           ||
1764                      LoadEntry->AM == AM65_IMM)                                 &&
1765                     !MemAccess (S, Load+1, Xfer-1, LoadEntry)) {
1766
1767                     /* Generate the replacement load insn */
1768                     CodeEntry* X = 0;
1769                     switch (XferEntry->OPC) {
1770
1771                         case OP65_TXA:
1772                         case OP65_TYA:
1773                             X = NewCodeEntry (OP65_LDA,
1774                                               LoadEntry->AM,
1775                                               LoadEntry->Arg,
1776                                               0,
1777                                               LoadEntry->LI);
1778                             break;
1779
1780                         case OP65_TAX:
1781                             X = NewCodeEntry (OP65_LDX,
1782                                               LoadEntry->AM,
1783                                               LoadEntry->Arg,
1784                                               0,
1785                                               LoadEntry->LI);
1786                             break;
1787
1788                         case OP65_TAY:
1789                             X = NewCodeEntry (OP65_LDY,
1790                                               LoadEntry->AM,
1791                                               LoadEntry->Arg,
1792                                               0,
1793                                               LoadEntry->LI);
1794                             break;
1795
1796                         default:
1797                             break;
1798                     }
1799
1800                     /* If we have a replacement load, change the code */
1801                     if (X) {
1802                         /* Insert after the xfer insn */
1803                         CS_InsertEntry (S, X, Xfer+1);
1804
1805                         /* Remove the xfer instead */
1806                         CS_DelEntry (S, Xfer);
1807
1808                         /* Remove the initial load */
1809                         CS_DelEntry (S, Load);
1810
1811                         /* Correct I so we continue with the next insn */
1812                         I -= 2;
1813
1814                         /* Remember we had changes */
1815                         ++Changes;
1816                     } else {
1817                         /* Restart after last xfer insn */
1818                         I = Xfer;
1819                     }
1820                 } else {
1821                     /* Restart after last xfer insn */
1822                     I = Xfer;
1823                 }
1824                 State = Search;
1825                 break;
1826
1827         }
1828
1829         /* Next entry */
1830         ++I;
1831     }
1832
1833     /* Return the number of changes made */
1834     return Changes;
1835 }
1836
1837
1838
1839 unsigned OptPushPop (CodeSeg* S)
1840 /* Remove a PHA/PLA sequence were A is not used later */
1841 {
1842     unsigned Changes = 0;
1843     unsigned Push    = 0;       /* Index of push insn */
1844     unsigned Pop     = 0;       /* Index of pop insn */
1845     unsigned ChgA    = 0;       /* Flag for A changed */
1846     enum {
1847         Searching,
1848         FoundPush,
1849         FoundPop
1850     } State = Searching;
1851
1852     /* Walk over the entries. Look for a push instruction that is followed by
1853      * a pop later, where the pop is not followed by an conditional branch,
1854      * and where the value of the A register is not used later on.
1855      * Look out for the following problems:
1856      *
1857      *  - There may be another PHA/PLA inside the sequence: Restart it.
1858      *  - If the PLA has a label, all jumps to this label must be inside
1859      *    the sequence, otherwise we cannot remove the PHA/PLA.
1860      */
1861     unsigned I = 0;
1862     while (I < CS_GetEntryCount (S)) {
1863
1864         CodeEntry* X;
1865
1866         /* Get next entry */
1867         CodeEntry* E = CS_GetEntry (S, I);
1868
1869         switch (State) {
1870
1871             case Searching:
1872                 if (E->OPC == OP65_PHA) {
1873                     /* Found start of sequence */
1874                     Push  = I;
1875                     ChgA  = 0;
1876                     State = FoundPush;
1877                 }
1878                 break;
1879
1880             case FoundPush:
1881                 if (E->OPC == OP65_PHA) {
1882                     /* Inner push/pop, restart */
1883                     Push = I;
1884                     ChgA = 0;
1885                 } else if (E->OPC == OP65_PLA) {
1886                     /* Found a matching pop */
1887                     Pop = I;
1888                     /* Check that the block between Push and Pop is a basic
1889                      * block (one entry, one exit). Otherwise ignore it.
1890                      */
1891                     if (CS_IsBasicBlock (S, Push, Pop)) {
1892                         State = FoundPop;
1893                     } else {
1894                         /* Go into searching mode again */
1895                         State = Searching;
1896                     }
1897                 } else if (E->Chg & REG_A) {
1898                     ChgA = 1;
1899                 }
1900                 break;
1901
1902             case FoundPop:
1903                 /* We're at the instruction after the PLA.
1904                  * Check for the following conditions:
1905                  *   - If this instruction is a store of A, and A is not used
1906                  *     later, we may replace the PHA by the store and remove
1907                  *     pla if several other conditions are met.
1908                  *   - If this instruction is not a conditional branch, and A
1909                  *     is either unused later, or not changed by the code
1910                  *     between push and pop, we may remove PHA and PLA.
1911                  */
1912                 if (E->OPC == OP65_STA                  &&
1913                     !RegAUsed (S, I+1)                  &&
1914                     !MemAccess (S, Push+1, Pop-1, E)) {
1915
1916                     /* Insert a STA after the PHA */
1917                     X = NewCodeEntry (E->OPC, E->AM, E->Arg, E->JumpTo, E->LI);
1918                     CS_InsertEntry (S, X, Push+1);
1919
1920                     /* Remove the PHA instead */
1921                     CS_DelEntry (S, Push);
1922
1923                     /* Remove the PLA/STA sequence */
1924                     CS_DelEntries (S, Pop, 2);
1925
1926                     /* Correct I so we continue with the next insn */
1927                     I -= 2;
1928
1929                     /* Remember we had changes */
1930                     ++Changes;
1931
1932                 } else if ((E->Info & OF_CBRA) == 0     &&
1933                            (!RegAUsed (S, I) || !ChgA)) {
1934
1935                     /* We can remove the PHA and PLA instructions */
1936                     CS_DelEntry (S, Pop);
1937                     CS_DelEntry (S, Push);
1938
1939                     /* Correct I so we continue with the next insn */
1940                     I -= 2;
1941
1942                     /* Remember we had changes */
1943                     ++Changes;
1944
1945                 }
1946                 /* Go into search mode again */
1947                 State = Searching;
1948                 break;
1949
1950         }
1951
1952         /* Next entry */
1953         ++I;
1954     }
1955
1956     /* Return the number of changes made */
1957     return Changes;
1958 }
1959
1960
1961
1962 unsigned OptPrecalc (CodeSeg* S)
1963 /* Replace immediate operations with the accu where the current contents are
1964  * known by a load of the final value.
1965  */
1966 {
1967     unsigned Changes = 0;
1968     unsigned I;
1969
1970     /* Generate register info for this step */
1971     CS_GenRegInfo (S);
1972
1973     /* Walk over the entries */
1974     I = 0;
1975     while (I < CS_GetEntryCount (S)) {
1976
1977         /* Get next entry */
1978         CodeEntry* E = CS_GetEntry (S, I);
1979
1980         /* Get pointers to the input and output registers of the insn */
1981         const RegContents* Out = &E->RI->Out;
1982         const RegContents* In  = &E->RI->In;
1983
1984         /* Argument for LDn and flag */
1985         const char* Arg = 0;
1986         opc_t OPC = OP65_LDA;
1987
1988         /* Handle the different instructions */
1989         switch (E->OPC) {
1990
1991             case OP65_LDA:
1992                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegA)) {
1993                     /* Result of load is known */
1994                     Arg = MakeHexArg (Out->RegA);
1995                 }
1996                 break;
1997
1998             case OP65_LDX:
1999                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegX)) {
2000                     /* Result of load is known but register is X */
2001                     Arg = MakeHexArg (Out->RegX);
2002                     OPC = OP65_LDX;
2003                 }
2004                 break;
2005
2006             case OP65_LDY:
2007                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegY)) {
2008                     /* Result of load is known but register is Y */
2009                     Arg = MakeHexArg (Out->RegY);
2010                     OPC = OP65_LDY;
2011                 }
2012                 break;
2013
2014             case OP65_EOR:
2015                 if (RegValIsKnown (Out->RegA)) {
2016                     /* Accu op zp with known contents */
2017                     Arg = MakeHexArg (Out->RegA);
2018                 }
2019                 break;
2020
2021             case OP65_ADC:
2022             case OP65_SBC:
2023                 /* If this is an operation with an immediate operand of zero,
2024                  * and the register is zero, the operation won't give us any
2025                  * results we don't already have (including the flags), so
2026                  * remove it. Something like this is generated as a result of
2027                  * a compare where parts of the values are known to be zero.
2028                  */
2029                 if (In->RegA == 0 && CE_IsKnownImm (E, 0x00)) {
2030                     /* 0-0 or 0+0 -> remove */
2031                     CS_DelEntry (S, I);
2032                     ++Changes;
2033                 }
2034                 break;
2035
2036             case OP65_AND:
2037                 if (CE_IsKnownImm (E, 0xFF)) {
2038                     /* AND with 0xFF, remove */
2039                     CS_DelEntry (S, I);
2040                     ++Changes;
2041                 } else if (CE_IsKnownImm (E, 0x00)) {
2042                     /* AND with 0x00, replace by lda #$00 */
2043                     Arg = MakeHexArg (0x00);
2044                 } else if (RegValIsKnown (Out->RegA)) {
2045                     /* Accu AND zp with known contents */
2046                     Arg = MakeHexArg (Out->RegA);
2047                 } else if (In->RegA == 0xFF) {
2048                     /* AND but A contains 0xFF - replace by lda */
2049                     CE_ReplaceOPC (E, OP65_LDA);
2050                     ++Changes;
2051                 }
2052                 break;
2053
2054             case OP65_ORA:
2055                 if (CE_IsKnownImm (E, 0x00)) {
2056                     /* ORA with zero, remove */
2057                     CS_DelEntry (S, I);
2058                     ++Changes;
2059                 } else if (CE_IsKnownImm (E, 0xFF)) {
2060                     /* ORA with 0xFF, replace by lda #$ff */
2061                     Arg = MakeHexArg (0xFF);
2062                 } else if (RegValIsKnown (Out->RegA)) {
2063                     /* Accu AND zp with known contents */
2064                     Arg = MakeHexArg (Out->RegA);
2065                 } else if (In->RegA == 0) {
2066                     /* ORA but A contains 0x00 - replace by lda */
2067                     CE_ReplaceOPC (E, OP65_LDA);
2068                     ++Changes;
2069                 }
2070                 break;
2071
2072             default:
2073                 break;
2074
2075         }
2076
2077         /* Check if we have to replace the insn by LDA */
2078         if (Arg) {
2079             CodeEntry* X = NewCodeEntry (OPC, AM65_IMM, Arg, 0, E->LI);
2080             CS_InsertEntry (S, X, I+1);
2081             CS_DelEntry (S, I);
2082             ++Changes;
2083         }
2084
2085         /* Next entry */
2086         ++I;
2087     }
2088
2089     /* Free register info */
2090     CS_FreeRegInfo (S);
2091
2092     /* Return the number of changes made */
2093     return Changes;
2094 }
2095
2096
2097
2098 /*****************************************************************************/
2099 /*                           Optimize branch types                           */
2100 /*****************************************************************************/
2101
2102
2103
2104 unsigned OptBranchDist (CodeSeg* S)
2105 /* Change branches for the distance needed. */
2106 {
2107     unsigned Changes = 0;
2108
2109     /* Walk over the entries */
2110     unsigned I = 0;
2111     while (I < CS_GetEntryCount (S)) {
2112
2113         /* Get next entry */
2114         CodeEntry* E = CS_GetEntry (S, I);
2115
2116         /* Check if it's a conditional branch to a local label. */
2117         if (E->Info & OF_CBRA) {
2118
2119             /* Is this a branch to a local symbol? */
2120             if (E->JumpTo != 0) {
2121
2122                 /* Check if the branch distance is short */
2123                 int IsShort = IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner));
2124
2125                 /* Make the branch short/long according to distance */
2126                 if ((E->Info & OF_LBRA) == 0 && !IsShort) {
2127                     /* Short branch but long distance */
2128                     CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
2129                     ++Changes;
2130                 } else if ((E->Info & OF_LBRA) != 0 && IsShort) {
2131                     /* Long branch but short distance */
2132                     CE_ReplaceOPC (E, MakeShortBranch (E->OPC));
2133                     ++Changes;
2134                 }
2135
2136             } else if ((E->Info & OF_LBRA) == 0) {
2137
2138                 /* Short branch to external symbol - make it long */
2139                 CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
2140                 ++Changes;
2141
2142             }
2143
2144         } else if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 &&
2145                    (E->Info & OF_UBRA) != 0               &&
2146                    E->JumpTo != 0                         &&
2147                    IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner))) {
2148
2149             /* The jump is short and may be replaced by a BRA on the 65C02 CPU */
2150             CE_ReplaceOPC (E, OP65_BRA);
2151             ++Changes;
2152         }
2153
2154         /* Next entry */
2155         ++I;
2156
2157     }
2158
2159     /* Return the number of changes made */
2160     return Changes;
2161 }
2162
2163
2164
2165 /*****************************************************************************/
2166 /*                          Optimize indirect loads                          */
2167 /*****************************************************************************/
2168
2169
2170
2171 unsigned OptIndLoads1 (CodeSeg* S)
2172 /* Change
2173  *
2174  *     lda      (zp),y
2175  *
2176  * into
2177  *
2178  *     lda      (zp,x)
2179  *
2180  * provided that x and y are both zero.
2181  */
2182 {
2183     unsigned Changes = 0;
2184     unsigned I;
2185
2186     /* Generate register info for this step */
2187     CS_GenRegInfo (S);
2188
2189     /* Walk over the entries */
2190     I = 0;
2191     while (I < CS_GetEntryCount (S)) {
2192
2193         /* Get next entry */
2194         CodeEntry* E = CS_GetEntry (S, I);
2195
2196         /* Check if it's what we're looking for */
2197         if (E->OPC == OP65_LDA          &&
2198             E->AM == AM65_ZP_INDY       &&
2199             E->RI->In.RegY == 0         &&
2200             E->RI->In.RegX == 0) {
2201
2202             /* Replace by the same insn with other addressing mode */
2203             CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZPX_IND, E->Arg, 0, E->LI);
2204             CS_InsertEntry (S, X, I+1);
2205
2206             /* Remove the old insn */
2207             CS_DelEntry (S, I);
2208             ++Changes;
2209         }
2210
2211         /* Next entry */
2212         ++I;
2213
2214     }
2215
2216     /* Free register info */
2217     CS_FreeRegInfo (S);
2218
2219     /* Return the number of changes made */
2220     return Changes;
2221 }
2222
2223
2224
2225 unsigned OptIndLoads2 (CodeSeg* S)
2226 /* Change
2227  *
2228  *     lda      (zp,x)
2229  *
2230  * into
2231  *
2232  *     lda      (zp),y
2233  *
2234  * provided that x and y are both zero.
2235  */
2236 {
2237     unsigned Changes = 0;
2238     unsigned I;
2239
2240     /* Generate register info for this step */
2241     CS_GenRegInfo (S);
2242
2243     /* Walk over the entries */
2244     I = 0;
2245     while (I < CS_GetEntryCount (S)) {
2246
2247         /* Get next entry */
2248         CodeEntry* E = CS_GetEntry (S, I);
2249
2250         /* Check if it's what we're looking for */
2251         if (E->OPC == OP65_LDA          &&
2252             E->AM == AM65_ZPX_IND       &&
2253             E->RI->In.RegY == 0         &&
2254             E->RI->In.RegX == 0) {
2255
2256             /* Replace by the same insn with other addressing mode */
2257             CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZP_INDY, E->Arg, 0, E->LI);
2258             CS_InsertEntry (S, X, I+1);
2259
2260             /* Remove the old insn */
2261             CS_DelEntry (S, I);
2262             ++Changes;
2263         }
2264
2265         /* Next entry */
2266         ++I;
2267
2268     }
2269
2270     /* Free register info */
2271     CS_FreeRegInfo (S);
2272
2273     /* Return the number of changes made */
2274     return Changes;
2275 }
2276
2277
2278