]> git.sur5r.net Git - cc65/blob - src/cc65/coptstop.c
ValidSegName now defined in segnames.h
[cc65] / src / cc65 / coptstop.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 coptstop.c                                */
4 /*                                                                           */
5 /*           Optimize operations that take operands via the stack            */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001-2002 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdlib.h>
37 #include <ctype.h>
38
39 /* cc65 */
40 #include "codeent.h"
41 #include "codeinfo.h"
42 #include "coptstop.h"
43
44
45
46 /*****************************************************************************/
47 /*                                   Data                                    */
48 /*****************************************************************************/
49
50
51
52 /* Structure that holds the needed data */
53 typedef struct StackOpData StackOpData;
54 struct StackOpData {
55     CodeSeg*    Code;                   /* Pointer to code segment */
56     unsigned    Flags;                  /* Flags to remember things */
57     unsigned    PushIndex;              /* Index of call to pushax in codeseg */
58     unsigned    OpIndex;                /* Index of actual operation */
59     CodeEntry*  PrevEntry;              /* Entry before the call to pushax */
60     CodeEntry*  PushEntry;              /* Pointer to entry with call to pushax */
61     CodeEntry*  OpEntry;                /* Pointer to entry with op */
62     CodeEntry*  NextEntry;              /* Entry after the op */
63     const char* ZPLo;                   /* Lo byte of zero page loc to use */
64     const char* ZPHi;                   /* Hi byte of zero page loc to use */
65     unsigned    IP;                     /* Insertion point used by some routines */
66 };
67
68 /* Flags returned by DirectOp */
69 #define OP_DIRECT       0x01            /* Direct op may be used */
70 #define OP_RELOAD_Y     0x02            /* Must reload index register Y */
71
72
73
74 /*****************************************************************************/
75 /*                                  Helpers                                  */
76 /*****************************************************************************/
77
78
79
80 static unsigned AdjustStackOffset (CodeSeg* S, unsigned Start, unsigned Stop,
81                                    unsigned Offs)
82 /* Adjust the offset for all stack accesses in the range Start to Stop, both
83  * inclusive. The function returns the number of instructions that have been
84  * inserted.
85  */
86 {
87     /* Number of inserted instructions */
88     unsigned Inserted = 0;
89
90     /* Walk over all entries */
91     unsigned I = Start;
92     while (I <= Stop) {
93
94         CodeEntry* E = CS_GetEntry (S, I);
95
96         int NeedCorrection = 0;
97         if ((E->Use & REG_SP) != 0) {
98
99             /* Check for some things that should not happen */
100             CHECK (E->AM == AM65_ZP_INDY || E->RI->In.RegY >= (short) Offs);
101             CHECK (strcmp (E->Arg, "sp") == 0);
102
103             /* We need to correct this one */
104             NeedCorrection = 1;
105
106         } else if (CE_IsCallTo (E, "ldaxysp")) {
107
108             /* We need to correct this one */
109             NeedCorrection = 1;
110
111         }
112
113         if (NeedCorrection) {
114
115             CodeEntry* P;
116
117             /* Get the code entry before this one. If it's a LDY, adjust the
118              * value.
119              */
120             P = CS_GetPrevEntry (S, I);
121             if (P && P->OPC == OP65_LDY && CE_KnownImm (P)) {
122
123                 /* The Y load is just before the stack access, adjust it */
124                 CE_SetNumArg (P, P->Num - Offs);
125
126             } else {
127
128                 /* Insert a new load instruction before the stack access */
129                 const char* Arg = MakeHexArg (E->RI->In.RegY - Offs);
130                 CodeEntry* X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
131                 CS_InsertEntry (S, X, I);
132
133                 /* One more inserted entries */
134                 ++Inserted;
135                 ++Stop;
136
137                 /* Be sure to skip the stack access for the next round */
138                 ++I;
139
140             }
141
142         }
143
144         /* Next entry */
145         ++I;
146     }
147
148     /* Return the number of inserted entries */
149     return Inserted;
150 }
151
152
153
154 static void InsertEntry (StackOpData* D, CodeEntry* E, unsigned Index)
155 /* Insert a new entry. Depending on Index, D->PushIndex and D->OpIndex will
156  * be adjusted by this function.
157  */
158 {
159     /* Insert the entry into the code segment */
160     CS_InsertEntry (D->Code, E, Index);
161
162     /* Adjust the indices if necessary */
163     if (D->PushEntry && Index <= D->PushIndex) {
164         ++D->PushIndex;
165     }
166     if (D->OpEntry && Index <= D->OpIndex) {
167         ++D->OpIndex;
168     }
169 }
170
171
172
173 static void DelEntry (StackOpData* D, unsigned Index)
174 /* Delete an entry. Depending on Index, D->PushIndex and D->OpIndex will be
175  * adjusted by this function, and PushEntry/OpEntry may get invalidated.
176  */
177 {
178     /* Delete the entry from the code segment */
179     CS_DelEntry (D->Code, Index);
180
181     /* Adjust the indices if necessary */
182     if (Index < D->PushIndex) {
183         --D->PushIndex;
184     } else if (Index == D->PushIndex) {
185         D->PushEntry = 0;
186     }
187     if (Index < D->OpIndex) {
188         --D->OpIndex;
189     } else if (Index == D->OpIndex) {
190         D->OpEntry = 0;
191     }
192 }
193
194
195
196 static void CheckDirectOp (StackOpData* D)
197 /* Check if the given entry is a lda instruction with an addressing mode
198  * that allows us to replace it by another operation (like ora). If so, we may
199  * use this location for the or and must not save the value in the zero
200  * page location.
201  */
202 {
203     /* We need the entry before the push */
204     CodeEntry* E;
205     CHECK ((E = D->PrevEntry) != 0);
206
207     if (E->OPC == OP65_LDA) {
208         if (E->AM == AM65_IMM || E->AM == AM65_ZP || E->AM == AM65_ABS) {
209             /* These insns are all ok and replaceable */
210             D->Flags |= OP_DIRECT;
211         } else if (E->AM == AM65_ZP_INDY && RegValIsKnown (E->RI->In.RegY) &&
212                    strcmp (E->Arg, D->ZPLo) != 0 && strcmp (E->Arg, D->ZPHi) != 0) {
213             /* Load indirect with known offset is also ok, provided that
214              * the zeropage location used is not the same as the one we're
215              * using for the temp storage.
216              */
217             D->Flags |= (OP_DIRECT | OP_RELOAD_Y);
218         }
219     }
220 }
221
222
223
224 static void ReplacePushByStore (StackOpData* D)
225 /* Replace the call to the push subroutine by a store into the zero page
226  * location (actually, the push is not replaced, because we need it for
227  * later, but the name is still ok since the push will get removed at the
228  * end of each routine).
229  */
230 {
231     CodeEntry* X;
232
233     /* Store the value into the zeropage instead of pushing it */
234     X = NewCodeEntry (OP65_STX, AM65_ZP, D->ZPHi, 0, D->PushEntry->LI);
235     InsertEntry (D, X, D->PushIndex+1);
236     if ((D->Flags & OP_DIRECT) == 0) {
237         X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->PushEntry->LI);
238         InsertEntry (D, X, D->PushIndex+1);
239     }
240 }
241
242
243
244 static void AddOpLow (StackOpData* D, opc_t OPC)
245 /* Add an op for the low byte of an operator. This function honours the
246  * OP_DIRECT and OP_RELOAD_Y flags and generates the necessary instructions.
247  * All code is inserted at the current insertion point.
248  */
249 {
250     CodeEntry* X;
251
252     if ((D->Flags & OP_DIRECT) != 0) {
253         /* Op with a variable location. If the location is on the stack, we
254          * need to reload the Y register.
255          */
256         if ((D->Flags & OP_RELOAD_Y) != 0) {
257             const char* Arg = MakeHexArg (D->PrevEntry->RI->In.RegY);
258             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
259             InsertEntry (D, X, D->IP++);
260         }
261         X = NewCodeEntry (OPC, D->PrevEntry->AM, D->PrevEntry->Arg, 0, D->OpEntry->LI);
262     } else {
263         /* Op with temp storage */
264         X = NewCodeEntry (OPC, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
265     }
266     InsertEntry (D, X, D->IP++);
267 }
268
269
270
271 static void AddOpHigh (StackOpData* D, opc_t OPC)
272 /* Add an op for the high byte of an operator. Special cases (constant values
273  * or similar have to be checked separately, the function covers only the
274  * generic case. Code is inserted at the insertion point.
275  */
276 {
277     CodeEntry* X;
278
279     /* High byte is unknown */
280     X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
281     InsertEntry (D, X, D->IP++);
282     X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
283     InsertEntry (D, X, D->IP++);
284     X = NewCodeEntry (OPC, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
285     InsertEntry (D, X, D->IP++);
286     X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, D->OpEntry->LI);
287     InsertEntry (D, X, D->IP++);
288     X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
289     InsertEntry (D, X, D->IP++);
290 }
291
292
293
294 static void RemovePushAndOp (StackOpData* D)
295 /* Remove the call to pushax and the call to the operator subroutine */
296 {
297     DelEntry (D, D->OpIndex);
298     DelEntry (D, D->PushIndex);
299 }
300
301
302
303 static const char* IsRegVar (const StackOpData* D)
304 /* If the value pushed is that of a register variable, return the name of the
305  * entry in the register bank. Otherwise return NULL.
306  */
307 {
308     CodeEntry* P;
309
310     if (D->PushIndex >= 2                                &&
311         (P = D->PrevEntry) != 0                          &&
312         P->OPC == OP65_LDX                               &&
313         P->AM == AM65_ZP                                 &&
314         strncmp (P->Arg, "regbank+", 7) == 0             &&
315         isdigit (P->Arg[8])                              &&
316         (P = CS_GetEntry (D->Code, D->PushIndex-2)) != 0 &&
317         P->OPC == OP65_LDA                               &&
318         P->AM == AM65_ZP                                 &&
319         strncmp (P->Arg, "regbank+", 7) == 0             &&
320         isdigit (P->Arg[8])) {
321         /* Ok, it loads the register variable */
322         return P->Arg;
323     } else {
324         return 0;
325     }
326 }
327
328
329
330 /*****************************************************************************/
331 /*                       Actual optimization functions                       */
332 /*****************************************************************************/
333
334
335
336 static unsigned Opt_staspidx (StackOpData* D)
337 /* Optimize the staspidx sequence if possible */
338 {
339     CodeEntry* X;
340     const char* ZPLo;
341
342     /* Check if we're using a register variable */
343     if ((ZPLo = IsRegVar (D)) == 0) {
344
345         /* Store the value into the zeropage instead of pushing it */
346         ReplacePushByStore (D);
347
348         /* Use the given zero page loc */
349         ZPLo = D->ZPLo;
350     }
351
352     /* Replace the store subroutine call by a direct op */
353     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
354     InsertEntry (D, X, D->OpIndex+1);
355
356     /* Remove the push and the call to the staspidx function */
357     RemovePushAndOp (D);
358
359     /* We changed the sequence */
360     return 1;
361 }
362
363
364
365 static unsigned Opt_staxspidx (StackOpData* D)
366 /* Optimize the staxspidx sequence if possible */
367 {
368     CodeEntry* X;
369     const char* ZPLo;
370
371     /* Check if we're using a register variable */
372     if ((ZPLo = IsRegVar (D)) == 0) {
373
374         /* Store the value into the zeropage instead of pushing it */
375         ReplacePushByStore (D);
376
377         /* Use the given zero page loc */
378         ZPLo = D->ZPLo;
379     }
380
381     /* Inline the store */
382     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
383     InsertEntry (D, X, D->OpIndex+1);
384     X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI);
385     InsertEntry (D, X, D->OpIndex+2);
386     if (RegValIsKnown (D->OpEntry->RI->In.RegX)) {
387         /* Value of X is known */
388         const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegX);
389         X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, D->OpEntry->LI);
390     } else {
391         /* Value unknown */
392         X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
393     }
394     InsertEntry (D, X, D->OpIndex+3);
395     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
396     InsertEntry (D, X, D->OpIndex+4);
397
398     /* Remove the push and the call to the staspidx function */
399     RemovePushAndOp (D);
400
401     /* We changed the sequence */
402     return 1;
403 }
404
405
406
407 static unsigned Opt_tosaddax (StackOpData* D)
408 /* Optimize the tosaddax sequence if possible */
409 {
410     CodeEntry*  X;
411
412
413     /* We need the entry behind the add */
414     CHECK (D->NextEntry != 0);
415
416     /* Check the entry before the push. If it's a lda instruction with an
417      * addressing mode that allows us to replace it, we may use this
418      * location for the op and must not save the value in the zero page
419      * location.
420      */
421     CheckDirectOp (D);
422
423     /* Store the value into the zeropage instead of pushing it */
424     ReplacePushByStore (D);
425
426     /* Inline the add */
427     D->IP = D->OpIndex+1;
428     X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, D->OpEntry->LI);
429     InsertEntry (D, X, D->IP++);
430
431     /* Low byte */
432     AddOpLow (D, OP65_ADC);
433
434     /* High byte */
435     if (D->PushEntry->RI->In.RegX == 0) {
436         /* The high byte is the value in X plus the carry */
437         CodeLabel* L = CS_GenLabel (D->Code, D->NextEntry);
438         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
439         InsertEntry (D, X, D->IP++);
440         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
441         InsertEntry (D, X, D->IP++);
442     } else if (D->OpEntry->RI->In.RegX == 0) {
443         /* The high byte is that of the first operand plus carry */
444         CodeLabel* L;
445         if (RegValIsKnown (D->PushEntry->RI->In.RegX)) {
446             /* Value of first op high byte is known */
447             const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX);
448             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
449         } else {
450             /* Value of first op high byte is unknown */
451             X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
452         }
453         InsertEntry (D, X, D->IP++);
454         L = CS_GenLabel (D->Code, D->NextEntry);
455         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
456         InsertEntry (D, X, D->IP++);
457         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
458         InsertEntry (D, X, D->IP++);
459     } else {
460         /* High byte is unknown */
461         AddOpHigh (D, OP65_ADC);
462     }
463
464     /* Remove the push and the call to the tosaddax function */
465     RemovePushAndOp (D);
466
467     /* We changed the sequence */
468     return 1;
469 }
470
471
472
473 static unsigned Opt_tosandax (StackOpData* D)
474 /* Optimize the tosandax sequence if possible */
475 {
476     CodeEntry*  X;
477
478     /* Check the entry before the push. If it's a lda instruction with an
479      * addressing mode that allows us to replace it, we may use this
480      * location for the op and must not save the value in the zero page
481      * location.
482      */
483     CheckDirectOp (D);
484
485     /* Store the value into the zeropage instead of pushing it */
486     ReplacePushByStore (D);
487
488     /* Inline the and, low byte */
489     D->IP = D->OpIndex + 1;
490     AddOpLow (D, OP65_AND);
491
492     /* High byte */
493     if (D->PushEntry->RI->In.RegX == 0 || D->OpEntry->RI->In.RegX == 0) {
494         /* The high byte is zero */
495         X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
496         InsertEntry (D, X, D->IP++);
497     } else {
498         /* High byte is unknown */
499         AddOpHigh (D, OP65_AND);
500     }
501
502     /* Remove the push and the call to the tosandax function */
503     RemovePushAndOp (D);
504
505     /* We changed the sequence */
506     return 1;
507 }
508
509
510
511 static unsigned Opt_tosorax (StackOpData* D)
512 /* Optimize the tosorax sequence if possible */
513 {
514     CodeEntry*  X;
515
516     /* Check the entry before the push. If it's a lda instruction with an
517      * addressing mode that allows us to replace it, we may use this
518      * location for the op and must not save the value in the zero page
519      * location.
520      */
521     CheckDirectOp (D);
522
523     /* Store the value into the zeropage instead of pushing it */
524     ReplacePushByStore (D);
525
526     /* Inline the or, low byte */
527     D->IP = D->OpIndex + 1;
528     AddOpLow (D, OP65_ORA);
529
530     /* High byte */
531     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
532         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
533         /* Both values known, precalculate the result */
534         const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX | D->OpEntry->RI->In.RegX);
535         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
536         InsertEntry (D, X, D->IP++);
537     } else if (D->PushEntry->RI->In.RegX != 0) {
538         /* High byte is unknown */
539         AddOpHigh (D, OP65_ORA);
540     }
541
542     /* Remove the push and the call to the tosorax function */
543     RemovePushAndOp (D);
544
545     /* We changed the sequence */
546     return 1;
547 }
548
549
550
551 static unsigned Opt_tosxorax (StackOpData* D)
552 /* Optimize the tosxorax sequence if possible */
553 {
554     CodeEntry*  X;
555
556     /* Check the entry before the push. If it's a lda instruction with an
557      * addressing mode that allows us to replace it, we may use this
558      * location for the op and must not save the value in the zero page
559      * location.
560      */
561     CheckDirectOp (D);
562
563     /* Store the value into the zeropage instead of pushing it */
564     ReplacePushByStore (D);
565
566     /* Inline the xor, low byte */
567     D->IP = D->OpIndex + 1;
568     AddOpLow (D, OP65_EOR);
569
570     /* High byte */
571     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
572         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
573         /* Both values known, precalculate the result */
574         const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX ^ D->OpEntry->RI->In.RegX);
575         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
576         InsertEntry (D, X, D->IP++);
577     } else if (D->PushEntry->RI->In.RegX != 0) {
578         /* High byte is unknown */
579         AddOpHigh (D, OP65_EOR);
580     }
581
582     /* Remove the push and the call to the tosandax function */
583     RemovePushAndOp (D);
584
585     /* We changed the sequence */
586     return 1;
587 }
588
589
590
591 /*****************************************************************************/
592 /*                                   Code                                    */
593 /*****************************************************************************/
594
595
596
597 /* Flags for the functions */
598 typedef enum {
599     STOP_NONE,              /* Nothing special */
600     STOP_A_UNUSED           /* Call only if a unused later */
601 } STOP_FLAGS;
602
603
604 typedef unsigned (*OptFunc) (StackOpData* D);
605 typedef struct OptFuncDesc OptFuncDesc;
606 struct OptFuncDesc {
607     const char*     Name;   /* Name of the replaced runtime function */
608     OptFunc         Func;   /* Function pointer */
609     STOP_FLAGS      Flags;  /* Flags */
610 };
611
612 static const OptFuncDesc FuncTable[] = {
613     { "staspidx",   Opt_staspidx,  STOP_NONE },
614     { "staxspidx",  Opt_staxspidx, STOP_A_UNUSED },
615     { "tosaddax",   Opt_tosaddax,  STOP_NONE },
616     { "tosandax",   Opt_tosandax,  STOP_NONE },
617     { "tosorax",    Opt_tosorax,   STOP_NONE },
618     { "tosxorax",   Opt_tosxorax,  STOP_NONE },
619 };
620 #define FUNC_COUNT (sizeof(FuncTable) / sizeof(FuncTable[0]))
621
622
623
624 static int CmpFunc (const void* Key, const void* Func)
625 /* Compare function for bsearch */
626 {
627     return strcmp (Key, ((const OptFuncDesc*) Func)->Name);
628 }
629
630
631
632 static const OptFuncDesc* FindFunc (const char* Name)
633 /* Find the function with the given name. Return a pointer to the table entry
634  * or NULL if the function was not found.
635  */
636 {
637     return bsearch (Name, FuncTable, FUNC_COUNT, sizeof(OptFuncDesc), CmpFunc);
638 }
639
640
641
642 static int CmpHarmless (const void* Key, const void* Entry)
643 /* Compare function for bsearch */
644 {
645     return strcmp (Key, *(const char**)Entry);
646 }
647
648
649
650 static int HarmlessCall (const char* Name)
651 /* Check if this is a call to a harmless subroutine that will not interrupt
652  * the pushax/op sequence when encountered.
653  */
654 {
655     static const char* Tab[] = {
656         "ldaxidx",
657         "ldaxysp",
658         "negax",
659     };
660
661     void* R = bsearch (Name,
662                        Tab,
663                        sizeof (Tab) / sizeof (Tab[0]),
664                        sizeof (Tab[0]),
665                        CmpHarmless);
666     return (R != 0);
667 }
668
669
670
671 /*****************************************************************************/
672 /*                                   Code                                    */
673 /*****************************************************************************/
674
675
676
677 unsigned OptStackOps (CodeSeg* S)
678 /* Optimize operations that take operands via the stack */
679 {
680     unsigned    Changes = 0;    /* Number of changes in one run */
681     int         InSeq = 0;      /* Inside a sequence */
682     unsigned    Push = 0;       /* Index of pushax */
683     unsigned    UsedRegs = 0;   /* Zeropage registers used in sequence */
684     unsigned    I;
685
686
687     /* Generate register info */
688     CS_GenRegInfo (S);
689
690     /* Look for a call to pushax followed by a call to some other function
691      * that takes it's first argument on the stack, and the second argument
692      * in the primary register.
693      * It depends on the code between the two if we can handle/transform the
694      * sequence, so check this code for the following list of things:
695      *
696      *  - the range must be a basic block (one entry, one exit)
697      *  - there may not be accesses to local variables with unknown
698      *    offsets (because we have to adjust these offsets).
699      *  - no subroutine calls
700      *  - no jump labels
701      *
702      * Since we need a zero page register later, do also check the
703      * intermediate code for zero page use.
704      */
705     I = 0;
706     while (I < CS_GetEntryCount (S)) {
707
708         /* Get the next entry */
709         CodeEntry* E = CS_GetEntry (S, I);
710
711         /* Handling depends if we're inside a sequence or not */
712         if (InSeq) {
713
714             /* If we are using the stack, and we don't have "indirect Y"
715              * addressing mode, or the value of Y is unknown, or less than
716              * two, we cannot cope with this piece of code. Having an unknown
717              * value of Y means that we cannot correct the stack offset, while
718              * having an offset less than two means that the code works with
719              * the value on stack which is to be removed.
720              */
721             if ((E->Use & REG_SP) != 0 &&
722                 (E->AM != AM65_ZP_INDY || RegValIsUnknown (E->RI->In.RegY) ||
723                  E->RI->In.RegY < 2)) {
724
725                 /* All this stuff is not allowed in a sequence */
726                 InSeq = 0;
727
728             } else if (E->OPC == OP65_JSR) {
729
730                 /* Subroutine call: Check if this is one of our functions */
731                 const OptFuncDesc* F = FindFunc (E->Arg);
732                 if (F) {
733
734                     StackOpData Data;
735                     int PreCondOk = 1;
736
737                     /* Check the flags */
738                     if (F->Flags & STOP_A_UNUSED) {
739                         /* a must be unused later */
740                         if (RegAUsed (S, I+1)) {
741                             /* Cannot optimize */
742                             PreCondOk = 0;
743                         }
744                     }
745
746                     /* Determine the zero page locations to use */
747                     if (PreCondOk) {
748                         UsedRegs |= GetRegInfo (S, I+1, REG_SREG | REG_PTR1 | REG_PTR2);
749                         if ((UsedRegs & REG_SREG) == REG_NONE) {
750                             /* SREG is available */
751                             Data.ZPLo = "sreg";
752                             Data.ZPHi = "sreg+1";
753                         } else if ((UsedRegs & REG_PTR1) == REG_NONE) {
754                             Data.ZPLo = "ptr1";
755                             Data.ZPHi = "ptr1+1";
756                         } else if ((UsedRegs & REG_PTR2) == REG_NONE) {
757                             Data.ZPLo = "ptr2";
758                             Data.ZPHi = "ptr2+1";
759                         } else {
760                             /* No registers available */
761                             PreCondOk = 0;
762                         }
763                     }
764
765                     /* Determine if we have a basic block */
766                     if (PreCondOk) {
767                         PreCondOk = CS_IsBasicBlock (S, Push, I);
768                     }
769
770                     /* If preconditions are ok, call the optimizer function */
771                     if (PreCondOk) {
772
773                         /* Adjust stack offsets */
774                         Data.OpIndex = I + AdjustStackOffset (S, Push, I, 2);
775
776                         /* Prepare the remainder of the data structure */
777                         Data.Code      = S;
778                         Data.Flags     = 0;
779                         Data.PushIndex = Push;
780                         Data.PrevEntry = CS_GetPrevEntry (S, Data.PushIndex);
781                         Data.PushEntry = CS_GetEntry (S, Data.PushIndex);
782                         Data.OpEntry   = E;
783                         Data.NextEntry = CS_GetNextEntry (S, Data.OpIndex);
784
785                         /* Call the optimizer function */
786                         Changes += F->Func (&Data);
787
788                         /* Regenerate register info */
789                         CS_GenRegInfo (S);
790                     }
791
792                     /* End of sequence */
793                     InSeq = 0;
794
795                 } else if (strcmp (E->Arg, "pushax") == 0) {
796                     /* Restart the sequence */
797                     Push     = I;
798                     UsedRegs = REG_NONE;
799                 } else if (HarmlessCall (E->Arg)) {
800                     /* Track zeropage register usage */
801                     UsedRegs |= (E->Use | E->Chg);
802                 } else {
803                     /* A call to an unkown subroutine ends the sequence */
804                     InSeq = 0;
805                 }
806
807             } else {
808                 /* Other stuff: Track zeropage register usage */
809                 UsedRegs |= (E->Use | E->Chg);
810             }
811
812         } else if (CE_IsCallTo (E, "pushax")) {
813
814             /* This starts a sequence */
815             Push     = I;
816             UsedRegs = REG_NONE;
817             InSeq    = 1;
818
819         }
820
821         /* Next entry */
822         ++I;
823
824     }
825
826     /* Free the register info */
827     CS_FreeRegInfo (S);
828
829     /* Return the number of changes made */
830     return Changes;
831 }
832
833
834