struct / union in initializer, RFE #901.
[sdcc.git] / sdcc / src / z80 / ralloc.c
blobb658a39a62bac2d180bfbedfe29ae46f5c939047
1 /** @name Z80 Register allocation functions.
2 @author Michael Hope
4 Note: much of this is ripped straight from Sandeep's mcs51 code.
6 This code maps the virtual symbols and code onto the real
7 hardware. It allocates based on usage and how long the variable
8 lives into registers or temporary memory on the stack.
10 On the Z80 hl and ix and a are reserved for the code generator,
11 leaving bc and de for allocation. iy is unusable due to currently
12 as it's only addressable as a pair. The extra register pressure
13 from reserving hl is made up for by how much easier the sub
14 operations become. You could swap hl for iy if the undocumented
15 iyl/iyh instructions are available.
17 The stack frame is the common ix-bp style. Basically:
19 ix+4+n: param 1
20 ix+4: param 0
21 ix+2: return address
22 ix+0: calling functions ix
23 ix-n: local variables
24 ...
25 sp: end of local variables
27 There is currently no support for bit spaces or banked functions.
29 This program is free software; you can redistribute it and/or
30 modify it under the terms of the GNU General Public License as
31 published by the Free Software Foundation; either version 2, or (at
32 your option) any later version. This program is distributed in the
33 hope that it will be useful, but WITHOUT ANY WARRANTY; without even
34 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
35 PURPOSE. See the GNU General Public License for more details.
37 You should have received a copy of the GNU General Public License
38 along with this program; if not, write to the Free Software
39 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
40 USA. In other words, you are welcome to use, share and improve
41 this program. You are forbidden to forbid anyone else to use,
42 share and improve what you give them. Help stamp out
43 software-hoarding!
46 #include "z80.h"
47 #include "SDCCicode.h"
48 #include "dbuf_string.h"
50 /* Flags to turn off optimisations.
52 enum
54 DISABLE_PACK_ACC = 0,
55 DISABLE_PACK_ASSIGN = 0,
56 DISABLE_PACK_ONE_USE = 0,
57 DISABLE_PACK_HL = 0,
58 DISABLE_PACK_IY = 0
61 /* Flags to turn on debugging code.
63 enum
65 D_ALLOC = 0,
66 D_ALLOC2 = 0,
69 #if 1
70 #define D(_a, _s) if (_a) { printf _s; fflush(stdout); }
71 #else
72 #define D(_a, _s)
73 #endif
75 /** Local static variables */
76 static struct
78 bitVect *spiltSet;
79 set *stackSpil;
80 bitVect *regAssigned;
81 bitVect *totRegAssigned; /* final set of LRs that got into registers */
82 short blockSpil;
83 int slocNum;
84 /* registers used in a function */
85 bitVect *funcrUsed;
86 int stackExtend;
87 int dataExtend;
88 int nRegs;
89 } _G;
91 reg_info sm83_regs[] = {
92 {REG_GPR, A_IDX, "a", 1},
93 {REG_GPR, C_IDX, "c", 1},
94 {REG_GPR, B_IDX, "b", 1},
95 {REG_GPR, E_IDX, "e", 1},
96 {REG_GPR, D_IDX, "d", 1},
97 {REG_GPR, L_IDX, "l", 1},
98 {REG_GPR, H_IDX, "h", 1},
99 {REG_CND, CND_IDX, "c", 1}
102 reg_info z80_regs[] = {
103 {REG_GPR, A_IDX, "a", 1},
104 {REG_GPR, C_IDX, "c", 1},
105 {REG_GPR, B_IDX, "b", 1},
106 {REG_GPR, E_IDX, "e", 1},
107 {REG_GPR, D_IDX, "d", 1},
108 {REG_GPR, L_IDX, "l", 1},
109 {REG_GPR, H_IDX, "h", 1},
110 {REG_GPR, IYL_IDX, "iyl", 1},
111 {REG_GPR, IYH_IDX, "iyh", 1},
112 {REG_CND, CND_IDX, "c", 1}
115 reg_info *regsZ80;
117 /** Number of usable registers (all but C) */
118 #define Z80_MAX_REGS ((sizeof (z80_regs) / sizeof (z80_regs[0]))-1)
119 #define SM83_MAX_REGS ((sizeof (sm83_regs) / sizeof (sm83_regs[0]))-1)
121 void z80SpillThis (symbol *);
122 static void freeAllRegs ();
124 /** Returns pointer to register wit index number
126 reg_info *
127 regWithIdx (int idx)
129 int i;
131 for (i = C_IDX; i < _G.nRegs; i++)
133 if (regsZ80[i].rIdx == idx)
135 return &regsZ80[i];
139 wassertl (0, "regWithIdx not found");
140 exit (1);
143 /** Frees a register.
145 static void
146 freeReg (reg_info *reg)
148 wassert (!reg->isFree);
149 reg->isFree = 1;
150 D (D_ALLOC, ("freeReg: freed %p\n", reg));
153 /** noOverLap - will iterate through the list looking for over lap
155 static int
156 noOverLap (set *itmpStack, symbol *fsym)
158 symbol *sym;
160 for (sym = setFirstItem (itmpStack); sym; sym = setNextItem (itmpStack))
162 if (bitVectBitValue (sym->clashes, fsym->key))
163 return 0;
164 #if 0
165 // if sym starts before (or on) our end point
166 // and ends after (or on) our start point,
167 // it is an overlap.
168 if (sym->liveFrom <= fsym->liveTo && sym->liveTo >= fsym->liveFrom)
170 return 0;
172 #endif
174 return 1;
177 /*-----------------------------------------------------------------*/
178 /* isFree - will return 1 if the a free spil location is found */
179 /*-----------------------------------------------------------------*/
180 DEFSETFUNC (isFree)
182 symbol *sym = item;
183 V_ARG (symbol **, sloc);
184 V_ARG (symbol *, fsym);
186 /* if already found */
187 if (*sloc)
188 return 0;
190 /* if it is free && and the itmp assigned to
191 this does not have any overlapping live ranges
192 with the one currently being assigned and
193 the size can be accommodated */
194 if (sym->isFree && noOverLap (sym->usl.itmpStack, fsym) && getSize (sym->type) >= getSize (fsym->type))
196 *sloc = sym;
197 return 1;
200 return 0;
203 /*-----------------------------------------------------------------*/
204 /* createStackSpil - create a location on the stack to spil */
205 /*-----------------------------------------------------------------*/
206 static symbol *
207 createStackSpil (symbol *sym)
209 symbol *sloc = NULL;
210 struct dbuf_s dbuf;
212 D (D_ALLOC, ("createStackSpil: for sym %p (%s)\n", sym, sym->name));
214 /* first go try and find a free one that is already
215 existing on the stack */
216 if (applyToSet (_G.stackSpil, isFree, &sloc, sym) && USE_OLDSALLOC)
218 /* found a free one : just update & return */
219 sym->usl.spillLoc = sloc;
220 sym->stackSpil = 1;
221 sloc->isFree = 0;
222 addSetHead (&sloc->usl.itmpStack, sym);
223 D (D_ALLOC, ("createStackSpil: found existing\n"));
224 return sym;
227 /* could not then have to create one , this is the hard part
228 we need to allocate this on the stack : this is really a
229 hack!! but cannot think of anything better at this time */
231 dbuf_init (&dbuf, 128);
232 dbuf_printf (&dbuf, "sloc%d", _G.slocNum++);
233 sloc = newiTemp (dbuf_c_str (&dbuf));
234 dbuf_destroy (&dbuf);
236 /* set the type to the spilling symbol */
237 sloc->type = copyLinkChain (sym->type);
238 sloc->etype = getSpec (sloc->type);
239 SPEC_SCLS (sloc->etype) = S_AUTO;
240 SPEC_EXTR (sloc->etype) = 0;
241 SPEC_STAT (sloc->etype) = 0;
242 SPEC_VOLATILE (sloc->etype) = 0;
244 allocLocal (sloc);
246 sloc->isref = 1; /* to prevent compiler warning */
248 wassertl (currFunc, "Local variable used outside of function.");
250 /* if it is on the stack then update the stack */
251 if (IN_STACK (sloc->etype))
253 if (currFunc)
254 currFunc->stack += getSize (sloc->type);
255 _G.stackExtend += getSize (sloc->type);
257 else
259 _G.dataExtend += getSize (sloc->type);
262 /* add it to the stackSpil set */
263 addSetHead (&_G.stackSpil, sloc);
264 sym->usl.spillLoc = sloc;
265 sym->stackSpil = 1;
267 /* add it to the set of itempStack set
268 of the spill location */
269 addSetHead (&sloc->usl.itmpStack, sym);
271 D (D_ALLOC, ("createStackSpil: created new %s for %s\n", sloc->name, sym->name));
272 return sym;
275 /*-----------------------------------------------------------------*/
276 /* spillThis - spils a specific operand */
277 /*-----------------------------------------------------------------*/
278 void
279 z80SpillThis (symbol * sym)
281 int i;
283 D (D_ALLOC, ("z80SpillThis: spilling %p (%s)\n", sym, sym->name));
285 /* if this is rematerializable or has a spillLocation
286 we are okay, else we need to create a spillLocation
287 for it */
288 if (!(sym->remat || sym->usl.spillLoc) || (sym->usl.spillLoc && !sym->usl.spillLoc->onStack)) // z80 port currently only supports on-stack spill locations in code generation.
289 createStackSpil (sym);
290 else
291 D (D_ALLOC, ("Already has spilllocation %p, %s\n", sym->usl.spillLoc, sym->usl.spillLoc->name));
293 /* mark it as spilt & put it in the spilt set */
294 sym->isspilt = sym->spillA = 1;
295 _G.spiltSet = bitVectSetBit (_G.spiltSet, sym->key);
297 bitVectUnSetBit (_G.regAssigned, sym->key);
298 bitVectUnSetBit (_G.totRegAssigned, sym->key);
300 for (i = 0; i < sym->nRegs; i++)
302 if (sym->regs[i])
304 freeReg (sym->regs[i]);
305 sym->regs[i] = NULL;
309 if (sym->usl.spillLoc && !sym->remat)
311 sym->usl.spillLoc->allocreq++;
313 return;
316 /** Symbol has a given register.
318 static bool
319 symHasReg (symbol *sym, const reg_info *reg)
321 int i;
323 for (i = 0; i < sym->nRegs; i++)
324 if (sym->regs[i] == reg)
325 return TRUE;
327 return FALSE;
330 /** Check the live to and if they have registers & are not spilt then
331 free up the registers
333 static void
334 deassignLRs (iCode *ic, eBBlock *ebp)
336 symbol *sym;
337 int k;
339 for (sym = hTabFirstItem (liveRanges, &k); sym; sym = hTabNextItem (liveRanges, &k))
342 symbol *psym = NULL;
343 /* if it does not end here */
344 if (sym->liveTo > ic->seq)
345 continue;
347 /* if it was spilt on stack then we can
348 mark the stack spil location as free */
349 if (sym->isspilt)
351 if (sym->stackSpil)
353 sym->usl.spillLoc->isFree = 1;
354 sym->stackSpil = 0;
356 continue;
359 if (!bitVectBitValue (_G.regAssigned, sym->key))
360 continue;
362 D (D_ALLOC, ("deassignLRs: in loop on sym %p nregs %u\n", sym, sym->nRegs));
364 if (sym->nRegs)
366 int i = 0;
368 bitVectUnSetBit (_G.regAssigned, sym->key);
370 /* free the remaining */
371 for (; i < sym->nRegs; i++)
373 if (psym)
375 if (!symHasReg (psym, sym->regs[i]))
376 freeReg (sym->regs[i]);
378 else
379 freeReg (sym->regs[i]);
385 /*------------------------------------------------------------------*/
386 /* verifyRegsAssigned - make sure an iTemp is properly initialized; */
387 /* it should either have registers or have beed spilled. Otherwise, */
388 /* there was an uninitialized variable, so just spill this to get */
389 /* the operand in a valid state. */
390 /*------------------------------------------------------------------*/
391 static void
392 verifyRegsAssigned (operand *op, iCode *ic)
394 symbol *sym;
396 if (!op)
397 return;
398 if (!IS_ITEMP (op))
399 return;
401 sym = OP_SYMBOL (op);
402 if (sym->isspilt)
403 return;
404 if (!sym->nRegs)
405 return;
406 if (sym->regs[0])
407 return;
409 z80SpillThis (sym);
412 /*-----------------------------------------------------------------*/
413 /* rUmaskForOp :- returns register mask for an operand */
414 /*-----------------------------------------------------------------*/
415 bitVect *
416 rUmaskForOp (const operand * op)
418 bitVect *rumask;
419 symbol *sym;
420 int j;
422 /* only temporaries are assigned registers */
423 if (!IS_ITEMP (op))
424 return NULL;
426 sym = OP_SYMBOL_CONST (op);
428 /* if spilt or no registers assigned to it
429 then nothing */
430 if (sym->isspilt || !sym->nRegs)
431 return NULL;
433 rumask = newBitVect (IS_SM83 ? SM83_MAX_REGS : Z80_MAX_REGS);
435 for (j = 0; j < sym->nRegs; j++)
437 if (!(sym->regs[j]) || sym->regs[j]->rIdx < 0 || sym->regs[j]->rIdx > CND_IDX)
439 werror (E_INTERNAL_ERROR, __FILE__, __LINE__, "rUmaskForOp: Register not found");
440 exit (0);
442 rumask = bitVectSetBit (rumask, sym->regs[j]->rIdx);
445 return rumask;
448 bitVect *
449 z80_rUmaskForOp (const operand * op)
451 return rUmaskForOp (op);
454 /** Returns bit vector of registers used in iCode.
456 bitVect *
457 regsUsedIniCode (iCode * ic)
459 bitVect *rmask = newBitVect (IS_SM83 ? SM83_MAX_REGS : Z80_MAX_REGS);
461 /* of all other cases */
462 if (IC_LEFT (ic))
463 rmask = bitVectUnion (rmask, rUmaskForOp (IC_LEFT (ic)));
465 if (IC_RIGHT (ic))
466 rmask = bitVectUnion (rmask, rUmaskForOp (IC_RIGHT (ic)));
468 if (IC_RESULT (ic))
469 rmask = bitVectUnion (rmask, rUmaskForOp (IC_RESULT (ic)));
471 return rmask;
474 /*-----------------------------------------------------------------*/
475 /* regTypeNum - computes the type & number of registers required */
476 /*-----------------------------------------------------------------*/
477 static void
478 regTypeNum (void)
480 symbol *sym;
481 int k;
483 /* for each live range do */
484 for (sym = hTabFirstItem (liveRanges, &k); sym; sym = hTabNextItem (liveRanges, &k))
486 /* if used zero times then no registers needed */
487 if ((sym->liveTo - sym->liveFrom) == 0 && getSize (sym->type) <= 4)
488 continue;
489 else if ((sym->liveTo - sym->liveFrom) == 0 && bitVectnBitsOn (sym->defs) <= 1)
491 iCode *dic = hTabItemWithKey (iCodehTab, bitVectFirstBit (sym->defs));
492 if (!dic || dic->op != CALL && dic->op != PCALL)
493 continue;
494 if (IS_STRUCT (sym->type)) // We found an unused return value of struct or union type.
496 z80SpillThis (sym);
497 continue;
501 D (D_ALLOC, ("regTypeNum: loop on sym %p\n", sym));
503 /* if the live range is a temporary */
504 if (sym->isitmp)
506 /* if the type is marked as a conditional */
507 if (sym->regType == REG_CND)
508 continue;
510 /* if used in return only then we don't
511 need registers */
512 if (sym->ruonly || sym->accuse)
514 if (IS_AGGREGATE (sym->type) || sym->isptr)
515 sym->type = aggrToPtr (sym->type, FALSE);
516 continue;
519 /* if not then we require registers */
520 D (D_ALLOC,
521 ("regTypeNum: isagg %u nRegs %u type %p\n", IS_AGGREGATE (sym->type) || sym->isptr, sym->nRegs, sym->type));
522 sym->nRegs =
523 ((IS_AGGREGATE (sym->type)
524 || sym->isptr) ? getSize (sym->type = aggrToPtr (sym->type, FALSE)) : getSize (sym->type));
525 D (D_ALLOC, ("regTypeNum: setting nRegs of %s (%p) to %u\n", sym->name, sym, sym->nRegs));
527 D (D_ALLOC, ("regTypeNum: setup to assign regs sym %p\n", sym));
529 if (sym->nRegs > 8)
531 fprintf (stderr, "allocated more than 8 registers for type ");
532 printTypeChain (sym->type, stderr);
533 fprintf (stderr, "\n");
536 /* determine the type of register required */
537 /* Always general purpose */
538 sym->regType = REG_GPR;
540 else
542 /* for the first run we don't provide */
543 /* registers for true symbols we will */
544 /* see how things go */
545 D (D_ALLOC, ("regTypeNum: #2 setting num of %p to 0\n", sym));
546 sym->nRegs = 0;
551 /** Mark all registers as free.
553 static void
554 freeAllRegs ()
556 int i;
558 D (D_ALLOC, ("freeAllRegs: running.\n"));
560 for (i = C_IDX; i < _G.nRegs; i++)
561 regsZ80[i].isFree = 1;
564 /*-----------------------------------------------------------------*/
565 /* deallocStackSpil - this will set the stack pointer back */
566 /*-----------------------------------------------------------------*/
567 static
568 DEFSETFUNC (deallocStackSpil)
570 symbol *sym = item;
572 deallocLocal (sym);
573 return 0;
576 /** Register reduction for assignment.
578 static int
579 packRegsForAssign (iCode * ic, eBBlock * ebp)
581 iCode *dic, *sic;
583 D (D_ALLOC, ("packRegsForAssign: running on ic %p\n", ic));
585 if (!IS_ITEMP (IC_RIGHT (ic)) || OP_SYMBOL (IC_RIGHT (ic))->isind || OP_LIVETO (IC_RIGHT (ic)) > ic->seq)
586 return 0;
588 /* Avoid having multiple named address spaces in one iCode. */
589 if (IS_SYMOP (IC_RESULT (ic)) && SPEC_ADDRSPACE (OP_SYMBOL (IC_RESULT (ic))->etype))
590 return 0;
592 /* find the definition of iTempNN scanning backwards if we find a
593 a use of the true symbol in before we find the definition then
594 we cannot */
595 for (dic = ic->prev; dic; dic = dic->prev)
597 /* PENDING: Don't pack across function calls. */
598 if (dic->op == CALL || dic->op == PCALL || dic->op == INLINEASM || dic->op == CRITICAL || dic->op == ENDCRITICAL)
600 dic = NULL;
601 break;
604 if (SKIP_IC2 (dic))
605 continue;
607 if (dic->op == IFX)
609 if (IS_SYMOP (IC_COND (dic)) &&
610 (IC_COND (dic)->key == IC_RESULT (ic)->key || IC_COND (dic)->key == IC_RIGHT (ic)->key))
612 dic = NULL;
613 break;
616 else
618 if (IS_TRUE_SYMOP (IC_RESULT (dic)) && IS_OP_VOLATILE (IC_RESULT (dic)))
620 dic = NULL;
621 break;
624 if (IS_SYMOP (IC_RESULT (dic)) && IC_RESULT (dic)->key == IC_RIGHT (ic)->key)
626 if (POINTER_SET (dic))
627 dic = NULL;
629 break;
632 if (IS_SYMOP (IC_RIGHT (dic)) &&
633 (IC_RIGHT (dic)->key == IC_RESULT (ic)->key || IC_RIGHT (dic)->key == IC_RIGHT (ic)->key))
635 dic = NULL;
636 break;
639 if (IS_SYMOP (IC_LEFT (dic)) &&
640 (IC_LEFT (dic)->key == IC_RESULT (ic)->key || IC_LEFT (dic)->key == IC_RIGHT (ic)->key))
642 dic = NULL;
643 break;
646 if (IS_SYMOP (IC_RESULT (dic)) && IC_RESULT (dic)->key == IC_RESULT (ic)->key)
648 dic = NULL;
649 break;
654 if (!dic)
655 return 0; /* did not find */
657 /* if assignment then check that right is not a bit */
658 if (ASSIGNMENT (ic) && !POINTER_SET (ic))
660 sym_link *etype = operandType (IC_RESULT (dic));
661 if (IS_BITFIELD (etype))
663 /* if result is a bit too then it's ok */
664 etype = operandType (IC_RESULT (ic));
665 if (!IS_BITFIELD (etype))
667 return 0;
672 /* Keep assignment if it is an sfr write - not all of code generation can deal with result in sfr */
673 if (IC_RESULT (ic) && IS_TRUE_SYMOP (IC_RESULT (ic)) && SPEC_OCLS (OP_SYMBOL (IC_RESULT (ic))->etype) && IN_REGSP (SPEC_OCLS (OP_SYMBOL (IC_RESULT (ic))->etype)) &&
674 (dic->op == LEFT_OP || dic->op == RIGHT_OP))
675 return 0;
677 /* found the definition */
679 /* delete from liverange table also
680 delete from all the points inbetween and the new
681 one */
682 for (sic = dic; sic != ic; sic = sic->next)
684 bitVectUnSetBit (sic->rlive, IC_RESULT (ic)->key);
685 if (IS_ITEMP (IC_RESULT (dic)))
686 bitVectSetBit (sic->rlive, IC_RESULT (dic)->key);
689 /* replace the result with the result of */
690 /* this assignment and remove this assignment */
691 bitVectUnSetBit (OP_SYMBOL (IC_RESULT (dic))->defs, dic->key);
692 IC_RESULT (dic) = IC_RESULT (ic);
694 if (IS_ITEMP (IC_RESULT (dic)) && OP_SYMBOL (IC_RESULT (dic))->liveFrom > dic->seq)
696 OP_SYMBOL (IC_RESULT (dic))->liveFrom = dic->seq;
699 remiCodeFromeBBlock (ebp, ic);
700 // PENDING: Check vs mcs51
701 bitVectUnSetBit (OP_SYMBOL (IC_RESULT (ic))->defs, ic->key);
702 hTabDeleteItem (&iCodehTab, ic->key, ic, DELETE_ITEM, NULL);
703 OP_DEFS (IC_RESULT (dic)) = bitVectSetBit (OP_DEFS (IC_RESULT (dic)), dic->key);
704 return 1;
707 /** Scanning backwards looks for first assig found.
709 iCode *
710 findAssignToSym (operand * op, iCode * ic)
712 iCode *dic;
714 for (dic = ic->prev; dic; dic = dic->prev)
717 /* if definition by assignment */
718 if (dic->op == '=' && !POINTER_SET (dic) && IC_RESULT (dic)->key == op->key)
719 /* && IS_TRUE_SYMOP(IC_RIGHT(dic)) */
722 /* we are interested only if defined in far space */
723 /* or in stack space in case of + & - */
725 /* if assigned to a non-symbol then return
726 true */
727 if (!IS_SYMOP (IC_RIGHT (dic)))
728 break;
730 /* if the symbol is in far space then
731 we should not */
732 if (isOperandInFarSpace (IC_RIGHT (dic)))
733 return NULL;
735 /* for + & - operations make sure that
736 if it is on the stack it is the same
737 as one of the three operands */
738 if ((ic->op == '+' || ic->op == '-') && OP_SYMBOL (IC_RIGHT (dic))->onStack)
741 if (IC_RESULT (ic)->key != IC_RIGHT (dic)->key &&
742 IC_LEFT (ic)->key != IC_RIGHT (dic)->key && IC_RIGHT (ic)->key != IC_RIGHT (dic)->key)
743 return NULL;
746 break;
750 /* if we find an usage then we cannot delete it */
751 if (IC_LEFT (dic) && IC_LEFT (dic)->key == op->key)
752 return NULL;
754 if (IC_RIGHT (dic) && IC_RIGHT (dic)->key == op->key)
755 return NULL;
757 if (POINTER_SET (dic) && IC_RESULT (dic)->key == op->key)
758 return NULL;
761 /* now make sure that the right side of dic
762 is not defined between ic & dic */
763 if (dic)
765 iCode *sic = dic->next;
767 for (; sic != ic; sic = sic->next)
768 if (IC_RESULT (sic) && IC_RESULT (sic)->key == IC_RIGHT (dic)->key)
769 return NULL;
772 return dic;
777 /** Will reduce some registers for single use.
779 static iCode *
780 packRegsForOneuse (iCode * ic, operand * op, eBBlock * ebp)
782 bitVect *uses;
783 iCode *dic, *sic;
785 // PENDING: Disable
786 D (D_ALLOC, ("packRegsForOneUse: running on ic %p\n", ic));
788 /* if returning a literal then do nothing */
789 if (!IS_SYMOP (op))
790 return NULL;
792 /* only upto 2 bytes since we cannot predict
793 the usage of b, & acc */
794 if (getSize (operandType (op)) > 2)
795 return NULL;
797 if (ic->op != RETURN && ic->op != SEND)
798 return NULL;
800 /* this routine will mark the a symbol as used in one
801 instruction use only && if the definition is local
802 (ie. within the basic block) && has only one definition &&
803 that definition is either a return value from a
804 function or does not contain any variables in
805 far space */
806 uses = bitVectCopy (OP_USES (op));
807 bitVectUnSetBit (uses, ic->key); /* take away this iCode */
808 if (!bitVectIsZero (uses)) /* has other uses */
809 return NULL;
811 /* if it has only one definition */
812 if (bitVectnBitsOn (OP_DEFS (op)) > 1)
813 return NULL; /* has more than one definition */
815 /* get that definition */
816 if (!(dic = hTabItemWithKey (iCodehTab, bitVectFirstBit (OP_DEFS (op)))))
817 return NULL;
819 /* found the definition now check if it is local */
820 if (dic->seq < ebp->fSeq || dic->seq > ebp->lSeq)
821 return NULL; /* non-local */
823 /* now check if it is the return from a function call */
824 if (dic->op == CALL || dic->op == PCALL)
826 if (ic->op != SEND && ic->op != RETURN && !POINTER_SET (ic) && !POINTER_GET (ic))
828 OP_SYMBOL (op)->ruonly = 1;
829 return dic;
831 dic = dic->next;
834 /* otherwise check that the definition does
835 not contain any symbols in far space */
836 if (isOperandInFarSpace (IC_LEFT (dic)) ||
837 isOperandInFarSpace (IC_RIGHT (dic)) || IS_OP_RUONLY (IC_LEFT (ic)) || IS_OP_RUONLY (IC_RIGHT (ic)))
839 return NULL;
842 /* if pointer set then make sure the pointer is one byte */
843 if (POINTER_SET (dic))
844 return NULL;
846 if (POINTER_GET (dic))
847 return NULL;
849 sic = dic;
851 /* also make sure the intervenening instructions
852 don't have any thing in far space */
853 for (dic = dic->next; dic && dic != ic; dic = dic->next)
855 /* if there is an intervening function call then no */
856 if (dic->op == CALL || dic->op == PCALL)
857 return NULL;
858 /* if pointer set then make sure the pointer
859 is one byte */
860 if (POINTER_SET (dic))
861 return NULL;
863 if (POINTER_GET (dic))
864 return NULL;
866 /* if address of & the result is remat the okay */
867 if (dic->op == ADDRESS_OF && OP_SYMBOL (IC_RESULT (dic))->remat)
868 continue;
870 /* if left or right or result is in far space */
871 if (isOperandInFarSpace (IC_LEFT (dic)) ||
872 isOperandInFarSpace (IC_RIGHT (dic)) ||
873 isOperandInFarSpace (IC_RESULT (dic)) ||
874 IS_OP_RUONLY (IC_LEFT (dic)) || IS_OP_RUONLY (IC_RIGHT (dic)) || IS_OP_RUONLY (IC_RESULT (dic)))
876 return NULL;
880 /* Fixes #2646174, but there might be a better way */
881 if (ic->op == SEND)
882 return NULL;
884 /* Fixes #2982135, but there might be a better way */
885 if (ic->op == RETURN)
886 return NULL;
888 OP_SYMBOL (op)->ruonly = 1;
889 return sic;
892 /*-----------------------------------------------------------------*/
893 /* isBitwiseOptimizable - requirements of JEAN LOUIS VERN */
894 /*-----------------------------------------------------------------*/
895 static bool
896 isBitwiseOptimizable (iCode * ic)
898 sym_link *rtype = getSpec (operandType (IC_RIGHT (ic)));
900 /* bitwise operations are considered optimizable
901 under the following conditions (Jean-Louis VERN)
903 x & lit
904 bit & bit
905 bit & x
906 bit ^ bit
907 bit ^ x
908 x ^ lit
909 x | lit
910 bit | bit
911 bit | x
913 if (IS_LITERAL (rtype))
914 return TRUE;
915 return FALSE;
918 /** Does some transformations to reduce register pressure.
920 static void
921 packRegisters (eBBlock * ebp)
923 iCode *ic;
924 int change = 0;
926 D (D_ALLOC, ("packRegisters: entered.\n"));
928 while (1 && !DISABLE_PACK_ASSIGN)
930 change = 0;
931 /* look for assignments of the form */
932 /* iTempNN = TRueSym (someoperation) SomeOperand */
933 /* .... */
934 /* TrueSym := iTempNN:1 */
935 for (ic = ebp->sch; ic; ic = ic->next)
937 /* find assignment of the form TrueSym := iTempNN:1 */
938 if (ic->op == '=' && !POINTER_SET (ic))
939 change += packRegsForAssign (ic, ebp);
941 if (!change)
942 break;
945 for (ic = ebp->sch; ic; ic = ic->next)
947 D (D_ALLOC, ("packRegisters: looping on ic %p\n", ic));
949 /* Safe: address of a true sym is always constant. */
950 /* if this is an itemp & result of a address of a true sym
951 then mark this as rematerialisable */
952 if (ic->op == ADDRESS_OF &&
953 IS_ITEMP (IC_RESULT (ic)) && bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) == 1 && !IS_PARM (IC_RESULT (ic)) /* The receiving of the parameter is not accounted for in DEFS */ &&
954 IS_TRUE_SYMOP (IC_LEFT (ic)))
956 OP_SYMBOL (IC_RESULT (ic))->remat = 1;
957 OP_SYMBOL (IC_RESULT (ic))->rematiCode = ic;
958 OP_SYMBOL (IC_RESULT (ic))->usl.spillLoc = NULL;
961 /* Safe: just propagates the remat flag */
962 /* if straight assignment then carry remat flag if this is the
963 only definition */
964 if (ic->op == '=' && !POINTER_SET (ic) && IS_SYMOP (IC_RIGHT (ic)) && OP_SYMBOL (IC_RIGHT (ic))->remat &&
965 !isOperandGlobal (IC_RESULT (ic)) && bitVectnBitsOn (OP_SYMBOL (IC_RESULT (ic))->defs) == 1 && !IS_PARM (IC_RESULT (ic)) && /* The receiving of the parameter is not accounted for in DEFS */
966 !OP_SYMBOL (IC_RESULT (ic))->addrtaken)
968 OP_SYMBOL (IC_RESULT (ic))->remat = OP_SYMBOL (IC_RIGHT (ic))->remat;
969 OP_SYMBOL (IC_RESULT (ic))->rematiCode = OP_SYMBOL (IC_RIGHT (ic))->rematiCode;
972 /* if cast to a generic pointer & the pointer being
973 cast is remat, then we can remat this cast as well */
974 if (ic->op == CAST &&
975 IS_SYMOP (IC_RIGHT (ic)) && OP_SYMBOL (IC_RIGHT (ic))->remat &&
976 !isOperandGlobal (IC_RESULT (ic)) && bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) == 1 && !IS_PARM (IC_RESULT (ic)) && /* The receiving of the parameter is not accounted for in DEFS */
977 !OP_SYMBOL (IC_RESULT (ic))->addrtaken)
979 sym_link *to_type = operandType (IC_LEFT (ic));
980 sym_link *from_type = operandType (IC_RIGHT (ic));
981 if ((IS_PTR (to_type) || IS_INT (to_type)) && IS_PTR (from_type))
983 OP_SYMBOL (IC_RESULT (ic))->remat = 1;
984 OP_SYMBOL (IC_RESULT (ic))->rematiCode = ic;
985 OP_SYMBOL (IC_RESULT (ic))->usl.spillLoc = NULL;
989 /* if this is a +/- operation with a rematerizable
990 then mark this as rematerializable as well */
991 if ((ic->op == '+' || ic->op == '-') &&
992 (IS_SYMOP (IC_LEFT (ic)) &&
993 IS_ITEMP (IC_RESULT (ic)) &&
994 IS_OP_LITERAL (IC_RIGHT (ic))) &&
995 OP_SYMBOL (IC_LEFT (ic))->remat &&
996 (!IS_SYMOP (IC_RIGHT (ic)) || !IS_CAST_ICODE (OP_SYMBOL (IC_RIGHT (ic))->rematiCode)) &&
997 bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) == 1)
999 OP_SYMBOL (IC_RESULT (ic))->remat = 1;
1000 OP_SYMBOL (IC_RESULT (ic))->rematiCode = ic;
1001 OP_SYMBOL (IC_RESULT (ic))->usl.spillLoc = NULL;
1004 /* if the condition of an if instruction is defined in the
1005 previous instruction then mark the itemp as a conditional */
1006 if ((IS_CONDITIONAL (ic) ||
1007 ((ic->op == BITWISEAND ||
1008 ic->op == '|' ||
1009 ic->op == '^') &&
1010 isBitwiseOptimizable (ic))) &&
1011 ic->next && ic->next->op == IFX &&
1012 bitVectnBitsOn (OP_USES (IC_RESULT (ic))) == 1 &&
1013 isOperandEqual (IC_RESULT (ic), IC_COND (ic->next)) && OP_SYMBOL (IC_RESULT (ic))->liveTo <= ic->next->seq)
1016 OP_SYMBOL (IC_RESULT (ic))->regType = REG_CND;
1017 continue;
1020 /* some cases the redundant moves can
1021 can be eliminated for return statements */
1022 if (ic->op == RETURN || ic->op == SEND)
1024 packRegsForOneuse (ic, IC_LEFT (ic), ebp);
1027 /* if pointer set & left has a size more than
1028 one and right is not in far space */
1029 if (!DISABLE_PACK_ONE_USE && POINTER_SET (ic) && IS_SYMOP (IC_RESULT (ic)) &&
1030 /* MLH: no such thing.
1031 !isOperandInFarSpace(IC_RIGHT(ic)) && */
1032 !OP_SYMBOL (IC_RESULT (ic))->remat &&
1033 !IS_OP_RUONLY (IC_RIGHT (ic)) && getSize (aggrToPtr (operandType (IC_RESULT (ic)), FALSE)) > 1)
1035 packRegsForOneuse (ic, IC_RESULT (ic), ebp);
1038 /* if pointer get */
1039 if (!DISABLE_PACK_ONE_USE && POINTER_GET (ic) && IS_SYMOP (IC_LEFT (ic)) &&
1040 /* MLH: dont have far space
1041 !isOperandInFarSpace(IC_RESULT(ic))&& */
1042 !OP_SYMBOL (IC_LEFT (ic))->remat &&
1043 !IS_OP_RUONLY (IC_RESULT (ic)) && getSize (aggrToPtr (operandType (IC_LEFT (ic)), FALSE)) > 1)
1045 packRegsForOneuse (ic, IC_LEFT (ic), ebp);
1050 /** Joins together two byte constant pushes into one word push.
1052 static iCode *
1053 joinPushes (iCode * lic)
1055 iCode *ic, *uic, *fic;
1057 for (ic = lic; ic; ic = ic->next)
1059 int first, second;
1060 value *val;
1061 struct dbuf_s dbuf;
1063 uic = ic->next;
1065 /* Anything past this? */
1066 if (uic == NULL)
1067 continue;
1069 /* This and the next pushes? */
1070 if (ic->op != IPUSH || uic->op != IPUSH)
1071 continue;
1073 /* Find call */
1074 for(fic = uic; fic->op == IPUSH; fic = fic->next);
1075 if (ic->op != CALL && fic->op != PCALL)
1076 continue;
1078 sym_link *dtype = operandType (IC_LEFT (fic));
1079 sym_link *ftype = IS_FUNCPTR (dtype) ? dtype->next : dtype;
1080 if (IFFUNC_ISSMALLC (ftype)) /* SmallC calling convention pushes 8-bit values as 16 bit */
1081 continue;
1084 /* Both literals? */
1085 if (!IS_OP_LITERAL (IC_LEFT (ic)) || !IS_OP_LITERAL (IC_LEFT (uic)))
1086 continue;
1088 /* Both characters? */
1089 if (getSize (operandType (IC_LEFT (ic))) != 1 || getSize (operandType (IC_LEFT (uic))) != 1)
1091 continue;
1093 /* Pull out the values, make a new type, and create the new iCode for it.
1095 first = (int) operandLitValue (IC_LEFT (ic));
1096 second = (int) operandLitValue (IC_LEFT (uic));
1098 dbuf_init (&dbuf, 128);
1099 dbuf_printf (&dbuf, "%uu", ((first << 8) | (second & 0xFF)) & 0xFFFFU);
1100 val = constVal (dbuf_c_str (&dbuf));
1101 dbuf_destroy (&dbuf);
1102 SPEC_NOUN (val->type) = V_INT;
1103 IC_LEFT (ic) = operandFromValue (val, false);
1105 /* Now remove the second one from the list. */
1106 ic->next = uic->next;
1107 if (uic->next)
1109 /* Patch up the reverse link */
1110 uic->next->prev = ic;
1114 return lic;
1117 /** Serially allocate registers to the variables.
1118 This was the main register allocation function. It is called after
1119 packing.
1120 In the new register allocator it only serves to mark variables for the new register allocator.
1122 static void
1123 serialRegMark (eBBlock ** ebbs, int count)
1125 int i;
1126 short int max_alloc_bytes = SHRT_MAX; // Byte limit. Set this to a low value to pass only few variables to the register allocator. This can be useful for debugging.
1128 /* for all blocks */
1129 for (i = 0; i < count; i++)
1131 iCode *ic;
1133 if (ebbs[i]->noPath && (ebbs[i]->entryLabel != entryLabel && ebbs[i]->entryLabel != returnLabel))
1134 continue;
1136 /* for all instructions do */
1137 for (ic = ebbs[i]->sch; ic; ic = ic->next)
1139 /* if result is present && is a true symbol */
1140 if (IC_RESULT (ic) && ic->op != IFX && IS_TRUE_SYMOP (IC_RESULT (ic)))
1142 OP_SYMBOL (IC_RESULT (ic))->allocreq++;
1145 /* take away registers from live
1146 ranges that end at this instruction */
1147 deassignLRs (ic, ebbs[i]);
1149 /* some don't need registers */
1150 if (SKIP_IC2 (ic) ||
1151 ic->op == JUMPTABLE || ic->op == IFX || ic->op == IPUSH || (IC_RESULT (ic) && POINTER_SET (ic)))
1153 continue;
1156 /* now we need to allocate registers only for the result */
1157 if (IC_RESULT (ic))
1159 symbol *sym = OP_SYMBOL (IC_RESULT (ic));
1161 D (D_ALLOC, ("serialRegAssign: in loop on result %p (%s)\n", sym, sym->name));
1163 /* Make sure any spill location is definitely allocated */
1164 if (sym->isspilt && !sym->remat && sym->usl.spillLoc && !sym->usl.spillLoc->allocreq)
1166 sym->usl.spillLoc->allocreq++;
1169 /* if it does not need or is spilt
1170 or is already assigned to registers (or marked for the new allocator)
1171 or will not live beyond this instructions */
1172 if (!sym->nRegs ||
1173 sym->isspilt || bitVectBitValue (_G.regAssigned, sym->key) || sym->for_newralloc || (sym->liveTo <= ic->seq && (sym->nRegs <= 4 || ic->op != CALL && ic->op != PCALL)))
1175 D (D_ALLOC, ("serialRegAssign: won't live long enough.\n"));
1176 continue;
1179 /* if some liverange has been spilt at the block level
1180 and this one live beyond this block then spil this
1181 to be safe */
1182 if (_G.blockSpil && sym->liveTo > ebbs[i]->lSeq)
1184 D (D_ALLOC, ("serialRegAssign: \"spilling to be safe.\"\n"));
1185 sym->for_newralloc = 0;
1186 z80SpillThis (sym);
1187 continue;
1190 if (sym->usl.spillLoc && !sym->usl.spillLoc->_isparm && !USE_OLDSALLOC) // I have no idea where these spill locations come from. Sometime two symbols even have the same spill location, whic tends to mess up stack allocation. Those that come from previous iterations in this loop would be okay, but those from outside are a problem.
1192 sym->usl.spillLoc = 0;
1193 sym->isspilt = false;
1196 if (sym->nRegs > 4) /* TODO. Change this once we can allocate bigger variables (but still spill when its a big return value). Also change in ralloc2.cc, operand_on-stack in that case*/
1198 D (D_ALLOC, ("Spilling %s (too large)\n", sym->name));
1199 sym->for_newralloc = 0;
1200 z80SpillThis (sym);
1202 else if (max_alloc_bytes >= sym->nRegs)
1204 sym->for_newralloc = 1;
1205 max_alloc_bytes -= sym->nRegs;
1207 else if (!sym->for_newralloc)
1209 z80SpillThis (sym);
1210 printf ("Spilt %s due to byte limit.\n", sym->name);
1217 void
1218 Z80RegFix (eBBlock ** ebbs, int count)
1220 int i;
1222 /* Check for and fix any problems with uninitialized operands */
1223 for (i = 0; i < count; i++)
1225 iCode *ic;
1227 if (ebbs[i]->noPath && (ebbs[i]->entryLabel != entryLabel && ebbs[i]->entryLabel != returnLabel))
1228 continue;
1230 for (ic = ebbs[i]->sch; ic; ic = ic->next)
1232 deassignLRs (ic, ebbs[i]);
1234 if (SKIP_IC2 (ic))
1235 continue;
1237 verifyRegsAssigned (IC_RESULT (ic), ic);
1238 verifyRegsAssigned (IC_LEFT (ic), ic);
1239 verifyRegsAssigned (IC_RIGHT (ic), ic);
1244 /*-----------------------------------------------------------------*/
1245 /* Register allocator */
1246 /*-----------------------------------------------------------------*/
1247 void
1248 z80_ralloc (ebbIndex *ebbi)
1250 eBBlock **ebbs = ebbi->bbOrder;
1251 int count = ebbi->count;
1252 iCode *ic;
1253 int i;
1255 D (D_ALLOC, ("\n-> z80_ralloc: entered for %s.\n", currFunc ? currFunc->name : "[no function]"));
1257 setToNull ((void *) &_G.funcrUsed);
1258 setToNull ((void *) &_G.totRegAssigned);
1259 _G.stackExtend = _G.dataExtend = 0;
1261 _G.nRegs = IS_SM83 ? SM83_MAX_REGS : Z80_MAX_REGS;
1263 /* change assignments this will remove some
1264 live ranges reducing some register pressure */
1265 for (i = 0; i < count; i++)
1266 packRegisters (ebbs[i]);
1268 /* liveranges probably changed by register packing
1269 so we compute them again */
1270 recomputeLiveRanges (ebbs, count, FALSE);
1272 if (options.dump_i_code)
1273 dumpEbbsToFileExt (DUMP_PACK, ebbi);
1275 /* first determine for each live range the number of
1276 registers & the type of registers required for each */
1277 regTypeNum ();
1279 /* Mark variables for assignment by the new allocator */
1280 serialRegMark (ebbs, count);
1282 joinPushes (iCodeLabelOptimize(iCodeFromeBBlock (ebbs, count)));
1284 /* The new register allocator invokes its magic */
1285 ic = z80_ralloc2_cc (ebbi);
1287 if (options.dump_i_code)
1289 dumpEbbsToFileExt (DUMP_RASSGN, ebbi);
1290 dumpLiveRanges (DUMP_LRANGE, liveRanges);
1293 genZ80Code (ic);
1295 /* free up any stackSpil locations allocated */
1296 applyToSet (_G.stackSpil, deallocStackSpil);
1297 _G.slocNum = 0;
1298 setToNull ((void *) &_G.stackSpil);
1299 setToNull ((void *) &_G.spiltSet);
1300 /* mark all registers as free */
1301 freeAllRegs ();
1303 return;
1306 /*-----------------------------------------------------------------*/
1307 /* assignRegisters - assigns registers to each live range as need */
1308 /*-----------------------------------------------------------------*/
1309 void
1310 z80_assignRegisters (ebbIndex * ebbi)
1312 z80_ralloc (ebbi);