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