]> git.sur5r.net Git - cc65/blob - src/cc65/coptind.c
95022e6c102e97ad3a3e668df18d4bd96d8c7c61
[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 OptCondBranches1 (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 unsigned OptCondBranches2 (CodeSeg* S)
803 /* If on entry to a "rol a" instruction the accu is zero, and a beq/bne follows,
804  * we can remove the rol and branch on the state of the carry flag.
805  */
806 {
807     unsigned Changes = 0;
808
809     /* Generate register info for this step */
810     CS_GenRegInfo (S);
811
812     /* Walk over the entries */
813     unsigned I = 0;
814     while (I < CS_GetEntryCount (S)) {
815
816         CodeEntry* N;
817
818         /* Get next entry */
819         CodeEntry* E = CS_GetEntry (S, I);
820
821         /* Check if it's a rol insn with A in accu and a branch follows */
822         if (E->OPC == OP65_ROL                  &&
823             E->AM == AM65_ACC                   &&
824             E->RI->In.RegA == 0                 &&
825             !CE_HasLabel (E)                    &&
826             (N = CS_GetNextEntry (S, I)) != 0   &&
827             (N->Info & OF_ZBRA) != 0            &&
828             !RegAUsed (S, I+1)) {
829
830             /* Replace the branch condition */
831             switch (GetBranchCond (N->OPC)) {
832                 case BC_EQ:     CE_ReplaceOPC (N, OP65_JCC); break;
833                 case BC_NE:     CE_ReplaceOPC (N, OP65_JCS); break;
834                 default:        Internal ("Unknown branch condition in OptCondBranches2");
835             }
836
837             /* Delete the rol insn */
838             CS_DelEntry (S, I);
839
840             /* Remember, we had changes */
841             ++Changes;
842         }
843
844         /* Next entry */
845         ++I;
846     }
847
848     /* Free register info */
849     CS_FreeRegInfo (S);
850
851     /* Return the number of changes made */
852     return Changes;
853 }
854
855
856
857 /*****************************************************************************/
858 /*                      Remove unused loads and stores                       */
859 /*****************************************************************************/
860
861
862
863 unsigned OptUnusedLoads (CodeSeg* S)
864 /* Remove loads of registers where the value loaded is not used later. */
865 {
866     unsigned Changes = 0;
867
868     /* Walk over the entries */
869     unsigned I = 0;
870     while (I < CS_GetEntryCount (S)) {
871
872         CodeEntry* N;
873
874         /* Get next entry */
875         CodeEntry* E = CS_GetEntry (S, I);
876
877         /* Check if it's a register load or transfer insn */
878         if ((E->Info & (OF_LOAD | OF_XFR | OF_REG_INCDEC)) != 0         &&
879             (N = CS_GetNextEntry (S, I)) != 0                           &&
880             !CE_UseLoadFlags (N)) {
881
882             /* Check which sort of load or transfer it is */
883             unsigned R;
884             switch (E->OPC) {
885                 case OP65_DEA:
886                 case OP65_INA:
887                 case OP65_LDA:
888                 case OP65_TXA:
889                 case OP65_TYA:  R = REG_A;      break;
890                 case OP65_DEX:
891                 case OP65_INX:
892                 case OP65_LDX:
893                 case OP65_TAX:  R = REG_X;      break;
894                 case OP65_DEY:
895                 case OP65_INY:
896                 case OP65_LDY:
897                 case OP65_TAY:  R = REG_Y;      break;
898                 default:        goto NextEntry;         /* OOPS */
899             }
900
901             /* Get register usage and check if the register value is used later */
902             if ((GetRegInfo (S, I+1, R) & R) == 0) {
903
904                 /* Register value is not used, remove the load */
905                 CS_DelEntry (S, I);
906
907                 /* Remember, we had changes. Account the deleted entry in I. */
908                 ++Changes;
909                 --I;
910
911             }
912         }
913
914 NextEntry:
915         /* Next entry */
916         ++I;
917
918     }
919
920     /* Return the number of changes made */
921     return Changes;
922 }
923
924
925
926 unsigned OptUnusedStores (CodeSeg* S)
927 /* Remove stores into zero page registers that aren't used later */
928 {
929     unsigned Changes = 0;
930
931     /* Walk over the entries */
932     unsigned I = 0;
933     while (I < CS_GetEntryCount (S)) {
934
935         /* Get next entry */
936         CodeEntry* E = CS_GetEntry (S, I);
937
938         /* Check if it's a register load or transfer insn */
939         if ((E->Info & OF_STORE) != 0    &&
940             E->AM == AM65_ZP             &&
941             (E->Chg & REG_ZP) != 0) {
942
943             /* Check for the zero page location. We know that there cannot be
944              * more than one zero page location involved in the store.
945              */
946             unsigned R = E->Chg & REG_ZP;
947
948             /* Get register usage and check if the register value is used later */
949             if ((GetRegInfo (S, I+1, R) & R) == 0) {
950
951                 /* Register value is not used, remove the load */
952                 CS_DelEntry (S, I);
953
954                 /* Remember, we had changes */
955                 ++Changes;
956
957                 /* Continue with next insn */
958                 continue;
959             }
960         }
961
962         /* Next entry */
963         ++I;
964
965     }
966
967     /* Return the number of changes made */
968     return Changes;
969 }
970
971
972
973 unsigned OptDupLoads (CodeSeg* S)
974 /* Remove loads of registers where the value loaded is already in the register. */
975 {
976     unsigned Changes = 0;
977     unsigned I;
978
979     /* Generate register info for this step */
980     CS_GenRegInfo (S);
981
982     /* Walk over the entries */
983     I = 0;
984     while (I < CS_GetEntryCount (S)) {
985
986         CodeEntry* N;
987
988         /* Get next entry */
989         CodeEntry* E = CS_GetEntry (S, I);
990
991         /* Assume we won't delete the entry */
992         int Delete = 0;
993
994         /* Get a pointer to the input registers of the insn */
995         const RegContents* In  = &E->RI->In;
996
997         /* Handle the different instructions */
998         switch (E->OPC) {
999
1000             case OP65_LDA:
1001                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1002                     CE_IsKnownImm (E, In->RegA)       && /* Value to be loaded is known */
1003                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1004                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1005                     Delete = 1;
1006                 }
1007                 break;
1008
1009             case OP65_LDX:
1010                 if (RegValIsKnown (In->RegX)          && /* Value of X is known */
1011                     CE_IsKnownImm (E, In->RegX)       && /* Value to be loaded is known */
1012                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1013                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1014                     Delete = 1;
1015                 }
1016                 break;
1017
1018             case OP65_LDY:
1019                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1020                     CE_IsKnownImm (E, In->RegY)       && /* Value to be loaded is known */
1021                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1022                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1023                     Delete = 1;
1024                 }
1025                 break;
1026
1027             case OP65_STA:
1028                 /* If we store into a known zero page location, and this
1029                  * location does already contain the value to be stored,
1030                  * remove the store.
1031                  */
1032                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1033                     E->AM == AM65_ZP                  && /* Store into zp */
1034                     In->RegA == ZPRegVal (E->Chg, In)) { /* Value identical */
1035
1036                     Delete = 1;
1037                 }
1038                 break;
1039
1040             case OP65_STX:
1041                 /* If we store into a known zero page location, and this
1042                  * location does already contain the value to be stored,
1043                  * remove the store.
1044                  */
1045                 if (RegValIsKnown (In->RegX)          && /* Value of A is known */
1046                     E->AM == AM65_ZP                  && /* Store into zp */
1047                     In->RegX == ZPRegVal (E->Chg, In)) { /* Value identical */
1048
1049                     Delete = 1;
1050
1051                 /* If the value in the X register is known and the same as
1052                  * that in the A register, replace the store by a STA. The
1053                  * optimizer will then remove the load instruction for X
1054                  * later. STX does support the zeropage,y addressing mode,
1055                  * so be sure to check for that.
1056                  */
1057                 } else if (RegValIsKnown (In->RegX)   &&
1058                            In->RegX == In->RegA       &&
1059                            E->AM != AM65_ABSY         &&
1060                            E->AM != AM65_ZPY) {
1061                     /* Use the A register instead */
1062                     CE_ReplaceOPC (E, OP65_STA);
1063                 }
1064                 break;
1065
1066             case OP65_STY:
1067                 /* If we store into a known zero page location, and this
1068                  * location does already contain the value to be stored,
1069                  * remove the store.
1070                  */
1071                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1072                     E->AM == AM65_ZP                  && /* Store into zp */
1073                     In->RegY == ZPRegVal (E->Chg, In)) { /* Value identical */
1074
1075                     Delete = 1;
1076
1077                 /* If the value in the Y register is known and the same as
1078                  * that in the A register, replace the store by a STA. The
1079                  * optimizer will then remove the load instruction for Y
1080                  * later. If replacement by A is not possible try a
1081                  * replacement by X, but check for invalid addressing modes
1082                  * in this case.
1083                  */
1084                 } else if (RegValIsKnown (In->RegY)) {
1085                     if (In->RegY == In->RegA) {
1086                         CE_ReplaceOPC (E, OP65_STA);
1087                     } else if (In->RegY == In->RegX   &&
1088                                E->AM != AM65_ABSX     &&
1089                                E->AM != AM65_ZPX) {
1090                         CE_ReplaceOPC (E, OP65_STX);
1091                     }
1092                 }
1093                 break;
1094
1095             case OP65_STZ:
1096                 /* If we store into a known zero page location, and this
1097                  * location does already contain the value to be stored,
1098                  * remove the store.
1099                  */
1100                 if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && E->AM == AM65_ZP) {
1101                     if (ZPRegVal (E->Chg, In) == 0) {
1102                         Delete = 1;
1103                     }
1104                 }
1105                 break;
1106
1107             case OP65_TAX:
1108                 if (RegValIsKnown (In->RegA)          &&
1109                     In->RegA == In->RegX              &&
1110                     (N = CS_GetNextEntry (S, I)) != 0 &&
1111                     !CE_UseLoadFlags (N)) {
1112                     /* Value is identical and not followed by a branch */
1113                     Delete = 1;
1114                 }
1115                 break;
1116
1117             case OP65_TAY:
1118                 if (RegValIsKnown (In->RegA)            &&
1119                     In->RegA == In->RegY                &&
1120                     (N = CS_GetNextEntry (S, I)) != 0   &&
1121                     !CE_UseLoadFlags (N)) {
1122                     /* Value is identical and not followed by a branch */
1123                     Delete = 1;
1124                 }
1125                 break;
1126
1127             case OP65_TXA:
1128                 if (RegValIsKnown (In->RegX)            &&
1129                     In->RegX == In->RegA                &&
1130                     (N = CS_GetNextEntry (S, I)) != 0   &&
1131                     !CE_UseLoadFlags (N)) {
1132                     /* Value is identical and not followed by a branch */
1133                     Delete = 1;
1134                 }
1135                 break;
1136
1137             case OP65_TYA:
1138                 if (RegValIsKnown (In->RegY)            &&
1139                     In->RegY == In->RegA                &&
1140                     (N = CS_GetNextEntry (S, I)) != 0   &&
1141                     !CE_UseLoadFlags (N)) {
1142                     /* Value is identical and not followed by a branch */
1143                     Delete = 1;
1144                 }
1145                 break;
1146
1147             default:
1148                 break;
1149
1150         }
1151
1152         /* Delete the entry if requested */
1153         if (Delete) {
1154
1155             /* Register value is not used, remove the load */
1156             CS_DelEntry (S, I);
1157
1158             /* Remember, we had changes */
1159             ++Changes;
1160
1161         } else {
1162
1163             /* Next entry */
1164             ++I;
1165
1166         }
1167
1168     }
1169
1170     /* Free register info */
1171     CS_FreeRegInfo (S);
1172
1173     /* Return the number of changes made */
1174     return Changes;
1175 }
1176
1177
1178
1179 unsigned OptStoreLoad (CodeSeg* S)
1180 /* Remove a store followed by a load from the same location. */
1181 {
1182     unsigned Changes = 0;
1183
1184     /* Walk over the entries */
1185     unsigned I = 0;
1186     while (I < CS_GetEntryCount (S)) {
1187
1188         CodeEntry* N;
1189         CodeEntry* X;
1190
1191         /* Get next entry */
1192         CodeEntry* E = CS_GetEntry (S, I);
1193
1194         /* Check if it is a store instruction followed by a load from the
1195          * same address which is itself not followed by a conditional branch.
1196          */
1197         if ((E->Info & OF_STORE) != 0                       &&
1198             (N = CS_GetNextEntry (S, I)) != 0               &&
1199             !CE_HasLabel (N)                                &&
1200             E->AM == N->AM                                  &&
1201             ((E->OPC == OP65_STA && N->OPC == OP65_LDA) ||
1202              (E->OPC == OP65_STX && N->OPC == OP65_LDX) ||
1203              (E->OPC == OP65_STY && N->OPC == OP65_LDY))    &&
1204             strcmp (E->Arg, N->Arg) == 0                    &&
1205             (X = CS_GetNextEntry (S, I+1)) != 0             &&
1206             !CE_UseLoadFlags (X)) {
1207
1208             /* Register has already the correct value, remove the load */
1209             CS_DelEntry (S, I+1);
1210
1211             /* Remember, we had changes */
1212             ++Changes;
1213
1214         }
1215
1216         /* Next entry */
1217         ++I;
1218
1219     }
1220
1221     /* Return the number of changes made */
1222     return Changes;
1223 }
1224
1225
1226
1227 unsigned OptTransfers1 (CodeSeg* S)
1228 /* Remove transfers from one register to another and back */
1229 {
1230     unsigned Changes = 0;
1231
1232     /* Walk over the entries */
1233     unsigned I = 0;
1234     while (I < CS_GetEntryCount (S)) {
1235
1236         CodeEntry* N;
1237         CodeEntry* X;
1238         CodeEntry* P;
1239
1240         /* Get next entry */
1241         CodeEntry* E = CS_GetEntry (S, I);
1242
1243         /* Check if we have two transfer instructions */
1244         if ((E->Info & OF_XFR) != 0                 &&
1245             (N = CS_GetNextEntry (S, I)) != 0       &&
1246             !CE_HasLabel (N)                        &&
1247             (N->Info & OF_XFR) != 0) {
1248
1249             /* Check if it's a transfer and back */
1250             if ((E->OPC == OP65_TAX && N->OPC == OP65_TXA && !RegXUsed (S, I+2)) ||
1251                 (E->OPC == OP65_TAY && N->OPC == OP65_TYA && !RegYUsed (S, I+2)) ||
1252                 (E->OPC == OP65_TXA && N->OPC == OP65_TAX && !RegAUsed (S, I+2)) ||
1253                 (E->OPC == OP65_TYA && N->OPC == OP65_TAY && !RegAUsed (S, I+2))) {
1254
1255                 /* If the next insn is a conditional branch, check if the insn
1256                  * preceeding the first xfr will set the flags right, otherwise we
1257                  * may not remove the sequence.
1258                  */
1259                 if ((X = CS_GetNextEntry (S, I+1)) == 0) {
1260                     goto NextEntry;
1261                 }
1262                 if (CE_UseLoadFlags (X)) {
1263                     if (I == 0) {
1264                         /* No preceeding entry */
1265                         goto NextEntry;
1266                     }
1267                     P = CS_GetEntry (S, I-1);
1268                     if ((P->Info & OF_SETF) == 0) {
1269                         /* Does not set the flags */
1270                         goto NextEntry;
1271                     }
1272                 }
1273
1274                 /* Remove both transfers */
1275                 CS_DelEntry (S, I+1);
1276                 CS_DelEntry (S, I);
1277
1278                 /* Remember, we had changes */
1279                 ++Changes;
1280             }
1281         }
1282
1283 NextEntry:
1284         /* Next entry */
1285         ++I;
1286
1287     }
1288
1289     /* Return the number of changes made */
1290     return Changes;
1291 }
1292
1293
1294
1295 unsigned OptTransfers2 (CodeSeg* S)
1296 /* Replace loads followed by a register transfer by a load with the second
1297  * register if possible.
1298  */
1299 {
1300     unsigned Changes = 0;
1301
1302     /* Walk over the entries */
1303     unsigned I = 0;
1304     while (I < CS_GetEntryCount (S)) {
1305
1306         CodeEntry* N;
1307
1308         /* Get next entry */
1309         CodeEntry* E = CS_GetEntry (S, I);
1310
1311         /* Check if we have a load followed by a transfer where the loaded
1312          * register is not used later.
1313          */
1314         if ((E->Info & OF_LOAD) != 0                &&
1315             (N = CS_GetNextEntry (S, I)) != 0       &&
1316             !CE_HasLabel (N)                        &&
1317             (N->Info & OF_XFR) != 0                 &&
1318             GetRegInfo (S, I+2, E->Chg) != E->Chg) {
1319
1320             CodeEntry* X = 0;
1321
1322             if (E->OPC == OP65_LDA && N->OPC == OP65_TAX) {
1323                 /* LDA/TAX - check for the right addressing modes */
1324                 if (E->AM == AM65_IMM ||
1325                     E->AM == AM65_ZP  ||
1326                     E->AM == AM65_ABS ||
1327                     E->AM == AM65_ABSY) {
1328                     /* Replace */
1329                     X = NewCodeEntry (OP65_LDX, E->AM, E->Arg, 0, N->LI);
1330                 }
1331             } else if (E->OPC == OP65_LDA && N->OPC == OP65_TAY) {
1332                 /* LDA/TAY - check for the right addressing modes */
1333                 if (E->AM == AM65_IMM ||
1334                     E->AM == AM65_ZP  ||
1335                     E->AM == AM65_ZPX ||
1336                     E->AM == AM65_ABS ||
1337                     E->AM == AM65_ABSX) {
1338                     /* Replace */
1339                     X = NewCodeEntry (OP65_LDY, E->AM, E->Arg, 0, N->LI);
1340                 }
1341             } else if (E->OPC == OP65_LDY && N->OPC == OP65_TYA) {
1342                 /* LDY/TYA. LDA supports all addressing modes LDY does */
1343                 X = NewCodeEntry (OP65_LDA, E->AM, E->Arg, 0, N->LI);
1344             } else if (E->OPC == OP65_LDX && N->OPC == OP65_TXA) {
1345                 /* LDX/TXA. LDA doesn't support zp,y, so we must map it to
1346                  * abs,y instead.
1347                  */
1348                 am_t AM = (E->AM == AM65_ZPY)? AM65_ABSY : E->AM;
1349                 X = NewCodeEntry (OP65_LDA, AM, E->Arg, 0, N->LI);
1350             }
1351
1352             /* If we have a load entry, add it and remove the old stuff */
1353             if (X) {
1354                 CS_InsertEntry (S, X, I+2);
1355                 CS_DelEntries (S, I, 2);
1356                 ++Changes;
1357                 --I;    /* Correct for one entry less */
1358             }
1359         }
1360
1361         /* Next entry */
1362         ++I;
1363     }
1364
1365     /* Return the number of changes made */
1366     return Changes;
1367 }
1368
1369
1370
1371 unsigned OptTransfers3 (CodeSeg* S)
1372 /* Replace a register transfer followed by a store of the second register by a
1373  * store of the first register if this is possible.
1374  */
1375 {
1376     unsigned Changes      = 0;
1377     unsigned UsedRegs     = REG_NONE;   /* Track used registers */
1378     unsigned Xfer         = 0;          /* Index of transfer insn */
1379     unsigned Store        = 0;          /* Index of store insn */
1380     CodeEntry* XferEntry  = 0;          /* Pointer to xfer insn */
1381     CodeEntry* StoreEntry = 0;          /* Pointer to store insn */
1382
1383     enum {
1384         Initialize,
1385         Search,
1386         FoundXfer,
1387         FoundStore
1388     } State = Initialize;
1389
1390     /* Walk over the entries. Look for a xfer instruction that is followed by
1391      * a store later, where the value of the register is not used later.
1392      */
1393     unsigned I = 0;
1394     while (I < CS_GetEntryCount (S)) {
1395
1396         /* Get next entry */
1397         CodeEntry* E = CS_GetEntry (S, I);
1398
1399         switch (State) {
1400
1401             case Initialize:
1402                 /* Clear the list of used registers */
1403                 UsedRegs = REG_NONE;
1404                 /* FALLTHROUGH */
1405
1406             case Search:
1407                 if (E->Info & OF_XFR) {
1408                     /* Found start of sequence */
1409                     Xfer = I;
1410                     XferEntry = E;
1411                     State = FoundXfer;
1412                 }
1413                 break;
1414
1415             case FoundXfer:
1416                 /* If we find a conditional jump, abort the sequence, since
1417                  * handling them makes things really complicated.
1418                  */
1419                 if (E->Info & OF_CBRA) {
1420
1421                     /* Switch back to searching */
1422                     I = Xfer;
1423                     State = Initialize;
1424
1425                 /* Does this insn use the target register of the transfer? */
1426                 } else if ((E->Use & XferEntry->Chg) != 0) {
1427
1428                     /* It it's a store instruction, and the block is a basic
1429                      * block, proceed. Otherwise restart
1430                      */
1431                     if ((E->Info & OF_STORE) != 0       &&
1432                         CS_IsBasicBlock (S, Xfer, I)) {
1433                         Store = I;
1434                         StoreEntry = E;
1435                         State = FoundStore;
1436                     } else {
1437                         I = Xfer;
1438                         State = Initialize;
1439                     }
1440
1441                 /* Does this insn change the target register of the transfer? */
1442                 } else if (E->Chg & XferEntry->Chg) {
1443
1444                     /* We *may* add code here to remove the transfer, but I'm
1445                      * currently not sure about the consequences, so I won't
1446                      * do that and bail out instead.
1447                      */
1448                     I = Xfer;
1449                     State = Initialize;
1450
1451                 /* Does this insn have a label? */
1452                 } else if (CE_HasLabel (E)) {
1453
1454                     /* Too complex to handle - bail out */
1455                     I = Xfer;
1456                     State = Initialize;
1457
1458                 } else {
1459                     /* Track used registers */
1460                     UsedRegs |= E->Use;
1461                 }
1462                 break;
1463
1464             case FoundStore:
1465                 /* We are at the instruction behind the store. If the register
1466                  * isn't used later, and we have an address mode match, we can
1467                  * replace the transfer by a store and remove the store here.
1468                  */
1469                 if ((GetRegInfo (S, I, XferEntry->Chg) & XferEntry->Chg) == 0   &&
1470                     (StoreEntry->AM == AM65_ABS         ||
1471                      StoreEntry->AM == AM65_ZP)                                 &&
1472                     (StoreEntry->AM != AM65_ZP ||
1473                      (StoreEntry->Chg & UsedRegs) == 0)                         &&
1474                     !MemAccess (S, Xfer+1, Store-1, StoreEntry->Arg)) {
1475
1476                     /* Generate the replacement store insn */
1477                     CodeEntry* X = 0;
1478                     switch (XferEntry->OPC) {
1479
1480                         case OP65_TXA:
1481                             X = NewCodeEntry (OP65_STX,
1482                                               StoreEntry->AM,
1483                                               StoreEntry->Arg,
1484                                               0,
1485                                               StoreEntry->LI);
1486                             break;
1487
1488                         case OP65_TAX:
1489                             X = NewCodeEntry (OP65_STA,
1490                                               StoreEntry->AM,
1491                                               StoreEntry->Arg,
1492                                               0,
1493                                               StoreEntry->LI);
1494                             break;
1495
1496                         case OP65_TYA:
1497                             X = NewCodeEntry (OP65_STY,
1498                                               StoreEntry->AM,
1499                                               StoreEntry->Arg,
1500                                               0,
1501                                               StoreEntry->LI);
1502                             break;
1503
1504                         case OP65_TAY:
1505                             X = NewCodeEntry (OP65_STA,
1506                                               StoreEntry->AM,
1507                                               StoreEntry->Arg,
1508                                               0,
1509                                               StoreEntry->LI);
1510                             break;
1511
1512                         default:
1513                             break;
1514                     }
1515
1516                     /* If we have a replacement store, change the code */
1517                     if (X) {
1518                         /* Insert after the xfer insn */
1519                         CS_InsertEntry (S, X, Xfer+1);
1520
1521                         /* Remove the xfer instead */
1522                         CS_DelEntry (S, Xfer);
1523
1524                         /* Remove the final store */
1525                         CS_DelEntry (S, Store);
1526
1527                         /* Correct I so we continue with the next insn */
1528                         I -= 2;
1529
1530                         /* Remember we had changes */
1531                         ++Changes;
1532                     } else {
1533                         /* Restart after last xfer insn */
1534                         I = Xfer;
1535                     }
1536                 } else {
1537                     /* Restart after last xfer insn */
1538                     I = Xfer;
1539                 }
1540                 State = Initialize;
1541                 break;
1542
1543         }
1544
1545         /* Next entry */
1546         ++I;
1547     }
1548
1549     /* Return the number of changes made */
1550     return Changes;
1551 }
1552
1553
1554
1555 unsigned OptTransfers4 (CodeSeg* S)
1556 /* Replace a load of a register followed by a transfer insn of the same register
1557  * by a load of the second register if possible.
1558  */
1559 {
1560     unsigned Changes      = 0;
1561     unsigned Load         = 0;  /* Index of load insn */
1562     unsigned Xfer         = 0;  /* Index of transfer insn */
1563     CodeEntry* LoadEntry  = 0;  /* Pointer to load insn */
1564     CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
1565
1566     enum {
1567         Search,
1568         FoundLoad,
1569         FoundXfer
1570     } State = Search;
1571
1572     /* Walk over the entries. Look for a load instruction that is followed by
1573      * a load later.
1574      */
1575     unsigned I = 0;
1576     while (I < CS_GetEntryCount (S)) {
1577
1578         /* Get next entry */
1579         CodeEntry* E = CS_GetEntry (S, I);
1580
1581         switch (State) {
1582
1583             case Search:
1584                 if (E->Info & OF_LOAD) {
1585                     /* Found start of sequence */
1586                     Load = I;
1587                     LoadEntry = E;
1588                     State = FoundLoad;
1589                 }
1590                 break;
1591
1592             case FoundLoad:
1593                 /* If we find a conditional jump, abort the sequence, since
1594                  * handling them makes things really complicated.
1595                  */
1596                 if (E->Info & OF_CBRA) {
1597
1598                     /* Switch back to searching */
1599                     I = Load;
1600                     State = Search;
1601
1602                 /* Does this insn use the target register of the load? */
1603                 } else if ((E->Use & LoadEntry->Chg) != 0) {
1604
1605                     /* It it's a xfer instruction, and the block is a basic
1606                      * block, proceed. Otherwise restart
1607                      */
1608                     if ((E->Info & OF_XFR) != 0       &&
1609                         CS_IsBasicBlock (S, Load, I)) {
1610                         Xfer = I;
1611                         XferEntry = E;
1612                         State = FoundXfer;
1613                     } else {
1614                         I = Load;
1615                         State = Search;
1616                     }
1617
1618                 /* Does this insn change the target register of the load? */
1619                 } else if (E->Chg & LoadEntry->Chg) {
1620
1621                     /* We *may* add code here to remove the load, but I'm
1622                      * currently not sure about the consequences, so I won't
1623                      * do that and bail out instead.
1624                      */
1625                     I = Load;
1626                     State = Search;
1627                 }
1628                 break;
1629
1630             case FoundXfer:
1631                 /* We are at the instruction behind the xfer. If the register
1632                  * isn't used later, and we have an address mode match, we can
1633                  * replace the transfer by a load and remove the initial load.
1634                  */
1635                 if ((GetRegInfo (S, I, LoadEntry->Chg) & LoadEntry->Chg) == 0   &&
1636                     (LoadEntry->AM == AM65_ABS          ||
1637                      LoadEntry->AM == AM65_ZP           ||
1638                      LoadEntry->AM == AM65_IMM)                                 &&
1639                     !MemAccess (S, Load+1, Xfer-1, LoadEntry->Arg)) {
1640
1641                     /* Generate the replacement load insn */
1642                     CodeEntry* X = 0;
1643                     switch (XferEntry->OPC) {
1644
1645                         case OP65_TXA:
1646                         case OP65_TYA:
1647                             X = NewCodeEntry (OP65_LDA,
1648                                               LoadEntry->AM,
1649                                               LoadEntry->Arg,
1650                                               0,
1651                                               LoadEntry->LI);
1652                             break;
1653
1654                         case OP65_TAX:
1655                             X = NewCodeEntry (OP65_LDX,
1656                                               LoadEntry->AM,
1657                                               LoadEntry->Arg,
1658                                               0,
1659                                               LoadEntry->LI);
1660                             break;
1661
1662                         case OP65_TAY:
1663                             X = NewCodeEntry (OP65_LDY,
1664                                               LoadEntry->AM,
1665                                               LoadEntry->Arg,
1666                                               0,
1667                                               LoadEntry->LI);
1668                             break;
1669
1670                         default:
1671                             break;
1672                     }
1673
1674                     /* If we have a replacement load, change the code */
1675                     if (X) {
1676                         /* Insert after the xfer insn */
1677                         CS_InsertEntry (S, X, Xfer+1);
1678
1679                         /* Remove the xfer instead */
1680                         CS_DelEntry (S, Xfer);
1681
1682                         /* Remove the initial load */
1683                         CS_DelEntry (S, Load);
1684
1685                         /* Correct I so we continue with the next insn */
1686                         I -= 2;
1687
1688                         /* Remember we had changes */
1689                         ++Changes;
1690                     } else {
1691                         /* Restart after last xfer insn */
1692                         I = Xfer;
1693                     }
1694                 } else {
1695                     /* Restart after last xfer insn */
1696                     I = Xfer;
1697                 }
1698                 State = Search;
1699                 break;
1700
1701         }
1702
1703         /* Next entry */
1704         ++I;
1705     }
1706
1707     /* Return the number of changes made */
1708     return Changes;
1709 }
1710
1711
1712
1713 unsigned OptPushPop (CodeSeg* S)
1714 /* Remove a PHA/PLA sequence were A is not used later */
1715 {
1716     unsigned Changes = 0;
1717     unsigned Push    = 0;       /* Index of push insn */
1718     unsigned Pop     = 0;       /* Index of pop insn */
1719     enum {
1720         Searching,
1721         FoundPush,
1722         FoundPop
1723     } State = Searching;
1724
1725     /* Walk over the entries. Look for a push instruction that is followed by
1726      * a pop later, where the pop is not followed by an conditional branch,
1727      * and where the value of the A register is not used later on.
1728      * Look out for the following problems:
1729      *
1730      *  - There may be another PHA/PLA inside the sequence: Restart it.
1731      *  - If the PLA has a label, all jumps to this label must be inside
1732      *    the sequence, otherwise we cannot remove the PHA/PLA.
1733      */
1734     unsigned I = 0;
1735     while (I < CS_GetEntryCount (S)) {
1736
1737         CodeEntry* X;
1738
1739         /* Get next entry */
1740         CodeEntry* E = CS_GetEntry (S, I);
1741
1742         switch (State) {
1743
1744             case Searching:
1745                 if (E->OPC == OP65_PHA) {
1746                     /* Found start of sequence */
1747                     Push  = I;
1748                     State = FoundPush;
1749                 }
1750                 break;
1751
1752             case FoundPush:
1753                 if (E->OPC == OP65_PHA) {
1754                     /* Inner push/pop, restart */
1755                     Push = I;
1756                 } else if (E->OPC == OP65_PLA) {
1757                     /* Found a matching pop */
1758                     Pop = I;
1759                     /* Check that the block between Push and Pop is a basic
1760                      * block (one entry, one exit). Otherwise ignore it.
1761                      */
1762                     if (CS_IsBasicBlock (S, Push, Pop)) {
1763                         State = FoundPop;
1764                     } else {
1765                         /* Go into searching mode again */
1766                         State = Searching;
1767                     }
1768                 }
1769                 break;
1770
1771             case FoundPop:
1772                 /* We're at the instruction after the PLA.
1773                  * Check for the following conditions:
1774                  *   - If this instruction is a store of A, and A is not used
1775                  *     later, we may replace the PHA by the store and remove
1776                  *     pla if several other conditions are met.
1777                  *   - If this instruction is not a conditional branch, and A
1778                  *     is unused later, we may remove PHA and PLA.
1779                  */
1780                 if (E->OPC == OP65_STA                  &&
1781                     !RegAUsed (S, I+1)                  &&
1782                     !MemAccess (S, Push+1, Pop-1, E->Arg)) {
1783
1784                     /* Insert a STA after the PHA */
1785                     X = NewCodeEntry (E->OPC, E->AM, E->Arg, E->JumpTo, E->LI);
1786                     CS_InsertEntry (S, X, Push+1);
1787
1788                     /* Remove the PHA instead */
1789                     CS_DelEntry (S, Push);
1790
1791                     /* Remove the PLA/STA sequence */
1792                     CS_DelEntries (S, Pop, 2);
1793
1794                     /* Correct I so we continue with the next insn */
1795                     I -= 2;
1796
1797                     /* Remember we had changes */
1798                     ++Changes;
1799
1800                 } else if ((E->Info & OF_CBRA) == 0     &&
1801                            !RegAUsed (S, I)) {
1802
1803                     /* We can remove the PHA and PLA instructions */
1804                     CS_DelEntry (S, Pop);
1805                     CS_DelEntry (S, Push);
1806
1807                     /* Correct I so we continue with the next insn */
1808                     I -= 2;
1809
1810                     /* Remember we had changes */
1811                     ++Changes;
1812
1813                 }
1814                 /* Go into search mode again */
1815                 State = Searching;
1816                 break;
1817
1818         }
1819
1820         /* Next entry */
1821         ++I;
1822     }
1823
1824     /* Return the number of changes made */
1825     return Changes;
1826 }
1827
1828
1829
1830 unsigned OptPrecalc (CodeSeg* S)
1831 /* Replace immediate operations with the accu where the current contents are
1832  * known by a load of the final value.
1833  */
1834 {
1835     unsigned Changes = 0;
1836     unsigned I;
1837
1838     /* Generate register info for this step */
1839     CS_GenRegInfo (S);
1840
1841     /* Walk over the entries */
1842     I = 0;
1843     while (I < CS_GetEntryCount (S)) {
1844
1845         /* Get next entry */
1846         CodeEntry* E = CS_GetEntry (S, I);
1847
1848         /* Get pointers to the input and output registers of the insn */
1849         const RegContents* Out = &E->RI->Out;
1850         const RegContents* In  = &E->RI->In;
1851
1852         /* Argument for LDn and flag */
1853         const char* Arg = 0;
1854         opc_t OPC = OP65_LDA;
1855
1856         /* Handle the different instructions */
1857         switch (E->OPC) {
1858
1859             case OP65_LDA:
1860                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegA)) {
1861                     /* Result of load is known */
1862                     Arg = MakeHexArg (Out->RegA);
1863                 }
1864                 break;
1865
1866             case OP65_LDX:
1867                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegX)) {
1868                     /* Result of load is known but register is X */
1869                     Arg = MakeHexArg (Out->RegX);
1870                     OPC = OP65_LDX;
1871                 }
1872                 break;
1873
1874             case OP65_LDY:
1875                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegY)) {
1876                     /* Result of load is known but register is Y */
1877                     Arg = MakeHexArg (Out->RegY);
1878                     OPC = OP65_LDY;
1879                 }
1880                 break;
1881
1882             case OP65_ADC:
1883             case OP65_ASL:
1884             case OP65_EOR:
1885             case OP65_LSR:
1886             case OP65_SBC:
1887                 if (RegValIsKnown (Out->RegA)) {
1888                     /* Accu op zp with known contents */
1889                     Arg = MakeHexArg (Out->RegA);
1890                 }
1891                 break;
1892
1893             case OP65_AND:
1894                 if (CE_IsKnownImm (E, 0xFF)) {
1895                     /* AND with 0xFF, remove */
1896                     CS_DelEntry (S, I);
1897                     ++Changes;
1898                 } else if (CE_IsKnownImm (E, 0x00)) {
1899                     /* AND with 0x00, replace by lda #$00 */
1900                     Arg = MakeHexArg (0x00);
1901                 } else if (RegValIsKnown (Out->RegA)) {
1902                     /* Accu AND zp with known contents */
1903                     Arg = MakeHexArg (Out->RegA);
1904                 } else if (In->RegA == 0xFF) {
1905                     /* AND but A contains 0xFF - replace by lda */
1906                     CE_ReplaceOPC (E, OP65_LDA);
1907                     ++Changes;
1908                 }
1909                 break;
1910
1911             case OP65_ORA:
1912                 if (CE_IsKnownImm (E, 0x00)) {
1913                     /* ORA with zero, remove */
1914                     CS_DelEntry (S, I);
1915                     ++Changes;
1916                 } else if (CE_IsKnownImm (E, 0xFF)) {
1917                     /* ORA with 0xFF, replace by lda #$ff */
1918                     Arg = MakeHexArg (0xFF);
1919                 } else if (RegValIsKnown (Out->RegA)) {
1920                     /* Accu AND zp with known contents */
1921                     Arg = MakeHexArg (Out->RegA);
1922                 } else if (In->RegA == 0) {
1923                     /* ORA but A contains 0x00 - replace by lda */
1924                     CE_ReplaceOPC (E, OP65_LDA);
1925                     ++Changes;
1926                 }
1927                 break;
1928
1929             default:
1930                 break;
1931
1932         }
1933
1934         /* Check if we have to replace the insn by LDA */
1935         if (Arg) {
1936             CodeEntry* X = NewCodeEntry (OPC, AM65_IMM, Arg, 0, E->LI);
1937             CS_InsertEntry (S, X, I+1);
1938             CS_DelEntry (S, I);
1939             ++Changes;
1940         }
1941
1942         /* Next entry */
1943         ++I;
1944     }
1945
1946     /* Free register info */
1947     CS_FreeRegInfo (S);
1948
1949     /* Return the number of changes made */
1950     return Changes;
1951 }
1952
1953
1954
1955 /*****************************************************************************/
1956 /*                           Optimize branch types                           */
1957 /*****************************************************************************/
1958
1959
1960
1961 unsigned OptBranchDist (CodeSeg* S)
1962 /* Change branches for the distance needed. */
1963 {
1964     unsigned Changes = 0;
1965
1966     /* Walk over the entries */
1967     unsigned I = 0;
1968     while (I < CS_GetEntryCount (S)) {
1969
1970         /* Get next entry */
1971         CodeEntry* E = CS_GetEntry (S, I);
1972
1973         /* Check if it's a conditional branch to a local label. */
1974         if (E->Info & OF_CBRA) {
1975
1976             /* Is this a branch to a local symbol? */
1977             if (E->JumpTo != 0) {
1978
1979                 /* Check if the branch distance is short */
1980                 int IsShort = IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner));
1981
1982                 /* Make the branch short/long according to distance */
1983                 if ((E->Info & OF_LBRA) == 0 && !IsShort) {
1984                     /* Short branch but long distance */
1985                     CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
1986                     ++Changes;
1987                 } else if ((E->Info & OF_LBRA) != 0 && IsShort) {
1988                     /* Long branch but short distance */
1989                     CE_ReplaceOPC (E, MakeShortBranch (E->OPC));
1990                     ++Changes;
1991                 }
1992
1993             } else if ((E->Info & OF_LBRA) == 0) {
1994
1995                 /* Short branch to external symbol - make it long */
1996                 CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
1997                 ++Changes;
1998
1999             }
2000
2001         } else if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 &&
2002                    (E->Info & OF_UBRA) != 0               &&
2003                    E->JumpTo != 0                         &&
2004                    IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner))) {
2005
2006             /* The jump is short and may be replaced by a BRA on the 65C02 CPU */
2007             CE_ReplaceOPC (E, OP65_BRA);
2008             ++Changes;
2009         }
2010
2011         /* Next entry */
2012         ++I;
2013
2014     }
2015
2016     /* Return the number of changes made */
2017     return Changes;
2018 }
2019
2020
2021