]> git.sur5r.net Git - cc65/blob - src/cc65/coptstop.c
Fixed compiler warnings
[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     X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI);
485     InsertEntry (D, X, D->OpIndex+2);
486     if (RegValIsKnown (D->OpEntry->RI->In.RegX)) {
487         /* Value of X is known */
488         const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegX);
489         X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, D->OpEntry->LI);
490     } else {
491         /* Value unknown */
492         X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
493     }
494     InsertEntry (D, X, D->OpIndex+3);
495     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI);
496     InsertEntry (D, X, D->OpIndex+4);
497
498     /* Remove the push and the call to the staspidx function */
499     RemovePushAndOp (D);
500
501     /* We changed the sequence */
502     return 1;
503 }
504
505
506
507 static unsigned Opt_tosaddax (StackOpData* D)
508 /* Optimize the tosaddax sequence if possible */
509 {
510     CodeEntry*  X;
511
512
513     /* We need the entry behind the add */
514     CHECK (D->NextEntry != 0);
515
516     /* Check the entry before the push. If it's a lda instruction with an
517      * addressing mode that allows us to replace it, we may use this
518      * location for the op and must not save the value in the zero page
519      * location.
520      */
521     CheckDirectOp (D);
522
523     /* Store the value into the zeropage instead of pushing it */
524     ReplacePushByStore (D);
525
526     /* Inline the add */
527     D->IP = D->OpIndex+1;
528     X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, D->OpEntry->LI);
529     InsertEntry (D, X, D->IP++);
530
531     /* Low byte */
532     AddOpLow (D, OP65_ADC);
533
534     /* High byte */
535     if (D->PushEntry->RI->In.RegX == 0) {
536         /* The high byte is the value in X plus the carry */
537         CodeLabel* L = CS_GenLabel (D->Code, D->NextEntry);
538         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
539         InsertEntry (D, X, D->IP++);
540         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
541         InsertEntry (D, X, D->IP++);
542     } else if (D->OpEntry->RI->In.RegX == 0) {
543         /* The high byte is that of the first operand plus carry */
544         CodeLabel* L;
545         if (RegValIsKnown (D->PushEntry->RI->In.RegX)) {
546             /* Value of first op high byte is known */
547             const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX);
548             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
549         } else {
550             /* Value of first op high byte is unknown */
551             X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
552         }
553         InsertEntry (D, X, D->IP++);
554         L = CS_GenLabel (D->Code, D->NextEntry);
555         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
556         InsertEntry (D, X, D->IP++);
557         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
558         InsertEntry (D, X, D->IP++);
559     } else {
560         /* High byte is unknown */
561         AddOpHigh (D, OP65_ADC);
562     }
563
564     /* Remove the push and the call to the tosaddax function */
565     RemovePushAndOp (D);
566
567     /* We changed the sequence */
568     return 1;
569 }
570
571
572
573 static unsigned Opt_tosandax (StackOpData* D)
574 /* Optimize the tosandax 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 and, low byte */
589     D->IP = D->OpIndex + 1;
590     AddOpLow (D, OP65_AND);
591
592     /* High byte */
593     if (D->PushEntry->RI->In.RegX == 0 || D->OpEntry->RI->In.RegX == 0) {
594         /* The high byte is zero */
595         X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
596         InsertEntry (D, X, D->IP++);
597     } else {
598         /* High byte is unknown */
599         AddOpHigh (D, OP65_AND);
600     }
601
602     /* Remove the push and the call to the tosandax function */
603     RemovePushAndOp (D);
604
605     /* We changed the sequence */
606     return 1;
607 }
608
609
610
611 static unsigned Opt_tosorax (StackOpData* D)
612 /* Optimize the tosorax sequence if possible */
613 {
614     CodeEntry*  X;
615
616     /* Check the entry before the push. If it's a lda instruction with an
617      * addressing mode that allows us to replace it, we may use this
618      * location for the op and must not save the value in the zero page
619      * location.
620      */
621     CheckDirectOp (D);
622
623     /* Store the value into the zeropage instead of pushing it */
624     ReplacePushByStore (D);
625
626     /* Inline the or, low byte */
627     D->IP = D->OpIndex + 1;
628     AddOpLow (D, OP65_ORA);
629
630     /* High byte */
631     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
632         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
633         /* Both values known, precalculate the result */
634         unsigned char Result = D->PushEntry->RI->In.RegX | D->OpEntry->RI->In.RegX;
635         const char* Arg = MakeHexArg (Result);
636         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
637         InsertEntry (D, X, D->IP++);
638     } else if (D->PushEntry->RI->In.RegX != 0) {
639         /* High byte is unknown */
640         AddOpHigh (D, OP65_ORA);
641     }
642
643     /* Remove the push and the call to the tosorax function */
644     RemovePushAndOp (D);
645
646     /* We changed the sequence */
647     return 1;
648 }
649
650
651
652 static unsigned Opt_tosxorax (StackOpData* D)
653 /* Optimize the tosxorax sequence if possible */
654 {
655     CodeEntry*  X;
656
657     /* Check the entry before the push. If it's a lda instruction with an
658      * addressing mode that allows us to replace it, we may use this
659      * location for the op and must not save the value in the zero page
660      * location.
661      */
662     CheckDirectOp (D);
663
664     /* Store the value into the zeropage instead of pushing it */
665     ReplacePushByStore (D);
666
667     /* Inline the xor, low byte */
668     D->IP = D->OpIndex + 1;
669     AddOpLow (D, OP65_EOR);
670
671     /* High byte */
672     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
673         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
674         /* Both values known, precalculate the result */
675         const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX ^ D->OpEntry->RI->In.RegX);
676         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
677         InsertEntry (D, X, D->IP++);
678     } else if (D->PushEntry->RI->In.RegX != 0) {
679         /* High byte is unknown */
680         AddOpHigh (D, OP65_EOR);
681     }
682
683     /* Remove the push and the call to the tosandax function */
684     RemovePushAndOp (D);
685
686     /* We changed the sequence */
687     return 1;
688 }
689
690
691
692 /*****************************************************************************/
693 /*                                   Code                                    */
694 /*****************************************************************************/
695
696
697
698 /* Flags for the functions */
699 typedef enum {
700     STOP_NONE       = 0x00,     /* Nothing special */
701     STOP_A_UNUSED   = 0x01,     /* Call only if a unused later */
702     STOP_A_KNOWN    = 0x02,     /* Call only if A is known */
703     STOP_X_ZERO     = 0x04      /* Call only if X is zero */
704 } STOP_FLAGS;
705
706
707 typedef unsigned (*OptFunc) (StackOpData* D);
708 typedef struct OptFuncDesc OptFuncDesc;
709 struct OptFuncDesc {
710     const char*     Name;   /* Name of the replaced runtime function */
711     OptFunc         Func;   /* Function pointer */
712     STOP_FLAGS      Flags;  /* Flags */
713 };
714
715 static const OptFuncDesc FuncTable[] = {
716     { "__bzero",    Opt___bzero,   STOP_NONE     },
717     { "staspidx",   Opt_staspidx,  STOP_NONE     },
718     { "staxspidx",  Opt_staxspidx, STOP_A_UNUSED },
719     { "tosaddax",   Opt_tosaddax,  STOP_NONE     },
720     { "tosandax",   Opt_tosandax,  STOP_NONE     },
721     { "tosorax",    Opt_tosorax,   STOP_NONE     },
722     { "tosxorax",   Opt_tosxorax,  STOP_NONE     },
723 };
724 #define FUNC_COUNT (sizeof(FuncTable) / sizeof(FuncTable[0]))
725
726
727
728 static int CmpFunc (const void* Key, const void* Func)
729 /* Compare function for bsearch */
730 {
731     return strcmp (Key, ((const OptFuncDesc*) Func)->Name);
732 }
733
734
735
736 static const OptFuncDesc* FindFunc (const char* Name)
737 /* Find the function with the given name. Return a pointer to the table entry
738  * or NULL if the function was not found.
739  */
740 {
741     return bsearch (Name, FuncTable, FUNC_COUNT, sizeof(OptFuncDesc), CmpFunc);
742 }
743
744
745
746 static int CmpHarmless (const void* Key, const void* Entry)
747 /* Compare function for bsearch */
748 {
749     return strcmp (Key, *(const char**)Entry);
750 }
751
752
753
754 static int HarmlessCall (const char* Name)
755 /* Check if this is a call to a harmless subroutine that will not interrupt
756  * the pushax/op sequence when encountered.
757  */
758 {
759     static const char* Tab[] = {
760         "ldaxidx",
761         "ldaxysp",
762         "negax",
763     };
764
765     void* R = bsearch (Name,
766                        Tab,
767                        sizeof (Tab) / sizeof (Tab[0]),
768                        sizeof (Tab[0]),
769                        CmpHarmless);
770     return (R != 0);
771 }
772
773
774
775 /*****************************************************************************/
776 /*                                   Code                                    */
777 /*****************************************************************************/
778
779
780
781 unsigned OptStackOps (CodeSeg* S)
782 /* Optimize operations that take operands via the stack */
783 {
784     unsigned    Changes = 0;    /* Number of changes in one run */
785     int         InSeq = 0;      /* Inside a sequence */
786     unsigned    Push = 0;       /* Index of pushax */
787     unsigned    UsedRegs = 0;   /* Zeropage registers used in sequence */
788     unsigned    I;
789
790
791     /* Generate register info */
792     CS_GenRegInfo (S);
793
794     /* Look for a call to pushax followed by a call to some other function
795      * that takes it's first argument on the stack, and the second argument
796      * in the primary register.
797      * It depends on the code between the two if we can handle/transform the
798      * sequence, so check this code for the following list of things:
799      *
800      *  - the range must be a basic block (one entry, one exit)
801      *  - there may not be accesses to local variables with unknown
802      *    offsets (because we have to adjust these offsets).
803      *  - no subroutine calls
804      *  - no jump labels
805      *
806      * Since we need a zero page register later, do also check the
807      * intermediate code for zero page use.
808      */
809     I = 0;
810     while (I < CS_GetEntryCount (S)) {
811
812         /* Get the next entry */
813         CodeEntry* E = CS_GetEntry (S, I);
814
815         /* Handling depends if we're inside a sequence or not */
816         if (InSeq) {
817
818             /* If we are using the stack, and we don't have "indirect Y"
819              * addressing mode, or the value of Y is unknown, or less than
820              * two, we cannot cope with this piece of code. Having an unknown
821              * value of Y means that we cannot correct the stack offset, while
822              * having an offset less than two means that the code works with
823              * the value on stack which is to be removed.
824              */
825             if ((E->Use & REG_SP) != 0 &&
826                 (E->AM != AM65_ZP_INDY || RegValIsUnknown (E->RI->In.RegY) ||
827                  E->RI->In.RegY < 2)) {
828
829                 /* All this stuff is not allowed in a sequence */
830                 InSeq = 0;
831
832             } else if (E->OPC == OP65_JSR) {
833
834                 /* Subroutine call: Check if this is one of our functions */
835                 const OptFuncDesc* F = FindFunc (E->Arg);
836                 if (F) {
837
838                     StackOpData Data;
839                     int PreCondOk = 1;
840
841                     /* Check the flags */
842                     if ((F->Flags & STOP_A_UNUSED) != 0 && RegAUsed (S, I+1)) {
843                         /* Cannot optimize */
844                         PreCondOk = 0;
845                     } else if ((F->Flags & STOP_A_KNOWN) != 0 && RegValIsUnknown (E->RI->In.RegA)) {
846                         /* Cannot optimize */
847                         PreCondOk = 0;
848                     } else if ((F->Flags & STOP_X_ZERO) != 0 && E->RI->In.RegX != 0) {
849                         /* Cannot optimize */
850                         PreCondOk = 0;
851                     }
852
853                     /* Determine the zero page locations to use */
854                     if (PreCondOk) {
855                         UsedRegs |= GetRegInfo (S, I+1, REG_SREG | REG_PTR1 | REG_PTR2);
856                         if ((UsedRegs & REG_SREG) == REG_NONE) {
857                             /* SREG is available */
858                             Data.ZPLo = "sreg";
859                             Data.ZPHi = "sreg+1";
860                         } else if ((UsedRegs & REG_PTR1) == REG_NONE) {
861                             Data.ZPLo = "ptr1";
862                             Data.ZPHi = "ptr1+1";
863                         } else if ((UsedRegs & REG_PTR2) == REG_NONE) {
864                             Data.ZPLo = "ptr2";
865                             Data.ZPHi = "ptr2+1";
866                         } else {
867                             /* No registers available */
868                             PreCondOk = 0;
869                         }
870                     }
871
872                     /* Determine if we have a basic block */
873                     if (PreCondOk) {
874                         PreCondOk = CS_IsBasicBlock (S, Push, I);
875                     }
876
877                     /* If preconditions are ok, call the optimizer function */
878                     if (PreCondOk) {
879
880                         /* Adjust stack offsets */
881                         Data.OpIndex = I + AdjustStackOffset (S, Push, I, 2);
882
883                         /* Prepare the remainder of the data structure */
884                         Data.Code      = S;
885                         Data.Flags     = 0;
886                         Data.PushIndex = Push;
887                         Data.PrevEntry = CS_GetPrevEntry (S, Data.PushIndex);
888                         Data.PushEntry = CS_GetEntry (S, Data.PushIndex);
889                         Data.OpEntry   = E;
890                         Data.NextEntry = CS_GetNextEntry (S, Data.OpIndex);
891
892                         /* Call the optimizer function */
893                         Changes += F->Func (&Data);
894
895                         /* Regenerate register info */
896                         CS_GenRegInfo (S);
897                     }
898
899                     /* End of sequence */
900                     InSeq = 0;
901
902                 } else if (strcmp (E->Arg, "pushax") == 0) {
903                     /* Restart the sequence */
904                     Push     = I;
905                     UsedRegs = REG_NONE;
906                 } else if (HarmlessCall (E->Arg)) {
907                     /* Track zeropage register usage */
908                     UsedRegs |= (E->Use | E->Chg);
909                 } else {
910                     /* A call to an unkown subroutine ends the sequence */
911                     InSeq = 0;
912                 }
913
914             } else {
915                 /* Other stuff: Track zeropage register usage */
916                 UsedRegs |= (E->Use | E->Chg);
917             }
918
919         } else if (CE_IsCallTo (E, "pushax")) {
920
921             /* This starts a sequence */
922             Push     = I;
923             UsedRegs = REG_NONE;
924             InSeq    = 1;
925
926         }
927
928         /* Next entry */
929         ++I;
930
931     }
932
933     /* Free the register info */
934     CS_FreeRegInfo (S);
935
936     /* Return the number of changes made */
937     return Changes;
938 }
939
940
941