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