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