]> git.sur5r.net Git - cc65/blobdiff - src/cc65/coptstop.c
Adjusted to the current multiline-comment style.
[cc65] / src / cc65 / coptstop.c
index f00410fa5e251a40d4d3fcd32ff903f95f6021b2..53582d5659661abec300f46eeac45123735d35f1 100644 (file)
@@ -1,15 +1,15 @@
 /*****************************************************************************/
 /*                                                                           */
-/*                                coptstop.c                                */
+/*                                 coptstop.c                                */
 /*                                                                           */
-/*          Optimize operations that take operands via the stack            */
+/*           Optimize operations that take operands via the stack            */
 /*                                                                           */
 /*                                                                           */
 /*                                                                           */
-/* (C) 2001-2009 Ullrich von Bassewitz                                       */
-/*               Roemerstrasse 52                                            */
-/*               D-70794 Filderstadt                                         */
-/* EMail:        uz@cc65.org                                                 */
+/* (C) 2001-2019, Ullrich von Bassewitz                                      */
+/*                Roemerstrasse 52                                           */
+/*                D-70794 Filderstadt                                        */
+/* EMail:         uz@cc65.org                                                */
 /*                                                                           */
 /*                                                                           */
 /* This software is provided 'as-is', without any expressed or implied       */
@@ -58,7 +58,8 @@ typedef enum {
   LI_DIRECT             = 0x01,         /* Direct op may be used */
   LI_RELOAD_Y           = 0x02,         /* Reload index register Y */
   LI_REMOVE             = 0x04,         /* Load may be removed */
-  LI_DUP_LOAD           = 0x08,         /* Duplicate load */
+  LI_DONT_REMOVE        = 0x08,         /* Load may not be removed */
+  LI_DUP_LOAD           = 0x10,         /* Duplicate load */
 } LI_FLAGS;
 
 /* Structure that tells us how to load the lhs values */
@@ -121,7 +122,7 @@ struct StackOpData {
     const OptFuncDesc*  OptFunc;
 
     /* ZP register usage inside the sequence */
-    unsigned            UsedRegs;
+    unsigned            ZPUsage;
 
     /* Register load information for lhs and rhs */
     LoadInfo            Lhs;
@@ -191,8 +192,8 @@ static void ClearLoadInfo (LoadInfo* LI)
 
 static void AdjustLoadRegInfo (LoadRegInfo* RI, int Index, int Change)
 /* Adjust a load register info struct after deleting or inserting an entry
- * with a given index
- */
+** with a given index
+*/
 {
     CHECK (abs (Change) == 1);
     if (Change < 0) {
@@ -245,6 +246,18 @@ static void AdjustLoadInfo (LoadInfo* LI, int Index, int Change)
 
 
 
+static void HonourUseAndChg (LoadRegInfo* RI, unsigned Reg, const CodeEntry* E)
+/* Honour use and change flags for an instruction */
+{
+    if (E->Chg & Reg) {
+        ClearLoadRegInfo (RI);
+    } else if ((E->Use & Reg) && RI->LoadIndex >= 0) {
+        RI->Flags |= LI_DONT_REMOVE;
+    }
+}
+
+
+
 static void TrackLoads (LoadInfo* LI, CodeEntry* E, int I)
 /* Track loads for a code entry */
 {
@@ -263,9 +276,9 @@ static void TrackLoads (LoadInfo* LI, CodeEntry* E, int I)
         CHECK (RI != 0);
 
         /* If we had a load or xfer op before, this is a duplicate load which
-         * can cause problems if it encountered between the pushax and the op,
-         * so remember it.
-         */
+        ** can cause problems if it encountered between the pushax and the op,
+        ** so remember it.
+        */
         if (RI->LoadIndex >= 0 || RI->XferIndex >= 0) {
             RI->Flags |= LI_DUP_LOAD;
         }
@@ -283,11 +296,11 @@ static void TrackLoads (LoadInfo* LI, CodeEntry* E, int I)
                    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
-             * a load indirect via other zero page locations is not ok, since
-             * these locations may change between the push and the actual
-             * operation.
-             */
+            ** case we must reload the index register later. Please note that
+            ** a load indirect via other zero page locations is not ok, since
+            ** these locations may change between the push and the actual
+            ** operation.
+            */
             RI->Offs  = (unsigned char) E->RI->In.RegY;
             RI->Flags |= (LI_DIRECT | LI_RELOAD_Y);
         }
@@ -309,9 +322,9 @@ static void TrackLoads (LoadInfo* LI, CodeEntry* E, int I)
         }
 
         /* If we had a load or xfer op before, this is a duplicate load which
-         * can cause problems if it encountered between the pushax and the op,
-         * so remember it.
-         */
+        ** can cause problems if it encountered between the pushax and the op,
+        ** so remember it.
+        */
         if (Tgt->LoadIndex >= 0 || Tgt->XferIndex >= 0) {
             Tgt->Flags |= LI_DUP_LOAD;
         }
@@ -326,9 +339,9 @@ static void TrackLoads (LoadInfo* LI, CodeEntry* E, int I)
     } else if (CE_IsCallTo (E, "ldaxysp") && RegValIsKnown (E->RI->In.RegY)) {
 
         /* If we had a load or xfer op before, this is a duplicate load which
-         * can cause problems if it encountered between the pushax and the op,
-         * so remember it for both registers involved.
-         */
+        ** can cause problems if it encountered between the pushax and the op,
+        ** so remember it for both registers involved.
+        */
         if (LI->A.LoadIndex >= 0 || LI->A.XferIndex >= 0) {
             LI->A.Flags |= LI_DUP_LOAD;
         }
@@ -349,30 +362,24 @@ static void TrackLoads (LoadInfo* LI, CodeEntry* E, int I)
 
         ClearLoadRegInfo (&LI->Y);
     } else {
-        if (E->Chg & REG_A) {
-            ClearLoadRegInfo (&LI->A);
-        }
-        if (E->Chg & REG_X) {
-            ClearLoadRegInfo (&LI->X);
-        }
-        if (E->Chg & REG_Y) {
-            ClearLoadRegInfo (&LI->Y);
-        }
+        HonourUseAndChg (&LI->A, REG_A, E);
+        HonourUseAndChg (&LI->X, REG_X, E);
+        HonourUseAndChg (&LI->Y, REG_Y, E);
     }
 }
 
 
 
 /*****************************************************************************/
-/*                                         Helpers                                  */
+/*                                  Helpers                                  */
 /*****************************************************************************/
 
 
 
 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.
- */
+** be adjusted by this function.
+*/
 {
     /* Insert the entry into the code segment */
     CS_InsertEntry (D->Code, E, Index);
@@ -394,8 +401,8 @@ static void InsertEntry (StackOpData* D, CodeEntry* E, int 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.
- */
+** adjusted by this function, and PushEntry/OpEntry may get invalidated.
+*/
 {
     /* Delete the entry from the code segment */
     CS_DelEntry (D->Code, Index);
@@ -421,21 +428,21 @@ static void DelEntry (StackOpData* D, int Index)
 
 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.
- */
+** OpIndex is adjusted according to the insertions.
+*/
 {
     /* Walk over all entries */
     int I = D->PushIndex + 1;
     while (I < D->OpIndex) {
 
-       CodeEntry* E = CS_GetEntry (D->Code, I);
+        CodeEntry* E = CS_GetEntry (D->Code, I);
 
         int NeedCorrection = 0;
-       if ((E->Use & REG_SP) != 0) {
+        if ((E->Use & REG_SP) != 0) {
 
-           /* Check for some things that should not happen */
-           CHECK (E->AM == AM65_ZP_INDY || E->RI->In.RegY >= (short) Offs);
-           CHECK (strcmp (E->Arg, "sp") == 0);
+            /* Check for some things that should not happen */
+            CHECK (E->AM == AM65_ZP_INDY || E->RI->In.RegY >= (short) Offs);
+            CHECK (strcmp (E->Arg, "sp") == 0);
 
             /* We need to correct this one */
             NeedCorrection = 1;
@@ -449,42 +456,42 @@ static void AdjustStackOffset (StackOpData* D, unsigned Offs)
 
         if (NeedCorrection) {
 
-           /* Get the code entry before this one. If it's a LDY, adjust the
-            * value.
-            */
-           CodeEntry* P = CS_GetPrevEntry (D->Code, I);
-           if (P && P->OPC == OP65_LDY && CE_IsConstImm (P)) {
+            /* Get the code entry before this one. If it's a LDY, adjust the
+            ** value.
+            */
+            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 {
+            } else {
 
-               /* 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);
-               InsertEntry (D, 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);
+                InsertEntry (D, X, I++);
 
-           }
+            }
 
             /* If we need the value of Y later, be sure to reload it */
             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);
-               InsertEntry (D, X, I+1);
+                const char* Arg = MakeHexArg (E->RI->In.RegY);
+                CodeEntry* X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
+                InsertEntry (D, X, I+1);
 
-               /* Skip this instruction in the next round */
-               ++I;
+                /* Skip this instruction in the next round */
+                ++I;
             }
-       }
+        }
 
-       /* Next entry */
-       ++I;
+        /* Next entry */
+        ++I;
     }
 
     /* If we have rhs load insns that load from stack, we'll have to adjust
-     * the offsets for these also.
-     */
+    ** the offsets for these also.
+    */
     if (D->Rhs.A.Flags & LI_RELOAD_Y) {
         D->Rhs.A.Offs -= Offs;
     }
@@ -515,14 +522,14 @@ static void AddStoreX (StackOpData* D)
 
 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
- * later, but the name is still ok since the push will get removed at the
- * end of each routine).
- */
+** location (actually, the push is not replaced, because we need it for
+** later, but the name is still ok since the push will get removed at the
+** end of each routine).
+*/
 {
     /* Store the value into the zeropage instead of pushing it. Check high
-     * byte first so that the store is later in A/X order.
-     */
+    ** byte first so that the store is later in A/X order.
+    */
     if ((D->Lhs.X.Flags & LI_DIRECT) == 0) {
         AddStoreX (D);
     }
@@ -535,16 +542,16 @@ static void ReplacePushByStore (StackOpData* D)
 
 static void AddOpLow (StackOpData* D, opc_t OPC, LoadInfo* LI)
 /* Add an op for the low byte of an operator. This function honours the
- * OP_DIRECT and OP_RELOAD_Y flags and generates the necessary instructions.
- * All code is inserted at the current insertion point.
- */
+** OP_DIRECT and OP_RELOAD_Y flags and generates the necessary instructions.
+** All code is inserted at the current insertion point.
+*/
 {
     CodeEntry* X;
 
     if ((LI->A.Flags & LI_DIRECT) != 0) {
-               /* Op with a variable location. If the location is on the stack, we
-         * need to reload the Y register.
-         */
+        /* Op with a variable location. If the location is on the stack, we
+        ** need to reload the Y register.
+        */
         if ((LI->A.Flags & LI_RELOAD_Y) == 0) {
 
             /* opc ... */
@@ -570,8 +577,8 @@ static void AddOpLow (StackOpData* D, opc_t OPC, LoadInfo* LI)
 
     } 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++);
 
     }
@@ -581,16 +588,16 @@ static void AddOpLow (StackOpData* D, opc_t OPC, LoadInfo* LI)
 
 static void AddOpHigh (StackOpData* D, opc_t OPC, LoadInfo* LI, int KeepResult)
 /* Add an op for the high byte of an operator. Special cases (constant values
- * or similar) have to be checked separately, the function covers only the
- * generic case. Code is inserted at the insertion point.
- */
+** or similar) have to be checked separately, the function covers only the
+** generic case. Code is inserted at the insertion point.
+*/
 {
     CodeEntry* X;
 
     if (KeepResult) {
-       /* pha */
-       X = NewCodeEntry (OP65_PHA, AM65_IMP, 0, 0, D->OpEntry->LI);
-       InsertEntry (D, X, D->IP++);
+        /* pha */
+        X = NewCodeEntry (OP65_PHA, AM65_IMP, 0, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
     }
 
     /* txa */
@@ -603,7 +610,7 @@ static void AddOpHigh (StackOpData* D, opc_t OPC, LoadInfo* LI, int KeepResult)
 
             /* opc xxx */
             CodeEntry* LoadX = LI->X.LoadEntry;
-           X = NewCodeEntry (OPC, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
+            X = NewCodeEntry (OPC, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->IP++);
 
         } else {
@@ -628,13 +635,13 @@ static void AddOpHigh (StackOpData* D, opc_t OPC, LoadInfo* LI, int KeepResult)
     }
 
     if (KeepResult) {
-       /* tax */
-       X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 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++);
 
-       /* pla */
-       X = NewCodeEntry (OP65_PLA, 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++);
     }
 }
 
@@ -644,9 +651,9 @@ 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.Flags & LI_REMOVE) {
+    ** case clear the other one.
+    */
+    if ((LI->A.Flags & (LI_REMOVE | LI_DONT_REMOVE)) == LI_REMOVE) {
         if (LI->A.LoadIndex >= 0) {
             DelEntry (D, LI->A.LoadIndex);
         }
@@ -654,7 +661,7 @@ static void RemoveRegLoads (StackOpData* D, LoadInfo* LI)
             DelEntry (D, LI->A.XferIndex);
         }
     }
-    if (LI->X.Flags & LI_REMOVE) {
+    if ((LI->X.Flags & (LI_REMOVE | LI_DONT_REMOVE)) == LI_REMOVE) {
         if (LI->X.LoadIndex >= 0) {
             DelEntry (D, LI->X.LoadIndex);
         }
@@ -682,9 +689,9 @@ static void RemoveRemainders (StackOpData* D)
 
 static int IsRegVar (StackOpData* D)
 /* 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.
- */
+** in the given StackOpData struct by the variable and return true. Otherwise
+** leave D untouched and return false.
+*/
 {
     CodeEntry*  LoadA = D->Lhs.A.LoadEntry;
     CodeEntry*  LoadX = D->Lhs.X.LoadEntry;
@@ -716,7 +723,7 @@ static int IsRegVar (StackOpData* D)
 
 
 /*****************************************************************************/
-/*                      Actual optimization functions                       */
+/*                       Actual optimization functions                       */
 /*****************************************************************************/
 
 
@@ -728,16 +735,16 @@ static unsigned Opt_toseqax_tosneax (StackOpData* D, const char* BoolTransformer
     CodeLabel* L;
 
     /* Create a call to the boolean transformer function and a label for this
-     * insn. This is needed for all variants. Other insns are inserted *before*
-     * the call.
-     */
+    ** insn. This is needed for all variants. Other insns are inserted *before*
+    ** the call.
+    */
     X = NewCodeEntry (OP65_JSR, AM65_ABS, BoolTransformer, 0, D->OpEntry->LI);
     InsertEntry (D, X, D->OpIndex + 1);
     L = CS_GenLabel (D->Code, X);
 
     /* If the lhs is direct (but not stack relative), encode compares with lhs
-     * effectively reverting the order (which doesn't matter for ==).
-     */
+    ** effectively reverting the order (which doesn't matter for ==).
+    */
     if ((D->Lhs.A.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT &&
         (D->Lhs.X.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT) {
 
@@ -791,15 +798,15 @@ static unsigned Opt_toseqax_tosneax (StackOpData* D, const char* BoolTransformer
 
         D->IP = D->OpIndex+1;
 
-       /* Add operand for low byte */
-       AddOpLow (D, OP65_CMP, &D->Rhs);
+        /* Add operand for low byte */
+        AddOpLow (D, OP65_CMP, &D->Rhs);
 
         /* bne L */
         X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, D->OpEntry->LI);
         InsertEntry (D, X, D->IP++);
 
-       /* Add operand for high byte */
-       AddOpHigh (D, OP65_CMP, &D->Rhs, 0);
+        /* Add operand for high byte */
+        AddOpHigh (D, OP65_CMP, &D->Rhs, 0);
 
     } else {
 
@@ -832,6 +839,80 @@ static unsigned Opt_toseqax_tosneax (StackOpData* D, const char* BoolTransformer
 
 
 
+static unsigned Opt_tosshift (StackOpData* D, const char* Name)
+/* Optimize shift sequences. */
+{
+    CodeEntry*  X;
+
+    /* Store the value into the zeropage instead of pushing it */
+    ReplacePushByStore (D);
+
+    /* If the lhs is direct (but not stack relative), we can just reload the
+    ** data later.
+    */
+    if ((D->Lhs.A.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT &&
+        (D->Lhs.X.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT) {
+
+        CodeEntry* LoadX = D->Lhs.X.LoadEntry;
+        CodeEntry* LoadA = D->Lhs.A.LoadEntry;
+
+        /* Inline the shift */
+        D->IP = D->OpIndex+1;
+
+        /* tay */
+        X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* lda */
+        X = NewCodeEntry (OP65_LDA, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* ldx */
+        X = NewCodeEntry (OP65_LDX, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* Lhs load entries can be removed */
+        D->Lhs.X.Flags |= LI_REMOVE;
+        D->Lhs.A.Flags |= LI_REMOVE;
+
+    } else {
+
+        /* Save lhs into zeropage and reload later */
+        AddStoreX (D);
+        AddStoreA (D);
+
+        /* Be sure to setup IP after adding the stores, otherwise it will get
+        ** messed up.
+        */
+        D->IP = D->OpIndex+1;
+
+        /* tay */
+        X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* lda zp */
+        X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+        /* ldx zp+1 */
+        X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
+        InsertEntry (D, X, D->IP++);
+
+    }
+
+    /* jsr shlaxy/aslaxy/whatever */
+    X = NewCodeEntry (OP65_JSR, AM65_ABS, Name, 0, D->OpEntry->LI);
+    InsertEntry (D, X, D->IP++);
+
+    /* Remove the push and the call to the shift function */
+    RemoveRemainders (D);
+
+    /* We changed the sequence */
+    return 1;
+}
+
+
+
 static unsigned Opt___bzero (StackOpData* D)
 /* Optimize the __bzero sequence */
 {
@@ -847,8 +928,8 @@ static unsigned Opt___bzero (StackOpData* D)
     }
 
     /* If the return value of __bzero is used, we have to add code to reload
-     * a/x from the pointer variable.
-     */
+    ** a/x from the pointer variable.
+    */
     if (RegAXUsed (D->Code, D->OpIndex+1)) {
         X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
         InsertEntry (D, X, D->OpIndex+1);
@@ -857,8 +938,8 @@ static unsigned Opt___bzero (StackOpData* D)
     }
 
     /* X is always zero, A contains the size of the data area to zero.
-     * Note: A may be zero, in which case the operation is null op.
-     */
+    ** Note: A may be zero, in which case the operation is null op.
+    */
     if (D->OpEntry->RI->In.RegA != 0) {
 
         /* lda #$00 */
@@ -871,7 +952,7 @@ static unsigned Opt___bzero (StackOpData* D)
             /* Loop using the sign bit */
 
             /* ldy #count-1 */
-           Arg = MakeHexArg (D->OpEntry->RI->In.RegA - 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);
 
@@ -906,7 +987,7 @@ static unsigned Opt___bzero (StackOpData* D)
             InsertEntry (D, X, D->OpIndex+4);
 
             /* cpy #count */
-           Arg = MakeHexArg (D->OpEntry->RI->In.RegA);
+            Arg = MakeHexArg (D->OpEntry->RI->In.RegA);
             X = NewCodeEntry (OP65_CPY, AM65_IMM, Arg, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->OpIndex+5);
 
@@ -971,20 +1052,20 @@ static unsigned Opt_staxspidx (StackOpData* D)
 
     if (RegValIsKnown (D->OpEntry->RI->In.RegY)) {
         /* Value of Y is known */
-               const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegY + 1);
-               X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        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);
-               X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, D->OpEntry->LI);
+        /* 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);
 
@@ -993,8 +1074,8 @@ static unsigned Opt_staxspidx (StackOpData* D)
     InsertEntry (D, X, D->OpIndex+4);
 
     /* If we remove staxspidx, we must restore the Y register to what the
-     * function would return.
-     */
+    ** function would return.
+    */
     X = NewCodeEntry (OP65_LDY, AM65_IMM, "$00", 0, D->OpEntry->LI);
     InsertEntry (D, X, D->OpIndex+5);
 
@@ -1017,16 +1098,16 @@ static unsigned Opt_tosaddax (StackOpData* D)
     CHECK (D->NextEntry != 0);
 
     /* 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.
-     */
+    ** 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.
+    */
     if (D->OpEntry->RI->In.RegX == 0                            &&
         D->NextEntry->OPC == OP65_LDY                           &&
         CE_IsKnownImm (D->NextEntry, 0)                         &&
@@ -1042,17 +1123,17 @@ static unsigned Opt_tosaddax (StackOpData* D)
         AddStoreA (D);
 
         /* 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.
-         */
+        ** 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.
-         */
+        ** 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);
@@ -1101,9 +1182,9 @@ static unsigned Opt_tosaddax (StackOpData* D)
             X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
             InsertEntry (D, X, D->IP++);
 
-        } else if (D->OpEntry->RI->In.RegX == 0                        &&
-                  (RegValIsKnown (D->PushEntry->RI->In.RegX)   ||
-                   (D->Lhs.X.Flags & LI_RELOAD_Y) == 0)) {
+        } else if (D->OpEntry->RI->In.RegX == 0                         &&
+                   (RegValIsKnown (D->PushEntry->RI->In.RegX)   ||
+                    (D->Lhs.X.Flags & LI_RELOAD_Y) == 0)) {
 
             /* The high byte is that of the first operand plus carry */
             CodeLabel* L;
@@ -1113,14 +1194,14 @@ static unsigned Opt_tosaddax (StackOpData* D)
                 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
             } else {
                 /* Value of first op high byte is unknown. Load from ZP or
-                * original storage.
-                */
-               if (D->Lhs.X.Flags & LI_DIRECT) {
-                   CodeEntry* LoadX = D->Lhs.X.LoadEntry;
-                   X = NewCodeEntry (OP65_LDX, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
-               } else {
+                ** original storage.
+                */
+                if (D->Lhs.X.Flags & LI_DIRECT) {
+                    CodeEntry* LoadX = D->Lhs.X.LoadEntry;
+                    X = NewCodeEntry (OP65_LDX, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI);
+                } else {
                     X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
-               }
+                }
             }
             InsertEntry (D, X, D->IP++);
 
@@ -1169,6 +1250,22 @@ static unsigned Opt_tosandax (StackOpData* D)
 
 
 
+static unsigned Opt_tosaslax (StackOpData* D)
+/* Optimize the tosaslax sequence */
+{
+    return Opt_tosshift (D, "aslaxy");
+}
+
+
+
+static unsigned Opt_tosasrax (StackOpData* D)
+/* Optimize the tosasrax sequence */
+{
+    return Opt_tosshift (D, "asraxy");
+}
+
+
+
 static unsigned Opt_toseqax (StackOpData* D)
 /* Optimize the toseqax sequence */
 {
@@ -1237,7 +1334,7 @@ static unsigned Opt_tosltax (StackOpData* D)
     CodeLabel* L;
 
 
-    /* Inline the sbc */
+    /* Inline the compare */
     D->IP = D->OpIndex+1;
 
     /* Must be true because of OP_RHS_LOAD */
@@ -1314,6 +1411,22 @@ static unsigned Opt_tosorax (StackOpData* D)
 
 
 
+static unsigned Opt_tosshlax (StackOpData* D)
+/* Optimize the tosshlax sequence */
+{
+    return Opt_tosshift (D, "shlaxy");
+}
+
+
+
+static unsigned Opt_tosshrax (StackOpData* D)
+/* Optimize the tosshrax sequence */
+{
+    return Opt_tosshift (D, "shraxy");
+}
+
+
+
 static unsigned Opt_tossubax (StackOpData* D)
 /* Optimize the tossubax sequence. Note: subtraction is not commutative! */
 {
@@ -1517,12 +1630,12 @@ static unsigned Opt_tosxorax (StackOpData* D)
     /* High byte */
     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
-       /* Both values known, precalculate the result */
-       const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX ^ D->OpEntry->RI->In.RegX);
-               X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
-       InsertEntry (D, X, D->IP++);
+        /* Both values known, precalculate the result */
+        const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX ^ D->OpEntry->RI->In.RegX);
+        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_EOR, &D->Lhs, 1);
     }
 
@@ -1536,7 +1649,7 @@ static unsigned Opt_tosxorax (StackOpData* D)
 
 
 /*****************************************************************************/
-/*                                  Code                                    */
+/*                                   Code                                    */
 /*****************************************************************************/
 
 
@@ -1547,11 +1660,15 @@ static const OptFuncDesc FuncTable[] = {
     { "staxspidx",  Opt_staxspidx, REG_AX,   OP_NONE                    },
     { "tosaddax",   Opt_tosaddax,  REG_NONE, OP_NONE                    },
     { "tosandax",   Opt_tosandax,  REG_NONE, OP_NONE                    },
+    { "tosaslax",   Opt_tosaslax,  REG_NONE, OP_NONE                    },
+    { "tosasrax",   Opt_tosasrax,  REG_NONE, OP_NONE                    },
     { "toseqax",    Opt_toseqax,   REG_NONE, OP_NONE                    },
     { "tosgeax",    Opt_tosgeax,   REG_NONE, OP_RHS_LOAD_DIRECT         },
     { "tosltax",    Opt_tosltax,   REG_NONE, OP_RHS_LOAD_DIRECT         },
     { "tosneax",    Opt_tosneax,   REG_NONE, OP_NONE                    },
     { "tosorax",    Opt_tosorax,   REG_NONE, OP_NONE                    },
+    { "tosshlax",   Opt_tosshlax,  REG_NONE, OP_NONE                    },
+    { "tosshrax",   Opt_tosshrax,  REG_NONE, OP_NONE                    },
     { "tossubax",   Opt_tossubax,  REG_NONE, OP_RHS_LOAD_DIRECT         },
     { "tosugeax",   Opt_tosugeax,  REG_NONE, OP_RHS_LOAD_DIRECT         },
     { "tosugtax",   Opt_tosugtax,  REG_NONE, OP_RHS_LOAD_DIRECT         },
@@ -1566,15 +1683,15 @@ static const OptFuncDesc FuncTable[] = {
 static int CmpFunc (const void* Key, const void* Func)
 /* Compare function for bsearch */
 {
-    return strcmp (Key, ((const        OptFuncDesc*) Func)->Name);
+    return strcmp (Key, ((const OptFuncDesc*) Func)->Name);
 }
 
 
 
 static const OptFuncDesc* FindFunc (const char* Name)
 /* Find the function with the given name. Return a pointer to the table entry
- * or NULL if the function was not found.
- */
+** or NULL if the function was not found.
+*/
 {
     return bsearch (Name, FuncTable, FUNC_COUNT, sizeof(OptFuncDesc), CmpFunc);
 }
@@ -1591,19 +1708,40 @@ static int CmpHarmless (const void* Key, const void* Entry)
 
 static int HarmlessCall (const char* Name)
 /* Check if this is a call to a harmless subroutine that will not interrupt
- * the pushax/op sequence when encountered.
- */
+** the pushax/op sequence when encountered.
+*/
 {
-    static const char* Tab[] = {
+    static const char* const Tab[] = {
         "aslax1",
         "aslax2",
         "aslax3",
         "aslax4",
+        "aslaxy",
         "asrax1",
         "asrax2",
         "asrax3",
         "asrax4",
+        "asraxy",
         "bnegax",
+        "complax",
+        "decax1",
+        "decax2",
+        "decax3",
+        "decax4",
+        "decax5",
+        "decax6",
+        "decax7",
+        "decax8",
+        "decaxy",
+        "incax1",
+        "incax2",
+        "incax3",
+        "incax4",
+        "incax5",
+        "incax6",
+        "incax7",
+        "incax8",
+        "incaxy",
         "ldaxidx",
         "ldaxysp",
         "negax",
@@ -1611,10 +1749,12 @@ static int HarmlessCall (const char* Name)
         "shlax2",
         "shlax3",
         "shlax4",
+        "shlaxy",
         "shrax1",
         "shrax2",
         "shrax3",
         "shrax4",
+        "shraxy",
     };
 
     void* R = bsearch (Name,
@@ -1631,7 +1771,7 @@ static void ResetStackOpData (StackOpData* Data)
 /* Reset the given data structure */
 {
     Data->OptFunc       = 0;
-    Data->UsedRegs      = REG_NONE;
+    Data->ZPUsage       = REG_NONE;
 
     ClearLoadInfo (&Data->Lhs);
     ClearLoadInfo (&Data->Rhs);
@@ -1644,9 +1784,9 @@ static void ResetStackOpData (StackOpData* Data)
 
 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.
- */
+** satisfied. As a side effect, this function will also choose the zero page
+** register to use.
+*/
 {
     /* Check the flags */
     unsigned UnusedRegs = D->OptFunc->UnusedRegs;
@@ -1692,14 +1832,16 @@ static int PreCondOk (StackOpData* D)
         return 0;
     }
 
-    /* Determine the zero page locations to use */
-    if ((D->UsedRegs & REG_PTR1) == REG_NONE) {
+    /* Determine the zero page locations to use. We've tracked the used
+    ** ZP locations, so try to find some for us that are unused.
+    */
+    if ((D->ZPUsage & REG_PTR1) == REG_NONE) {
         D->ZPLo = "ptr1";
         D->ZPHi = "ptr1+1";
-    } else if ((D->UsedRegs & REG_SREG) == REG_NONE) {
+    } else if ((D->ZPUsage & REG_SREG) == REG_NONE) {
         D->ZPLo = "sreg";
         D->ZPHi = "sreg+1";
-    } else if ((D->UsedRegs & REG_PTR2) == REG_NONE) {
+    } else if ((D->ZPUsage & REG_PTR2) == REG_NONE) {
         D->ZPLo = "ptr2";
         D->ZPHi = "ptr2+1";
     } else {
@@ -1714,7 +1856,7 @@ static int PreCondOk (StackOpData* D)
 
 
 /*****************************************************************************/
-/*                                  Code                                    */
+/*                                   Code                                    */
 /*****************************************************************************/
 
 
@@ -1726,6 +1868,9 @@ unsigned OptStackOps (CodeSeg* S)
     StackOpData         Data;
     int                 I;
     int                 OldEntryCount;  /* Old number of entries */
+    unsigned            UsedRegs = 0;   /* Registers used */
+    unsigned            ChangedRegs = 0;/* Registers changed */
+
 
     enum {
         Initialize,
@@ -1735,45 +1880,43 @@ unsigned OptStackOps (CodeSeg* S)
     } 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.
-     * It depends on the code between the two if we can handle/transform the
-     * sequence, so check this code for the following list of things:
-     *
-     *  - the range must be a basic block (one entry, one exit)
-     *  - there may not be accesses to local variables with unknown
-     *    offsets (because we have to adjust these offsets).
-     *  - no subroutine calls
-     *  - no jump labels
-     *
-     * Since we need a zero page register later, do also check the
-     * intermediate code for zero page use.
-     */
+    ** that takes it's first argument on the stack, and the second argument
+    ** in the primary register.
+    ** It depends on the code between the two if we can handle/transform the
+    ** sequence, so check this code for the following list of things:
+    **
+    **  - the range must be a basic block (one entry, one exit)
+    **  - there may not be accesses to local variables with unknown
+    **    offsets (because we have to adjust these offsets).
+    **  - no subroutine calls
+    **  - no jump labels
+    **
+    ** Since we need a zero page register later, do also check the
+    ** intermediate code for zero page use.
+    */
     I = 0;
     while (I < (int)CS_GetEntryCount (S)) {
 
-       /* Get the next entry */
-       CodeEntry* E = CS_GetEntry (S, I);
+        /* Get the next entry */
+        CodeEntry* E = CS_GetEntry (S, I);
 
         /* Actions depend on state */
         switch (State) {
 
             case Initialize:
                 ResetStackOpData (&Data);
+                UsedRegs = ChangedRegs = REG_NONE;
                 State = Search;
                 /* FALLTHROUGH */
 
             case Search:
                 /* While searching, track register load insns, so we can tell
-                 * what is in a register once pushax is encountered.
-                 */
+                ** what is in a register once pushax is encountered.
+                */
                 if (CE_HasLabel (E)) {
                     /* Currently we don't track across branches */
                     ClearLoadInfo (&Data.Lhs);
@@ -1789,9 +1932,9 @@ unsigned OptStackOps (CodeSeg* S)
 
             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.
-                 */
+                ** follow and in the meantime, track zeropage usage and check
+                ** for code that will disable us from translating the sequence.
+                */
                 if (CE_HasLabel (E)) {
                     /* Currently we don't track across branches */
                     ClearLoadInfo (&Data.Rhs);
@@ -1799,8 +1942,8 @@ unsigned OptStackOps (CodeSeg* S)
                 if (E->OPC == OP65_JSR) {
 
                     /* Subroutine call: Check if this is one of the functions,
-                     * we're going to replace.
-                     */
+                    ** we're going to replace.
+                    */
                     Data.OptFunc = FindFunc (E->Arg);
                     if (Data.OptFunc) {
                         /* Remember the op index and go on */
@@ -1810,23 +1953,23 @@ unsigned OptStackOps (CodeSeg* S)
                         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!
-                         */
+                        ** 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);
+                        Data.ZPUsage |= (E->Use | E->Chg);
                         TrackLoads (&Data.Rhs, E, I);
                     }
 
                 } else if (E->Info & OF_STORE && (E->Chg & REG_ZP) == 0) {
 
                     /* Too dangerous - there may be a change of a variable
-                     * within the sequence.
-                     */
+                    ** within the sequence.
+                    */
                     I = Data.PushIndex;
                     State = Initialize;
                     break;
@@ -1837,48 +1980,70 @@ unsigned OptStackOps (CodeSeg* S)
                             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.
-                     */
+                    ** 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;
 
                 } else {
                     /* Other stuff: Track register usage */
-                    Data.UsedRegs |= (E->Use | E->Chg);
+                    Data.ZPUsage |= (E->Use | E->Chg);
                     TrackLoads (&Data.Rhs, E, I);
                 }
+                /* If the registers from the push (A/X) are used before they're
+                ** changed, we cannot change the sequence, because this would
+                ** with a high probability change the register contents.
+                */
+                UsedRegs |= E->Use;
+                if ((UsedRegs & ~ChangedRegs) & REG_AX) {
+                    I = Data.PushIndex;
+                    State = Initialize;
+                    break;
+                }
+                ChangedRegs |= E->Chg;
                 break;
 
             case FoundOp:
                 /* Track zero page location usage beyond this point */
-                Data.UsedRegs |= GetRegInfo (S, I, REG_SREG | REG_PTR1 | REG_PTR2);
+                Data.ZPUsage |= GetRegInfo (S, I, REG_SREG | REG_PTR1 | REG_PTR2);
 
                 /* Finalize the load info */
                 FinalizeLoadInfo (&Data.Lhs, S);
                 FinalizeLoadInfo (&Data.Rhs, S);
 
-                /* If the Lhs loads do load from zeropage, we have to include
-                 * them into UsedRegs registers used. The Rhs loads have already
-                 * been tracked.
-                 */
+                /* Check if the lhs loads from zeropage. If this is true, these
+                ** zero page locations have to be added to ZPUsage, because
+                ** they cannot be used for intermediate storage. In addition,
+                ** if one of these zero page locations is destroyed between
+                ** pushing the lhs and the actual operation, we cannot use the
+                ** original zero page locations for the final op, but must
+                ** use another ZP location to save them.
+                */
+                ChangedRegs &= REG_ZP;
                 if (Data.Lhs.A.LoadEntry && Data.Lhs.A.LoadEntry->AM == AM65_ZP) {
-                    Data.UsedRegs |= Data.Lhs.A.LoadEntry->Use;
+                    Data.ZPUsage |= Data.Lhs.A.LoadEntry->Use;
+                    if ((Data.Lhs.A.LoadEntry->Use & ChangedRegs) != 0) {
+                        Data.Lhs.A.Flags &= ~(LI_DIRECT | LI_RELOAD_Y);
+                    }
                 }
                 if (Data.Lhs.X.LoadEntry && Data.Lhs.X.LoadEntry->AM == AM65_ZP) {
-                    Data.UsedRegs |= Data.Lhs.X.LoadEntry->Use;
+                    Data.ZPUsage |= Data.Lhs.X.LoadEntry->Use;
+                    if ((Data.Lhs.X.LoadEntry->Use & ChangedRegs) != 0) {
+                        Data.Lhs.X.Flags &= ~(LI_DIRECT | LI_RELOAD_Y);
+                    }
                 }
 
                 /* 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.
-                 */
+                ** 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;
@@ -1898,16 +2063,16 @@ unsigned OptStackOps (CodeSeg* S)
                 AdjustStackOffset (&Data, 2);
 
                 /* Regenerate register info, since AdjustStackOffset changed
-                 * the code
-                 */
+                ** the code
+                */
                 CS_GenRegInfo (S);
 
                 /* Call the optimizer function */
                 Changes += Data.OptFunc->Func (&Data);
 
                 /* Since the function may have added or deleted entries,
-                 * correct the index.
-                 */
+                ** correct the index.
+                */
                 I += CS_GetEntryCount (S) - OldEntryCount;
 
                 /* Regenerate register info */
@@ -1917,19 +2082,13 @@ unsigned OptStackOps (CodeSeg* S)
                 State = Initialize;
                 continue;
 
-       }
+        }
 
-       /* Next entry */
-       ++I;
+        /* Next entry */
+        ++I;
 
     }
 
-    /* Free the register info */
-    CS_FreeRegInfo (S);
-
     /* Return the number of changes made */
     return Changes;
 }
-
-
-