]> git.sur5r.net Git - cc65/blobdiff - src/cc65/coptstop.c
Changed code generated for compares. Fixed bugs in OptStackOps. Still
[cc65] / src / cc65 / coptstop.c
index 6eab4affe489094eeba79f7065799d242d7b96e0..fafc816f1e3571b1890c4f409c83c90143ad12ed 100644 (file)
@@ -6,8 +6,8 @@
 /*                                                                           */
 /*                                                                           */
 /*                                                                           */
-/* (C) 2001-2004 Ullrich von Bassewitz                                       */
-/*               Römerstrasse 52                                             */
+/* (C) 2001-2009 Ullrich von Bassewitz                                       */
+/*               Roemerstrasse 52                                            */
 /*               D-70794 Filderstadt                                         */
 /* EMail:        uz@cc65.org                                                 */
 /*                                                                           */
 
 
 
+/*****************************************************************************/
+/*                            Load tracking data                             */
+/*****************************************************************************/
+
+
+
+/* LoadRegInfo flags set by DirectOp */
+#define LI_NONE         0x00
+#define LI_DIRECT       0x01            /* Direct op may be used */
+#define LI_RELOAD_Y     0x02            /* Reload index register Y */
+#define LI_REMOVE       0x04            /* Load may be removed */
+
+/* Structure that tells us how to load the lhs values */
+typedef struct LoadRegInfo LoadRegInfo;
+struct LoadRegInfo {
+    int                 LoadIndex;      /* Index of load insn, -1 if invalid */
+    CodeEntry*          LoadEntry;      /* The actual entry, 0 if invalid */
+    unsigned char       Flags;          /* Tells us how to load */
+    unsigned char       Offs;           /* Stack offset if data is on stack */
+};
+
+/* Now combined for both registers */
+typedef struct LoadInfo LoadInfo;
+struct LoadInfo {
+    LoadRegInfo         A;              /* Info for A register */
+    LoadRegInfo         X;              /* Info for X register */
+    LoadRegInfo         Y;              /* Info for Y register */
+};
+
+
+
 /*****************************************************************************/
 /*                                   Data                                    */
 /*****************************************************************************/
 
 
 
-/* Structure that holds the needed data */
+/* Flags for the functions */
+typedef enum {
+    OP_NONE             = 0x00,         /* Nothing special */
+    OP_A_KNOWN          = 0x01,         /* Value of A must be known */
+    OP_X_ZERO           = 0x02,         /* X must be zero */
+    OP_LHS_LOAD         = 0x04,         /* Must have load insns for LHS */
+    OP_LHS_LOAD_DIRECT  = 0x0C,         /* Must have direct load insn for LHS */
+    OP_RHS_LOAD         = 0x10,         /* Must have load insns for RHS */
+    OP_RHS_LOAD_DIRECT  = 0x30,         /* Must have direct load insn for RHS */
+} OP_FLAGS;
+
+/* Structure forward decl */
 typedef struct StackOpData StackOpData;
+
+/* Structure that describes an optimizer subfunction for a specific op */
+typedef unsigned (*OptFunc) (StackOpData* D);
+typedef struct OptFuncDesc OptFuncDesc;
+struct OptFuncDesc {
+    const char*         Name;           /* Name of the replaced runtime function */
+    OptFunc             Func;           /* Function pointer */
+    unsigned            UnusedRegs;     /* Regs that must not be used later */
+    OP_FLAGS            Flags;          /* Flags */
+};
+
+/* Structure that holds the needed data */
 struct StackOpData {
-    CodeSeg*    Code;                   /* Pointer to code segment */
-    unsigned    Flags;                  /* Flags to remember things */
-    unsigned    PushIndex;              /* Index of call to pushax in codeseg */
-    unsigned    OpIndex;                /* Index of actual operation */
-    CodeEntry*  PrevEntry;              /* Entry before the call to pushax */
-    CodeEntry*  PushEntry;              /* Pointer to entry with call to pushax */
-    CodeEntry*  OpEntry;                /* Pointer to entry with op */
-    CodeEntry*  NextEntry;              /* Entry after the op */
-    const char* ZPLo;                   /* Lo byte of zero page loc to use */
-    const char* ZPHi;                   /* Hi byte of zero page loc to use */
-    unsigned    IP;                     /* Insertion point used by some routines */
+    CodeSeg*            Code;           /* Pointer to code segment */
+    unsigned            Flags;          /* Flags to remember things */
+
+    /* Pointer to optimizer subfunction description */
+    const OptFuncDesc*  OptFunc;
+
+    /* ZP register usage inside the sequence */
+    unsigned            UsedRegs;
+
+    /* Register load information for lhs and rhs */
+    LoadInfo            Lhs;
+    LoadInfo            Rhs;
+
+    /* Several indices of insns in the code segment */
+    int                 PushIndex;      /* Index of call to pushax in codeseg */
+    int                 OpIndex;        /* Index of actual operation */
+
+    /* Pointers to insns in the code segment */
+    CodeEntry*          PrevEntry;      /* Entry before the call to pushax */
+    CodeEntry*          PushEntry;      /* Pointer to entry with call to pushax */
+    CodeEntry*          OpEntry;        /* Pointer to entry with op */
+    CodeEntry*          NextEntry;      /* Entry after the op */
+
+    const char*         ZPLo;           /* Lo byte of zero page loc to use */
+    const char*         ZPHi;           /* Hi byte of zero page loc to use */
+    unsigned            IP;             /* Insertion point used by some routines */
 };
 
-/* Flags returned by DirectOp */
-#define OP_DIRECT       0x01            /* Direct op may be used */
-#define OP_RELOAD_Y     0x02            /* Must reload index register Y */
+
+
+/*****************************************************************************/
+/*                            Load tracking code                             */
+/*****************************************************************************/
+
+
+
+static void ClearLoadRegInfo (LoadRegInfo* RI)
+/* Clear a LoadRegInfo struct */
+{
+    RI->LoadIndex = -1;
+}
+
+
+
+static void FinalizeLoadRegInfo (LoadRegInfo* RI, CodeSeg* S)
+/* Prepare a LoadRegInfo struct for use */
+{
+    /* Get the entry */
+    if (RI->LoadIndex >= 0) {
+        RI->LoadEntry = CS_GetEntry (S, RI->LoadIndex);
+    } else {
+        RI->LoadEntry = 0;
+    }
+    RI->Flags = LI_NONE;
+}
+
+
+
+static void ClearLoadInfo (LoadInfo* LI)
+/* Clear a LoadInfo struct */
+{
+    ClearLoadRegInfo (&LI->A);
+    ClearLoadRegInfo (&LI->X);
+    ClearLoadRegInfo (&LI->Y);
+}
+
+
+
+static void AdjustLoadRegInfo (LoadRegInfo* RI, int DelIndex, int Change)
+/* Adjust a load register info struct after deleting or inserting an entry
+ * with a given index
+ */
+{
+    CHECK (abs (Change) == 1);
+    if (Change < 0) {
+        /* Deletion */
+        if (DelIndex < RI->LoadIndex) {
+            --RI->LoadIndex;
+        } else if (DelIndex == RI->LoadIndex) {
+            /* Has been removed */
+            RI->LoadIndex = -1;
+            RI->LoadEntry = 0;
+        }
+    } else {
+        /* Insertion */
+        if (DelIndex <= RI->LoadIndex) {
+            ++RI->LoadIndex;
+        }
+    }
+}
+
+
+
+static void FinalizeLoadInfo (LoadInfo* LI, CodeSeg* S)
+/* Prepare a LoadInfo struct for use */
+{
+    /* Get the entries */
+    FinalizeLoadRegInfo (&LI->A, S);
+    FinalizeLoadRegInfo (&LI->X, S);
+    FinalizeLoadRegInfo (&LI->Y, S);
+}
+
+
+
+static void AdjustLoadInfo (LoadInfo* LI, int DelIndex, int Change)
+/* Adjust a load info struct after deleting entry with a given index */
+{
+    AdjustLoadRegInfo (&LI->A, DelIndex, Change);
+    AdjustLoadRegInfo (&LI->X, DelIndex, Change);
+    AdjustLoadRegInfo (&LI->Y, DelIndex, Change);
+}
+
+
+
+static void TrackLoads (LoadInfo* LI, CodeEntry* E, int I)
+/* Track loads for a code entry */
+{
+    if (E->Info & OF_LOAD) {
+        if (E->Chg & REG_A) {
+            LI->A.LoadIndex = I;
+        }
+        if (E->Chg & REG_X) {
+            LI->X.LoadIndex = I;
+        }
+        if (E->Chg & REG_Y) {
+            LI->Y.LoadIndex = I;
+        }
+    } else if (E->Info & OF_XFR) {
+        switch (E->OPC) {
+            case OP65_TAX: LI->X.LoadIndex = LI->A.LoadIndex; break;
+            case OP65_TAY: LI->Y.LoadIndex = LI->A.LoadIndex; break;
+            case OP65_TXA: LI->A.LoadIndex = LI->X.LoadIndex; break;
+            case OP65_TYA: LI->A.LoadIndex = LI->Y.LoadIndex; break;
+            default:                                          break;
+        }
+    } else if (CE_IsCallTo (E, "ldaxysp")) {
+        /* Both registers set, Y changed */
+        LI->A.LoadIndex = I;
+        LI->X.LoadIndex = I;
+        LI->Y.LoadIndex = -1;
+    } else {
+        if (E->Chg & REG_A) {
+            LI->A.LoadIndex = -1;
+        }
+        if (E->Chg & REG_X) {
+            LI->X.LoadIndex = -1;
+        }
+        if (E->Chg & REG_Y) {
+            LI->Y.LoadIndex = -1;
+        }
+    }
+}
 
 
 
@@ -79,21 +269,16 @@ struct StackOpData {
 
 
 
-static unsigned AdjustStackOffset (CodeSeg* S, unsigned Start, unsigned Stop,
-                                  unsigned Offs)
-/* Adjust the offset for all stack accesses in the range Start to Stop, both
- * inclusive. The function returns the number of instructions that have been
- * inserted.
+static void AdjustStackOffset (StackOpData* D, unsigned Offs)
+/* Adjust the offset for all stack accesses in the range PushIndex to OpIndex.
+ * OpIndex is adjusted according to the insertions.
  */
 {
-    /* Number of inserted instructions */
-    unsigned Inserted = 0;
-
     /* Walk over all entries */
-    unsigned I = Start;
-    while (I <= Stop) {
+    int I = D->PushIndex + 1;
+    while (I < D->OpIndex) {
 
-       CodeEntry* E = CS_GetEntry (S, I);
+       CodeEntry* E = CS_GetEntry (D->Code, I);
 
         int NeedCorrection = 0;
        if ((E->Use & REG_SP) != 0) {
@@ -114,50 +299,37 @@ static unsigned AdjustStackOffset (CodeSeg* S, unsigned Start, unsigned Stop,
 
         if (NeedCorrection) {
 
-           CodeEntry* P;
-
-            /* If the Y register value is needed later, we have to reload the
-             * register after changing it.
-             */
-            int NeedY = RegYUsed (S, I+1);
-            unsigned YVal = E->RI->In.RegY;
-
            /* Get the code entry before this one. If it's a LDY, adjust the
             * value.
             */
-           P = CS_GetPrevEntry (S, I);
-           if (P && P->OPC == OP65_LDY && CE_KnownImm (P)) {
+           CodeEntry* P = CS_GetPrevEntry (D->Code, I);
+           if (P && P->OPC == OP65_LDY && CE_IsConstImm (P)) {
 
-               /* The Y load is just before the stack access, adjust it */
-               CE_SetNumArg (P, P->Num - Offs);
+               /* The Y load is just before the stack access, adjust it */
+               CE_SetNumArg (P, P->Num - Offs);
 
            } else {
 
-               /* Insert a new load instruction before the stack access */
-               const char* Arg = MakeHexArg (YVal - Offs);
-               CodeEntry* X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
-               CS_InsertEntry (S, X, I);
+               /* Insert a new load instruction before the stack access */
+               const char* Arg = MakeHexArg (E->RI->In.RegY - Offs);
+               CodeEntry* X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
+               CS_InsertEntry (D->Code, X, I++);
 
                /* One more inserted entries */
-               ++Inserted;
-               ++Stop;
-
-               /* Be sure to skip the stack access for the next round */
-               ++I;
+               ++D->OpIndex;
 
            }
 
             /* If we need the value of Y later, be sure to reload it */
-            if (NeedY) {
-               const char* Arg = MakeHexArg (YVal);
+            if (RegYUsed (D->Code, I+1)) {
+               const char* Arg = MakeHexArg (E->RI->In.RegY);
                CodeEntry* X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
-               CS_InsertEntry (S, X, I+1);
+               CS_InsertEntry (D->Code, X, I+1);
 
                /* One more inserted entries */
-               ++Inserted;
-               ++Stop;
+               ++D->OpIndex;
 
-               /* Skip this instruction int the next round */
+               /* Skip this instruction in the next round */
                ++I;
             }
        }
@@ -165,14 +337,11 @@ static unsigned AdjustStackOffset (CodeSeg* S, unsigned Start, unsigned Stop,
        /* Next entry */
        ++I;
     }
-
-    /* Return the number of inserted entries */
-    return Inserted;
 }
 
 
 
-static void InsertEntry (StackOpData* D, CodeEntry* E, unsigned Index)
+static void InsertEntry (StackOpData* D, CodeEntry* E, int Index)
 /* Insert a new entry. Depending on Index, D->PushIndex and D->OpIndex will
  * be adjusted by this function.
  */
@@ -180,6 +349,10 @@ static void InsertEntry (StackOpData* D, CodeEntry* E, unsigned Index)
     /* Insert the entry into the code segment */
     CS_InsertEntry (D->Code, E, Index);
 
+    /* Adjust register loads if necessary */
+    AdjustLoadInfo (&D->Lhs, Index, 1);
+    AdjustLoadInfo (&D->Rhs, Index, 1);
+
     /* Adjust the indices if necessary */
     if (D->PushEntry && Index <= D->PushIndex) {
         ++D->PushIndex;
@@ -191,7 +364,7 @@ static void InsertEntry (StackOpData* D, CodeEntry* E, unsigned Index)
 
 
 
-static void DelEntry (StackOpData* D, unsigned Index)
+static void DelEntry (StackOpData* D, int Index)
 /* Delete an entry. Depending on Index, D->PushIndex and D->OpIndex will be
  * adjusted by this function, and PushEntry/OpEntry may get invalidated.
  */
@@ -199,7 +372,11 @@ static void DelEntry (StackOpData* D, unsigned Index)
     /* Delete the entry from the code segment */
     CS_DelEntry (D->Code, Index);
 
-    /* Adjust the indices if necessary */
+    /* Adjust register loads if necessary */
+    AdjustLoadInfo (&D->Lhs, Index, -1);
+    AdjustLoadInfo (&D->Rhs, Index, -1);
+
+    /* Adjust the other indices if necessary */
     if (Index < D->PushIndex) {
         --D->PushIndex;
     } else if (Index == D->PushIndex) {
@@ -214,22 +391,37 @@ static void DelEntry (StackOpData* D, unsigned Index)
 
 
 
-static void CheckDirectOp (StackOpData* D)
+static void CheckOneDirectOp (LoadRegInfo* LI, unsigned char Offs)
 /* Check if the given entry is a lda instruction with an addressing mode
  * that allows us to replace it by another operation (like ora). If so, we may
  * use this location for the or and must not save the value in the zero
  * page location.
  */
 {
-    /* We need the entry before the push */
-    CodeEntry* E;
-    CHECK ((E = D->PrevEntry) != 0);
+    /* Get the load entry */
+    CodeEntry* E = LI->LoadEntry;
+    if (E == 0) {
+        /* No load insn */
+        return;
+    }
 
-    if (E->OPC == OP65_LDA) {
-        if (E->AM == AM65_IMM || E->AM == AM65_ZP || E->AM == AM65_ABS) {
+    /* Check the load entry */
+    if (E) {
+        /* Must check the call first since addressing mode is ABS, so second
+         * "if" will catch otherwise.
+         */
+        if (CE_IsCallTo (E, "ldaxysp")) {
+            /* Same as single loads from stack. Since we must distinguish
+             * between A and X here, the necessary offset is passed to the
+             * function as a parameter.
+             */
+            LI->Offs = (unsigned char) E->RI->In.RegY - Offs;
+            LI->Flags |= (LI_DIRECT | LI_RELOAD_Y);
+        } else if (E->AM == AM65_IMM || E->AM == AM65_ZP || E->AM == AM65_ABS) {
             /* These insns are all ok and replaceable */
-            D->Flags |= OP_DIRECT;
-        } else if (E->AM == AM65_ZP_INDY && RegValIsKnown (E->RI->In.RegY) &&
+            LI->Flags |= LI_DIRECT;
+        } else if (E->AM == AM65_ZP_INDY &&
+                   RegValIsKnown (E->RI->In.RegY) &&
                    strcmp (E->Arg, "sp") == 0) {
             /* A load from the stack with known offset is also ok, but in this
              * case we must reload the index register later. Please note that
@@ -237,13 +429,30 @@ static void CheckDirectOp (StackOpData* D)
              * these locations may change between the push and the actual
              * operation.
              */
-            D->Flags |= (OP_DIRECT | OP_RELOAD_Y);
+            LI->Offs  = (unsigned char) E->RI->In.RegY;
+            LI->Flags |= (LI_DIRECT | LI_RELOAD_Y);
         }
     }
 }
 
 
 
+static void CheckDirectOp (StackOpData* D)
+/* Check if the given entry is a lda instruction with an addressing mode
+ * that allows us to replace it by another operation (like ora). If so, we may
+ * use this location for the or and must not save the value in the zero
+ * page location.
+ */
+{
+    /* Check flags for all load instructions */
+    CheckOneDirectOp (&D->Lhs.A, 1);
+    CheckOneDirectOp (&D->Lhs.X, 0);
+    CheckOneDirectOp (&D->Rhs.A, 1);
+    CheckOneDirectOp (&D->Rhs.X, 0);
+}
+
+
+
 static void ReplacePushByStore (StackOpData* D)
 /* Replace the call to the push subroutine by a store into the zero page
  * location (actually, the push is not replaced, because we need it for
@@ -253,10 +462,14 @@ static void ReplacePushByStore (StackOpData* D)
 {
     CodeEntry* X;
 
-    /* Store the value into the zeropage instead of pushing it */
-    X = NewCodeEntry (OP65_STX, AM65_ZP, D->ZPHi, 0, D->PushEntry->LI);
-    InsertEntry (D, X, D->PushIndex+1);
-    if ((D->Flags & OP_DIRECT) == 0) {
+    /* Store the value into the zeropage instead of pushing it. Check high
+     * byte first so that the store is later in A/X order.
+     */
+    if ((D->Lhs.X.Flags & LI_DIRECT) == 0) {
+        X = NewCodeEntry (OP65_STX, AM65_ZP, D->ZPHi, 0, D->PushEntry->LI);
+        InsertEntry (D, X, D->PushIndex+1);
+    }
+    if ((D->Lhs.A.Flags & LI_DIRECT) == 0) {
        X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->PushEntry->LI);
                InsertEntry (D, X, D->PushIndex+1);
     }
@@ -272,21 +485,40 @@ static void AddOpLow (StackOpData* D, opc_t OPC)
 {
     CodeEntry* X;
 
-    if ((D->Flags & OP_DIRECT) != 0) {
+    if ((D->Lhs.A.Flags & LI_DIRECT) != 0) {
                /* Op with a variable location. If the location is on the stack, we
          * need to reload the Y register.
          */
-        if ((D->Flags & OP_RELOAD_Y) != 0) {
-            const char* Arg = MakeHexArg (D->PrevEntry->RI->In.RegY);
+        if ((D->Lhs.A.Flags & LI_RELOAD_Y) == 0) {
+
+            /* opc ... */
+            CodeEntry* LoadA = D->Lhs.A.LoadEntry;
+            X = NewCodeEntry (OPC, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+
+        } else {
+
+            /* ldy #offs */
+            const char* Arg = MakeHexArg (D->Lhs.A.Offs);
             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->IP++);
+
+            /* opc (sp),y */
+            X = NewCodeEntry (OPC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+
         }
-       X = NewCodeEntry (OPC, D->PrevEntry->AM, D->PrevEntry->Arg, 0, D->OpEntry->LI);
+
+        /* In both cases, we can remove the load */
+        D->Lhs.A.Flags |= LI_REMOVE;
+
     } else {
-       /* Op with temp storage */
-       X = NewCodeEntry (OPC, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
+
+       /* Op with temp storage */
+       X = NewCodeEntry (OPC, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
     }
-    InsertEntry (D, X, D->IP++);
 }
 
 
@@ -299,24 +531,79 @@ static void AddOpHigh (StackOpData* D, opc_t OPC)
 {
     CodeEntry* X;
 
-    /* High byte is unknown */
-    X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
+    /* pha */
+    X = NewCodeEntry (OP65_PHA, AM65_IMP, 0, 0, D->OpEntry->LI);
     InsertEntry (D, X, D->IP++);
+
+    /* txa */
     X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
     InsertEntry (D, X, D->IP++);
-    X = NewCodeEntry (OPC, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
-    InsertEntry (D, X, D->IP++);
+
+    if ((D->Lhs.X.Flags & LI_DIRECT) != 0) {
+
+        if ((D->Lhs.X.Flags & LI_RELOAD_Y) == 0) {
+
+            /* opc xxx */
+            CodeEntry* LoadX = D->Lhs.X.LoadEntry;
+           X = NewCodeEntry (OPC, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+
+        } else {
+
+            /* ldy #const */
+            const char* Arg = MakeHexArg (D->Lhs.X.Offs);
+            X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+
+            /* opc (sp),y */
+            X = NewCodeEntry (OPC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+        }
+
+        /* In both cases, we can remove the load */
+        D->Lhs.X.Flags |= LI_REMOVE;
+
+    } else {
+        /* opc zphi */
+        X = NewCodeEntry (OPC, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* tax */
     X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, D->OpEntry->LI);
     InsertEntry (D, X, D->IP++);
-    X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
+
+    /* pla */
+    X = NewCodeEntry (OP65_PLA, AM65_IMP, 0, 0, D->OpEntry->LI);
     InsertEntry (D, X, D->IP++);
 }
 
 
 
-static void RemovePushAndOp (StackOpData* D)
-/* Remove the call to pushax and the call to the operator subroutine */
+static void RemoveRegLoads (StackOpData* D, LoadInfo* LI)
+/* Remove register load insns */
 {
+    /* Both registers may be loaded with one insn, but DelEntry will in this
+     * case clear the other one.
+     */
+    if (LI->A.LoadIndex >= 0 && (LI->A.Flags & LI_REMOVE)) {
+        DelEntry (D, LI->A.LoadIndex);
+    }
+    if (LI->X.LoadIndex >= 0 && (LI->X.Flags & LI_REMOVE)) {
+        DelEntry (D, LI->X.LoadIndex);
+    }
+}
+
+
+
+static void RemoveRemainders (StackOpData* D)
+/* Remove the code that is unnecessary after translation of the sequence */
+{
+    /* Remove the register loads for lhs and rhs */
+    RemoveRegLoads (D, &D->Lhs);
+    RemoveRegLoads (D, &D->Rhs);
+
+    /* Remove the push and the operator routine */
     DelEntry (D, D->OpIndex);
     DelEntry (D, D->PushIndex);
 }
@@ -324,31 +611,36 @@ static void RemovePushAndOp (StackOpData* D)
 
 
 static int IsRegVar (StackOpData* D)
-/* If the value pushed is that of a register variable, replace ZPLo and ZPHi
- * in the given StackOpData struct by the register variables and return true.
- * Otherwise leave D untouched and return false.
+/* If the value pushed is that of a zeropage variable, replace ZPLo and ZPHi
+ * in the given StackOpData struct by the variable and return true. Otherwise
+ * leave D untouched and return false.
  */
 {
-    CodeEntry* P;
-
-    if (D->PushIndex >= 2                                &&
-        (P = D->PrevEntry) != 0                          &&
-        P->OPC == OP65_LDX                               &&
-        P->AM == AM65_ZP                                 &&
-        strncmp (P->Arg, "regbank+", 7) == 0             &&
-        IsDigit (P->Arg[8])                              &&
-        (P = CS_GetEntry (D->Code, D->PushIndex-2)) != 0 &&
-        P->OPC == OP65_LDA                               &&
-        P->AM == AM65_ZP                                 &&
-        strncmp (P->Arg, "regbank+", 7) == 0             &&
-        IsDigit (P->Arg[8])) {
-        /* Ok, it loads the register variable */
-        D->ZPHi = D->PrevEntry->Arg;
-        D->ZPLo = P->Arg;
-        return 1;
-    } else {
+    CodeEntry*  LoadA = D->Lhs.A.LoadEntry;
+    CodeEntry*  LoadX = D->Lhs.X.LoadEntry;
+    unsigned    Len;
+
+    /* Must have both load insns */
+    if (LoadA == 0 || LoadX == 0) {
         return 0;
     }
+
+    /* Must be loads from zp */
+    if (LoadA->AM != AM65_ZP || LoadX->AM != AM65_ZP) {
+        return 0;
+    }
+
+    /* Must be the same zp loc with high byte in X */
+    Len = strlen (LoadA->Arg);
+    if (strncmp (LoadA->Arg, LoadX->Arg, Len) != 0      ||
+        strcmp (LoadX->Arg + Len, "+1") != 0) {
+        return 0;
+    }
+
+    /* Use the zero page location directly */
+    D->ZPLo = LoadA->Arg;
+    D->ZPHi = LoadX->Arg;
+    return 1;
 }
 
 
@@ -387,55 +679,64 @@ static unsigned Opt___bzero (StackOpData* D)
      */
     if (D->OpEntry->RI->In.RegA != 0) {
 
+        /* lda #$00 */
+        X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->OpIndex+1);
+
         /* The value of A is known */
         if (D->OpEntry->RI->In.RegA <= 0x81) {
 
             /* Loop using the sign bit */
-            X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI);
-            InsertEntry (D, X, D->OpIndex+1);
 
+            /* ldy #count-1 */
            Arg = MakeHexArg (D->OpEntry->RI->In.RegA - 1);
             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+2);
 
+            /* L: sta (zp),y */
             X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+3);
             L = CS_GenLabel (D->Code, X);
 
+            /* dey */
             X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+4);
 
+            /* bpl L */
             X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+5);
 
         } else {
 
             /* Loop using an explicit compare */
-            X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI);
-            InsertEntry (D, X, D->OpIndex+1);
 
+            /* ldy #$00 */
             X = NewCodeEntry (OP65_LDY, AM65_IMM, "$00", 0, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+2);
 
+            /* L: sta (zp),y */
             X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+3);
             L = CS_GenLabel (D->Code, X);
 
+            /* iny */
             X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+4);
 
+            /* cpy #count */
            Arg = MakeHexArg (D->OpEntry->RI->In.RegA);
             X = NewCodeEntry (OP65_CPY, AM65_IMM, Arg, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+5);
 
-            X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, D->OpEntry->LI);
+            /* bne L */
+            X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+6);
         }
 
     }
 
     /* Remove the push and the call to the __bzero function */
-    RemovePushAndOp (D);
+    RemoveRemainders (D);
 
     /* We changed the sequence */
     return 1;
@@ -459,7 +760,7 @@ static unsigned Opt_staspidx (StackOpData* D)
     InsertEntry (D, X, D->OpIndex+1);
 
     /* Remove the push and the call to the staspidx function */
-    RemovePushAndOp (D);
+    RemoveRemainders (D);
 
     /* We changed the sequence */
     return 1;
@@ -479,30 +780,42 @@ static unsigned Opt_staxspidx (StackOpData* D)
     }
 
     /* Inline the store */
+
+    /* sta (zp),y */
     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
     InsertEntry (D, X, D->OpIndex+1);
+
     if (RegValIsKnown (D->OpEntry->RI->In.RegY)) {
         /* Value of Y is known */
-       const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegY + 1);
+               const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegY + 1);
                X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
     } else {
         X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI);
     }
     InsertEntry (D, X, D->OpIndex+2);
+
     if (RegValIsKnown (D->OpEntry->RI->In.RegX)) {
-       /* Value of X is known */
-       const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegX);
+               /* Value of X is known */
+               const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegX);
                X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, D->OpEntry->LI);
     } else {
-       /* Value unknown */
-       X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
+               /* Value unknown */
+               X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
     }
     InsertEntry (D, X, D->OpIndex+3);
+
+    /* sta (zp),y */
     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
     InsertEntry (D, X, D->OpIndex+4);
 
-    /* Remove the push and the call to the staspidx function */
-    RemovePushAndOp (D);
+    /* If we remove staxspidx, we must restore the Y register to what the
+     * function would return.
+     */
+    X = NewCodeEntry (OP65_LDY, AM65_IMM, "$00", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->OpIndex+5);
+
+    /* Remove the push and the call to the staxspidx function */
+    RemoveRemainders (D);
 
     /* We changed the sequence */
     return 1;
@@ -514,61 +827,118 @@ static unsigned Opt_tosaddax (StackOpData* D)
 /* Optimize the tosaddax sequence if possible */
 {
     CodeEntry*  X;
-
+    CodeEntry*  N;
 
     /* We need the entry behind the add */
     CHECK (D->NextEntry != 0);
 
-    /* Check the entry before the push. If it's a lda instruction with an
-     * addressing mode that allows us to replace it, we may use this
-     * location for the op and must not save the value in the zero page
-     * location.
+    /* Check if the X register is known and zero when the add is done, and
+     * if the add is followed by
+     *
+     *  ldy     #$00
+     *  jsr     ldauidx         ; or ldaidx
+     *
+     * If this is true, the addition does actually add an offset to a pointer
+     * before it is dereferenced. Since both subroutines take an offset in Y,
+     * we can pass the offset (instead of #$00) and remove the addition
+     * alltogether.
      */
-    CheckDirectOp (D);
+    if (D->OpEntry->RI->In.RegX == 0                            &&
+        D->NextEntry->OPC == OP65_LDY                           &&
+        CE_IsKnownImm (D->NextEntry, 0)                         &&
+        !CE_HasLabel (D->NextEntry)                             &&
+        (N = CS_GetNextEntry (D->Code, D->OpIndex + 1)) != 0    &&
+        (CE_IsCallTo (N, "ldauidx")                     ||
+         CE_IsCallTo (N, "ldaidx"))) {
 
-    /* Store the value into the zeropage instead of pushing it */
-    ReplacePushByStore (D);
+        int Signed = (strcmp (N->Arg, "ldaidx") == 0);
 
-    /* Inline the add */
-    D->IP = D->OpIndex+1;
-    X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, D->OpEntry->LI);
-    InsertEntry (D, X, D->IP++);
+        /* Store the value into the zeropage instead of pushing it */
+        ReplacePushByStore (D);
 
-    /* Low byte */
-    AddOpLow (D, OP65_ADC);
+        /* Replace the ldy by a tay. Be sure to create the new entry before
+         * deleting the ldy, since we will reference the line info from this
+         * insn.
+         */
+        X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, D->NextEntry->LI);
+        DelEntry (D, D->OpIndex + 1);
+        InsertEntry (D, X, D->OpIndex + 1);
+
+        /* Replace the call to ldaidx/ldauidx. Since X is already zero, and
+         * the ptr is in the zero page location, we just need to load from
+         * the pointer, and fix X in case of ldaidx.
+         */
+        X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, D->ZPLo, 0, N->LI);
+        DelEntry (D, D->OpIndex + 2);
+        InsertEntry (D, X, D->OpIndex + 2);
+        if (Signed) {
+
+            CodeLabel* L;
+
+            /* Add sign extension - N is unused now */
+            N = CS_GetNextEntry (D->Code, D->OpIndex + 2);
+            CHECK (N != 0);
+            L = CS_GenLabel (D->Code, N);
+
+            X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, X->LI);
+            InsertEntry (D, X, D->OpIndex + 3);
+
+            X = NewCodeEntry (OP65_DEX, AM65_IMP, 0, 0, X->LI);
+            InsertEntry (D, X, D->OpIndex + 4);
+        }
 
-    /* High byte */
-    if (D->PushEntry->RI->In.RegX == 0) {
-       /* The high byte is the value in X plus the carry */
-       CodeLabel* L = CS_GenLabel (D->Code, D->NextEntry);
-       X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
-       InsertEntry (D, X, D->IP++);
-       X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
-       InsertEntry (D, X, D->IP++);
-    } else if (D->OpEntry->RI->In.RegX == 0) {
-               /* The high byte is that of the first operand plus carry */
-       CodeLabel* L;
-       if (RegValIsKnown (D->PushEntry->RI->In.RegX)) {
-           /* Value of first op high byte is known */
-           const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX);
-           X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
-       } else {
-           /* Value of first op high byte is unknown */
-           X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
-       }
-       InsertEntry (D, X, D->IP++);
-       L = CS_GenLabel (D->Code, D->NextEntry);
-       X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
-       InsertEntry (D, X, D->IP++);
-       X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
-       InsertEntry (D, X, D->IP++);
     } else {
-       /* High byte is unknown */
-        AddOpHigh (D, OP65_ADC);
+
+        /* Store the value into the zeropage instead of pushing it */
+        ReplacePushByStore (D);
+
+        /* Inline the add */
+        D->IP = D->OpIndex+1;
+
+        /* clc */
+        X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* Low byte */
+        AddOpLow (D, OP65_ADC);
+
+        /* High byte */
+        if (D->PushEntry->RI->In.RegX == 0) {
+            /* The high byte is the value in X plus the carry */
+            CodeLabel* L = CS_GenLabel (D->Code, D->NextEntry);
+            X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+            X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+        } else if (D->OpEntry->RI->In.RegX == 0) {
+            /* The high byte is that of the first operand plus carry */
+            CodeLabel* L;
+            if (RegValIsKnown (D->PushEntry->RI->In.RegX)) {
+                /* Value of first op high byte is known */
+                const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX);
+                X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
+            } else {
+                /* Value of first op high byte is unknown */
+                X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
+            }
+            InsertEntry (D, X, D->IP++);
+
+            /* bcc label */
+            L = CS_GenLabel (D->Code, D->NextEntry);
+            X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+
+            /* inx */
+            X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
+            InsertEntry (D, X, D->IP++);
+        } else {
+            /* High byte is unknown */
+            AddOpHigh (D, OP65_ADC);
+        }
     }
 
     /* Remove the push and the call to the tosaddax function */
-    RemovePushAndOp (D);
+    RemoveRemainders (D);
 
     /* We changed the sequence */
     return 1;
@@ -581,13 +951,6 @@ static unsigned Opt_tosandax (StackOpData* D)
 {
     CodeEntry*  X;
 
-    /* Check the entry before the push. If it's a lda instruction with an
-     * addressing mode that allows us to replace it, we may use this
-     * location for the op and must not save the value in the zero page
-     * location.
-     */
-    CheckDirectOp (D);
-
     /* Store the value into the zeropage instead of pushing it */
     ReplacePushByStore (D);
 
@@ -599,14 +962,215 @@ static unsigned Opt_tosandax (StackOpData* D)
     if (D->PushEntry->RI->In.RegX == 0 || D->OpEntry->RI->In.RegX == 0) {
        /* The high byte is zero */
                X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
-       InsertEntry (D, X, D->IP++);
+               InsertEntry (D, X, D->IP++);
     } else {
        /* High byte is unknown */
         AddOpHigh (D, OP65_AND);
     }
 
     /* Remove the push and the call to the tosandax function */
-    RemovePushAndOp (D);
+    RemoveRemainders (D);
+
+    /* We changed the sequence */
+    return 1;
+}
+
+
+
+static unsigned Opt_tosgeax (StackOpData* D)
+/* Optimize the tosgeax sequence if possible. */
+{
+    CodeEntry*  X;
+    CodeLabel* L;
+
+    /* Inline the sbc */
+    D->IP = D->OpIndex+1;
+
+    /* Must be true because of OP_RHS_LOAD */
+    CHECK ((D->Rhs.A.Flags & LI_DIRECT) != 0);
+
+    /* If the location is on the stack, we need to reload the Y register. */
+    if ((D->Rhs.A.Flags & LI_RELOAD_Y) == 0) {
+
+        /* cmp ... */
+        CodeEntry* LoadA = D->Rhs.A.LoadEntry;
+        X = NewCodeEntry (OP65_CMP, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    } else {
+
+        /* ldy #offs */
+        const char* Arg = MakeHexArg (D->Rhs.A.Offs);
+        X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* cmp (sp),y */
+        X = NewCodeEntry (OP65_CMP, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* In both cases, we can remove the load */
+    D->Rhs.A.Flags |= LI_REMOVE;
+
+    /* txa */
+    X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Must be true because of OP_RHS_LOAD */
+    CHECK ((D->Rhs.X.Flags & LI_DIRECT) != 0);
+
+    /* If the location is on the stack, we need to reload the Y register. */
+    if ((D->Rhs.X.Flags & LI_RELOAD_Y) == 0) {
+
+        /* sbc ... */
+        CodeEntry* LoadX = D->Rhs.X.LoadEntry;
+        X = NewCodeEntry (OP65_SBC, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    } else {
+
+        /* ldy #offs */
+        const char* Arg = MakeHexArg (D->Rhs.X.Offs);
+        X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* sbc (sp),y */
+        X = NewCodeEntry (OP65_SBC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* In both cases, we can remove the load */
+    D->Rhs.X.Flags |= LI_REMOVE;
+
+    /* eor #$80 */
+    X = NewCodeEntry (OP65_EOR, AM65_IMM, "$80", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* asl a */
+    X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+    L = CS_GenLabel (D->Code, X);
+
+    /* Insert a bvs L before the eor insn */
+    X = NewCodeEntry (OP65_BVS, AM65_BRA, L->Name, L, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP - 2);
+    ++D->IP;
+
+    /* lda #$00 */
+    X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* ldx #$00 */
+    X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* rol a */
+    X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Remove the push and the call to the tosgeax function */
+    RemoveRemainders (D);
+
+    /* We changed the sequence */
+    return 1;
+}
+
+
+
+static unsigned Opt_tosltax (StackOpData* D)
+/* Optimize the tosltax sequence if possible. */
+{
+    CodeEntry*  X;
+    CodeLabel* L;
+
+
+    /* Inline the sbc */
+    D->IP = D->OpIndex+1;
+
+    /* Must be true because of OP_RHS_LOAD */
+    CHECK ((D->Rhs.A.Flags & LI_DIRECT) != 0);
+
+    /* If the location is on the stack, we need to reload the Y register. */
+    if ((D->Rhs.A.Flags & LI_RELOAD_Y) == 0) {
+
+        /* cmp ... */
+        CodeEntry* LoadA = D->Rhs.A.LoadEntry;
+        X = NewCodeEntry (OP65_CMP, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    } else {
+
+        /* ldy #offs */
+        const char* Arg = MakeHexArg (D->Rhs.A.Offs);
+        X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* cmp (sp),y */
+        X = NewCodeEntry (OP65_CMP, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* In both cases, we can remove the load */
+    D->Rhs.A.Flags |= LI_REMOVE;
+
+    /* txa */
+    X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Must be true because of OP_RHS_LOAD */
+    CHECK ((D->Rhs.X.Flags & LI_DIRECT) != 0);
+
+    /* If the location is on the stack, we need to reload the Y register. */
+    if ((D->Rhs.X.Flags & LI_RELOAD_Y) == 0) {
+
+        /* sbc ... */
+        CodeEntry* LoadX = D->Rhs.X.LoadEntry;
+        X = NewCodeEntry (OP65_SBC, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    } else {
+
+        /* ldy #offs */
+        const char* Arg = MakeHexArg (D->Rhs.X.Offs);
+        X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* sbc (sp),y */
+        X = NewCodeEntry (OP65_SBC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* In both cases, we can remove the load */
+    D->Rhs.X.Flags |= LI_REMOVE;
+
+    /* eor #$80 */
+    X = NewCodeEntry (OP65_EOR, AM65_IMM, "$80", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* asl a */
+    X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+    L = CS_GenLabel (D->Code, X);
+
+    /* Insert a bvc L before the eor insn */
+    X = NewCodeEntry (OP65_BVC, AM65_BRA, L->Name, L, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP - 2);
+    ++D->IP;
+
+    /* lda #$00 */
+    X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* ldx #$00 */
+    X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* rol a */
+    X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Remove the push and the call to the tosltax function */
+    RemoveRemainders (D);
 
     /* We changed the sequence */
     return 1;
@@ -619,13 +1183,6 @@ static unsigned Opt_tosorax (StackOpData* D)
 {
     CodeEntry*  X;
 
-    /* Check the entry before the push. If it's a lda instruction with an
-     * addressing mode that allows us to replace it, we may use this
-     * location for the op and must not save the value in the zero page
-     * location.
-     */
-    CheckDirectOp (D);
-
     /* Store the value into the zeropage instead of pushing it */
     ReplacePushByStore (D);
 
@@ -636,18 +1193,196 @@ static unsigned Opt_tosorax (StackOpData* D)
     /* High byte */
     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
-       /* Both values known, precalculate the result */
+               /* Both values known, precalculate the result */
         unsigned char Result = D->PushEntry->RI->In.RegX | D->OpEntry->RI->In.RegX;
         const char* Arg = MakeHexArg (Result);
         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
         InsertEntry (D, X, D->IP++);
     } else if (D->PushEntry->RI->In.RegX != 0) {
-       /* High byte is unknown */
+               /* High byte is unknown */
         AddOpHigh (D, OP65_ORA);
     }
 
     /* Remove the push and the call to the tosorax function */
-    RemovePushAndOp (D);
+    RemoveRemainders (D);
+
+    /* We changed the sequence */
+    return 1;
+}
+
+
+
+static unsigned Opt_tossubax (StackOpData* D)
+/* Optimize the tossubax sequence if possible. Note: subtraction is not
+ * commutative!
+ */
+{
+    CodeEntry*  X;
+
+
+    /* Inline the sbc */
+    D->IP = D->OpIndex+1;
+
+    /* sec */
+    X = NewCodeEntry (OP65_SEC, AM65_IMP, 0, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Must be true because of OP_RHS_LOAD */
+    CHECK ((D->Rhs.A.Flags & LI_DIRECT) != 0);
+
+    /* If the location is on the stack, we need to reload the Y register. */
+    if ((D->Rhs.A.Flags & LI_RELOAD_Y) == 0) {
+
+        /* sbc ... */
+        CodeEntry* LoadA = D->Rhs.A.LoadEntry;
+        X = NewCodeEntry (OP65_SBC, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    } else {
+
+        /* ldy #offs */
+        const char* Arg = MakeHexArg (D->Rhs.A.Offs);
+        X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* sbc (sp),y */
+        X = NewCodeEntry (OP65_SBC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* In both cases, we can remove the load */
+    D->Rhs.A.Flags |= LI_REMOVE;
+
+    /* pha */
+    X = NewCodeEntry (OP65_PHA, AM65_IMP, 0, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* txa */
+    X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Must be true because of OP_RHS_LOAD */
+    CHECK ((D->Rhs.X.Flags & LI_DIRECT) != 0);
+
+    /* If the location is on the stack, we need to reload the Y register. */
+    if ((D->Rhs.X.Flags & LI_RELOAD_Y) == 0) {
+
+        /* sbc ... */
+        CodeEntry* LoadX = D->Rhs.X.LoadEntry;
+        X = NewCodeEntry (OP65_SBC, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    } else {
+
+        /* ldy #offs */
+        const char* Arg = MakeHexArg (D->Rhs.X.Offs);
+        X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* sbc (sp),y */
+        X = NewCodeEntry (OP65_SBC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* In both cases, we can remove the load */
+    D->Rhs.X.Flags |= LI_REMOVE;
+
+    /* tax */
+    X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* pla */
+    X = NewCodeEntry (OP65_PLA, AM65_IMP, 0, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Remove the push and the call to the tossubax function */
+    RemoveRemainders (D);
+
+    /* We changed the sequence */
+    return 1;
+}
+
+
+
+static unsigned Opt_tosugeax (StackOpData* D)
+/* Optimize the tosugeax sequence if possible. */
+{
+    CodeEntry*  X;
+
+
+    /* Inline the sbc */
+    D->IP = D->OpIndex+1;
+
+    /* Must be true because of OP_RHS_LOAD */
+    CHECK ((D->Rhs.A.Flags & LI_DIRECT) != 0);
+
+    /* If the location is on the stack, we need to reload the Y register. */
+    if ((D->Rhs.A.Flags & LI_RELOAD_Y) == 0) {
+
+        /* cmp ... */
+        CodeEntry* LoadA = D->Rhs.A.LoadEntry;
+        X = NewCodeEntry (OP65_CMP, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    } else {
+
+        /* ldy #offs */
+        const char* Arg = MakeHexArg (D->Rhs.A.Offs);
+        X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* cmp (sp),y */
+        X = NewCodeEntry (OP65_CMP, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* In both cases, we can remove the load */
+    D->Rhs.A.Flags |= LI_REMOVE;
+
+    /* txa */
+    X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Must be true because of OP_RHS_LOAD */
+    CHECK ((D->Rhs.X.Flags & LI_DIRECT) != 0);
+
+    /* If the location is on the stack, we need to reload the Y register. */
+    if ((D->Rhs.X.Flags & LI_RELOAD_Y) == 0) {
+
+        /* sbc ... */
+        CodeEntry* LoadX = D->Rhs.X.LoadEntry;
+        X = NewCodeEntry (OP65_SBC, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    } else {
+
+        /* ldy #offs */
+        const char* Arg = MakeHexArg (D->Rhs.X.Offs);
+        X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* sbc (sp),y */
+        X = NewCodeEntry (OP65_SBC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+    }
+
+    /* In both cases, we can remove the load */
+    D->Rhs.X.Flags |= LI_REMOVE;
+
+    /* lda #$00 */
+    X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* ldx #$00 */
+    X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* rol a */
+    X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Remove the push and the call to the tosugeax function */
+    RemoveRemainders (D);
 
     /* We changed the sequence */
     return 1;
@@ -660,12 +1395,6 @@ static unsigned Opt_tosxorax (StackOpData* D)
 {
     CodeEntry*  X;
 
-    /* Check the entry before the push. If it's a lda instruction with an
-     * addressing mode that allows us to replace it, we may use this
-     * location for the op and must not save the value in the zero page
-     * location.
-     */
-    CheckDirectOp (D);
 
     /* Store the value into the zeropage instead of pushing it */
     ReplacePushByStore (D);
@@ -687,7 +1416,7 @@ static unsigned Opt_tosxorax (StackOpData* D)
     }
 
     /* Remove the push and the call to the tosandax function */
-    RemovePushAndOp (D);
+    RemoveRemainders (D);
 
     /* We changed the sequence */
     return 1;
@@ -696,36 +1425,23 @@ static unsigned Opt_tosxorax (StackOpData* D)
 
 
 /*****************************************************************************/
-/*                                  Code                                    */
+/*                                  Code                                    */
 /*****************************************************************************/
 
 
 
-/* Flags for the functions */
-typedef enum {
-    STOP_NONE       = 0x00,     /* Nothing special */
-    STOP_A_UNUSED   = 0x01,     /* Call only if a unused later */
-    STOP_A_KNOWN    = 0x02,     /* Call only if A is known */
-    STOP_X_ZERO     = 0x04      /* Call only if X is zero */
-} STOP_FLAGS;
-
-
-typedef unsigned (*OptFunc) (StackOpData* D);
-typedef struct OptFuncDesc OptFuncDesc;
-struct OptFuncDesc {
-    const char*     Name;   /* Name of the replaced runtime function */
-    OptFunc         Func;   /* Function pointer */
-    STOP_FLAGS      Flags;  /* Flags */
-};
-
 static const OptFuncDesc FuncTable[] = {
-    { "__bzero",    Opt___bzero,   STOP_X_ZERO   },
-    { "staspidx",   Opt_staspidx,  STOP_NONE     },
-    { "staxspidx",  Opt_staxspidx, STOP_A_UNUSED },
-    { "tosaddax",   Opt_tosaddax,  STOP_NONE     },
-    { "tosandax",   Opt_tosandax,  STOP_NONE     },
-    { "tosorax",    Opt_tosorax,   STOP_NONE     },
-    { "tosxorax",   Opt_tosxorax,  STOP_NONE     },
+    { "__bzero",    Opt___bzero,   REG_NONE, OP_X_ZERO | OP_A_KNOWN     },
+    { "staspidx",   Opt_staspidx,  REG_NONE, OP_NONE                    },
+    { "staxspidx",  Opt_staxspidx, REG_AX,   OP_NONE                    },
+    { "tosaddax",   Opt_tosaddax,  REG_NONE, OP_NONE                    },
+    { "tosandax",   Opt_tosandax,  REG_NONE, OP_NONE                    },
+    { "tosgeax",    Opt_tosgeax,   REG_NONE, OP_RHS_LOAD_DIRECT         },
+    { "tosltax",    Opt_tosltax,   REG_NONE, OP_RHS_LOAD_DIRECT         },
+    { "tosorax",    Opt_tosorax,   REG_NONE, OP_NONE                    },
+    { "tossubax",   Opt_tossubax,  REG_NONE, OP_RHS_LOAD_DIRECT         },
+    { "tosugeax",   Opt_tosugeax,  REG_NONE, OP_RHS_LOAD_DIRECT         },
+    { "tosxorax",   Opt_tosxorax,  REG_NONE, OP_NONE                    },
 };
 #define FUNC_COUNT (sizeof(FuncTable) / sizeof(FuncTable[0]))
 
@@ -763,9 +1479,18 @@ static int HarmlessCall (const char* Name)
  */
 {
     static const char* Tab[] = {
+        "aslax1",
+        "aslax2",
+        "asrax1",
+        "asrax2",
+        "bnegax",
         "ldaxidx",
         "ldaxysp",
         "negax",
+        "shlax1",
+        "shlax2",
+        "shrax1",
+        "shrax2",
     };
 
     void* R = bsearch (Name,
@@ -778,8 +1503,90 @@ static int HarmlessCall (const char* Name)
 
 
 
+static void ResetStackOpData (StackOpData* Data)
+/* Reset the given data structure */
+{
+    Data->OptFunc       = 0;
+    Data->UsedRegs      = REG_NONE;
+
+    ClearLoadInfo (&Data->Lhs);
+    ClearLoadInfo (&Data->Rhs);
+
+    Data->PushIndex     = -1;
+    Data->OpIndex       = -1;
+}
+
+
+
+static int PreCondOk (StackOpData* D)
+/* Check if the preconditions for a call to the optimizer subfunction are
+ * satisfied. As a side effect, this function will also choose the zero page
+ * register to use.
+ */
+{
+    /* Check the flags */
+    unsigned UnusedRegs = D->OptFunc->UnusedRegs;
+    if (UnusedRegs != REG_NONE &&
+        (GetRegInfo (D->Code, D->OpIndex+1, UnusedRegs) & UnusedRegs) != 0) {
+        /* Cannot optimize */
+        return 0;
+    }
+    if ((D->OptFunc->Flags & OP_A_KNOWN) != 0 &&
+        RegValIsUnknown (D->OpEntry->RI->In.RegA)) {
+        /* Cannot optimize */
+        return 0;
+    }
+    if ((D->OptFunc->Flags & OP_X_ZERO) != 0 &&
+        D->OpEntry->RI->In.RegX != 0) {
+        /* Cannot optimize */
+        return 0;
+    }
+    if ((D->OptFunc->Flags & OP_LHS_LOAD) != 0) {
+        if (D->Lhs.A.LoadIndex < 0 || D->Lhs.X.LoadIndex < 0) {
+            /* Cannot optimize */
+            return 0;
+        } else if ((D->OptFunc->Flags & OP_LHS_LOAD_DIRECT) != 0) {
+            if ((D->Lhs.A.Flags & D->Lhs.X.Flags & LI_DIRECT) == 0) {
+                /* Cannot optimize */
+                return 0;
+            }
+        }
+    }
+    if ((D->OptFunc->Flags & OP_RHS_LOAD) != 0) {
+        if (D->Rhs.A.LoadIndex < 0 || D->Rhs.X.LoadIndex < 0) {
+            /* Cannot optimize */
+            return 0;
+        } else if ((D->OptFunc->Flags & OP_RHS_LOAD_DIRECT) != 0) {
+            if ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) == 0) {
+                /* Cannot optimize */
+                return 0;
+            }
+        }
+    }
+
+    /* Determine the zero page locations to use */
+    if ((D->UsedRegs & REG_PTR1) == REG_NONE) {
+        D->ZPLo = "ptr1";
+        D->ZPHi = "ptr1+1";
+    } else if ((D->UsedRegs & REG_SREG) == REG_NONE) {
+        D->ZPLo = "sreg";
+        D->ZPHi = "sreg+1";
+    } else if ((D->UsedRegs & REG_PTR2) == REG_NONE) {
+        D->ZPLo = "ptr2";
+        D->ZPHi = "ptr2+1";
+    } else {
+        /* No registers available */
+        return 0;
+    }
+
+    /* Determine if we have a basic block */
+    return CS_IsBasicBlock (D->Code, D->PushIndex, D->OpIndex);
+}
+
+
+
 /*****************************************************************************/
-/*                                  Code                                    */
+/*                                  Code                                    */
 /*****************************************************************************/
 
 
@@ -787,16 +1594,24 @@ static int HarmlessCall (const char* Name)
 unsigned OptStackOps (CodeSeg* S)
 /* Optimize operations that take operands via the stack */
 {
-    unsigned    Changes = 0;    /* Number of changes in one run */
-    int         InSeq = 0;      /* Inside a sequence */
-    unsigned    Push = 0;      /* Index of pushax */
-    unsigned    UsedRegs = 0;   /* Zeropage registers used in sequence */
-    unsigned    I;
+    unsigned            Changes = 0;    /* Number of changes in one run */
+    StackOpData         Data;
+    unsigned            I;
+
+    enum {
+        Initialize,
+        Search,
+        FoundPush,
+        FoundOp
+    } State = Initialize;
 
 
     /* Generate register info */
     CS_GenRegInfo (S);
 
+    /* Remember the code segment in the info struct */
+    Data.Code = S;
+
     /* Look for a call to pushax followed by a call to some other function
      * that takes it's first argument on the stack, and the second argument
      * in the primary register.
@@ -815,119 +1630,150 @@ unsigned OptStackOps (CodeSeg* S)
     I = 0;
     while (I < CS_GetEntryCount (S)) {
 
-       /* Get the next entry */
-       CodeEntry* E = CS_GetEntry (S, I);
+       /* Get the next entry */
+       CodeEntry* E = CS_GetEntry (S, I);
 
-       /* Handling depends if we're inside a sequence or not */
-       if (InSeq) {
+        /* Actions depend on state */
+        switch (State) {
 
-            /* If we are using the stack, and we don't have "indirect Y"
-             * addressing mode, or the value of Y is unknown, or less than
-             * two, we cannot cope with this piece of code. Having an unknown
-             * value of Y means that we cannot correct the stack offset, while
-             * having an offset less than two means that the code works with
-             * the value on stack which is to be removed.
-             */
-                   if ((E->Use & REG_SP) != 0 &&
-               (E->AM != AM65_ZP_INDY || RegValIsUnknown (E->RI->In.RegY) ||
-                 E->RI->In.RegY < 2)) {
-
-               /* All this stuff is not allowed in a sequence */
-               InSeq = 0;
-
-           } else if (E->OPC == OP65_JSR) {
-
-                       /* Subroutine call: Check if this is one of our functions */
-               const OptFuncDesc* F = FindFunc (E->Arg);
-               if (F) {
-
-                    StackOpData Data;
-                   int PreCondOk = 1;
-
-                   /* Check the flags */
-                   if ((F->Flags & STOP_A_UNUSED) != 0 && RegAUsed (S, I+1)) {
-                        /* Cannot optimize */
-                       PreCondOk = 0;
-                   } else if ((F->Flags & STOP_A_KNOWN) != 0 && RegValIsUnknown (E->RI->In.RegA)) {
-                        /* Cannot optimize */
-                        PreCondOk = 0;
-                    } else if ((F->Flags & STOP_X_ZERO) != 0 && E->RI->In.RegX != 0) {
-                        /* Cannot optimize */
-                        PreCondOk = 0;
-                    }
-
-                   /* Determine the zero page locations to use */
-                   if (PreCondOk) {
-                       UsedRegs |= GetRegInfo (S, I+1, REG_SREG | REG_PTR1 | REG_PTR2);
-                       if ((UsedRegs & REG_SREG) == REG_NONE) {
-                           /* SREG is available */
-                           Data.ZPLo = "sreg";
-                           Data.ZPHi = "sreg+1";
-                       } else if ((UsedRegs & REG_PTR1) == REG_NONE) {
-                           Data.ZPLo = "ptr1";
-                           Data.ZPHi = "ptr1+1";
-                       } else if ((UsedRegs & REG_PTR2) == REG_NONE) {
-                           Data.ZPLo = "ptr2";
-                           Data.ZPHi = "ptr2+1";
-                       } else {
-                           /* No registers available */
-                           PreCondOk = 0;
-                       }
-                   }
-
-                    /* Determine if we have a basic block */
-                    if (PreCondOk) {
-                        PreCondOk = CS_IsBasicBlock (S, Push, I);
-                    }
+            case Initialize:
+                ResetStackOpData (&Data);
+                State = Search;
+                /* FALLTHROUGH */
 
-                   /* If preconditions are ok, call the optimizer function */
-                   if (PreCondOk) {
-
-                       /* Adjust stack offsets */
-                       Data.OpIndex = I + AdjustStackOffset (S, Push, I, 2);
-
-                        /* Prepare the remainder of the data structure */
-                        Data.Code      = S;
-                        Data.Flags     = 0;
-                        Data.PushIndex = Push;
-                        Data.PrevEntry = CS_GetPrevEntry (S, Data.PushIndex);
-                        Data.PushEntry = CS_GetEntry (S, Data.PushIndex);
-                        Data.OpEntry   = E;
-                        Data.NextEntry = CS_GetNextEntry (S, Data.OpIndex);
-
-                               /* Call the optimizer function */
-                       Changes += F->Func (&Data);
-
-                       /* Regenerate register info */
-                       CS_GenRegInfo (S);
-                   }
-
-                   /* End of sequence */
-                   InSeq = 0;
-
-               } else if (strcmp (E->Arg, "pushax") == 0) {
-                   /* Restart the sequence */
-                   Push     = I;
-                   UsedRegs = REG_NONE;
-               } else if (HarmlessCall (E->Arg)) {
-                    /* Track zeropage register usage */
-                    UsedRegs |= (E->Use | E->Chg);
+            case Search:
+                /* While searching, track register load insns, so we can tell
+                 * what is in a register once pushax is encountered.
+                 */
+                if (CE_IsCallTo (E, "pushax")) {
+                    Data.PushIndex = I;
+                    State = FoundPush;
                 } else {
-                   /* A call to an unkown subroutine ends the sequence */
-                   InSeq = 0;
-               }
-
-           } else {
-               /* Other stuff: Track zeropage register usage */
-               UsedRegs |= (E->Use | E->Chg);
-           }
+                    /* Track load insns */
+                    TrackLoads (&Data.Lhs, E, I);
+                }
+                break;
+
+            case FoundPush:
+                /* We' found a pushax before. Search for a stack op that may
+                 * follow and in the meantime, track zeropage usage and check
+                 * for code that will disable us from translating the sequence.
+                 */
+                if (E->OPC == OP65_JSR) {
+
+                    /* Subroutine call: Check if this is one of the functions,
+                     * we're going to replace.
+                     */
+                    Data.OptFunc = FindFunc (E->Arg);
+                    if (Data.OptFunc) {
+                        /* Remember the op index and go on */
+                        Data.OpIndex = I;
+                        Data.OpEntry = E;
+                        State = FoundOp;
+                        break;
+                    } else if (!HarmlessCall (E->Arg)) {
+                        /* A call to an unkown subroutine: We need to start
+                         * over after the last pushax. Note: This will also
+                         * happen if we encounter a call to pushax!
+                         */
+                        I = Data.PushIndex;
+                        State = Initialize;
+                        break;
+                    } else {
+                        /* Track register usage */
+                        Data.UsedRegs |= (E->Use | E->Chg);
+                        TrackLoads (&Data.Rhs, E, I);
+                    }
 
-       } else if (CE_IsCallTo (E, "pushax")) {
+                } else if (E->Info & OF_STORE && (E->Chg & REG_ZP) == 0) {
+
+                    /* Too dangerous - there may be a change of a variable
+                     * within the sequence.
+                     */
+                    I = Data.PushIndex;
+                    State = Initialize;
+                    break;
+
+                } else if ((E->Use & REG_SP) != 0                       &&
+                           (E->AM != AM65_ZP_INDY               ||
+                            RegValIsUnknown (E->RI->In.RegY)    ||
+                            E->RI->In.RegY < 2)) {
+
+                    /* If we are using the stack, and we don't have "indirect Y"
+                     * addressing mode, or the value of Y is unknown, or less
+                     * than two, we cannot cope with this piece of code. Having
+                     * an unknown value of Y means that we cannot correct the
+                     * stack offset, while having an offset less than two means
+                     * that the code works with the value on stack which is to
+                     * be removed.
+                     */
+                    I = Data.PushIndex;
+                    State = Initialize;
+                    break;
 
-           /* This starts a sequence */
-           Push     = I;
-           UsedRegs = REG_NONE;
-           InSeq    = 1;
+                } else {
+                    /* Other stuff: Track register usage */
+                    Data.UsedRegs |= (E->Use | E->Chg);
+                    TrackLoads (&Data.Rhs, E, I);
+                }
+                break;
+
+            case FoundOp:
+                /* Track zero page location usage beyond this point */
+                Data.UsedRegs |= GetRegInfo (S, I, REG_SREG | REG_PTR1 | REG_PTR2);
+
+                /* Finalize the load info */
+                FinalizeLoadInfo (&Data.Lhs, S);
+                FinalizeLoadInfo (&Data.Rhs, S);
+
+                /* Set flags for direct operations */
+                CheckDirectOp (&Data);
+
+                /* If the Lhs loads do load from zeropage, we have to include
+                 * them into UsedRegs registers used. The Rhs loads have already
+                 * been tracked.
+                 */
+                if (Data.Lhs.A.LoadEntry && Data.Lhs.A.LoadEntry->AM == AM65_ZP) {
+                    Data.UsedRegs |= Data.Lhs.A.LoadEntry->Use;
+                }
+                if (Data.Lhs.X.LoadEntry && Data.Lhs.X.LoadEntry->AM == AM65_ZP) {
+                    Data.UsedRegs |= Data.Lhs.X.LoadEntry->Use;
+                }
+
+                /* Check the preconditions. If they aren't ok, reset the insn
+                 * pointer to the pushax and start over. We will loose part of
+                 * load tracking but at least a/x has probably lost between
+                 * pushax and here and will be tracked again when restarting.
+                 */
+                if (!PreCondOk (&Data)) {
+                    I = Data.PushIndex;
+                    State = Initialize;
+                    break;
+                }
+
+                /* Adjust stack offsets to account for the upcoming removal */
+                AdjustStackOffset (&Data, 2);
+
+                /* Regenerate register info, since AdjustStackOffset changed
+                 * the code
+                 */
+                CS_GenRegInfo (S);
+
+                /* Prepare the remainder of the data structure. */
+                Data.PrevEntry = CS_GetPrevEntry (S, Data.PushIndex);
+                Data.PushEntry = CS_GetEntry (S, Data.PushIndex);
+                Data.OpEntry   = CS_GetEntry (S, Data.OpIndex);
+                Data.NextEntry = CS_GetNextEntry (S, Data.OpIndex);
+
+                /* Call the optimizer function */
+                Changes += Data.OptFunc->Func (&Data);
+
+                /* Regenerate register info */
+                CS_GenRegInfo (S);
+
+                /* Done */
+                State = Initialize;
+                break;
 
        }