]> git.sur5r.net Git - cc65/blob - src/cc65/coptstop.c
6008261999ab331d2d6450f2c7b94b2f96e9f11a
[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-2004 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 int IsRegVar (StackOpData* D)
325 /* If the value pushed is that of a register variable, replace ZPLo and ZPHi
326  * in the given StackOpData struct by the register variables and return true.
327  * Otherwise leave D untouched and return false.
328  */
329 {
330     CodeEntry* P;
331
332     if (D->PushIndex >= 2                                &&
333         (P = D->PrevEntry) != 0                          &&
334         P->OPC == OP65_LDX                               &&
335         P->AM == AM65_ZP                                 &&
336         strncmp (P->Arg, "regbank+", 7) == 0             &&
337         isdigit (P->Arg[8])                              &&
338         (P = CS_GetEntry (D->Code, D->PushIndex-2)) != 0 &&
339         P->OPC == OP65_LDA                               &&
340         P->AM == AM65_ZP                                 &&
341         strncmp (P->Arg, "regbank+", 7) == 0             &&
342         isdigit (P->Arg[8])) {
343         /* Ok, it loads the register variable */
344         D->ZPHi = D->PrevEntry->Arg;
345         D->ZPLo = P->Arg;
346         return 1;
347     } else {
348         return 0;
349     }
350 }
351
352
353
354 /*****************************************************************************/
355 /*                       Actual optimization functions                       */
356 /*****************************************************************************/
357
358
359
360 static unsigned Opt___bzero (StackOpData* D)
361 /* Optimize the __bzero sequence if possible */
362 {
363     CodeEntry*  X;
364     const char* Arg;
365     CodeLabel*  L;
366
367     /* Check if we're using a register variable */
368     if (!IsRegVar (D)) {
369         /* Store the value into the zeropage instead of pushing it */
370         ReplacePushByStore (D);
371     }
372
373     /* If the return value of __bzero is used, we have to add code to reload
374      * a/x from the pointer variable.
375      */
376     if (RegAXUsed (D->Code, D->OpIndex+1)) {
377         X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
378         InsertEntry (D, X, D->OpIndex+1);
379         X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
380         InsertEntry (D, X, D->OpIndex+2);
381     }
382
383     /* X is always zero, A contains the size of the data area to zero.
384      * Note: A may be zero, in which case the operation is null op.
385      */
386     if (D->OpEntry->RI->In.RegA != 0) {
387
388         /* The value of A is known */
389         if (D->OpEntry->RI->In.RegA <= 0x81) {
390
391             /* Loop using the sign bit */
392             X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI);
393             InsertEntry (D, X, D->OpIndex+1);
394
395             Arg = MakeHexArg (D->OpEntry->RI->In.RegA - 1);
396             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
397             InsertEntry (D, X, D->OpIndex+2);
398
399             X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
400             InsertEntry (D, X, D->OpIndex+3);
401             L = CS_GenLabel (D->Code, X);
402
403             X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, D->OpEntry->LI);
404             InsertEntry (D, X, D->OpIndex+4);
405
406             X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, D->OpEntry->LI);
407             InsertEntry (D, X, D->OpIndex+5);
408
409         } else {
410
411             /* Loop using an explicit compare */
412             X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI);
413             InsertEntry (D, X, D->OpIndex+1);
414
415             X = NewCodeEntry (OP65_LDY, AM65_IMM, "$00", 0, D->OpEntry->LI);
416             InsertEntry (D, X, D->OpIndex+2);
417
418             X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
419             InsertEntry (D, X, D->OpIndex+3);
420             L = CS_GenLabel (D->Code, X);
421
422             X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI);
423             InsertEntry (D, X, D->OpIndex+4);
424
425             Arg = MakeHexArg (D->OpEntry->RI->In.RegA);
426             X = NewCodeEntry (OP65_CPY, AM65_IMM, Arg, 0, D->OpEntry->LI);
427             InsertEntry (D, X, D->OpIndex+5);
428
429             X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, D->OpEntry->LI);
430             InsertEntry (D, X, D->OpIndex+6);
431         }
432
433     }
434
435     /* Remove the push and the call to the __bzero function */
436     RemovePushAndOp (D);
437
438     /* We changed the sequence */
439     return 1;
440 }
441
442
443
444 static unsigned Opt_staspidx (StackOpData* D)
445 /* Optimize the staspidx sequence if possible */
446 {
447     CodeEntry* X;
448
449     /* Check if we're using a register variable */
450     if (!IsRegVar (D)) {
451         /* Store the value into the zeropage instead of pushing it */
452         ReplacePushByStore (D);
453     }
454
455     /* Replace the store subroutine call by a direct op */
456     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
457     InsertEntry (D, X, D->OpIndex+1);
458
459     /* Remove the push and the call to the staspidx function */
460     RemovePushAndOp (D);
461
462     /* We changed the sequence */
463     return 1;
464 }
465
466
467
468 static unsigned Opt_staxspidx (StackOpData* D)
469 /* Optimize the staxspidx sequence if possible */
470 {
471     CodeEntry* X;
472
473     /* Check if we're using a register variable */
474     if (!IsRegVar (D)) {
475         /* Store the value into the zeropage instead of pushing it */
476         ReplacePushByStore (D);
477     }
478
479     /* Inline the store */
480     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
481     InsertEntry (D, X, D->OpIndex+1);
482     X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI);
483     InsertEntry (D, X, D->OpIndex+2);
484     if (RegValIsKnown (D->OpEntry->RI->In.RegX)) {
485         /* Value of X is known */
486         const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegX);
487         X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, D->OpEntry->LI);
488     } else {
489         /* Value unknown */
490         X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
491     }
492     InsertEntry (D, X, D->OpIndex+3);
493     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
494     InsertEntry (D, X, D->OpIndex+4);
495
496     /* Remove the push and the call to the staspidx function */
497     RemovePushAndOp (D);
498
499     /* We changed the sequence */
500     return 1;
501 }
502
503
504
505 static unsigned Opt_tosaddax (StackOpData* D)
506 /* Optimize the tosaddax sequence if possible */
507 {
508     CodeEntry*  X;
509
510
511     /* We need the entry behind the add */
512     CHECK (D->NextEntry != 0);
513
514     /* Check the entry before the push. If it's a lda instruction with an
515      * addressing mode that allows us to replace it, we may use this
516      * location for the op and must not save the value in the zero page
517      * location.
518      */
519     CheckDirectOp (D);
520
521     /* Store the value into the zeropage instead of pushing it */
522     ReplacePushByStore (D);
523
524     /* Inline the add */
525     D->IP = D->OpIndex+1;
526     X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, D->OpEntry->LI);
527     InsertEntry (D, X, D->IP++);
528
529     /* Low byte */
530     AddOpLow (D, OP65_ADC);
531
532     /* High byte */
533     if (D->PushEntry->RI->In.RegX == 0) {
534         /* The high byte is the value in X plus the carry */
535         CodeLabel* L = CS_GenLabel (D->Code, D->NextEntry);
536         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
537         InsertEntry (D, X, D->IP++);
538         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
539         InsertEntry (D, X, D->IP++);
540     } else if (D->OpEntry->RI->In.RegX == 0) {
541         /* The high byte is that of the first operand plus carry */
542         CodeLabel* L;
543         if (RegValIsKnown (D->PushEntry->RI->In.RegX)) {
544             /* Value of first op high byte is known */
545             const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX);
546             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
547         } else {
548             /* Value of first op high byte is unknown */
549             X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
550         }
551         InsertEntry (D, X, D->IP++);
552         L = CS_GenLabel (D->Code, D->NextEntry);
553         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
554         InsertEntry (D, X, D->IP++);
555         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
556         InsertEntry (D, X, D->IP++);
557     } else {
558         /* High byte is unknown */
559         AddOpHigh (D, OP65_ADC);
560     }
561
562     /* Remove the push and the call to the tosaddax function */
563     RemovePushAndOp (D);
564
565     /* We changed the sequence */
566     return 1;
567 }
568
569
570
571 static unsigned Opt_tosandax (StackOpData* D)
572 /* Optimize the tosandax sequence if possible */
573 {
574     CodeEntry*  X;
575
576     /* Check the entry before the push. If it's a lda instruction with an
577      * addressing mode that allows us to replace it, we may use this
578      * location for the op and must not save the value in the zero page
579      * location.
580      */
581     CheckDirectOp (D);
582
583     /* Store the value into the zeropage instead of pushing it */
584     ReplacePushByStore (D);
585
586     /* Inline the and, low byte */
587     D->IP = D->OpIndex + 1;
588     AddOpLow (D, OP65_AND);
589
590     /* High byte */
591     if (D->PushEntry->RI->In.RegX == 0 || D->OpEntry->RI->In.RegX == 0) {
592         /* The high byte is zero */
593         X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
594         InsertEntry (D, X, D->IP++);
595     } else {
596         /* High byte is unknown */
597         AddOpHigh (D, OP65_AND);
598     }
599
600     /* Remove the push and the call to the tosandax function */
601     RemovePushAndOp (D);
602
603     /* We changed the sequence */
604     return 1;
605 }
606
607
608
609 static unsigned Opt_tosorax (StackOpData* D)
610 /* Optimize the tosorax sequence if possible */
611 {
612     CodeEntry*  X;
613
614     /* Check the entry before the push. If it's a lda instruction with an
615      * addressing mode that allows us to replace it, we may use this
616      * location for the op and must not save the value in the zero page
617      * location.
618      */
619     CheckDirectOp (D);
620
621     /* Store the value into the zeropage instead of pushing it */
622     ReplacePushByStore (D);
623
624     /* Inline the or, low byte */
625     D->IP = D->OpIndex + 1;
626     AddOpLow (D, OP65_ORA);
627
628     /* High byte */
629     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
630         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
631         /* Both values known, precalculate the result */
632         unsigned char Result = D->PushEntry->RI->In.RegX | D->OpEntry->RI->In.RegX;
633         const char* Arg = MakeHexArg (Result);
634         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
635         InsertEntry (D, X, D->IP++);
636     } else if (D->PushEntry->RI->In.RegX != 0) {
637         /* High byte is unknown */
638         AddOpHigh (D, OP65_ORA);
639     }
640
641     /* Remove the push and the call to the tosorax function */
642     RemovePushAndOp (D);
643
644     /* We changed the sequence */
645     return 1;
646 }
647
648
649
650 static unsigned Opt_tosxorax (StackOpData* D)
651 /* Optimize the tosxorax sequence if possible */
652 {
653     CodeEntry*  X;
654
655     /* Check the entry before the push. If it's a lda instruction with an
656      * addressing mode that allows us to replace it, we may use this
657      * location for the op and must not save the value in the zero page
658      * location.
659      */
660     CheckDirectOp (D);
661
662     /* Store the value into the zeropage instead of pushing it */
663     ReplacePushByStore (D);
664
665     /* Inline the xor, low byte */
666     D->IP = D->OpIndex + 1;
667     AddOpLow (D, OP65_EOR);
668
669     /* High byte */
670     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
671         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
672         /* Both values known, precalculate the result */
673         const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX ^ D->OpEntry->RI->In.RegX);
674         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
675         InsertEntry (D, X, D->IP++);
676     } else if (D->PushEntry->RI->In.RegX != 0) {
677         /* High byte is unknown */
678         AddOpHigh (D, OP65_EOR);
679     }
680
681     /* Remove the push and the call to the tosandax function */
682     RemovePushAndOp (D);
683
684     /* We changed the sequence */
685     return 1;
686 }
687
688
689
690 /*****************************************************************************/
691 /*                                   Code                                    */
692 /*****************************************************************************/
693
694
695
696 /* Flags for the functions */
697 typedef enum {
698     STOP_NONE       = 0x00,     /* Nothing special */
699     STOP_A_UNUSED   = 0x01,     /* Call only if a unused later */
700     STOP_A_KNOWN    = 0x02,     /* Call only if A is known */
701     STOP_X_ZERO     = 0x04      /* Call only if X is zero */
702 } STOP_FLAGS;
703
704
705 typedef unsigned (*OptFunc) (StackOpData* D);
706 typedef struct OptFuncDesc OptFuncDesc;
707 struct OptFuncDesc {
708     const char*     Name;   /* Name of the replaced runtime function */
709     OptFunc         Func;   /* Function pointer */
710     STOP_FLAGS      Flags;  /* Flags */
711 };
712
713 static const OptFuncDesc FuncTable[] = {
714     { "__bzero",    Opt___bzero,   STOP_NONE     },
715     { "staspidx",   Opt_staspidx,  STOP_NONE     },
716     { "staxspidx",  Opt_staxspidx, STOP_A_UNUSED },
717     { "tosaddax",   Opt_tosaddax,  STOP_NONE     },
718     { "tosandax",   Opt_tosandax,  STOP_NONE     },
719     { "tosorax",    Opt_tosorax,   STOP_NONE     },
720     { "tosxorax",   Opt_tosxorax,  STOP_NONE     },
721 };
722 #define FUNC_COUNT (sizeof(FuncTable) / sizeof(FuncTable[0]))
723
724
725
726 static int CmpFunc (const void* Key, const void* Func)
727 /* Compare function for bsearch */
728 {
729     return strcmp (Key, ((const OptFuncDesc*) Func)->Name);
730 }
731
732
733
734 static const OptFuncDesc* FindFunc (const char* Name)
735 /* Find the function with the given name. Return a pointer to the table entry
736  * or NULL if the function was not found.
737  */
738 {
739     return bsearch (Name, FuncTable, FUNC_COUNT, sizeof(OptFuncDesc), CmpFunc);
740 }
741
742
743
744 static int CmpHarmless (const void* Key, const void* Entry)
745 /* Compare function for bsearch */
746 {
747     return strcmp (Key, *(const char**)Entry);
748 }
749
750
751
752 static int HarmlessCall (const char* Name)
753 /* Check if this is a call to a harmless subroutine that will not interrupt
754  * the pushax/op sequence when encountered.
755  */
756 {
757     static const char* Tab[] = {
758         "ldaxidx",
759         "ldaxysp",
760         "negax",
761     };
762
763     void* R = bsearch (Name,
764                        Tab,
765                        sizeof (Tab) / sizeof (Tab[0]),
766                        sizeof (Tab[0]),
767                        CmpHarmless);
768     return (R != 0);
769 }
770
771
772
773 /*****************************************************************************/
774 /*                                   Code                                    */
775 /*****************************************************************************/
776
777
778
779 unsigned OptStackOps (CodeSeg* S)
780 /* Optimize operations that take operands via the stack */
781 {
782     unsigned    Changes = 0;    /* Number of changes in one run */
783     int         InSeq = 0;      /* Inside a sequence */
784     unsigned    Push = 0;       /* Index of pushax */
785     unsigned    UsedRegs = 0;   /* Zeropage registers used in sequence */
786     unsigned    I;
787
788
789     /* Generate register info */
790     CS_GenRegInfo (S);
791
792     /* Look for a call to pushax followed by a call to some other function
793      * that takes it's first argument on the stack, and the second argument
794      * in the primary register.
795      * It depends on the code between the two if we can handle/transform the
796      * sequence, so check this code for the following list of things:
797      *
798      *  - the range must be a basic block (one entry, one exit)
799      *  - there may not be accesses to local variables with unknown
800      *    offsets (because we have to adjust these offsets).
801      *  - no subroutine calls
802      *  - no jump labels
803      *
804      * Since we need a zero page register later, do also check the
805      * intermediate code for zero page use.
806      */
807     I = 0;
808     while (I < CS_GetEntryCount (S)) {
809
810         /* Get the next entry */
811         CodeEntry* E = CS_GetEntry (S, I);
812
813         /* Handling depends if we're inside a sequence or not */
814         if (InSeq) {
815
816             /* If we are using the stack, and we don't have "indirect Y"
817              * addressing mode, or the value of Y is unknown, or less than
818              * two, we cannot cope with this piece of code. Having an unknown
819              * value of Y means that we cannot correct the stack offset, while
820              * having an offset less than two means that the code works with
821              * the value on stack which is to be removed.
822              */
823             if ((E->Use & REG_SP) != 0 &&
824                 (E->AM != AM65_ZP_INDY || RegValIsUnknown (E->RI->In.RegY) ||
825                  E->RI->In.RegY < 2)) {
826
827                 /* All this stuff is not allowed in a sequence */
828                 InSeq = 0;
829
830             } else if (E->OPC == OP65_JSR) {
831
832                 /* Subroutine call: Check if this is one of our functions */
833                 const OptFuncDesc* F = FindFunc (E->Arg);
834                 if (F) {
835
836                     StackOpData Data;
837                     int PreCondOk = 1;
838
839                     /* Check the flags */
840                     if ((F->Flags & STOP_A_UNUSED) != 0 && RegAUsed (S, I+1)) {
841                         /* Cannot optimize */
842                         PreCondOk = 0;
843                     } else if ((F->Flags & STOP_A_KNOWN) != 0 && RegValIsUnknown (E->RI->In.RegA)) {
844                         /* Cannot optimize */
845                         PreCondOk = 0;
846                     } else if ((F->Flags & STOP_X_ZERO) != 0 && E->RI->In.RegX != 0) {
847                         /* Cannot optimize */
848                         PreCondOk = 0;
849                     }
850
851                     /* Determine the zero page locations to use */
852                     if (PreCondOk) {
853                         UsedRegs |= GetRegInfo (S, I+1, REG_SREG | REG_PTR1 | REG_PTR2);
854                         if ((UsedRegs & REG_SREG) == REG_NONE) {
855                             /* SREG is available */
856                             Data.ZPLo = "sreg";
857                             Data.ZPHi = "sreg+1";
858                         } else if ((UsedRegs & REG_PTR1) == REG_NONE) {
859                             Data.ZPLo = "ptr1";
860                             Data.ZPHi = "ptr1+1";
861                         } else if ((UsedRegs & REG_PTR2) == REG_NONE) {
862                             Data.ZPLo = "ptr2";
863                             Data.ZPHi = "ptr2+1";
864                         } else {
865                             /* No registers available */
866                             PreCondOk = 0;
867                         }
868                     }
869
870                     /* Determine if we have a basic block */
871                     if (PreCondOk) {
872                         PreCondOk = CS_IsBasicBlock (S, Push, I);
873                     }
874
875                     /* If preconditions are ok, call the optimizer function */
876                     if (PreCondOk) {
877
878                         /* Adjust stack offsets */
879                         Data.OpIndex = I + AdjustStackOffset (S, Push, I, 2);
880
881                         /* Prepare the remainder of the data structure */
882                         Data.Code      = S;
883                         Data.Flags     = 0;
884                         Data.PushIndex = Push;
885                         Data.PrevEntry = CS_GetPrevEntry (S, Data.PushIndex);
886                         Data.PushEntry = CS_GetEntry (S, Data.PushIndex);
887                         Data.OpEntry   = E;
888                         Data.NextEntry = CS_GetNextEntry (S, Data.OpIndex);
889
890                         /* Call the optimizer function */
891                         Changes += F->Func (&Data);
892
893                         /* Regenerate register info */
894                         CS_GenRegInfo (S);
895                     }
896
897                     /* End of sequence */
898                     InSeq = 0;
899
900                 } else if (strcmp (E->Arg, "pushax") == 0) {
901                     /* Restart the sequence */
902                     Push     = I;
903                     UsedRegs = REG_NONE;
904                 } else if (HarmlessCall (E->Arg)) {
905                     /* Track zeropage register usage */
906                     UsedRegs |= (E->Use | E->Chg);
907                 } else {
908                     /* A call to an unkown subroutine ends the sequence */
909                     InSeq = 0;
910                 }
911
912             } else {
913                 /* Other stuff: Track zeropage register usage */
914                 UsedRegs |= (E->Use | E->Chg);
915             }
916
917         } else if (CE_IsCallTo (E, "pushax")) {
918
919             /* This starts a sequence */
920             Push     = I;
921             UsedRegs = REG_NONE;
922             InSeq    = 1;
923
924         }
925
926         /* Next entry */
927         ++I;
928
929     }
930
931     /* Free the register info */
932     CS_FreeRegInfo (S);
933
934     /* Return the number of changes made */
935     return Changes;
936 }
937
938
939