]> git.sur5r.net Git - cc65/blob - src/cc65/coptstop.c
Re-added register variables.
[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             /* Load indirect with known offset is also ok */
213             D->Flags |= (OP_DIRECT | OP_RELOAD_Y);
214         }
215     }
216 }
217
218
219
220 static void ReplacePushByStore (StackOpData* D)
221 /* Replace the call to the push subroutine by a store into the zero page
222  * location (actually, the push is not replaced, because we need it for
223  * later, but the name is still ok since the push will get removed at the
224  * end of each routine).
225  */
226 {
227     CodeEntry* X;
228
229     /* Store the value into the zeropage instead of pushing it */
230     X = NewCodeEntry (OP65_STX, AM65_ZP, D->ZPHi, 0, D->PushEntry->LI);
231     InsertEntry (D, X, D->PushIndex+1);
232     if ((D->Flags & OP_DIRECT) == 0) {
233         X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->PushEntry->LI);
234         InsertEntry (D, X, D->PushIndex+1);
235     }
236 }
237
238
239
240 static void AddOpLow (StackOpData* D, opc_t OPC)
241 /* Add an op for the low byte of an operator. This function honours the
242  * OP_DIRECT and OP_RELOAD_Y flags and generates the necessary instructions.
243  * All code is inserted at the current insertion point.
244  */
245 {
246     CodeEntry* X;
247
248     if ((D->Flags & OP_DIRECT) != 0) {
249         /* Op with a variable location. If the location is on the stack, we
250          * need to reload the Y register.
251          */
252         if ((D->Flags & OP_RELOAD_Y) != 0) {
253             const char* Arg = MakeHexArg (D->PrevEntry->RI->In.RegY);
254             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
255             InsertEntry (D, X, D->IP++);
256         }
257         X = NewCodeEntry (OPC, D->PrevEntry->AM, D->PrevEntry->Arg, 0, D->OpEntry->LI);
258     } else {
259         /* Op with temp storage */
260         X = NewCodeEntry (OPC, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
261     }
262     InsertEntry (D, X, D->IP++);
263 }
264
265
266
267 static void AddOpHigh (StackOpData* D, opc_t OPC)
268 /* Add an op for the high byte of an operator. Special cases (constant values
269  * or similar have to be checked separately, the function covers only the
270  * generic case. Code is inserted at the insertion point.
271  */
272 {
273     CodeEntry* X;
274
275     /* High byte is unknown */
276     X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
277     InsertEntry (D, X, D->IP++);
278     X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
279     InsertEntry (D, X, D->IP++);
280     X = NewCodeEntry (OPC, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
281     InsertEntry (D, X, D->IP++);
282     X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, D->OpEntry->LI);
283     InsertEntry (D, X, D->IP++);
284     X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
285     InsertEntry (D, X, D->IP++);
286 }
287
288
289
290 static void RemovePushAndOp (StackOpData* D)
291 /* Remove the call to pushax and the call to the operator subroutine */
292 {
293     DelEntry (D, D->OpIndex);
294     DelEntry (D, D->PushIndex);
295 }
296
297
298
299 static const char* IsRegVar (const StackOpData* D)
300 /* If the value pushed is that of a register variable, return the name of the
301  * entry in the register bank. Otherwise return NULL.
302  */
303 {
304     CodeEntry* P;
305
306     if (D->PushIndex >= 2                                &&
307         (P = D->PrevEntry) != 0                          &&
308         P->OPC == OP65_LDX                               &&
309         P->AM == AM65_ZP                                 &&
310         strncmp (P->Arg, "regbank+", 7) == 0             &&
311         isdigit (P->Arg[8])                              &&
312         (P = CS_GetEntry (D->Code, D->PushIndex-2)) != 0 &&
313         P->OPC == OP65_LDA                               &&
314         P->AM == AM65_ZP                                 &&
315         strncmp (P->Arg, "regbank+", 7) == 0             &&
316         isdigit (P->Arg[8])) {
317         /* Ok, it loads the register variable */
318         return P->Arg;
319     } else {
320         return 0;
321     }
322 }
323
324
325
326 /*****************************************************************************/
327 /*                       Actual optimization functions                       */
328 /*****************************************************************************/
329
330
331
332 static unsigned Opt_staspidx (StackOpData* D)
333 /* Optimize the staspidx sequence if possible */
334 {
335     CodeEntry* X;
336     const char* ZPLo;
337
338     /* Check if we're using a register variable */
339     if ((ZPLo = IsRegVar (D)) == 0) {
340
341         /* Store the value into the zeropage instead of pushing it */
342         ReplacePushByStore (D);
343
344         /* Use the given zero page loc */
345         ZPLo = D->ZPLo;
346     }
347
348     /* Replace the store subroutine call by a direct op */
349     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
350     InsertEntry (D, X, D->OpIndex+1);
351
352     /* Remove the push and the call to the staspidx function */
353     RemovePushAndOp (D);
354
355     /* We changed the sequence */
356     return 1;
357 }
358
359
360
361 static unsigned Opt_staxspidx (StackOpData* D)
362 /* Optimize the staxspidx sequence if possible */
363 {
364     CodeEntry* X;
365     const char* ZPLo;
366
367     /* Check if we're using a register variable */
368     if ((ZPLo = IsRegVar (D)) == 0) {
369
370         /* Store the value into the zeropage instead of pushing it */
371         ReplacePushByStore (D);
372
373         /* Use the given zero page loc */
374         ZPLo = D->ZPLo;
375     }
376
377     /* Inline the store */
378     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
379     InsertEntry (D, X, D->OpIndex+1);
380     X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI);
381     InsertEntry (D, X, D->OpIndex+2);
382     if (RegValIsKnown (D->OpEntry->RI->In.RegX)) {
383         /* Value of X is known */
384         const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegX);
385         X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, D->OpEntry->LI);
386     } else {
387         /* Value unknown */
388         X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
389     }
390     InsertEntry (D, X, D->OpIndex+3);
391     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
392     InsertEntry (D, X, D->OpIndex+4);
393
394     /* Remove the push and the call to the staspidx function */
395     RemovePushAndOp (D);
396
397     /* We changed the sequence */
398     return 1;
399 }
400
401
402
403 static unsigned Opt_tosaddax (StackOpData* D)
404 /* Optimize the tosaddax sequence if possible */
405 {
406     CodeEntry*  X;
407
408
409     /* We need the entry behind the add */
410     CHECK (D->NextEntry != 0);
411
412     /* Check the entry before the push. If it's a lda instruction with an
413      * addressing mode that allows us to replace it, we may use this
414      * location for the op and must not save the value in the zero page
415      * location.
416      */
417     CheckDirectOp (D);
418
419     /* Store the value into the zeropage instead of pushing it */
420     ReplacePushByStore (D);
421
422     /* Inline the add */
423     D->IP = D->OpIndex+1;
424     X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, D->OpEntry->LI);
425     InsertEntry (D, X, D->IP++);
426
427     /* Low byte */
428     AddOpLow (D, OP65_ADC);
429
430     /* High byte */
431     if (D->PushEntry->RI->In.RegX == 0) {
432         /* The high byte is the value in X plus the carry */
433         CodeLabel* L = CS_GenLabel (D->Code, D->NextEntry);
434         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
435         InsertEntry (D, X, D->IP++);
436         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
437         InsertEntry (D, X, D->IP++);
438     } else if (D->OpEntry->RI->In.RegX == 0) {
439         /* The high byte is that of the first operand plus carry */
440         CodeLabel* L;
441         if (RegValIsKnown (D->PushEntry->RI->In.RegX)) {
442             /* Value of first op high byte is known */
443             const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX);
444             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
445         } else {
446             /* Value of first op high byte is unknown */
447             X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
448         }
449         InsertEntry (D, X, D->IP++);
450         L = CS_GenLabel (D->Code, D->NextEntry);
451         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
452         InsertEntry (D, X, D->IP++);
453         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
454         InsertEntry (D, X, D->IP++);
455     } else {
456         /* High byte is unknown */
457         AddOpHigh (D, OP65_ADC);
458     }
459
460     /* Remove the push and the call to the tosaddax function */
461     RemovePushAndOp (D);
462
463     /* We changed the sequence */
464     return 1;
465 }
466
467
468
469 static unsigned Opt_tosandax (StackOpData* D)
470 /* Optimize the tosandax sequence if possible */
471 {
472     CodeEntry*  X;
473
474     /* Check the entry before the push. If it's a lda instruction with an
475      * addressing mode that allows us to replace it, we may use this
476      * location for the op and must not save the value in the zero page
477      * location.
478      */
479     CheckDirectOp (D);
480
481     /* Store the value into the zeropage instead of pushing it */
482     ReplacePushByStore (D);
483
484     /* Inline the and, low byte */
485     D->IP = D->OpIndex + 1;
486     AddOpLow (D, OP65_AND);
487
488     /* High byte */
489     if (D->PushEntry->RI->In.RegX == 0 || D->OpEntry->RI->In.RegX == 0) {
490         /* The high byte is zero */
491         X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
492         InsertEntry (D, X, D->IP++);
493     } else {
494         /* High byte is unknown */
495         AddOpHigh (D, OP65_AND);
496     }
497
498     /* Remove the push and the call to the tosandax function */
499     RemovePushAndOp (D);
500
501     /* We changed the sequence */
502     return 1;
503 }
504
505
506
507 static unsigned Opt_tosorax (StackOpData* D)
508 /* Optimize the tosorax sequence if possible */
509 {
510     CodeEntry*  X;
511
512     /* Check the entry before the push. If it's a lda instruction with an
513      * addressing mode that allows us to replace it, we may use this
514      * location for the op and must not save the value in the zero page
515      * location.
516      */
517     CheckDirectOp (D);
518
519     /* Store the value into the zeropage instead of pushing it */
520     ReplacePushByStore (D);
521
522     /* Inline the or, low byte */
523     D->IP = D->OpIndex + 1;
524     AddOpLow (D, OP65_ORA);
525
526     /* High byte */
527     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
528         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
529         /* Both values known, precalculate the result */
530         const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX | D->OpEntry->RI->In.RegX);
531         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
532         InsertEntry (D, X, D->IP++);
533     } else if (D->PushEntry->RI->In.RegX != 0) {
534         /* High byte is unknown */
535         AddOpHigh (D, OP65_ORA);
536     }
537
538     /* Remove the push and the call to the tosorax function */
539     RemovePushAndOp (D);
540
541     /* We changed the sequence */
542     return 1;
543 }
544
545
546
547 static unsigned Opt_tosxorax (StackOpData* D)
548 /* Optimize the tosxorax sequence if possible */
549 {
550     CodeEntry*  X;
551
552     /* Check the entry before the push. If it's a lda instruction with an
553      * addressing mode that allows us to replace it, we may use this
554      * location for the op and must not save the value in the zero page
555      * location.
556      */
557     CheckDirectOp (D);
558
559     /* Store the value into the zeropage instead of pushing it */
560     ReplacePushByStore (D);
561
562     /* Inline the xor, low byte */
563     D->IP = D->OpIndex + 1;
564     AddOpLow (D, OP65_EOR);
565
566     /* High byte */
567     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
568         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
569         /* Both values known, precalculate the result */
570         const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX ^ D->OpEntry->RI->In.RegX);
571         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
572         InsertEntry (D, X, D->IP++);
573     } else if (D->PushEntry->RI->In.RegX != 0) {
574         /* High byte is unknown */
575         AddOpHigh (D, OP65_EOR);
576     }
577
578     /* Remove the push and the call to the tosandax function */
579     RemovePushAndOp (D);
580
581     /* We changed the sequence */
582     return 1;
583 }
584
585
586
587 /*****************************************************************************/
588 /*                                   Code                                    */
589 /*****************************************************************************/
590
591
592
593 /* Flags for the functions */
594 typedef enum {
595     STOP_NONE,              /* Nothing special */
596     STOP_A_UNUSED           /* Call only if a unused later */
597 } STOP_FLAGS;
598
599
600 typedef unsigned (*OptFunc) (StackOpData* D);
601 typedef struct OptFuncDesc OptFuncDesc;
602 struct OptFuncDesc {
603     const char*     Name;   /* Name of the replaced runtime function */
604     OptFunc         Func;   /* Function pointer */
605     STOP_FLAGS      Flags;  /* Flags */
606 };
607
608 static const OptFuncDesc FuncTable[] = {
609     { "staspidx",   Opt_staspidx,  STOP_NONE },
610     { "staxspidx",  Opt_staxspidx, STOP_A_UNUSED },
611     { "tosaddax",   Opt_tosaddax,  STOP_NONE },
612     { "tosandax",   Opt_tosandax,  STOP_NONE },
613     { "tosorax",    Opt_tosorax,   STOP_NONE },
614     { "tosxorax",   Opt_tosxorax,  STOP_NONE },
615 };
616 #define FUNC_COUNT (sizeof(FuncTable) / sizeof(FuncTable[0]))
617
618
619
620 static int CmpFunc (const void* Key, const void* Func)
621 /* Compare function for bsearch */
622 {
623     return strcmp (Key, ((const OptFuncDesc*) Func)->Name);
624 }
625
626
627
628 static const OptFuncDesc* FindFunc (const char* Name)
629 /* Find the function with the given name. Return a pointer to the table entry
630  * or NULL if the function was not found.
631  */
632 {
633     return bsearch (Name, FuncTable, FUNC_COUNT, sizeof(OptFuncDesc), CmpFunc);
634 }
635
636
637
638 static int CmpHarmless (const void* Key, const void* Entry)
639 /* Compare function for bsearch */
640 {
641     return strcmp (Key, *(const char**)Entry);
642 }
643
644
645
646 static int HarmlessCall (const char* Name)
647 /* Check if this is a call to a harmless subroutine that will not interrupt
648  * the pushax/op sequence when encountered.
649  */
650 {
651     static const char* Tab[] = {
652         "ldaxidx",
653         "ldaxysp",
654     };
655
656     void* R = bsearch (Name,
657                        Tab,
658                        sizeof (Tab) / sizeof (Tab[0]),
659                        sizeof (Tab[0]),
660                        CmpHarmless);
661     return (R != 0);
662 }
663
664
665
666 /*****************************************************************************/
667 /*                                   Code                                    */
668 /*****************************************************************************/
669
670
671
672 unsigned OptStackOps (CodeSeg* S)
673 /* Optimize operations that take operands via the stack */
674 {
675     unsigned    Changes = 0;    /* Number of changes in one run */
676     int         InSeq = 0;      /* Inside a sequence */
677     unsigned    Push = 0;       /* Index of pushax */
678     unsigned    UsedRegs = 0;   /* Zeropage registers used in sequence */
679     unsigned    I;
680
681
682     /* Generate register info */
683     CS_GenRegInfo (S);
684
685     /* Look for a call to pushax followed by a call to some other function
686      * that takes it's first argument on the stack, and the second argument
687      * in the primary register.
688      * It depends on the code between the two if we can handle/transform the
689      * sequence, so check this code for the following list of things:
690      *
691      *  - the range must be a basic block (one entry, one exit)
692      *  - there may not be accesses to local variables with unknown
693      *    offsets (because we have to adjust these offsets).
694      *  - no subroutine calls
695      *  - no jump labels
696      *
697      * Since we need a zero page register later, do also check the
698      * intermediate code for zero page use.
699      */
700     I = 0;
701     while (I < CS_GetEntryCount (S)) {
702
703         /* Get the next entry */
704         CodeEntry* E = CS_GetEntry (S, I);
705
706         /* Handling depends if we're inside a sequence or not */
707         if (InSeq) {
708
709             if (((E->Use & REG_SP) != 0 &&
710                  (E->AM != AM65_ZP_INDY || RegValIsUnknown (E->RI->In.RegY)))) {
711
712                 /* All this stuff is not allowed in a sequence */
713                 InSeq = 0;
714
715             } else if (E->OPC == OP65_JSR) {
716
717                 /* Subroutine call: Check if this is one of our functions */
718                 const OptFuncDesc* F = FindFunc (E->Arg);
719                 if (F) {
720
721                     StackOpData Data;
722                     int PreCondOk = 1;
723
724                     /* Check the flags */
725                     if (F->Flags & STOP_A_UNUSED) {
726                         /* a must be unused later */
727                         if (RegAUsed (S, I+1)) {
728                             /* Cannot optimize */
729                             PreCondOk = 0;
730                         }
731                     }
732
733                     /* Determine the zero page locations to use */
734                     if (PreCondOk) {
735                         UsedRegs |= GetRegInfo (S, I+1, REG_SREG | REG_PTR1 | REG_PTR2);
736                         if ((UsedRegs & REG_SREG) == REG_NONE) {
737                             /* SREG is available */
738                             Data.ZPLo = "sreg";
739                             Data.ZPHi = "sreg+1";
740                         } else if ((UsedRegs & REG_PTR1) == REG_NONE) {
741                             Data.ZPLo = "ptr1";
742                             Data.ZPHi = "ptr1+1";
743                         } else if ((UsedRegs & REG_PTR2) == REG_NONE) {
744                             Data.ZPLo = "ptr2";
745                             Data.ZPHi = "ptr2+1";
746                         } else {
747                             /* No registers available */
748                             PreCondOk = 0;
749                         }
750                     }
751
752                     /* Determine if we have a basic block */
753                     if (PreCondOk) {
754                         PreCondOk = CS_IsBasicBlock (S, Push, I);
755                     }
756
757                     /* If preconditions are ok, call the optimizer function */
758                     if (PreCondOk) {
759
760                         /* Adjust stack offsets */
761                         Data.OpIndex = I + AdjustStackOffset (S, Push, I, 2);
762
763                         /* Prepare the remainder of the data structure */
764                         Data.Code      = S;
765                         Data.Flags     = 0;
766                         Data.PushIndex = Push;
767                         Data.PrevEntry = CS_GetPrevEntry (S, Data.PushIndex);
768                         Data.PushEntry = CS_GetEntry (S, Data.PushIndex);
769                         Data.OpEntry   = E;
770                         Data.NextEntry = CS_GetNextEntry (S, Data.OpIndex);
771
772                         /* Call the optimizer function */
773                         Changes += F->Func (&Data);
774
775                         /* Regenerate register info */
776                         CS_GenRegInfo (S);
777                     }
778
779                     /* End of sequence */
780                     InSeq = 0;
781
782                 } else if (strcmp (E->Arg, "pushax") == 0) {
783                     /* Restart the sequence */
784                     Push     = I;
785                     UsedRegs = REG_NONE;
786                 } else if (HarmlessCall (E->Arg)) {
787                     /* Track zeropage register usage */
788                     UsedRegs |= (E->Use | E->Chg);
789                 } else {
790                     /* A call to an unkown subroutine ends the sequence */
791                     InSeq = 0;
792                 }
793
794             } else {
795                 /* Other stuff: Track zeropage register usage */
796                 UsedRegs |= (E->Use | E->Chg);
797             }
798
799         } else if (CE_IsCallTo (E, "pushax")) {
800
801             /* This starts a sequence */
802             Push     = I;
803             UsedRegs = REG_NONE;
804             InSeq    = 1;
805
806         }
807
808         /* Next entry */
809         ++I;
810
811     }
812
813     /* Free the register info */
814     CS_FreeRegInfo (S);
815
816     /* Return the number of changes made */
817     return Changes;
818 }
819
820
821