]> git.sur5r.net Git - cc65/blobdiff - src/cc65/coptind.c
Added a new option --dep-target to the compiler. This option allows to set the
[cc65] / src / cc65 / coptind.c
index eee07f879fced780f3c765c3c9e90819bc853dd0..c8a1061ac03ec1803339e9eb32382d06a86be1f8 100644 (file)
 
 
 
-static int MemAccess (CodeSeg* S, unsigned From, unsigned To, const char* Arg)
-/* Checks a range of code entries if there are any memory accesses to Arg.
- * Note: This function is not 100% safe, because there is more than one way
- * to express a memory location ("foo" and "foo+0" comes to mind) and there
- * may be other accesses through pointers. For the code generated by cc65 and
- * for the purpose of the caller (OptPushPop) it is assumed to be safe enough
- * however.
- */
+static int MemAccess (CodeSeg* S, unsigned From, unsigned To, const CodeEntry* N)
+/* Checks a range of code entries if there are any memory accesses to N->Arg */
 {
+    /* Get the length of the argument */
+    unsigned NLen = strlen (N->Arg);
+
+    /* What to check for? */
+    enum {
+        None    = 0x00,
+        Base    = 0x01,         /* Check for location without "+1" */
+        Word    = 0x02,         /* Check for location with "+1" added */
+    } What = None;
+
+
+    /* If the argument of N is a zero page location that ends with "+1", we
+     * must also check for word accesses to the location without +1.
+     */
+    if (N->AM == AM65_ZP && NLen > 2 && strcmp (N->Arg + NLen - 2, "+1") == 0) {
+        What |= Base;
+    }
+
+    /* If the argument is zero page indirect, we must also check for accesses
+     * to "arg+1"
+     */
+    if (N->AM == AM65_ZP_INDY || N->AM == AM65_ZPX_IND || N->AM == AM65_ZP_IND) {
+        What |= Word;
+    }
+
     /* Walk over all code entries */
     while (From <= To) {
 
        /* Get the next entry */
        CodeEntry* E = CS_GetEntry (S, From);
 
-        /* For simplicity, we just check if there is an argument and if this
-         * argument equals Arg.
+        /* Check if there is an argument and if this argument equals Arg in
+         * some variants.
          */
-        if (E->Arg && strcmp (E->Arg, Arg) == 0) {
-            /* Found an access */
-            return 1;
+        if (E->Arg[0] != '\0') {
+
+            unsigned ELen;
+
+            if (strcmp (E->Arg, N->Arg) == 0) {
+                /* Found an access */
+                return 1;
+            }
+
+            ELen = strlen (E->Arg);
+            if ((What & Base) != 0) {
+                if (ELen == NLen - 2 && strncmp (E->Arg, N->Arg, NLen-2) == 0) {
+                    /* Found an access */
+                    return 1;
+                }
+            }
+
+            if ((What & Word) != 0) {
+                if (ELen == NLen + 2 && strncmp (E->Arg, N->Arg, NLen) == 0 &&
+                    E->Arg[NLen] == '+' && E->Arg[NLen+1] == '1') {
+                    /* Found an access */
+                    return 1;
+                }
+            }
         }
 
         /* Next entry */
@@ -207,50 +247,77 @@ unsigned OptRTSJumps1 (CodeSeg* S)
 
 
 unsigned OptRTSJumps2 (CodeSeg* S)
-/* Replace long conditional jumps to RTS */
+/* Replace long conditional jumps to RTS or to a final target */
 {
     unsigned Changes = 0;
 
     /* Walk over all entries minus the last one */
     unsigned I = 0;
-    while (I < CS_GetEntryCount (S)) {
-
-       CodeEntry* N;
+    while (I < CS_GetEntryCount (S) - 1) {
 
        /* Get the next entry */
        CodeEntry* E = CS_GetEntry (S, I);
 
-               /* Check if it's an unconditional branch to a local target */
+               /* Check if it's an conditional branch to a local target */
                if ((E->Info & OF_CBRA) != 0            &&   /* Conditional branch */
            (E->Info & OF_LBRA) != 0            &&   /* Long branch */
-           E->JumpTo != 0                      &&   /* Local label */
-           E->JumpTo->Owner->OPC == OP65_RTS   &&   /* Target is an RTS */
-           (N = CS_GetNextEntry (S, I)) != 0) {     /* There is a next entry */
+           E->JumpTo != 0) {                        /* Local label */
 
-           CodeEntry* X;
-           CodeLabel* LN;
-           opc_t      NewBranch;
 
-           /* We will create a jump around an RTS instead of the long branch */
-           X = NewCodeEntry (OP65_RTS, AM65_IMP, 0, 0, E->JumpTo->Owner->LI);
-           CS_InsertEntry (S, X, I+1);
+            /* Get the jump target and the next entry. There's always a next
+             * entry, because we don't cover the last entry in the loop.
+             */
+            CodeEntry* X = 0;
+            CodeEntry* T = E->JumpTo->Owner;
+            CodeEntry* N = CS_GetNextEntry (S, I);
 
-           /* Get the new branch opcode */
-           NewBranch = MakeShortBranch (GetInverseBranch (E->OPC));
+            /* Check if it's a jump to an RTS insn */
+            if (T->OPC == OP65_RTS) {
 
-           /* Get the label attached to N, create a new one if needed */
-           LN = CS_GenLabel (S, N);
+                /* It's a jump to RTS. Create a conditional branch around an
+                 * RTS insn.
+                 */
+                X = NewCodeEntry (OP65_RTS, AM65_IMP, 0, 0, T->LI);
 
-           /* Generate the branch */
-           X = NewCodeEntry (NewBranch, AM65_BRA, LN->Name, LN, E->LI);
-           CS_InsertEntry (S, X, I+1);
+            } else if (T->OPC == OP65_JMP && T->JumpTo == 0) {
 
-           /* Delete the long branch */
-           CS_DelEntry (S, I);
+                /* It's a jump to a label outside the function. Create a
+                 * conditional branch around a jump to the external label.
+                 */
+                X = NewCodeEntry (OP65_JMP, AM65_ABS, T->Arg, T->JumpTo, T->LI);
 
-           /* Remember, we had changes */
-           ++Changes;
+            }
+
+            /* If we have a replacement insn, insert it */
+            if (X) {
+
+                CodeLabel* LN;
+                opc_t      NewBranch;
+
+                /* Insert the new insn */
+                CS_InsertEntry (S, X, I+1);
+
+                /* Create a conditional branch with the inverse condition
+                 * around the replacement insn
+                 */
+
+                /* Get the new branch opcode */
+                NewBranch = MakeShortBranch (GetInverseBranch (E->OPC));
+
+                /* Get the label attached to N, create a new one if needed */
+                LN = CS_GenLabel (S, N);
+
+                /* Generate the branch */
+                X = NewCodeEntry (NewBranch, AM65_BRA, LN->Name, LN, E->LI);
+                CS_InsertEntry (S, X, I+1);
+
+                /* Delete the long branch */
+                CS_DelEntry (S, I);
 
+                /* Remember, we had changes */
+                ++Changes;
+
+            }
        }
 
        /* Next entry */
@@ -390,14 +457,24 @@ unsigned OptJumpCascades (CodeSeg* S)
        /* Get this entry */
        CodeEntry* E = CS_GetEntry (S, I);
 
-               /* Check if it's a branch, if it has a jump label, if this jump
-        * label is not attached to the instruction itself, and if the
-        * target instruction is itself a branch.
+               /* Check:
+         *   - if it's a branch,
+         *   - if it has a jump label,
+         *   - if this jump label is not attached to the instruction itself,
+         *   - if the target instruction is itself a branch,
+         *   - if either the first branch is unconditional or the target of
+         *     the second branch is internal to the function.
+         * The latter condition will avoid conditional branches to targets
+         * outside of the function (usually incspx), which won't simplify the
+         * code, since conditional far branches are emulated by a short branch
+         * around a jump.
         */
-       if ((E->Info & OF_BRA) != 0        &&
-           (OldLabel = E->JumpTo) != 0    &&
-           (N = OldLabel->Owner) != E     &&
-           (N->Info & OF_BRA) != 0) {
+       if ((E->Info & OF_BRA) != 0             &&
+           (OldLabel = E->JumpTo) != 0         &&
+           (N = OldLabel->Owner) != E          &&
+           (N->Info & OF_BRA) != 0             &&
+            ((E->Info & OF_CBRA) == 0   ||
+             N->JumpTo != 0)) {
 
            /* Check if we can use the final target label. This is the case,
             * if the target branch is an absolut branch, or if it is a
@@ -564,12 +641,13 @@ unsigned OptJumpTarget1 (CodeSeg* S)
        /* Get next entry */
                E2 = CS_GetNextEntry (S, I);
 
-       /* Check if we have a jump or branch, and a matching label, which
-        * is not attached to the jump itself
+       /* Check if we have a jump or branch without a label attached, and
+         * a jump target, which is not attached to the jump itself
         */
-               if (E2 != 0                     &&
+               if (E2 != 0                     &&
            (E2->Info & OF_UBRA) != 0   &&
-           E2->JumpTo                  &&
+            !CE_HasLabel (E2)           &&
+           E2->JumpTo                  &&
            E2->JumpTo->Owner != E2) {
 
            /* Get the entry preceeding the branch target */
@@ -579,6 +657,13 @@ unsigned OptJumpTarget1 (CodeSeg* S)
                goto NextEntry;
            }
 
+            /* The entry preceeding the branch target may not be the branch
+             * insn.
+             */
+            if (T1 == E2) {
+                goto NextEntry;
+            }
+
            /* Get the entry preceeding the jump */
            E1 = CS_GetEntry (S, I);
 
@@ -700,13 +785,101 @@ NextEntry:
 
 
 
+unsigned OptJumpTarget3 (CodeSeg* S)
+/* Jumps to load instructions of a register, that do already have the matching
+ * register contents may skip the load instruction, since it's job is already
+ * done.
+ */
+{
+    unsigned Changes = 0;
+    unsigned I;
+
+    /* Generate register info for this step */
+    CS_GenRegInfo (S);
+
+    /* Walk over the entries */
+    I = 0;
+    while (I < CS_GetEntryCount (S)) {
+
+        CodeEntry* N;
+
+       /* Get next entry */
+               CodeEntry* E = CS_GetEntry (S, I);
+
+        /* Check if this is a load insn with a label and the next insn is not
+         * a conditional branch that needs the flags from the load.
+         */
+        if ((E->Info & OF_LOAD) != 0            &&
+            CE_IsConstImm (E)                   &&
+            CE_HasLabel (E)                     &&
+            (N = CS_GetNextEntry (S, I)) != 0   &&
+            !CE_UseLoadFlags (N)) {
+
+            unsigned J;
+            int      K;
+
+            /* New jump label */
+            CodeLabel* LN = 0;
+
+            /* Walk over all insn that jump here */
+            for (J = 0; J < CE_GetLabelCount (E); ++J) {
+
+                /* Get the label */
+                CodeLabel* L = CE_GetLabel (E, J);
+
+                /* Loop over all insn that reference this label. Since we may
+                 * eventually remove a reference in the loop, we must loop
+                 * from end down to start.
+                 */
+                for (K = CL_GetRefCount (L) - 1; K >= 0; --K) {
+
+                    /* Get the entry that jumps here */
+                    CodeEntry* Jump = CL_GetRef (L, K);
+
+                    /* Get the register info from this insn */
+                    short Val = RegVal (E->Chg, &Jump->RI->Out2);
+
+                    /* Check if the outgoing value is the one thats's loaded */
+                    if (Val == (unsigned char) E->Num) {
+
+                        /* Ok, skip the insn. First, generate a label for the
+                         * next insn after E.
+                         */
+                        if (LN == 0) {
+                            LN = CS_GenLabel (S, N);
+                        }
+
+                        /* Change the jump target to point to this new label */
+                        CS_MoveLabelRef (S, Jump, LN);
+
+                        /* Remember that we had changes */
+                        ++Changes;
+                    }
+                }
+            }
+
+        }
+
+        /* Next entry */
+        ++I;
+    }
+
+    /* Free register info */
+    CS_FreeRegInfo (S);
+
+    /* Return the number of changes made */
+    return Changes;
+}
+
+
+
 /*****************************************************************************/
 /*                      Optimize conditional branches                       */
 /*****************************************************************************/
 
 
 
-unsigned OptCondBranches (CodeSeg* S)
+unsigned OptCondBranches1 (CodeSeg* S)
 /* Performs several optimization steps:
  *
  *  - If an immidiate load of a register is followed by a conditional jump that
@@ -752,7 +925,7 @@ unsigned OptCondBranches (CodeSeg* S)
                CS_DelEntry (S, I+1);
 
                /* Remember, we had changes */
-               ++Changes;
+               ++Changes;
 
            } else if ((BC == BC_EQ && E->Num == 0)             ||
                       (BC == BC_NE && E->Num != 0)             ||
@@ -769,7 +942,7 @@ unsigned OptCondBranches (CodeSeg* S)
        }
 
        if ((E->Info & OF_CBRA) != 0              &&  /* It's a conditional branch */
-           (L = E->JumpTo) != 0                  &&  /* ..referencing a local label */
+           (L = E->JumpTo) != 0                  &&  /* ..referencing a local label */
                    (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
            (N->Info & OF_UBRA) != 0              &&  /* ..which is an uncond branch, */
            !CE_HasLabel (N)                      &&  /* ..has no label attached */
@@ -799,6 +972,62 @@ unsigned OptCondBranches (CodeSeg* S)
 
 
 
+unsigned OptCondBranches2 (CodeSeg* S)
+/* If on entry to a "rol a" instruction the accu is zero, and a beq/bne follows,
+ * we can remove the rol and branch on the state of the carry flag.
+ */
+{
+    unsigned Changes = 0;
+    unsigned I;
+
+    /* Generate register info for this step */
+    CS_GenRegInfo (S);
+
+    /* Walk over the entries */
+    I = 0;
+    while (I < CS_GetEntryCount (S)) {
+
+               CodeEntry* N;
+
+               /* Get next entry */
+               CodeEntry* E = CS_GetEntry (S, I);
+
+       /* Check if it's a rol insn with A in accu and a branch follows */
+               if (E->OPC == OP65_ROL                  &&
+            E->AM == AM65_ACC                   &&
+            E->RI->In.RegA == 0                 &&
+            !CE_HasLabel (E)                    &&
+            (N = CS_GetNextEntry (S, I)) != 0   &&
+            (N->Info & OF_ZBRA) != 0            &&
+            !RegAUsed (S, I+1)) {
+
+           /* Replace the branch condition */
+           switch (GetBranchCond (N->OPC)) {
+                case BC_EQ:     CE_ReplaceOPC (N, OP65_JCC); break;
+                case BC_NE:     CE_ReplaceOPC (N, OP65_JCS); break;
+                default:        Internal ("Unknown branch condition in OptCondBranches2");
+            }
+
+            /* Delete the rol insn */
+            CS_DelEntry (S, I);
+
+            /* Remember, we had changes */
+            ++Changes;
+       }
+
+               /* Next entry */
+               ++I;
+    }
+
+    /* Free register info */
+    CS_FreeRegInfo (S);
+
+    /* Return the number of changes made */
+    return Changes;
+}
+
+
+
 /*****************************************************************************/
 /*                     Remove unused loads and stores                       */
 /*****************************************************************************/
@@ -827,17 +1056,17 @@ unsigned OptUnusedLoads (CodeSeg* S)
            /* Check which sort of load or transfer it is */
            unsigned R;
            switch (E->OPC) {
-               case OP65_DEA:
-               case OP65_INA:
-               case OP65_LDA:
+               case OP65_DEA:
+               case OP65_INA:
+               case OP65_LDA:
                case OP65_TXA:
                case OP65_TYA:  R = REG_A;      break;
-               case OP65_DEX:
-               case OP65_INX:
-               case OP65_LDX:
+               case OP65_DEX:
+               case OP65_INX:
+               case OP65_LDX:
                case OP65_TAX:  R = REG_X;      break;
-               case OP65_DEY:
-               case OP65_INY:
+               case OP65_DEY:
+               case OP65_INY:
                        case OP65_LDY:
                case OP65_TAY:  R = REG_Y;      break;
                default:        goto NextEntry;         /* OOPS */
@@ -847,11 +1076,11 @@ unsigned OptUnusedLoads (CodeSeg* S)
            if ((GetRegInfo (S, I+1, R) & R) == 0) {
 
                /* Register value is not used, remove the load */
-               CS_DelEntry (S, I);
+               CS_DelEntry (S, I);
 
-               /* Remember, we had changes. Account the deleted entry in I. */
-               ++Changes;
-               --I;
+               /* Remember, we had changes. Account the deleted entry in I. */
+               ++Changes;
+               --I;
 
            }
        }
@@ -970,12 +1199,12 @@ unsigned OptDupLoads (CodeSeg* S)
                break;
 
            case OP65_STA:
-               /* If we store into a known zero page location, and this
+               /* If we store into a known zero page location, and this
                 * location does already contain the value to be stored,
                 * remove the store.
                 */
                if (RegValIsKnown (In->RegA)          && /* Value of A is known */
-                   E->AM == AM65_ZP                  && /* Store into zp */
+                           E->AM == AM65_ZP                  && /* Store into zp */
                    In->RegA == ZPRegVal (E->Chg, In)) { /* Value identical */
 
                    Delete = 1;
@@ -1003,7 +1232,7 @@ unsigned OptDupLoads (CodeSeg* S)
                           In->RegX == In->RegA       &&
                           E->AM != AM65_ABSY         &&
                           E->AM != AM65_ZPY) {
-                   /* Use the A register instead */
+                   /* Use the A register instead */
                            CE_ReplaceOPC (E, OP65_STA);
                }
                break;
@@ -1023,12 +1252,12 @@ unsigned OptDupLoads (CodeSeg* S)
                 * that in the A register, replace the store by a STA. The
                 * optimizer will then remove the load instruction for Y
                 * later. If replacement by A is not possible try a
-                * replacement by X, but check for invalid addressing modes
+                * replacement by X, but check for invalid addressing modes
                 * in this case.
                 */
                        } else if (RegValIsKnown (In->RegY)) {
                    if (In->RegY == In->RegA) {
-                       CE_ReplaceOPC (E, OP65_STA);
+                               CE_ReplaceOPC (E, OP65_STA);
                    } else if (In->RegY == In->RegX   &&
                               E->AM != AM65_ABSX     &&
                               E->AM != AM65_ZPX) {
@@ -1056,7 +1285,7 @@ unsigned OptDupLoads (CodeSeg* S)
                            !CE_UseLoadFlags (N)) {
                    /* Value is identical and not followed by a branch */
                    Delete = 1;
-               }
+               }
                break;
 
            case OP65_TAY:
@@ -1076,39 +1305,39 @@ unsigned OptDupLoads (CodeSeg* S)
                            !CE_UseLoadFlags (N)) {
                    /* Value is identical and not followed by a branch */
                    Delete = 1;
-               }
-               break;
+               }
+               break;
 
-           case OP65_TYA:
+           case OP65_TYA:
                 if (RegValIsKnown (In->RegY)            &&
-                   In->RegY == In->RegA                &&
-                   (N = CS_GetNextEntry (S, I)) != 0   &&
+                           In->RegY == In->RegA                &&
+                   (N = CS_GetNextEntry (S, I)) != 0   &&
                            !CE_UseLoadFlags (N)) {
-                   /* Value is identical and not followed by a branch */
-                   Delete = 1;
-               }
-               break;
+                   /* Value is identical and not followed by a branch */
+                   Delete = 1;
+               }
+               break;
 
-           default:
-               break;
+           default:
+               break;
 
-       }
+       }
 
-       /* Delete the entry if requested */
-       if (Delete) {
+       /* Delete the entry if requested */
+       if (Delete) {
 
-           /* Register value is not used, remove the load */
-           CS_DelEntry (S, I);
+           /* Register value is not used, remove the load */
+           CS_DelEntry (S, I);
 
-           /* Remember, we had changes */
-           ++Changes;
+           /* Remember, we had changes */
+           ++Changes;
 
-       } else {
+       } else {
 
-           /* Next entry */
-           ++I;
+           /* Next entry */
+           ++I;
 
-       }
+       }
 
     }
 
@@ -1130,10 +1359,10 @@ unsigned OptStoreLoad (CodeSeg* S)
     unsigned I = 0;
     while (I < CS_GetEntryCount (S)) {
 
-       CodeEntry* N;
-       CodeEntry* X;
+               CodeEntry* N;
+               CodeEntry* X;
 
-       /* Get next entry */
+               /* Get next entry */
                CodeEntry* E = CS_GetEntry (S, I);
 
        /* Check if it is a store instruction followed by a load from the
@@ -1319,16 +1548,18 @@ unsigned OptTransfers3 (CodeSeg* S)
  */
 {
     unsigned Changes      = 0;
-    unsigned Xfer         = 0;  /* Index of transfer insn */
-    unsigned Store        = 0;  /* Index of store insn */
-    CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
-    CodeEntry* StoreEntry = 0;  /* Pointer to store insn */
+    unsigned UsedRegs     = REG_NONE;   /* Track used registers */
+    unsigned Xfer         = 0;          /* Index of transfer insn */
+    unsigned Store        = 0;          /* Index of store insn */
+    CodeEntry* XferEntry  = 0;          /* Pointer to xfer insn */
+    CodeEntry* StoreEntry = 0;          /* Pointer to store insn */
 
     enum {
-        Searching,
+        Initialize,
+        Search,
         FoundXfer,
         FoundStore
-    } State = Searching;
+    } State = Initialize;
 
     /* Walk over the entries. Look for a xfer instruction that is followed by
      * a store later, where the value of the register is not used later.
@@ -1341,7 +1572,12 @@ unsigned OptTransfers3 (CodeSeg* S)
 
         switch (State) {
 
-            case Searching:
+            case Initialize:
+                /* Clear the list of used registers */
+                UsedRegs = REG_NONE;
+                /* FALLTHROUGH */
+
+            case Search:
                 if (E->Info & OF_XFR) {
                     /* Found start of sequence */
                     Xfer = I;
@@ -1358,7 +1594,7 @@ unsigned OptTransfers3 (CodeSeg* S)
 
                     /* Switch back to searching */
                     I = Xfer;
-                    State = Searching;
+                    State = Initialize;
 
                 /* Does this insn use the target register of the transfer? */
                 } else if ((E->Use & XferEntry->Chg) != 0) {
@@ -1373,7 +1609,7 @@ unsigned OptTransfers3 (CodeSeg* S)
                         State = FoundStore;
                     } else {
                         I = Xfer;
-                        State = Searching;
+                        State = Initialize;
                     }
 
                 /* Does this insn change the target register of the transfer? */
@@ -1384,15 +1620,18 @@ unsigned OptTransfers3 (CodeSeg* S)
                      * do that and bail out instead.
                      */
                     I = Xfer;
-                    State = Searching;
+                    State = Initialize;
 
                 /* Does this insn have a label? */
                 } else if (CE_HasLabel (E)) {
 
                     /* Too complex to handle - bail out */
                     I = Xfer;
-                    State = Searching;
+                    State = Initialize;
 
+                } else {
+                    /* Track used registers */
+                    UsedRegs |= E->Use;
                 }
                 break;
 
@@ -1402,8 +1641,11 @@ unsigned OptTransfers3 (CodeSeg* S)
                  * replace the transfer by a store and remove the store here.
                  */
                 if ((GetRegInfo (S, I, XferEntry->Chg) & XferEntry->Chg) == 0   &&
-                    (StoreEntry->AM == AM65_ABS || StoreEntry->AM == AM65_ZP)   &&
-                    !MemAccess (S, Xfer+1, Store-1, StoreEntry->Arg)) {
+                    (StoreEntry->AM == AM65_ABS         ||
+                     StoreEntry->AM == AM65_ZP)                                 &&
+                    (StoreEntry->AM != AM65_ZP ||
+                     (StoreEntry->Chg & UsedRegs) == 0)                         &&
+                    !MemAccess (S, Xfer+1, Store-1, StoreEntry)) {
 
                     /* Generate the replacement store insn */
                     CodeEntry* X = 0;
@@ -1469,7 +1711,7 @@ unsigned OptTransfers3 (CodeSeg* S)
                     /* Restart after last xfer insn */
                     I = Xfer;
                 }
-                State = Searching;
+                State = Initialize;
                 break;
 
         }
@@ -1496,10 +1738,10 @@ unsigned OptTransfers4 (CodeSeg* S)
     CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
 
     enum {
-        Searching,
+        Search,
         FoundLoad,
         FoundXfer
-    } State = Searching;
+    } State = Search;
 
     /* Walk over the entries. Look for a load instruction that is followed by
      * a load later.
@@ -1512,7 +1754,7 @@ unsigned OptTransfers4 (CodeSeg* S)
 
         switch (State) {
 
-            case Searching:
+            case Search:
                 if (E->Info & OF_LOAD) {
                     /* Found start of sequence */
                     Load = I;
@@ -1529,7 +1771,7 @@ unsigned OptTransfers4 (CodeSeg* S)
 
                     /* Switch back to searching */
                     I = Load;
-                    State = Searching;
+                    State = Search;
 
                 /* Does this insn use the target register of the load? */
                 } else if ((E->Use & LoadEntry->Chg) != 0) {
@@ -1544,7 +1786,7 @@ unsigned OptTransfers4 (CodeSeg* S)
                         State = FoundXfer;
                     } else {
                         I = Load;
-                        State = Searching;
+                        State = Search;
                     }
 
                 /* Does this insn change the target register of the load? */
@@ -1555,7 +1797,7 @@ unsigned OptTransfers4 (CodeSeg* S)
                      * do that and bail out instead.
                      */
                     I = Load;
-                    State = Searching;
+                    State = Search;
                 }
                 break;
 
@@ -1568,7 +1810,7 @@ unsigned OptTransfers4 (CodeSeg* S)
                     (LoadEntry->AM == AM65_ABS          ||
                      LoadEntry->AM == AM65_ZP           ||
                      LoadEntry->AM == AM65_IMM)                                 &&
-                    !MemAccess (S, Load+1, Xfer-1, LoadEntry->Arg)) {
+                    !MemAccess (S, Load+1, Xfer-1, LoadEntry)) {
 
                     /* Generate the replacement load insn */
                     CodeEntry* X = 0;
@@ -1627,7 +1869,7 @@ unsigned OptTransfers4 (CodeSeg* S)
                     /* Restart after last xfer insn */
                     I = Xfer;
                 }
-                State = Searching;
+                State = Search;
                 break;
 
         }
@@ -1648,6 +1890,7 @@ unsigned OptPushPop (CodeSeg* S)
     unsigned Changes = 0;
     unsigned Push    = 0;       /* Index of push insn */
     unsigned Pop     = 0;       /* Index of pop insn */
+    unsigned ChgA    = 0;       /* Flag for A changed */
     enum {
         Searching,
         FoundPush,
@@ -1677,6 +1920,7 @@ unsigned OptPushPop (CodeSeg* S)
                 if (E->OPC == OP65_PHA) {
                     /* Found start of sequence */
                     Push  = I;
+                    ChgA  = 0;
                     State = FoundPush;
                 }
                 break;
@@ -1685,6 +1929,7 @@ unsigned OptPushPop (CodeSeg* S)
                 if (E->OPC == OP65_PHA) {
                     /* Inner push/pop, restart */
                     Push = I;
+                    ChgA = 0;
                 } else if (E->OPC == OP65_PLA) {
                     /* Found a matching pop */
                     Pop = I;
@@ -1697,21 +1942,26 @@ unsigned OptPushPop (CodeSeg* S)
                         /* Go into searching mode again */
                         State = Searching;
                     }
+                } else if (E->Chg & REG_A) {
+                    ChgA = 1;
                 }
                 break;
 
             case FoundPop:
                 /* We're at the instruction after the PLA.
                  * Check for the following conditions:
-                 *   - If this instruction is a store of A, and A is not used
-                 *     later, we may replace the PHA by the store and remove
-                 *     pla if several other conditions are met.
+                 *   - If this instruction is a store of A, does not have a
+                 *     label, and A is not used later, we may replace the PHA
+                 *     by the store and remove pla if several other conditions
+                 *     are met.
                  *   - If this instruction is not a conditional branch, and A
-                 *     is unused later, we may remove PHA and PLA.
+                 *     is either unused later, or not changed by the code
+                 *     between push and pop, we may remove PHA and PLA.
                  */
                 if (E->OPC == OP65_STA                  &&
+                    !CE_HasLabel (E)                    &&
                     !RegAUsed (S, I+1)                  &&
-                    !MemAccess (S, Push+1, Pop-1, E->Arg)) {
+                    !MemAccess (S, Push+1, Pop-1, E)) {
 
                     /* Insert a STA after the PHA */
                     X = NewCodeEntry (E->OPC, E->AM, E->Arg, E->JumpTo, E->LI);
@@ -1730,7 +1980,7 @@ unsigned OptPushPop (CodeSeg* S)
                     ++Changes;
 
                 } else if ((E->Info & OF_CBRA) == 0     &&
-                           !RegAUsed (S, I)) {
+                           (!RegAUsed (S, I) || !ChgA)) {
 
                     /* We can remove the PHA and PLA instructions */
                     CS_DelEntry (S, Pop);
@@ -1777,8 +2027,9 @@ unsigned OptPrecalc (CodeSeg* S)
        /* Get next entry */
                CodeEntry* E = CS_GetEntry (S, I);
 
-               /* Get a pointer to the output registers of the insn */
+               /* Get pointers to the input and output registers of the insn */
                const RegContents* Out = &E->RI->Out;
+        const RegContents* In  = &E->RI->In;
 
         /* Argument for LDn and flag */
         const char* Arg = 0;
@@ -1810,25 +2061,43 @@ unsigned OptPrecalc (CodeSeg* S)
                 }
                 break;
 
-            case OP65_ADC:
-            case OP65_ASL:
             case OP65_EOR:
-            case OP65_LSR:
-            case OP65_SBC:
                 if (RegValIsKnown (Out->RegA)) {
                     /* Accu op zp with known contents */
                     Arg = MakeHexArg (Out->RegA);
                 }
                 break;
 
+            case OP65_ADC:
+            case OP65_SBC:
+                /* If this is an operation with an immediate operand of zero,
+                 * and the register is zero, the operation won't give us any
+                 * results we don't already have (including the flags), so
+                 * remove it. Something like this is generated as a result of
+                 * a compare where parts of the values are known to be zero.
+                 */
+                if (In->RegA == 0 && CE_IsKnownImm (E, 0x00)) {
+                    /* 0-0 or 0+0 -> remove */
+                    CS_DelEntry (S, I);
+                    ++Changes;
+                }
+                break;
+
             case OP65_AND:
                 if (CE_IsKnownImm (E, 0xFF)) {
                     /* AND with 0xFF, remove */
                     CS_DelEntry (S, I);
                     ++Changes;
+                } else if (CE_IsKnownImm (E, 0x00)) {
+                    /* AND with 0x00, replace by lda #$00 */
+                    Arg = MakeHexArg (0x00);
                 } else if (RegValIsKnown (Out->RegA)) {
                     /* Accu AND zp with known contents */
                     Arg = MakeHexArg (Out->RegA);
+                } else if (In->RegA == 0xFF) {
+                    /* AND but A contains 0xFF - replace by lda */
+                    CE_ReplaceOPC (E, OP65_LDA);
+                    ++Changes;
                 }
                 break;
 
@@ -1837,9 +2106,16 @@ unsigned OptPrecalc (CodeSeg* S)
                     /* ORA with zero, remove */
                     CS_DelEntry (S, I);
                     ++Changes;
+                } else if (CE_IsKnownImm (E, 0xFF)) {
+                    /* ORA with 0xFF, replace by lda #$ff */
+                    Arg = MakeHexArg (0xFF);
                 } else if (RegValIsKnown (Out->RegA)) {
                     /* Accu AND zp with known contents */
                     Arg = MakeHexArg (Out->RegA);
+                } else if (In->RegA == 0) {
+                    /* ORA but A contains 0x00 - replace by lda */
+                    CE_ReplaceOPC (E, OP65_LDA);
+                    ++Changes;
                 }
                 break;
 
@@ -1936,3 +2212,117 @@ unsigned OptBranchDist (CodeSeg* S)
 
 
 
+/*****************************************************************************/
+/*                          Optimize indirect loads                          */
+/*****************************************************************************/
+
+
+
+unsigned OptIndLoads1 (CodeSeg* S)
+/* Change
+ *
+ *     lda      (zp),y
+ *
+ * into
+ *
+ *     lda      (zp,x)
+ *
+ * provided that x and y are both zero.
+ */
+{
+    unsigned Changes = 0;
+    unsigned I;
+
+    /* Generate register info for this step */
+    CS_GenRegInfo (S);
+
+    /* Walk over the entries */
+    I = 0;
+    while (I < CS_GetEntryCount (S)) {
+
+       /* Get next entry */
+               CodeEntry* E = CS_GetEntry (S, I);
+
+       /* Check if it's what we're looking for */
+               if (E->OPC == OP65_LDA          &&
+            E->AM == AM65_ZP_INDY       &&
+            E->RI->In.RegY == 0         &&
+            E->RI->In.RegX == 0) {
+
+           /* Replace by the same insn with other addressing mode */
+            CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZPX_IND, E->Arg, 0, E->LI);
+            CS_InsertEntry (S, X, I+1);
+
+            /* Remove the old insn */
+            CS_DelEntry (S, I);
+            ++Changes;
+       }
+
+       /* Next entry */
+       ++I;
+
+    }
+
+    /* Free register info */
+    CS_FreeRegInfo (S);
+
+    /* Return the number of changes made */
+    return Changes;
+}
+
+
+
+unsigned OptIndLoads2 (CodeSeg* S)
+/* Change
+ *
+ *     lda      (zp,x)
+ *
+ * into
+ *
+ *     lda      (zp),y
+ *
+ * provided that x and y are both zero.
+ */
+{
+    unsigned Changes = 0;
+    unsigned I;
+
+    /* Generate register info for this step */
+    CS_GenRegInfo (S);
+
+    /* Walk over the entries */
+    I = 0;
+    while (I < CS_GetEntryCount (S)) {
+
+       /* Get next entry */
+               CodeEntry* E = CS_GetEntry (S, I);
+
+       /* Check if it's what we're looking for */
+               if (E->OPC == OP65_LDA          &&
+            E->AM == AM65_ZPX_IND       &&
+            E->RI->In.RegY == 0         &&
+            E->RI->In.RegX == 0) {
+
+           /* Replace by the same insn with other addressing mode */
+            CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZP_INDY, E->Arg, 0, E->LI);
+            CS_InsertEntry (S, X, I+1);
+
+            /* Remove the old insn */
+            CS_DelEntry (S, I);
+            ++Changes;
+       }
+
+       /* Next entry */
+       ++I;
+
+    }
+
+    /* Free register info */
+    CS_FreeRegInfo (S);
+
+    /* Return the number of changes made */
+    return Changes;
+}
+
+
+