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