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