e8d338fa9d409da4f53d03dff5114c8457b231af
[fw/sdcc] / src / z80 / ralloc.c
1 /** @name Z80 Register allocation functions.
2     @author Michael Hope
3
4     Note: much of this is ripped straight from Sandeep's mcs51 code.
5
6     This code maps the virtual symbols and code onto the real
7     hardware.  It allocates based on usage and how long the varible
8     lives into registers or temporary memory on the stack.
9
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 adressable 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.
16
17     The stack frame is the common ix-bp style.  Basically:
18
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 varibles 
24     ...  
25     sp:         end of local varibles
26
27     There is currently no support for bit spaces or banked functions.
28     
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.
36     
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!  
44 */
45
46 #include "z80.h"
47 #include "SDCCicode.h"
48
49 /* Flags to turn off optimisations.
50  */
51 enum
52   {
53     DISABLE_PACK_ACC = 0,
54     DISABLE_PACK_ASSIGN = 0,
55     DISABLE_PACK_ONE_USE = 0,
56     DISABLE_PACK_HL = 0,
57   };
58
59 /* Flags to turn on debugging code.
60  */
61 enum
62   {
63     D_ALLOC = 0,
64     D_ALLOC2 = 0,
65     D_ACCUSE2 = 0,
66     D_ACCUSE2_VERBOSE = 0,
67     D_HLUSE = 0,
68     D_HLUSE2 = 0,
69     D_HLUSE2_VERBOSE = 0,
70     D_FILL_GAPS = 0
71   };
72
73 #if 1
74 #define D(_a, _s)       if (_a)  { printf _s; fflush(stdout); }
75 #else
76 #define D(_a, _s)
77 #endif
78
79 #define DISABLE_PACKREGSFORSUPPORT      1
80 #define DISABLE_PACKREGSFORACCUSE       1
81
82 extern void genZ80Code (iCode *);
83
84 /** Local static variables */
85 static struct
86 {
87   bitVect *spiltSet;
88   set *stackSpil;
89   bitVect *regAssigned;
90   bitVect *totRegAssigned;    /* final set of LRs that got into registers */
91   short blockSpil;
92   int slocNum;
93   /* registers used in a function */
94   bitVect *funcrUsed;
95   int stackExtend;
96   int dataExtend;
97   int nRegs;
98 } _G;
99
100 static regs _gbz80_regs[] =
101 {
102   {REG_GPR, C_IDX, "c", 1},
103   {REG_GPR, B_IDX, "b", 1},
104   {REG_CND, CND_IDX, "c", 1}
105 };
106
107 static regs _z80_regs[] =
108 {
109   {REG_GPR, C_IDX, "c", 1},
110   {REG_GPR, B_IDX, "b", 1},
111   {REG_GPR, E_IDX, "e", 1},
112   {REG_GPR, D_IDX, "d", 1},
113   {REG_CND, CND_IDX, "c", 1}
114 };
115
116 regs *regsZ80;
117
118 /** Number of usable registers (all but C) */
119 #define Z80_MAX_REGS ((sizeof(_z80_regs)/sizeof(_z80_regs[0]))-1)
120 #define GBZ80_MAX_REGS ((sizeof(_gbz80_regs)/sizeof(_gbz80_regs[0]))-1)
121
122 static void spillThis (symbol *);
123 static void freeAllRegs ();
124
125 /** Allocates register of given type.
126     'type' is not used on the z80 version.  It was used to select
127     between pointer and general purpose registers on the mcs51 version.
128
129     @return             Pointer to the newly allocated register.
130  */
131 static regs *
132 allocReg (short type)
133 {
134   int i;
135
136   for (i = 0; i < _G.nRegs; i++)
137     {
138       /* For now we allocate from any free */
139       if (regsZ80[i].isFree)
140         {
141           regsZ80[i].isFree = 0;
142           if (currFunc)
143             {
144               currFunc->regsUsed = bitVectSetBit (currFunc->regsUsed, i);
145             }
146           D (D_ALLOC, ("allocReg: alloced %p\n", &regsZ80[i]));
147           return &regsZ80[i];
148         }
149     }
150   D (D_ALLOC, ("allocReg: No free.\n"));
151   return NULL;
152 }
153
154 /** Returns pointer to register wit index number
155  */
156 regs *
157 regWithIdx (int idx)
158 {
159   int i;
160
161   for (i = 0; i < _G.nRegs; i++)
162     {
163       if (regsZ80[i].rIdx == idx)
164         {
165           return &regsZ80[i];
166         }
167     }
168
169   wassertl (0, "regWithIdx not found");
170   exit (1);
171 }
172
173 /** Frees a register.
174  */
175 static void 
176 freeReg (regs * reg)
177 {
178   wassert (!reg->isFree);
179   reg->isFree = 1;
180   D (D_ALLOC, ("freeReg: freed %p\n", reg));
181 }
182
183
184 /** Returns number of free registers.
185  */
186 static int 
187 nFreeRegs (int type)
188 {
189   int i;
190   int nfr = 0;
191
192   for (i = 0; i < _G.nRegs; i++)
193     {
194       /* For now only one reg type */
195       if (regsZ80[i].isFree)
196         {
197           nfr++;
198         }
199     }
200   return nfr;
201 }
202
203 /** Free registers with type.
204  */
205 static int 
206 nfreeRegsType (int type)
207 {
208   int nfr;
209   if (type == REG_PTR)
210     {
211       if ((nfr = nFreeRegs (type)) == 0)
212         {
213           return nFreeRegs (REG_GPR);
214         }
215     }
216
217   return nFreeRegs (type);
218 }
219
220 /*-----------------------------------------------------------------*/
221 /* useReg - marks a register  as used                              */
222 /*-----------------------------------------------------------------*/
223 static void
224 useReg (regs * reg)
225 {
226   reg->isFree = 0;
227 }
228
229 #if 0
230 /*-----------------------------------------------------------------*/
231 /* allDefsOutOfRange - all definitions are out of a range          */
232 /*-----------------------------------------------------------------*/
233 static bool 
234 allDefsOutOfRange (bitVect * defs, int fseq, int toseq)
235 {
236   int i;
237
238   if (!defs)
239     return TRUE;
240
241   for (i = 0; i < defs->size; i++)
242     {
243       iCode *ic;
244
245       if (bitVectBitValue (defs, i) &&
246           (ic = hTabItemWithKey (iCodehTab, i)) &&
247           (ic->seq >= fseq && ic->seq <= toseq))
248
249         return FALSE;
250
251     }
252
253   return TRUE;
254 }
255 #endif
256
257 /*-----------------------------------------------------------------*/
258 /* computeSpillable - given a point find the spillable live ranges */
259 /*-----------------------------------------------------------------*/
260 static bitVect *
261 computeSpillable (iCode * ic)
262 {
263   bitVect *spillable;
264
265   /* spillable live ranges are those that are live at this 
266      point . the following categories need to be subtracted
267      from this set. 
268      a) - those that are already spilt
269      b) - if being used by this one
270      c) - defined by this one */
271
272   spillable = bitVectCopy (ic->rlive);
273   spillable =
274     bitVectCplAnd (spillable, _G.spiltSet);     /* those already spilt */
275   spillable =
276     bitVectCplAnd (spillable, ic->uses);        /* used in this one */
277   bitVectUnSetBit (spillable, ic->defKey);
278   spillable = bitVectIntersect (spillable, _G.regAssigned);
279
280   return spillable;
281 }
282
283 /*-----------------------------------------------------------------*/
284 /* noSpilLoc - return true if a variable has no spil location      */
285 /*-----------------------------------------------------------------*/
286 static int 
287 noSpilLoc (symbol * sym, eBBlock * ebp, iCode * ic)
288 {
289   return (sym->usl.spillLoc ? 0 : 1);
290 }
291
292 /*-----------------------------------------------------------------*/
293 /* hasSpilLoc - will return 1 if the symbol has spil location      */
294 /*-----------------------------------------------------------------*/
295 static int 
296 hasSpilLoc (symbol * sym, eBBlock * ebp, iCode * ic)
297 {
298   return (sym->usl.spillLoc ? 1 : 0);
299 }
300
301 /** Will return 1 if the remat flag is set.
302     A symbol is rematerialisable if it doesnt need to be allocated
303     into registers at creation as it can be re-created at any time -
304     i.e. it's constant in some way.
305 */
306 static int 
307 rematable (symbol * sym, eBBlock * ebp, iCode * ic)
308 {
309   return sym->remat;
310 }
311
312 /*-----------------------------------------------------------------*/
313 /* allLRs - return true for all                                    */
314 /*-----------------------------------------------------------------*/
315 static int 
316 allLRs (symbol * sym, eBBlock * ebp, iCode * ic)
317 {
318   return 1;
319 }
320
321 /** liveRangesWith - applies function to a given set of live range 
322  */
323 static set *
324 liveRangesWith (bitVect * lrs, int (func) (symbol *, eBBlock *, iCode *),
325                 eBBlock * ebp, iCode * ic)
326 {
327   set *rset = NULL;
328   int i;
329
330   if (!lrs || !lrs->size)
331     return NULL;
332
333   for (i = 1; i < lrs->size; i++)
334     {
335       symbol *sym;
336       if (!bitVectBitValue (lrs, i))
337         continue;
338
339       /* if we don't find it in the live range 
340          hash table we are in serious trouble */
341       if (!(sym = hTabItemWithKey (liveRanges, i)))
342         {
343           wassertl (0, "liveRangesWith could not find liveRange");
344           exit (1);
345         }
346
347       if (func (sym, ebp, ic) && bitVectBitValue (_G.regAssigned, sym->key))
348         {
349           addSetHead (&rset, sym);
350         }
351     }
352
353   return rset;
354 }
355
356
357 /** leastUsedLR - given a set determines which is the least used 
358  */
359 static symbol *
360 leastUsedLR (set * sset)
361 {
362   symbol *sym = NULL, *lsym = NULL;
363
364   sym = lsym = setFirstItem (sset);
365
366   if (!lsym)
367     return NULL;
368
369   for (; lsym; lsym = setNextItem (sset))
370     {
371
372       /* if usage is the same then prefer
373          the spill the smaller of the two */
374       if (lsym->used == sym->used)
375         if (getSize (lsym->type) < getSize (sym->type))
376           sym = lsym;
377
378       /* if less usage */
379       if (lsym->used < sym->used)
380         sym = lsym;
381
382     }
383
384   setToNull ((void **) &sset);
385   sym->blockSpil = 0;
386   return sym;
387 }
388
389 /** noOverLap - will iterate through the list looking for over lap
390  */
391 static int 
392 noOverLap (set * itmpStack, symbol * fsym)
393 {
394   symbol *sym;
395
396   for (sym = setFirstItem (itmpStack); sym;
397        sym = setNextItem (itmpStack))
398     {
399       if (bitVectBitValue(sym->clashes,fsym->key)) 
400         return 0;
401 #if 0
402             // if sym starts before (or on) our end point
403             // and ends after (or on) our start point, 
404             // it is an overlap.
405             if (sym->liveFrom <= fsym->liveTo &&
406                 sym->liveTo   >= fsym->liveFrom)
407             {
408                 return 0;
409             }
410 #endif
411     }
412   return 1;
413 }
414
415 /*-----------------------------------------------------------------*/
416 /* isFree - will return 1 if the a free spil location is found     */
417 /*-----------------------------------------------------------------*/
418 DEFSETFUNC (isFree)
419 {
420   symbol *sym = item;
421   V_ARG (symbol **, sloc);
422   V_ARG (symbol *, fsym);
423
424   /* if already found */
425   if (*sloc)
426     return 0;
427
428   /* if it is free && and the itmp assigned to
429      this does not have any overlapping live ranges
430      with the one currently being assigned and
431      the size can be accomodated  */
432   if (sym->isFree &&
433       noOverLap (sym->usl.itmpStack, fsym) &&
434       getSize (sym->type) >= getSize (fsym->type))
435     {
436       *sloc = sym;
437       return 1;
438     }
439
440   return 0;
441 }
442
443 /*-----------------------------------------------------------------*/
444 /* createStackSpil - create a location on the stack to spil        */
445 /*-----------------------------------------------------------------*/
446 static symbol *
447 createStackSpil (symbol * sym)
448 {
449   symbol *sloc = NULL;
450
451   D (D_ALLOC, ("createStackSpil: for sym %p\n", sym));
452
453   /* first go try and find a free one that is already 
454      existing on the stack */
455   if (applyToSet (_G.stackSpil, isFree, &sloc, sym))
456     {
457       /* found a free one : just update & return */
458       sym->usl.spillLoc = sloc;
459       sym->stackSpil = 1;
460       sloc->isFree = 0;
461       addSetHead (&sloc->usl.itmpStack, sym);
462       D (D_ALLOC, ("createStackSpil: found existing\n"));
463       return sym;
464     }
465
466   /* could not then have to create one , this is the hard part
467      we need to allocate this on the stack : this is really a
468      hack!! but cannot think of anything better at this time */
469
470   sprintf (buffer, "sloc%d", _G.slocNum++);
471   sloc = newiTemp (buffer);
472
473   /* set the type to the spilling symbol */
474   sloc->type = copyLinkChain (sym->type);
475   sloc->etype = getSpec (sloc->type);
476   SPEC_SCLS (sloc->etype) = S_AUTO;
477   SPEC_EXTR (sloc->etype) = 0;
478   SPEC_STAT (sloc->etype) = 0;
479   SPEC_VOLATILE(sloc->etype) = 0;
480
481   allocLocal (sloc);
482
483   sloc->isref = 1;              /* to prevent compiler warning */
484
485   /* if it is on the stack then update the stack */
486   if (IN_STACK (sloc->etype))
487     {
488       currFunc->stack += getSize (sloc->type);
489       _G.stackExtend += getSize (sloc->type);
490     }
491   else
492     {
493       _G.dataExtend += getSize (sloc->type);
494     }
495
496   /* add it to the stackSpil set */
497   addSetHead (&_G.stackSpil, sloc);
498   sym->usl.spillLoc = sloc;
499   sym->stackSpil = 1;
500
501   /* add it to the set of itempStack set 
502      of the spill location */
503   addSetHead (&sloc->usl.itmpStack, sym);
504
505   D (D_ALLOC, ("createStackSpil: created new\n"));
506   return sym;
507 }
508
509 /*-----------------------------------------------------------------*/
510 /* spillThis - spils a specific operand                            */
511 /*-----------------------------------------------------------------*/
512 static void 
513 spillThis (symbol * sym)
514 {
515   int i;
516
517   D (D_ALLOC, ("spillThis: spilling %p\n", sym));
518
519   /* if this is rematerializable or has a spillLocation
520      we are okay, else we need to create a spillLocation
521      for it */
522   if (!(sym->remat || sym->usl.spillLoc))
523     {
524       createStackSpil (sym);
525     }
526
527   /* mark it has spilt & put it in the spilt set */
528   sym->isspilt = sym->spillA = 1;
529   _G.spiltSet = bitVectSetBit (_G.spiltSet, sym->key);
530
531   bitVectUnSetBit (_G.regAssigned, sym->key);
532   bitVectUnSetBit (_G.totRegAssigned, sym->key);
533
534   for (i = 0; i < sym->nRegs; i++)
535     {
536       if (sym->regs[i])
537         {
538           freeReg (sym->regs[i]);
539           sym->regs[i] = NULL;
540         }
541     }
542
543   if (sym->usl.spillLoc && !sym->remat)
544     {
545       sym->usl.spillLoc->allocreq++;
546     }
547   return;
548 }
549
550 #if DISABLED
551 /*-----------------------------------------------------------------*/
552 /* allDefsOutOfRange - all definitions are out of a range          */
553 /*-----------------------------------------------------------------*/
554 static bool
555 allDefsOutOfRange (bitVect * defs, int fseq, int toseq)
556 {
557   int i;
558
559   if (!defs)
560     return TRUE;
561
562   for (i = 0; i < defs->size; i++)
563     {
564       iCode *ic;
565
566       if (bitVectBitValue (defs, i) &&
567           (ic = hTabItemWithKey (iCodehTab, i)) &&
568           (ic->seq >= fseq && ic->seq <= toseq))
569
570         return FALSE;
571
572     }
573
574   return TRUE;
575 }
576
577 /*-----------------------------------------------------------------*/
578 /* hasSpilLocnoUptr - will return 1 if the symbol has spil location */
579 /*                    but is not used as a pointer                 */
580 /*-----------------------------------------------------------------*/
581 static int
582 hasSpilLocnoUptr (symbol * sym, eBBlock * ebp, iCode * ic)
583 {
584   return ((sym->usl.spillLoc && !sym->uptr) ? 1 : 0);
585 }
586
587 /*-----------------------------------------------------------------*/
588 /* notUsedInBlock - not used in this block                         */
589 /*-----------------------------------------------------------------*/
590 static int
591 notUsedInBlock (symbol * sym, eBBlock * ebp, iCode * ic)
592 {
593   return (!bitVectBitsInCommon (sym->defs, ebp->usesDefs) &&
594           allDefsOutOfRange (sym->defs, ebp->fSeq, ebp->lSeq));
595 /*     return (!bitVectBitsInCommon(sym->defs,ebp->usesDefs)); */
596 }
597
598 /*-----------------------------------------------------------------*/
599 /* notUsedInRemaining - not used or defined in remain of the block */
600 /*-----------------------------------------------------------------*/
601 static int
602 notUsedInRemaining (symbol * sym, eBBlock * ebp, iCode * ic)
603 {
604   return ((usedInRemaining (operandFromSymbol (sym), ic) ? 0 : 1) &&
605           allDefsOutOfRange (sym->defs, ebp->fSeq, ebp->lSeq));
606 }
607 #endif
608
609 /** Select a iTemp to spil : rather a simple procedure.
610  */
611 symbol *
612 selectSpil (iCode * ic, eBBlock * ebp, symbol * forSym)
613 {
614   bitVect *lrcs = NULL;
615   set *selectS;
616   symbol *sym;
617
618   D (D_ALLOC, ("selectSpil: finding spill for ic %p\n", ic));
619   /* get the spillable live ranges */
620   lrcs = computeSpillable (ic);
621
622   /* get all live ranges that are rematerizable */
623   if ((selectS = liveRangesWith (lrcs, rematable, ebp, ic)))
624     {
625       D (D_ALLOC, ("selectSpil: using remat.\n"));
626       /* return the least used of these */
627       return leastUsedLR (selectS);
628     }
629
630 #if 0
631   /* get live ranges with spillLocations in direct space */
632   if ((selectS = liveRangesWith (lrcs, directSpilLoc, ebp, ic)))
633     {
634       sym = leastUsedLR (selectS);
635       strcpy (sym->rname, (sym->usl.spillLoc->rname[0] ?
636                            sym->usl.spillLoc->rname :
637                            sym->usl.spillLoc->name));
638       sym->spildir = 1;
639       /* mark it as allocation required */
640       sym->usl.spillLoc->allocreq++;
641       return sym;
642     }
643
644   /* if the symbol is local to the block then */
645   if (forSym->liveTo < ebp->lSeq)
646     {
647
648       /* check if there are any live ranges allocated
649          to registers that are not used in this block */
650       if (!_G.blockSpil && (selectS = liveRangesWith (lrcs, notUsedInBlock, ebp, ic)))
651         {
652           sym = leastUsedLR (selectS);
653           /* if this is not rematerializable */
654           if (!sym->remat)
655             {
656               _G.blockSpil++;
657               wassertl (0, "Attempted to do an unsupported block spill");
658               sym->blockSpil = 1;
659             }
660           return sym;
661         }
662
663       /* check if there are any live ranges that not
664          used in the remainder of the block */
665       if (!_G.blockSpil && (selectS = liveRangesWith (lrcs, notUsedInRemaining, ebp, ic)))
666         {
667           sym = leastUsedLR (selectS);
668           if (sym != forSym)
669             {
670               if (!sym->remat)
671                 {
672                   wassertl (0, "Attempted to do an unsupported remain spill");
673                   sym->remainSpil = 1;
674                   _G.blockSpil++;
675                 }
676               return sym;
677             }
678         }
679     }
680   /* find live ranges with spillocation && not used as pointers */
681   if ((selectS = liveRangesWith (lrcs, hasSpilLocnoUptr, ebp, ic)))
682     {
683
684       sym = leastUsedLR (selectS);
685       /* mark this as allocation required */
686       sym->usl.spillLoc->allocreq++;
687       return sym;
688     }
689 #endif
690
691   /* find live ranges with spillocation */
692   if ((selectS = liveRangesWith (lrcs, hasSpilLoc, ebp, ic)))
693     {
694       D (D_ALLOC, ("selectSpil: using with spill.\n"));
695       sym = leastUsedLR (selectS);
696       sym->usl.spillLoc->allocreq++;
697       return sym;
698     }
699
700   /* couldn't find then we need to create a spil
701      location on the stack , for which one? the least
702      used ofcourse */
703   if ((selectS = liveRangesWith (lrcs, noSpilLoc, ebp, ic)))
704     {
705       D (D_ALLOC, ("selectSpil: creating new spill.\n"));
706       /* return a created spil location */
707       sym = createStackSpil (leastUsedLR (selectS));
708       sym->usl.spillLoc->allocreq++;
709       return sym;
710     }
711
712   /* this is an extreme situation we will spill
713      this one : happens very rarely but it does happen */
714   D (D_ALLOC, ("selectSpil: using spillThis.\n"));
715   spillThis (forSym);
716   return forSym;
717
718 }
719
720 /** Spil some variable & mark registers as free.
721     A spill occurs when an iTemp wont fit into the available registers.
722  */
723 bool 
724 spilSomething (iCode * ic, eBBlock * ebp, symbol * forSym)
725 {
726   symbol *ssym;
727   int i;
728
729   D (D_ALLOC, ("spilSomething: spilling on ic %p\n", ic));
730
731   /* get something we can spil */
732   ssym = selectSpil (ic, ebp, forSym);
733
734   /* mark it as spilt */
735   ssym->isspilt = ssym->spillA = 1;
736   _G.spiltSet = bitVectSetBit (_G.spiltSet, ssym->key);
737
738   /* mark it as not register assigned &
739      take it away from the set */
740   bitVectUnSetBit (_G.regAssigned, ssym->key);
741   bitVectUnSetBit (_G.totRegAssigned, ssym->key);
742
743   /* mark the registers as free */
744   for (i = 0; i < ssym->nRegs; i++)
745     if (ssym->regs[i])
746       freeReg (ssym->regs[i]);
747
748   wassertl (ssym->blockSpil == 0, "Encountered a sym with a block spill");
749   wassertl (ssym->remainSpil == 0, "Encountered a sym with a remain spill");
750 #if 0
751   /* if spilt on stack then free up r0 & r1 
752      if they could have been assigned to as gprs */
753   if (!ptrRegReq && isSpiltOnStack (ssym))
754     {
755       ptrRegReq++;
756       spillLRWithPtrReg (ssym);
757     }
758
759   /* if this was a block level spil then insert push & pop 
760      at the start & end of block respectively */
761   if (ssym->blockSpil)
762     {
763       iCode *nic = newiCode (IPUSH, operandFromSymbol (ssym), NULL);
764       /* add push to the start of the block */
765       addiCodeToeBBlock (ebp, nic, (ebp->sch->op == LABEL ?
766                                     ebp->sch->next : ebp->sch));
767       nic = newiCode (IPOP, operandFromSymbol (ssym), NULL);
768       /* add pop to the end of the block */
769       addiCodeToeBBlock (ebp, nic, NULL);
770     }
771
772   /* if spilt because not used in the remainder of the
773      block then add a push before this instruction and
774      a pop at the end of the block */
775   if (ssym->remainSpil)
776     {
777
778       iCode *nic = newiCode (IPUSH, operandFromSymbol (ssym), NULL);
779       /* add push just before this instruction */
780       addiCodeToeBBlock (ebp, nic, ic);
781
782       nic = newiCode (IPOP, operandFromSymbol (ssym), NULL);
783       /* add pop to the end of the block */
784       addiCodeToeBBlock (ebp, nic, NULL);
785     }
786 #endif
787
788   D (D_ALLOC, ("spilSomething: done.\n"));
789
790   if (ssym == forSym)
791     return FALSE;
792   else
793     return TRUE;
794 }
795
796 /** Will try for GPR if not spil.
797  */
798 regs *
799 getRegGpr (iCode * ic, eBBlock * ebp, symbol * sym)
800 {
801   regs *reg;
802
803   D (D_ALLOC, ("getRegGpr: on ic %p\n", ic));
804 tryAgain:
805   /* try for gpr type */
806   if ((reg = allocReg (REG_GPR)))
807     {
808       D (D_ALLOC, ("getRegGpr: got a reg.\n"));
809       return reg;
810     }
811
812   /* we have to spil */
813   if (!spilSomething (ic, ebp, sym))
814     {
815       D (D_ALLOC, ("getRegGpr: have to spill.\n"));
816       return NULL;
817     }
818
819   /* this looks like an infinite loop but 
820      in really selectSpil will abort  */
821   goto tryAgain;
822 }
823
824 static regs *getRegGprNoSpil()
825 {
826   regs *reg;
827
828   /* try for gpr type */
829   if ((reg = allocReg (REG_GPR)))
830     {
831       D (D_ALLOC, ("getRegGprNoSpil: got a reg.\n"));
832       return reg;
833     }
834   assert(0);
835 }
836
837 /** Symbol has a given register.
838  */
839 static bool 
840 symHasReg (symbol * sym, regs * reg)
841 {
842   int i;
843
844   for (i = 0; i < sym->nRegs; i++)
845     if (sym->regs[i] == reg)
846       return TRUE;
847
848   return FALSE;
849 }
850
851 /** Check the live to and if they have registers & are not spilt then
852     free up the registers 
853 */
854 static void 
855 deassignLRs (iCode * ic, eBBlock * ebp)
856 {
857   symbol *sym;
858   int k;
859   symbol *result;
860
861   for (sym = hTabFirstItem (liveRanges, &k); sym;
862        sym = hTabNextItem (liveRanges, &k))
863     {
864
865       symbol *psym = NULL;
866       /* if it does not end here */
867       if (sym->liveTo > ic->seq)
868         continue;
869
870       /* if it was spilt on stack then we can 
871          mark the stack spil location as free */
872       if (sym->isspilt)
873         {
874           if (sym->stackSpil)
875             {
876               sym->usl.spillLoc->isFree = 1;
877               sym->stackSpil = 0;
878             }
879           continue;
880         }
881
882       if (!bitVectBitValue (_G.regAssigned, sym->key))
883         continue;
884
885       /* special case check if this is an IFX &
886          the privious one was a pop and the 
887          previous one was not spilt then keep track
888          of the symbol */
889       if (ic->op == IFX && ic->prev &&
890           ic->prev->op == IPOP &&
891           !ic->prev->parmPush &&
892           !OP_SYMBOL (IC_LEFT (ic->prev))->isspilt)
893         psym = OP_SYMBOL (IC_LEFT (ic->prev));
894
895       D (D_ALLOC, ("deassignLRs: in loop on sym %p nregs %u\n", sym, sym->nRegs));
896
897       if (sym->nRegs)
898         {
899           int i = 0;
900
901           bitVectUnSetBit (_G.regAssigned, sym->key);
902
903           /* if the result of this one needs registers
904              and does not have it then assign it right
905              away */
906           if (IC_RESULT (ic) &&
907               !(SKIP_IC2 (ic) ||        /* not a special icode */
908                 ic->op == JUMPTABLE ||
909                 ic->op == IFX ||
910                 ic->op == IPUSH ||
911                 ic->op == IPOP ||
912                 ic->op == RETURN) &&
913               (result = OP_SYMBOL (IC_RESULT (ic))) &&  /* has a result */
914               result->liveTo > ic->seq &&       /* and will live beyond this */
915               result->liveTo <= ebp->lSeq &&    /* does not go beyond this block */
916               result->regType == sym->regType &&        /* same register types */
917               result->nRegs &&  /* which needs registers */
918               !result->isspilt &&       /* and does not already have them */
919               !result->remat &&
920               !bitVectBitValue (_G.regAssigned, result->key) &&
921           /* the number of free regs + number of regs in this LR
922              can accomodate the what result Needs */
923               ((nfreeRegsType (result->regType) +
924                 sym->nRegs) >= result->nRegs)
925             )
926             {
927               for (i = 0; i < result->nRegs; i++)
928                 {
929                   if (i < sym->nRegs)
930                     result->regs[i] = sym->regs[i];
931                   else
932                     result->regs[i] = getRegGpr (ic, ebp, result);
933
934                   /* if the allocation falied which means
935                      this was spilt then break */
936                   if (!result->regs[i])
937                     {
938                       wassert (0);
939                       assert (0);
940                       break;
941                     }
942                 }
943
944               _G.regAssigned = bitVectSetBit (_G.regAssigned, result->key);
945               _G.totRegAssigned = bitVectSetBit (_G.totRegAssigned, result->key);
946             }
947
948           /* free the remaining */
949           for (; i < sym->nRegs; i++)
950             {
951               if (psym)
952                 {
953                   if (!symHasReg (psym, sym->regs[i]))
954                     freeReg (sym->regs[i]);
955                 }
956               else
957                 freeReg (sym->regs[i]);
958               //              sym->regs[i] = NULL;
959             }
960         }
961     }
962 }
963
964
965 /** Reassign this to registers.
966  */
967 static void 
968 reassignLR (operand * op)
969 {
970   symbol *sym = OP_SYMBOL (op);
971   int i;
972
973   D (D_ALLOC, ("reassingLR: on sym %p\n", sym));
974
975   /* not spilt any more */
976   sym->isspilt = sym->spillA = sym->blockSpil = sym->remainSpil = 0;
977   bitVectUnSetBit (_G.spiltSet, sym->key);
978
979   _G.regAssigned = bitVectSetBit (_G.regAssigned, sym->key);
980   _G.totRegAssigned = bitVectSetBit (_G.totRegAssigned, sym->key);
981
982   _G.blockSpil--;
983
984   for (i = 0; i < sym->nRegs; i++)
985     sym->regs[i]->isFree = 0;
986 }
987
988 /** Determines if allocating will cause a spill.
989  */
990 static int 
991 willCauseSpill (int nr, int rt)
992 {
993   /* first check if there are any avlb registers
994      of te type required */
995   if (nFreeRegs (0) >= nr)
996     return 0;
997
998   /* it will cause a spil */
999   return 1;
1000 }
1001
1002 /** The allocator can allocate same registers to result and operand,
1003     if this happens make sure they are in the same position as the operand
1004     otherwise chaos results.
1005 */
1006 static int
1007 positionRegs (symbol * result, symbol * opsym)
1008 {
1009   int count = min (result->nRegs, opsym->nRegs);
1010   int i, j = 0, shared = 0;
1011   int change = 0;
1012
1013   D (D_ALLOC, ("positionRegs: on result %p opsum %p line %u\n", result, opsym, lineno));
1014
1015   /* if the result has been spilt then cannot share */
1016   if (opsym->isspilt)
1017     return 0;
1018 again:
1019   shared = 0;
1020   /* first make sure that they actually share */
1021   for (i = 0; i < count; i++)
1022     {
1023       for (j = 0; j < count; j++)
1024         {
1025           if (result->regs[i] == opsym->regs[j] && i != j)
1026             {
1027               shared = 1;
1028               goto xchgPositions;
1029             }
1030         }
1031     }
1032 xchgPositions:
1033   if (shared)
1034     {
1035       regs *tmp = result->regs[i];
1036       result->regs[i] = result->regs[j];
1037       result->regs[j] = tmp;
1038       change ++;
1039       goto again;
1040     }
1041   return change ;
1042 }
1043
1044 /** Try to allocate a pair of registers to the symbol.
1045  */
1046 bool 
1047 tryAllocatingRegPair (symbol * sym)
1048 {
1049   int i;
1050   wassert (sym->nRegs == 2);
1051   for (i = 0; i < _G.nRegs; i += 2)
1052     {
1053       if ((regsZ80[i].isFree) && (regsZ80[i + 1].isFree))
1054         {
1055           regsZ80[i].isFree = 0;
1056           sym->regs[0] = &regsZ80[i];
1057           regsZ80[i + 1].isFree = 0;
1058           sym->regs[1] = &regsZ80[i + 1];
1059           sym->regType = REG_PAIR;
1060
1061           if (currFunc)
1062             {
1063               currFunc->regsUsed =
1064                 bitVectSetBit (currFunc->regsUsed, i);
1065               currFunc->regsUsed =
1066                 bitVectSetBit (currFunc->regsUsed, i + 1);
1067             }
1068           D (D_ALLOC, ("tryAllocRegPair: succeded for sym %p\n", sym));
1069           return TRUE;
1070         }
1071     }
1072   D (D_ALLOC, ("tryAllocRegPair: failed on sym %p\n", sym));
1073   return FALSE;
1074 }
1075
1076 /** Serially allocate registers to the variables.
1077     This is the main register allocation function.  It is called after
1078     packing.
1079  */
1080 static void 
1081 serialRegAssign (eBBlock ** ebbs, int count)
1082 {
1083   int i;
1084
1085   /* for all blocks */
1086   for (i = 0; i < count; i++)
1087     {
1088
1089       iCode *ic;
1090
1091       if (ebbs[i]->noPath &&
1092           (ebbs[i]->entryLabel != entryLabel &&
1093            ebbs[i]->entryLabel != returnLabel))
1094         continue;
1095
1096       /* of all instructions do */
1097       for (ic = ebbs[i]->sch; ic; ic = ic->next)
1098         {
1099
1100           /* if this is an ipop that means some live
1101              range will have to be assigned again */
1102           if (ic->op == IPOP)
1103             {
1104               wassert (0);
1105               reassignLR (IC_LEFT (ic));
1106             }
1107
1108           /* if result is present && is a true symbol */
1109           if (IC_RESULT (ic) && ic->op != IFX &&
1110               IS_TRUE_SYMOP (IC_RESULT (ic)))
1111             OP_SYMBOL (IC_RESULT (ic))->allocreq++;
1112
1113           /* take away registers from live
1114              ranges that end at this instruction */
1115           deassignLRs (ic, ebbs[i]);
1116
1117           /* some don't need registers */
1118           /* MLH: removed RESULT and POINTER_SET condition */
1119           if (SKIP_IC2 (ic) ||
1120               ic->op == JUMPTABLE ||
1121               ic->op == IFX ||
1122               ic->op == IPUSH ||
1123               ic->op == IPOP)
1124             continue;
1125
1126           /* now we need to allocate registers only for the result */
1127           if (IC_RESULT (ic))
1128             {
1129               symbol *sym = OP_SYMBOL (IC_RESULT (ic));
1130               bitVect *spillable;
1131               int willCS;
1132               int j;
1133
1134               D (D_ALLOC, ("serialRegAssign: in loop on result %p\n", sym));
1135
1136               /* if it does not need or is spilt 
1137                  or is already assigned to registers
1138                  or will not live beyond this instructions */
1139               if (!sym->nRegs ||
1140                   sym->isspilt ||
1141                   bitVectBitValue (_G.regAssigned, sym->key) ||
1142                   sym->liveTo <= ic->seq)
1143                 {
1144                   D (D_ALLOC, ("serialRegAssign: wont live long enough.\n"));
1145                   continue;
1146                 }
1147
1148               /* if some liverange has been spilt at the block level
1149                  and this one live beyond this block then spil this
1150                  to be safe */
1151               if (_G.blockSpil && sym->liveTo > ebbs[i]->lSeq)
1152                 {
1153                   D (D_ALLOC, ("serialRegAssign: \"spilling to be safe.\"\n"));
1154                   spillThis (sym);
1155                   continue;
1156                 }
1157               /* if trying to allocate this will cause
1158                  a spill and there is nothing to spill 
1159                  or this one is rematerializable then
1160                  spill this one */
1161               willCS = willCauseSpill (sym->nRegs, sym->regType);
1162               spillable = computeSpillable (ic);
1163               if (sym->remat ||
1164                   (willCS && bitVectIsZero (spillable)))
1165                 {
1166
1167                   D (D_ALLOC, ("serialRegAssign: \"remat spill\"\n"));
1168                   spillThis (sym);
1169                   continue;
1170
1171                 }
1172
1173               /* if it has a spillocation & is used less than
1174                  all other live ranges then spill this */
1175               if (willCS) {
1176                       if (sym->usl.spillLoc) {
1177                               symbol *leastUsed = leastUsedLR (liveRangesWith (spillable,
1178                                                                                allLRs, ebbs[i], ic));
1179                               if (leastUsed && leastUsed->used > sym->used) {
1180                                       spillThis (sym);
1181                                       continue;
1182                               }
1183                       } else {
1184                               /* if none of the liveRanges have a spillLocation then better
1185                                  to spill this one than anything else already assigned to registers */
1186                               if (liveRangesWith(spillable,noSpilLoc,ebbs[i],ic)) {
1187                                   /* if this is local to this block then we might find a block spil */
1188                                   if (!(sym->liveFrom >= ebbs[i]->fSeq && sym->liveTo <= ebbs[i]->lSeq)) {
1189                                       spillThis (sym);
1190                                       continue;
1191                                   }
1192                               }
1193                       }
1194               }
1195
1196               /* else we assign registers to it */
1197               _G.regAssigned = bitVectSetBit (_G.regAssigned, sym->key);
1198               _G.totRegAssigned = bitVectSetBit (_G.totRegAssigned, sym->key);
1199
1200               /* Special case:  Try to fit into a reg pair if
1201                  available */
1202               D (D_ALLOC, ("serialRegAssign: actually allocing regs!\n"));
1203               if ((sym->nRegs == 2) && tryAllocatingRegPair (sym))
1204                 {
1205                 }
1206               else
1207                 {
1208                   for (j = 0; j < sym->nRegs; j++)
1209                     {
1210                       sym->regs[j] = getRegGpr (ic, ebbs[i], sym);
1211
1212                       /* if the allocation falied which means
1213                          this was spilt then break */
1214                       if (!sym->regs[j])
1215                         {
1216                           D (D_ALLOC, ("Couldnt alloc (spill)\n"))
1217                             break;
1218                         }
1219                     }
1220                 }
1221               /* if it shares registers with operands make sure
1222                  that they are in the same position */
1223               if (IC_LEFT (ic) && IS_SYMOP (IC_LEFT (ic)) &&
1224                   OP_SYMBOL (IC_LEFT (ic))->nRegs && ic->op != '=')
1225                 positionRegs (OP_SYMBOL (IC_RESULT (ic)),
1226                               OP_SYMBOL (IC_LEFT (ic)));
1227               /* do the same for the right operand */
1228               if (IC_RIGHT (ic) && IS_SYMOP (IC_RIGHT (ic)) &&
1229                   OP_SYMBOL (IC_RIGHT (ic))->nRegs)
1230                 positionRegs (OP_SYMBOL (IC_RESULT (ic)),
1231                               OP_SYMBOL (IC_RIGHT (ic)));
1232
1233             }
1234         }
1235     }
1236 }
1237
1238 /*-----------------------------------------------------------------*/
1239 /* fillGaps - Try to fill in the Gaps left by Pass1                */
1240 /*-----------------------------------------------------------------*/
1241 static void fillGaps()
1242 {
1243     symbol *sym =NULL;
1244     int key =0;    
1245     
1246     if (getenv("DISABLE_FILL_GAPS")) return;
1247     
1248     /* look for livernages that was spilt by the allocator */
1249     for (sym = hTabFirstItem(liveRanges,&key) ; sym ; 
1250          sym = hTabNextItem(liveRanges,&key)) {
1251
1252         int i;
1253         int pdone = 0;
1254
1255         if (!sym->spillA || !sym->clashes || sym->remat) continue ;
1256
1257         /* find the liveRanges this one clashes with, that are
1258            still assigned to registers & mark the registers as used*/
1259         for ( i = 0 ; i < sym->clashes->size ; i ++) {
1260             int k;
1261             symbol *clr;
1262
1263             if (bitVectBitValue(sym->clashes,i) == 0 ||    /* those that clash with this */
1264                 bitVectBitValue(_G.totRegAssigned,i) == 0) /* and are still assigned to registers */
1265                 continue ;
1266
1267             assert (clr = hTabItemWithKey(liveRanges,i));
1268          
1269             /* mark these registers as used */
1270             for (k = 0 ; k < clr->nRegs ; k++ ) 
1271                 useReg(clr->regs[k]);
1272         }
1273
1274         if (willCauseSpill(sym->nRegs,sym->regType)) {
1275             /* NOPE :( clear all registers & and continue */
1276             freeAllRegs();
1277             continue ;
1278         }
1279
1280         /* THERE IS HOPE !!!! */
1281         for (i=0; i < sym->nRegs ; i++ ) {
1282                 sym->regs[i] = getRegGprNoSpil ();                
1283         }
1284
1285         /* for all its definitions check if the registers
1286            allocated needs positioning NOTE: we can position
1287            only ONCE if more than One positioning required 
1288            then give up */
1289         sym->isspilt = 0;
1290         for (i = 0 ; i < sym->defs->size ; i++ ) {
1291             if (bitVectBitValue(sym->defs,i)) {
1292                 iCode *ic;
1293                 if (!(ic = hTabItemWithKey(iCodehTab,i))) continue ;
1294                 if (SKIP_IC(ic)) continue;
1295                 assert(isSymbolEqual(sym,OP_SYMBOL(IC_RESULT(ic)))); /* just making sure */
1296                 /* if left is assigned to registers */
1297                 if (IS_SYMOP(IC_LEFT(ic)) && 
1298                     bitVectBitValue(_G.totRegAssigned,OP_SYMBOL(IC_LEFT(ic))->key)) {
1299                     pdone += positionRegs(sym,OP_SYMBOL(IC_LEFT(ic)));
1300                 }
1301                 if (IS_SYMOP(IC_RIGHT(ic)) && 
1302                     bitVectBitValue(_G.totRegAssigned,OP_SYMBOL(IC_RIGHT(ic))->key)) {
1303                     pdone += positionRegs(sym,OP_SYMBOL(IC_RIGHT(ic)));
1304                 }
1305                 if (pdone > 1) break;
1306             }
1307         }
1308         /* had to position more than once GIVE UP */
1309         if (pdone > 1) {
1310             /* UNDO all the changes we made to try this */
1311             sym->isspilt = 0;
1312             for (i=0; i < sym->nRegs ; i++ ) {
1313                 sym->regs[i] = NULL;
1314             }
1315             freeAllRegs();
1316             D(D_FILL_GAPS,("Fill Gap gave up due to positioning for %s in function %s\n",sym->name, currFunc ? currFunc->name : "UNKNOWN"));
1317             continue ;      
1318         }
1319         D(D_FILL_GAPS,("FILLED GAP for %s in function %s\n",sym->name, currFunc ? currFunc->name : "UNKNOWN"));
1320         _G.totRegAssigned = bitVectSetBit(_G.totRegAssigned,sym->key);
1321         sym->isspilt = sym->spillA = 0 ;
1322         sym->usl.spillLoc->allocreq--;
1323         freeAllRegs();
1324     }
1325 }
1326
1327 /*-----------------------------------------------------------------*/
1328 /* rUmaskForOp :- returns register mask for an operand             */
1329 /*-----------------------------------------------------------------*/
1330 bitVect *
1331 rUmaskForOp (operand * op)
1332 {
1333   bitVect *rumask;
1334   symbol *sym;
1335   int j;
1336
1337   /* only temporaries are assigned registers */
1338   if (!IS_ITEMP (op))
1339     return NULL;
1340
1341   sym = OP_SYMBOL (op);
1342
1343   /* if spilt or no registers assigned to it
1344      then nothing */
1345   if (sym->isspilt || !sym->nRegs)
1346     return NULL;
1347
1348   rumask = newBitVect (_G.nRegs);
1349
1350   for (j = 0; j < sym->nRegs; j++)
1351     {
1352       rumask = bitVectSetBit (rumask, sym->regs[j]->rIdx);
1353     }
1354
1355   return rumask;
1356 }
1357
1358 bitVect *
1359 z80_rUmaskForOp (operand * op)
1360 {
1361   return rUmaskForOp (op);
1362 }
1363
1364 /** Returns bit vector of registers used in iCode.
1365  */
1366 bitVect *
1367 regsUsedIniCode (iCode * ic)
1368 {
1369   bitVect *rmask = newBitVect (_G.nRegs);
1370
1371   /* do the special cases first */
1372   if (ic->op == IFX)
1373     {
1374       rmask = bitVectUnion (rmask,
1375                             rUmaskForOp (IC_COND (ic)));
1376       goto ret;
1377     }
1378
1379   /* for the jumptable */
1380   if (ic->op == JUMPTABLE)
1381     {
1382       rmask = bitVectUnion (rmask,
1383                             rUmaskForOp (IC_JTCOND (ic)));
1384
1385       goto ret;
1386     }
1387
1388   /* of all other cases */
1389   if (IC_LEFT (ic))
1390     rmask = bitVectUnion (rmask,
1391                           rUmaskForOp (IC_LEFT (ic)));
1392
1393
1394   if (IC_RIGHT (ic))
1395     rmask = bitVectUnion (rmask,
1396                           rUmaskForOp (IC_RIGHT (ic)));
1397
1398   if (IC_RESULT (ic))
1399     rmask = bitVectUnion (rmask,
1400                           rUmaskForOp (IC_RESULT (ic)));
1401
1402 ret:
1403   return rmask;
1404 }
1405
1406 /** For each instruction will determine the regsUsed.
1407  */
1408 static void 
1409 createRegMask (eBBlock ** ebbs, int count)
1410 {
1411   int i;
1412
1413   /* for all blocks */
1414   for (i = 0; i < count; i++)
1415     {
1416       iCode *ic;
1417
1418       if (ebbs[i]->noPath &&
1419           (ebbs[i]->entryLabel != entryLabel &&
1420            ebbs[i]->entryLabel != returnLabel))
1421         continue;
1422
1423       /* for all instructions */
1424       for (ic = ebbs[i]->sch; ic; ic = ic->next)
1425         {
1426
1427           int j;
1428
1429           if (SKIP_IC2 (ic) || !ic->rlive)
1430             continue;
1431
1432           /* first mark the registers used in this
1433              instruction */
1434           ic->rUsed = regsUsedIniCode (ic);
1435           _G.funcrUsed = bitVectUnion (_G.funcrUsed, ic->rUsed);
1436
1437           /* now create the register mask for those 
1438              registers that are in use : this is a
1439              super set of ic->rUsed */
1440           ic->rMask = newBitVect (_G.nRegs + 1);
1441
1442           /* for all live Ranges alive at this point */
1443           for (j = 1; j < ic->rlive->size; j++)
1444             {
1445               symbol *sym;
1446               int k;
1447
1448               /* if not alive then continue */
1449               if (!bitVectBitValue (ic->rlive, j))
1450                 continue;
1451
1452               /* find the live range we are interested in */
1453               if (!(sym = hTabItemWithKey (liveRanges, j)))
1454                 {
1455                   werror (E_INTERNAL_ERROR, __FILE__, __LINE__,
1456                           "createRegMask cannot find live range");
1457                   exit (0);
1458                 }
1459
1460               /* if no register assigned to it */
1461               if (!sym->nRegs || sym->isspilt)
1462                 continue;
1463
1464               /* for all the registers allocated to it */
1465               for (k = 0; k < sym->nRegs; k++)
1466                 if (sym->regs[k])
1467                   ic->rMask =
1468                     bitVectSetBit (ic->rMask, sym->regs[k]->rIdx);
1469             }
1470         }
1471     }
1472 }
1473
1474 /** Returns the rematerialized string for a remat var.
1475  */
1476 char *
1477 rematStr (symbol * sym)
1478 {
1479   char *s = buffer;
1480   iCode *ic = sym->rematiCode;
1481
1482   while (1)
1483     {
1484
1485       /* if plus or minus print the right hand side */
1486       if (ic->op == '+' || ic->op == '-')
1487         {
1488           sprintf (s, "0x%04x %c ", (int) operandLitValue (IC_RIGHT (ic)),
1489                    ic->op);
1490           s += strlen (s);
1491           ic = OP_SYMBOL (IC_LEFT (ic))->rematiCode;
1492           continue;
1493         }
1494       /* we reached the end */
1495       sprintf (s, "%s", OP_SYMBOL (IC_LEFT (ic))->rname);
1496       break;
1497     }
1498
1499   return buffer;
1500 }
1501
1502 /*-----------------------------------------------------------------*/
1503 /* regTypeNum - computes the type & number of registers required   */
1504 /*-----------------------------------------------------------------*/
1505 static void 
1506 regTypeNum (void)
1507 {
1508   symbol *sym;
1509   int k;
1510
1511   /* for each live range do */
1512   for (sym = hTabFirstItem (liveRanges, &k); sym;
1513        sym = hTabNextItem (liveRanges, &k))
1514     {
1515
1516       /* if used zero times then no registers needed */
1517       if ((sym->liveTo - sym->liveFrom) == 0)
1518         continue;
1519
1520       D (D_ALLOC, ("regTypeNum: loop on sym %p\n", sym));
1521
1522       /* if the live range is a temporary */
1523       if (sym->isitmp)
1524         {
1525
1526           /* if the type is marked as a conditional */
1527           if (sym->regType == REG_CND)
1528             continue;
1529
1530           /* if used in return only then we don't 
1531              need registers */
1532           if (sym->ruonly || sym->accuse)
1533             {
1534               if (IS_AGGREGATE (sym->type) || sym->isptr)
1535                 sym->type = aggrToPtr (sym->type, FALSE);
1536               continue;
1537             }
1538
1539           /* if not then we require registers */
1540           D (D_ALLOC, ("regTypeNum: isagg %u nRegs %u type %p\n", IS_AGGREGATE (sym->type) || sym->isptr, sym->nRegs, sym->type));
1541           sym->nRegs = ((IS_AGGREGATE (sym->type) || sym->isptr) ?
1542                         getSize (sym->type = aggrToPtr (sym->type, FALSE)) :
1543                         getSize (sym->type));
1544           D (D_ALLOC, ("regTypeNum: setting nRegs of %s (%p) to %u\n", sym->name, sym, sym->nRegs));
1545
1546           D (D_ALLOC, ("regTypeNum: setup to assign regs sym %p\n", sym));
1547
1548           if (sym->nRegs > 4)
1549             {
1550               fprintf (stderr, "allocated more than 4 or 0 registers for type ");
1551               printTypeChain (sym->type, stderr);
1552               fprintf (stderr, "\n");
1553             }
1554
1555           /* determine the type of register required */
1556           /* Always general purpose */
1557           sym->regType = REG_GPR;
1558
1559         }
1560       else
1561         {
1562           /* for the first run we don't provide */
1563           /* registers for true symbols we will */
1564           /* see how things go                  */
1565           D (D_ALLOC, ("regTypeNum: #2 setting num of %p to 0\n", sym));
1566           sym->nRegs = 0;
1567         }
1568     }
1569
1570 }
1571
1572 /** Mark all registers as free.
1573  */
1574 static void 
1575 freeAllRegs ()
1576 {
1577   int i;
1578
1579   D (D_ALLOC, ("freeAllRegs: running.\n"));
1580
1581   for (i = 0; i < _G.nRegs; i++)
1582     regsZ80[i].isFree = 1;
1583 }
1584
1585 /*-----------------------------------------------------------------*/
1586 /* deallocStackSpil - this will set the stack pointer back         */
1587 /*-----------------------------------------------------------------*/
1588 DEFSETFUNC (deallocStackSpil)
1589 {
1590   symbol *sym = item;
1591
1592   deallocLocal (sym);
1593   return 0;
1594 }
1595
1596 /** Register reduction for assignment.
1597  */
1598 static int 
1599 packRegsForAssign (iCode * ic, eBBlock * ebp)
1600 {
1601   iCode *dic, *sic;
1602
1603   D (D_ALLOC, ("packRegsForAssign: running on ic %p\n", ic));
1604
1605   if (!IS_ITEMP (IC_RIGHT (ic)) ||
1606       OP_SYMBOL (IC_RIGHT (ic))->isind ||
1607       OP_LIVETO (IC_RIGHT (ic)) > ic->seq)
1608     {
1609       return 0;
1610     }
1611
1612   /* find the definition of iTempNN scanning backwards if we find a 
1613      a use of the true symbol in before we find the definition then 
1614      we cannot */
1615   for (dic = ic->prev; dic; dic = dic->prev)
1616     {
1617       /* PENDING: Don't pack across function calls. */
1618       if (dic->op == CALL || dic->op == PCALL)
1619         {
1620           dic = NULL;
1621           break;
1622         }
1623
1624       if (SKIP_IC2 (dic))
1625         continue;
1626
1627       if (IS_SYMOP (IC_RESULT (dic)) &&
1628           IC_RESULT (dic)->key == IC_RIGHT (ic)->key)
1629         {
1630           break;
1631         }
1632
1633       if (IS_SYMOP (IC_RIGHT (dic)) &&
1634           (IC_RIGHT (dic)->key == IC_RESULT (ic)->key ||
1635            IC_RIGHT (dic)->key == IC_RIGHT (ic)->key))
1636         {
1637           dic = NULL;
1638           break;
1639         }
1640
1641       if (IS_SYMOP (IC_LEFT (dic)) &&
1642           (IC_LEFT (dic)->key == IC_RESULT (ic)->key ||
1643            IC_LEFT (dic)->key == IC_RIGHT (ic)->key))
1644         {
1645           dic = NULL;
1646           break;
1647         }
1648     }
1649
1650   if (!dic)
1651     return 0;                   /* did not find */
1652
1653   /* if the result is on stack or iaccess then it must be
1654      the same atleast one of the operands */
1655   if (OP_SYMBOL (IC_RESULT (ic))->onStack ||
1656       OP_SYMBOL (IC_RESULT (ic))->iaccess)
1657     {
1658       /* the operation has only one symbol
1659          operator then we can pack */
1660       if ((IC_LEFT (dic) && !IS_SYMOP (IC_LEFT (dic))) ||
1661           (IC_RIGHT (dic) && !IS_SYMOP (IC_RIGHT (dic))))
1662         goto pack;
1663
1664       if (!((IC_LEFT (dic) &&
1665              IC_RESULT (ic)->key == IC_LEFT (dic)->key) ||
1666             (IC_RIGHT (dic) &&
1667              IC_RESULT (ic)->key == IC_RIGHT (dic)->key)))
1668         return 0;
1669     }
1670 pack:
1671   /* found the definition */
1672   /* replace the result with the result of */
1673   /* this assignment and remove this assignment */
1674   bitVectUnSetBit(OP_SYMBOL(IC_RESULT(dic))->defs,dic->key);
1675   IC_RESULT (dic) = IC_RESULT (ic);
1676
1677   if (IS_ITEMP (IC_RESULT (dic)) && OP_SYMBOL (IC_RESULT (dic))->liveFrom > dic->seq)
1678     {
1679       OP_SYMBOL (IC_RESULT (dic))->liveFrom = dic->seq;
1680     }
1681   /* delete from liverange table also 
1682      delete from all the points inbetween and the new
1683      one */
1684   for (sic = dic; sic != ic; sic = sic->next)
1685     {
1686       bitVectUnSetBit (sic->rlive, IC_RESULT (ic)->key);
1687       if (IS_ITEMP (IC_RESULT (dic)))
1688         bitVectSetBit (sic->rlive, IC_RESULT (dic)->key);
1689     }
1690
1691   remiCodeFromeBBlock (ebp, ic);
1692   // PENDING: Check vs mcs51
1693   bitVectUnSetBit(OP_SYMBOL(IC_RESULT(ic))->defs,ic->key);
1694   hTabDeleteItem (&iCodehTab, ic->key, ic, DELETE_ITEM, NULL);
1695   OP_DEFS (IC_RESULT (dic)) = bitVectSetBit (OP_DEFS (IC_RESULT (dic)), dic->key);
1696   return 1;
1697 }
1698
1699 /** Scanning backwards looks for first assig found.
1700  */
1701 iCode *
1702 findAssignToSym (operand * op, iCode * ic)
1703 {
1704   iCode *dic;
1705
1706   for (dic = ic->prev; dic; dic = dic->prev)
1707     {
1708
1709       /* if definition by assignment */
1710       if (dic->op == '=' &&
1711           !POINTER_SET (dic) &&
1712           IC_RESULT (dic)->key == op->key)
1713         /*      &&  IS_TRUE_SYMOP(IC_RIGHT(dic)) */
1714         {
1715
1716           /* we are interested only if defined in far space */
1717           /* or in stack space in case of + & - */
1718
1719           /* if assigned to a non-symbol then return
1720              true */
1721           if (!IS_SYMOP (IC_RIGHT (dic)))
1722             break;
1723
1724           /* if the symbol is in far space then
1725              we should not */
1726           if (isOperandInFarSpace (IC_RIGHT (dic)))
1727             return NULL;
1728
1729           /* for + & - operations make sure that
1730              if it is on the stack it is the same
1731              as one of the three operands */
1732           if ((ic->op == '+' || ic->op == '-') &&
1733               OP_SYMBOL (IC_RIGHT (dic))->onStack)
1734             {
1735
1736               if (IC_RESULT (ic)->key != IC_RIGHT (dic)->key &&
1737                   IC_LEFT (ic)->key != IC_RIGHT (dic)->key &&
1738                   IC_RIGHT (ic)->key != IC_RIGHT (dic)->key)
1739                 return NULL;
1740             }
1741
1742           break;
1743
1744         }
1745
1746       /* if we find an usage then we cannot delete it */
1747       if (IC_LEFT (dic) && IC_LEFT (dic)->key == op->key)
1748         return NULL;
1749
1750       if (IC_RIGHT (dic) && IC_RIGHT (dic)->key == op->key)
1751         return NULL;
1752
1753       if (POINTER_SET (dic) && IC_RESULT (dic)->key == op->key)
1754         return NULL;
1755     }
1756
1757   /* now make sure that the right side of dic
1758      is not defined between ic & dic */
1759   if (dic)
1760     {
1761       iCode *sic = dic->next;
1762
1763       for (; sic != ic; sic = sic->next)
1764         if (IC_RESULT (sic) &&
1765             IC_RESULT (sic)->key == IC_RIGHT (dic)->key)
1766           return NULL;
1767     }
1768
1769   return dic;
1770
1771
1772 }
1773
1774 #if !DISABLE_PACKREGSFORSUPPORT
1775 // PENDING
1776
1777 /*-----------------------------------------------------------------*/
1778 /* packRegsForSupport :- reduce some registers for support calls   */
1779 /*-----------------------------------------------------------------*/
1780 static int 
1781 packRegsForSupport (iCode * ic, eBBlock * ebp)
1782 {
1783   int change = 0;
1784   /* for the left & right operand :- look to see if the
1785      left was assigned a true symbol in far space in that
1786      case replace them */
1787   D (D_ALLOC, ("packRegsForSupport: running on ic %p\n", ic));
1788
1789   if (IS_ITEMP (IC_LEFT (ic)) &&
1790       OP_SYMBOL (IC_LEFT (ic))->liveTo <= ic->seq)
1791     {
1792       iCode *dic = findAssignToSym (IC_LEFT (ic), ic);
1793       iCode *sic;
1794
1795       if (!dic)
1796         goto right;
1797
1798       /* found it we need to remove it from the
1799          block */
1800       for (sic = dic; sic != ic; sic = sic->next)
1801         bitVectUnSetBit (sic->rlive, IC_LEFT (ic)->key);
1802
1803       IC_LEFT (ic)->operand.symOperand =
1804         IC_RIGHT (dic)->operand.symOperand;
1805       IC_LEFT (ic)->key = IC_RIGHT (dic)->operand.symOperand->key;
1806       remiCodeFromeBBlock (ebp, dic);
1807       bitVectUnSetBit(OP_SYMBOL(IC_RESULT(dic))->defs,dic->key);
1808       hTabDeleteItem (&iCodehTab, dic->key, dic, DELETE_ITEM, NULL);
1809       // PENDING: Check vs mcs51
1810       change++;
1811     }
1812
1813   /* do the same for the right operand */
1814 right:
1815   if (!change &&
1816       IS_ITEMP (IC_RIGHT (ic)) &&
1817       OP_SYMBOL (IC_RIGHT (ic))->liveTo <= ic->seq)
1818     {
1819       iCode *dic = findAssignToSym (IC_RIGHT (ic), ic);
1820       iCode *sic;
1821
1822       if (!dic)
1823         return change;
1824
1825       /* found it we need to remove it from the block */
1826       for (sic = dic; sic != ic; sic = sic->next)
1827         bitVectUnSetBit (sic->rlive, IC_RIGHT (ic)->key);
1828
1829       IC_RIGHT (ic)->operand.symOperand =
1830         IC_RIGHT (dic)->operand.symOperand;
1831       IC_RIGHT (ic)->key = IC_RIGHT (dic)->operand.symOperand->key;
1832
1833       remiCodeFromeBBlock (ebp, dic);
1834       bitVectUnSetBit(OP_SYMBOL(IC_RESULT(dic))->defs,dic->key);
1835       hTabDeleteItem (&iCodehTab, dic->key, dic, DELETE_ITEM, NULL);
1836       // PENDING: vs mcs51
1837       change++;
1838     }
1839
1840   return change;
1841 }
1842 #endif
1843
1844 #define IS_OP_RUONLY(x) (x && IS_SYMOP(x) && OP_SYMBOL(x)->ruonly)
1845
1846 /** Will reduce some registers for single use.
1847  */
1848 static iCode *
1849 packRegsForOneuse (iCode * ic, operand * op, eBBlock * ebp)
1850 {
1851   bitVect *uses;
1852   iCode *dic, *sic;
1853
1854   // PENDING: Disable
1855   D (D_ALLOC, ("packRegsForOneUse: running on ic %p\n", ic));
1856
1857   /* if returning a literal then do nothing */
1858   if (!IS_SYMOP (op))
1859     return NULL;
1860
1861   /* only upto 2 bytes since we cannot predict
1862      the usage of b, & acc */
1863   if (getSize (operandType (op)) > 2)
1864     return NULL;
1865
1866   if (ic->op != RETURN &&
1867       ic->op != SEND)
1868     return NULL;
1869
1870   /* this routine will mark the a symbol as used in one 
1871      instruction use only && if the defintion is local 
1872      (ie. within the basic block) && has only one definition &&
1873      that definiion is either a return value from a 
1874      function or does not contain any variables in
1875      far space */
1876   uses = bitVectCopy (OP_USES (op));
1877   bitVectUnSetBit (uses, ic->key);      /* take away this iCode */
1878   if (!bitVectIsZero (uses))    /* has other uses */
1879     return NULL;
1880
1881   /* if it has only one defintion */
1882   if (bitVectnBitsOn (OP_DEFS (op)) > 1)
1883     return NULL;                /* has more than one definition */
1884
1885   /* get the that definition */
1886   if (!(dic =
1887         hTabItemWithKey (iCodehTab,
1888                          bitVectFirstBit (OP_DEFS (op)))))
1889     return NULL;
1890
1891   /* found the definition now check if it is local */
1892   if (dic->seq < ebp->fSeq ||
1893       dic->seq > ebp->lSeq)
1894     return NULL;                /* non-local */
1895
1896   /* now check if it is the return from a function call */
1897   if (dic->op == CALL || dic->op == PCALL)
1898     {
1899       if (ic->op != SEND && ic->op != RETURN)
1900         {
1901           OP_SYMBOL (op)->ruonly = 1;
1902           return dic;
1903         }
1904       dic = dic->next;
1905     }
1906
1907   /* otherwise check that the definition does
1908      not contain any symbols in far space */
1909   if (isOperandInFarSpace (IC_LEFT (dic)) ||
1910       isOperandInFarSpace (IC_RIGHT (dic)) ||
1911       IS_OP_RUONLY (IC_LEFT (ic)) ||
1912       IS_OP_RUONLY (IC_RIGHT (ic)))
1913     {
1914       return NULL;
1915     }
1916
1917   /* if pointer set then make sure the pointer is one byte */
1918   if (POINTER_SET (dic))
1919     return NULL;
1920
1921   if (POINTER_GET (dic))
1922     return NULL;
1923
1924   sic = dic;
1925
1926   /* also make sure the intervenening instructions
1927      don't have any thing in far space */
1928   for (dic = dic->next; dic && dic != ic; dic = dic->next)
1929     {
1930       /* if there is an intervening function call then no */
1931       if (dic->op == CALL || dic->op == PCALL)
1932         return NULL;
1933       /* if pointer set then make sure the pointer
1934          is one byte */
1935       if (POINTER_SET (dic))
1936         return NULL;
1937
1938       if (POINTER_GET (dic))
1939         return NULL;
1940
1941       /* if address of & the result is remat the okay */
1942       if (dic->op == ADDRESS_OF &&
1943           OP_SYMBOL (IC_RESULT (dic))->remat)
1944         continue;
1945
1946       /* if left or right or result is in far space */
1947       if (isOperandInFarSpace (IC_LEFT (dic)) ||
1948           isOperandInFarSpace (IC_RIGHT (dic)) ||
1949           isOperandInFarSpace (IC_RESULT (dic)) ||
1950           IS_OP_RUONLY (IC_LEFT (dic)) ||
1951           IS_OP_RUONLY (IC_RIGHT (dic)) ||
1952           IS_OP_RUONLY (IC_RESULT (dic)))
1953         {
1954           return NULL;
1955         }
1956     }
1957
1958   OP_SYMBOL (op)->ruonly = 1;
1959   return sic;
1960 }
1961
1962 /*-----------------------------------------------------------------*/
1963 /* isBitwiseOptimizable - requirements of JEAN LOUIS VERN          */
1964 /*-----------------------------------------------------------------*/
1965 static bool 
1966 isBitwiseOptimizable (iCode * ic)
1967 {
1968   sym_link *rtype = getSpec (operandType (IC_RIGHT (ic)));
1969
1970   /* bitwise operations are considered optimizable
1971      under the following conditions (Jean-Louis VERN) 
1972
1973      x & lit
1974      bit & bit
1975      bit & x
1976      bit ^ bit
1977      bit ^ x
1978      x   ^ lit
1979      x   | lit
1980      bit | bit
1981      bit | x
1982    */
1983   if (IS_LITERAL (rtype))
1984     return TRUE;
1985   return FALSE;
1986 }
1987
1988 /** Optimisations:
1989     Certian assignments involving pointers can be temporarly stored
1990     in HL.  Esp.
1991 genAssign
1992     ld  iy,#_Blah
1993     ld  bc,(iy)
1994 genAssign (ptr)
1995     ld  hl,bc
1996     ld  iy,#_Blah2
1997     ld  (iy),(hl)
1998 */
1999
2000 #if !DISABLE_PACKREGSFORACCUSE
2001 // PENDING
2002
2003 /** Pack registers for acc use.
2004     When the result of this operation is small and short lived it may
2005     be able to be stored in the accumelator.
2006  */
2007 static void 
2008 packRegsForAccUse (iCode * ic)
2009 {
2010   iCode *uic;
2011
2012   /* if this is an aggregate, e.g. a one byte char array */
2013   if (IS_AGGREGATE(operandType(IC_RESULT(ic)))) {
2014     return;
2015   }
2016
2017   /* if + or - then it has to be one byte result */
2018   if ((ic->op == '+' || ic->op == '-')
2019       && getSize (operandType (IC_RESULT (ic))) > 1)
2020     return;
2021
2022   /* if shift operation make sure right side is not a literal */
2023   if (ic->op == RIGHT_OP &&
2024       (isOperandLiteral (IC_RIGHT (ic)) ||
2025        getSize (operandType (IC_RESULT (ic))) > 1))
2026     return;
2027
2028   if (ic->op == LEFT_OP &&
2029       (isOperandLiteral (IC_RIGHT (ic)) ||
2030        getSize (operandType (IC_RESULT (ic))) > 1))
2031     return;
2032
2033   /* has only one definition */
2034   if (bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) > 1)
2035     return;
2036
2037   /* has only one use */
2038   if (bitVectnBitsOn (OP_USES (IC_RESULT (ic))) > 1)
2039     return;
2040
2041   /* and the usage immediately follows this iCode */
2042   if (!(uic = hTabItemWithKey (iCodehTab,
2043                                bitVectFirstBit (OP_USES (IC_RESULT (ic))))))
2044     return;
2045
2046   if (ic->next != uic)
2047     return;
2048
2049   /* if it is a conditional branch then we definitely can */
2050   if (uic->op == IFX)
2051     goto accuse;
2052
2053   if (uic->op == JUMPTABLE)
2054     return;
2055
2056 #if 0
2057   /* if the usage is not is an assignment or an 
2058      arithmetic / bitwise / shift operation then not */
2059   if (POINTER_SET (uic) &&
2060       getSize (aggrToPtr (operandType (IC_RESULT (uic)), FALSE)) > 1)
2061     return;
2062 #endif
2063
2064   if (uic->op != '=' &&
2065       !IS_ARITHMETIC_OP (uic) &&
2066       !IS_BITWISE_OP (uic) &&
2067       uic->op != LEFT_OP &&
2068       uic->op != RIGHT_OP)
2069     return;
2070
2071   /* if used in ^ operation then make sure right is not a 
2072      literl */
2073   if (uic->op == '^' && isOperandLiteral (IC_RIGHT (uic)))
2074     return;
2075
2076   /* if shift operation make sure right side is not a literal */
2077   if (uic->op == RIGHT_OP &&
2078       (isOperandLiteral (IC_RIGHT (uic)) ||
2079        getSize (operandType (IC_RESULT (uic))) > 1))
2080     return;
2081
2082   if (uic->op == LEFT_OP &&
2083       (isOperandLiteral (IC_RIGHT (uic)) ||
2084        getSize (operandType (IC_RESULT (uic))) > 1))
2085     return;
2086
2087 #if 0
2088   /* make sure that the result of this icode is not on the
2089      stack, since acc is used to compute stack offset */
2090   if (IS_TRUE_SYMOP (IC_RESULT (uic)) &&
2091       OP_SYMBOL (IC_RESULT (uic))->onStack)
2092     return;
2093 #endif
2094
2095 #if 0
2096   /* if either one of them in far space then we cannot */
2097   if ((IS_TRUE_SYMOP (IC_LEFT (uic)) &&
2098        isOperandInFarSpace (IC_LEFT (uic))) ||
2099       (IS_TRUE_SYMOP (IC_RIGHT (uic)) &&
2100        isOperandInFarSpace (IC_RIGHT (uic))))
2101     return;
2102 #endif
2103
2104   /* if the usage has only one operand then we can */
2105   if (IC_LEFT (uic) == NULL ||
2106       IC_RIGHT (uic) == NULL)
2107     goto accuse;
2108
2109   /* make sure this is on the left side if not
2110      a '+' since '+' is commutative */
2111   if (ic->op != '+' &&
2112       IC_LEFT (uic)->key != IC_RESULT (ic)->key)
2113     return;
2114
2115   // See mcs51 ralloc for reasoning
2116 #if 0
2117   /* if one of them is a literal then we can */
2118   if ((IC_LEFT (uic) && IS_OP_LITERAL (IC_LEFT (uic))) ||
2119       (IC_RIGHT (uic) && IS_OP_LITERAL (IC_RIGHT (uic))))
2120     {
2121       goto accuse;
2122       return;
2123     }
2124 #endif
2125
2126 /** This is confusing :)  Guess for now */
2127   if (IC_LEFT (uic)->key == IC_RESULT (ic)->key &&
2128       (IS_ITEMP (IC_RIGHT (uic)) ||
2129        (IS_TRUE_SYMOP (IC_RIGHT (uic)))))
2130     goto accuse;
2131
2132   if (IC_RIGHT (uic)->key == IC_RESULT (ic)->key &&
2133       (IS_ITEMP (IC_LEFT (uic)) ||
2134        (IS_TRUE_SYMOP (IC_LEFT (uic)))))
2135     goto accuse;
2136   return;
2137 accuse:
2138   OP_SYMBOL (IC_RESULT (ic))->accuse = ACCUSE_A;
2139 }
2140 #endif
2141
2142 static void 
2143 packRegsForHLUse (iCode * ic)
2144 {
2145   iCode *uic;
2146
2147   /* PENDING: Could do IFX */
2148   if (ic->op == IFX)
2149     {
2150       return;
2151     }
2152
2153   /* has only one definition */
2154   if (bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) > 1)
2155     {
2156       D (D_HLUSE, ("  + Dropping as has more than one def\n"));
2157       return;
2158     }
2159
2160   /* has only one use */
2161   if (bitVectnBitsOn (OP_USES (IC_RESULT (ic))) > 1)
2162     {
2163       D (D_HLUSE, ("  + Dropping as has more than one use\n"));
2164       return;
2165     }
2166
2167   /* and the usage immediately follows this iCode */
2168   if (!(uic = hTabItemWithKey (iCodehTab,
2169                                bitVectFirstBit (OP_USES (IC_RESULT (ic))))))
2170     {
2171       D (D_HLUSE, ("  + Dropping as usage isn't in this block\n"));
2172       return;
2173     }
2174
2175   if (ic->next != uic)
2176     {
2177       D (D_HLUSE, ("  + Dropping as usage doesn't follow this\n"));
2178       return;
2179     }
2180
2181   if (uic->op ==IFX)
2182     {
2183       return;
2184     }
2185
2186   if (getSize (operandType (IC_RESULT (ic))) != 2 ||
2187       (IC_LEFT(uic) && getSize (operandType (IC_LEFT (uic))) != 2) ||
2188       (IC_RIGHT(uic) && getSize (operandType (IC_RIGHT (uic))) != 2))
2189     {
2190       D (D_HLUSE, ("  + Dropping as the result size is not 2\n"));
2191       return;
2192     }
2193
2194   if (IS_Z80)
2195     {
2196       if (ic->op == CAST && uic->op == IPUSH)
2197         goto hluse;
2198       if (ic->op == ADDRESS_OF && uic->op == IPUSH)
2199         goto hluse;
2200       if (ic->op == ADDRESS_OF && POINTER_GET (uic) && IS_ITEMP( IC_RESULT (uic)))
2201         goto hluse;
2202       if (ic->op == CALL && ic->parmBytes == 0 && (uic->op == '-' || uic->op == '+'))
2203         goto hluse;
2204     }
2205   else if (IS_GB)
2206     {
2207       /* Case of assign a constant to offset in a static array. */
2208       if (ic->op == '+' && IS_VALOP (IC_RIGHT (ic)))
2209         {
2210           if (uic->op == '=' && POINTER_SET (uic))
2211             {
2212               goto hluse;
2213             }
2214           else if (uic->op == IPUSH && getSize (operandType (IC_LEFT (uic))) == 2)
2215             {
2216               goto hluse;
2217             }
2218         }
2219     }
2220
2221   D (D_HLUSE, ("  + Dropping as it's a bad op\n"));
2222   return;
2223 hluse:
2224   OP_SYMBOL (IC_RESULT (ic))->accuse = ACCUSE_SCRATCH;
2225 }
2226
2227 static iCode *
2228 packRegsForHLUse3 (iCode * lic, operand * op, eBBlock * ebp)
2229 {
2230   int i, key;
2231   symbol *sym;
2232   iCode *ic, *dic;
2233   bool isFirst = TRUE;
2234
2235 #if 0
2236   printf("Checking:\n");
2237   piCode(lic, NULL);
2238 #endif
2239
2240   if ( OP_SYMBOL(op)->accuse)
2241     {
2242       return NULL;
2243     }
2244
2245   if (OP_SYMBOL(op)->remat)
2246     {
2247       return NULL; 
2248     }
2249
2250   /* Only defined once */
2251   if (bitVectnBitsOn (OP_DEFS (op)) > 1)
2252     return NULL;
2253
2254   if (getSize (operandType (op)) > 2)
2255     return NULL;
2256
2257   /* And this is the definition */
2258   if (bitVectFirstBit (OP_DEFS (op)) != lic->key)
2259     return NULL;
2260
2261   /* first check if any overlapping liverange has already been
2262      assigned to DPTR */
2263   if (OP_SYMBOL(op)->clashes) 
2264     {
2265       for (i = 0 ; i < OP_SYMBOL(op)->clashes->size ; i++ ) 
2266         {
2267           if (bitVectBitValue(OP_SYMBOL(op)->clashes,i)) 
2268             {
2269               sym = hTabItemWithKey(liveRanges,i);
2270               if (sym->accuse == ACCUSE_SCRATCH)
2271                 {
2272                   return NULL;
2273                 }
2274             }
2275         }
2276     }
2277
2278   /* Nothing else that clashes with this is using the scratch
2279      register.  Scan through all of the intermediate instructions and
2280      see if any of them could nuke HL.
2281   */
2282   dic = ic = hTabFirstItemWK(iCodeSeqhTab,OP_SYMBOL(op)->liveFrom);
2283
2284   for (; ic && ic->seq <= OP_SYMBOL(op)->liveTo;
2285        ic = hTabNextItem(iCodeSeqhTab,&key)) 
2286     {
2287 #if 0
2288       piCode(ic, NULL);
2289       printf("(op: %u)\n", ic->op);
2290 #endif
2291       if (isFirst)
2292         {
2293           isFirst = FALSE;
2294           if (ic->op == ADDRESS_OF)
2295             continue;
2296           if (POINTER_GET (ic))
2297             continue;
2298         }
2299
2300       if (IC_RESULT(ic) && IS_SYMOP(IC_RESULT(ic))
2301           && isOperandInDirSpace (IC_RESULT (ic)))
2302         return NULL;
2303
2304       if (IC_LEFT(ic) && IS_SYMOP(IC_LEFT(ic))
2305           && isOperandInDirSpace (IC_LEFT (ic)))
2306         return NULL;
2307
2308       if (IC_RIGHT(ic) && IS_SYMOP(IC_RIGHT(ic))
2309           && isOperandInDirSpace (IC_RIGHT (ic)))
2310         return NULL;
2311
2312       /* Handle the non left/right/result ones first */
2313       if (ic->op == IFX)
2314         continue;
2315       if (ic->op == JUMPTABLE)
2316         return NULL;
2317
2318       if (SKIP_IC2(ic))
2319         continue;
2320
2321       if (ic->op == CAST)
2322         continue;
2323
2324       if (ic->op == IPUSH && isOperandEqual (op, IC_LEFT (ic)))
2325         continue;
2326
2327       if (ic->op == SEND && isOperandEqual (op, IC_LEFT (ic)))
2328         continue;
2329
2330       if (ic->op == CALL && isOperandEqual (op, IC_RESULT (ic)))
2331         continue;
2332
2333       if ((ic->op == '=' && !POINTER_SET(ic)) ||
2334           ic->op == UNARYMINUS ||
2335           ic->op == '+' ||
2336           ic->op == '-' ||
2337           0)
2338         continue;
2339
2340       if (POINTER_GET (ic) && isOperandEqual (op, IC_LEFT (ic)))
2341         continue;
2342
2343       if (IS_VALOP (IC_RIGHT (ic)) &&
2344           (ic->op == EQ_OP ||
2345            0))
2346         {
2347           continue;
2348         }
2349
2350       /* By default give up */
2351       return NULL;
2352     }
2353
2354 #if 0
2355   printf("Succeeded!\n");
2356 #endif
2357   OP_SYMBOL (op)->accuse = ACCUSE_SCRATCH;
2358
2359   return dic;
2360 }
2361
2362 static iCode *
2363 packRegsForIYUse (iCode * lic, operand * op, eBBlock * ebp)
2364 {
2365   int i, key;
2366   symbol *sym;
2367   iCode *ic, *dic;
2368   bitVect *uses;
2369
2370 #if 0
2371   printf("Checking IY on %p lic key %u first def %u:\n", OP_SYMBOL(op), lic->key, bitVectFirstBit(OP_DEFS(op)));
2372   piCode(lic, NULL);
2373 #endif
2374
2375   if ( OP_SYMBOL(op)->accuse)
2376     {
2377       return NULL;
2378     }
2379
2380   if (OP_SYMBOL(op)->remat)
2381     {
2382       return NULL; 
2383     }
2384
2385   /* Only defined once */
2386   if (bitVectnBitsOn (OP_DEFS (op)) > 1)
2387     return NULL;
2388
2389   /* And this is the definition */
2390   if (bitVectFirstBit (OP_DEFS (op)) != lic->key)
2391     return NULL;
2392
2393   /* first check if any overlapping liverange has already been
2394      assigned to DPTR */
2395   if (OP_SYMBOL(op)->clashes) 
2396     {
2397       for (i = 0 ; i < OP_SYMBOL(op)->clashes->size ; i++ ) 
2398         {
2399           if (bitVectBitValue(OP_SYMBOL(op)->clashes,i)) 
2400             {
2401               sym = hTabItemWithKey(liveRanges,i);
2402               if (sym->accuse == ACCUSE_IY)
2403                 {
2404                   return NULL;
2405                 }
2406             }
2407         }
2408     }
2409
2410   /* Only a few instructions can load into IY */
2411   if (lic->op != '=')
2412     {
2413       return NULL;
2414     }
2415
2416   /* Nothing else that clashes with this is using the scratch
2417      register.  Scan through all of the intermediate instructions and
2418      see if any of them could nuke HL.
2419   */
2420   dic = ic = hTabFirstItemWK(iCodeSeqhTab,OP_SYMBOL(op)->liveFrom);
2421   uses = OP_USES(op);
2422
2423   for (; ic && ic->seq <= OP_SYMBOL(op)->liveTo;
2424        ic = hTabNextItem(iCodeSeqhTab,&key)) 
2425     {
2426 #if 0
2427       piCode(ic, NULL);
2428       printf("(op: %u uses %u)\n", ic->op, bitVectBitValue(uses, ic->key));
2429 #endif
2430
2431       if (ic->op == PCALL || 
2432           ic->op == CALL ||
2433           ic->op == JUMPTABLE
2434           )
2435         return NULL;
2436
2437       if (SKIP_IC2(ic))
2438         continue;
2439
2440       /* Only certain rules will work against IY.  Check if this iCode uses
2441          this symbol. */
2442       if (bitVectBitValue(uses, ic->key) != 0)
2443         {
2444           if (ic->op == IFX)
2445             return NULL;
2446
2447           if (ic->op == '=' &&
2448               isOperandEqual(IC_RESULT(ic), op))
2449             continue;
2450
2451           if (ic->op == GET_VALUE_AT_ADDRESS &&
2452               isOperandEqual(IC_LEFT(ic), op))
2453             continue;
2454
2455           if (isOperandEqual(IC_RESULT(ic), IC_LEFT(ic)) == FALSE)
2456             return NULL;
2457
2458           if (IC_RIGHT (ic) && IS_VALOP (IC_RIGHT (ic)))
2459             {
2460               if (ic->op == '+' ||
2461                   ic->op == '-')
2462                 {
2463                   /* Only works if the constant is small */
2464                   if (operandLitValue (IC_RIGHT (ic)) < 4)
2465                     continue;
2466                 }
2467             }
2468
2469           return NULL;
2470         }
2471       else
2472         {
2473           if (ic->op == IFX)
2474             continue;
2475
2476           /* This iCode doesn't use the sym.  See if this iCode preserves IY.
2477            */
2478           if (IC_RESULT(ic) && IS_SYMOP(IC_RESULT(ic)) && 
2479               isOperandInDirSpace(IC_RESULT(ic)))
2480             return NULL;
2481           
2482           if (IC_RIGHT(ic) && IS_SYMOP(IC_RIGHT(ic)) && 
2483               isOperandInFarSpace(IC_RIGHT(ic)))
2484             return NULL;
2485
2486           if (IC_LEFT(ic) && IS_SYMOP(IC_LEFT(ic)) && 
2487               isOperandInFarSpace(IC_LEFT(ic)))
2488             return NULL;
2489           
2490           continue;
2491         }
2492
2493       /* By default give up */
2494       return NULL;
2495     }
2496
2497 #if 0
2498   printf("Succeeded IY!\n");
2499 #endif
2500   OP_SYMBOL (op)->accuse = ACCUSE_IY;
2501
2502   return dic;
2503 }
2504
2505 /** Returns TRUE if this operation can use acc and if it preserves the value.
2506  */
2507 static bool 
2508 opPreservesA (iCode * uic)
2509 {
2510   if (uic->op == IFX)
2511     {
2512       /* If we've gotten this far then the thing to compare must be
2513          small enough and must be in A.
2514       */
2515       return TRUE;
2516     }
2517
2518   if (uic->op == JUMPTABLE)
2519     {
2520       D (D_ACCUSE2, ("  + Dropping as operation is a Jumptable\n"));
2521       return FALSE;
2522     }
2523
2524   /* A pointer assign preserves A if A is the left value. */
2525   if (uic->op == '=' && POINTER_SET (uic))
2526     {
2527       return TRUE;
2528     }
2529
2530   /* if the usage has only one operand then we can */
2531   /* PENDING: check */
2532   if (IC_LEFT (uic) == NULL ||
2533       IC_RIGHT (uic) == NULL)
2534     {
2535       D (D_ACCUSE2, ("  + Dropping as operation has only one operand\n"));
2536       return FALSE;
2537     }
2538
2539   /* PENDING: check this rule */
2540   if (getSize (operandType (IC_RESULT (uic))) > 1)
2541     {
2542       D (D_ACCUSE2, ("  + Dropping as operation has size is too big\n"));
2543       return FALSE;
2544     }
2545
2546
2547   /* Disabled all of the old rules as they weren't verified and have
2548      caused at least one problem.
2549    */
2550   return FALSE;
2551 }
2552
2553 /** Returns true if this operand preserves the value of A.
2554  */
2555 static bool
2556 opIgnoresA (iCode * ic, iCode * uic)
2557 {
2558   /* A increment of an iTemp by a constant is OK. */
2559   if ( uic->op == '+' &&
2560        IS_ITEMP (IC_LEFT (uic)) &&
2561        IS_ITEMP (IC_RESULT (uic)) &&
2562        IS_OP_LITERAL (IC_RIGHT (uic)))
2563     {
2564       unsigned int icount = (unsigned int) floatFromVal (IC_RIGHT (uic)->operand.valOperand);
2565
2566       /* Being an ITEMP means that we're already a symbol. */
2567       if (icount == 1 &&
2568           IC_RESULT (uic)->operand.symOperand->key == IC_LEFT (uic)->operand.symOperand->key
2569           )
2570         {
2571           return TRUE;
2572         }
2573     }
2574   else if (uic->op == '=' && !POINTER_SET (uic))
2575     {
2576       /* If they are equal and get optimised out then things are OK. */
2577       if (isOperandEqual (IC_RESULT (uic), IC_RIGHT (uic)))
2578         {
2579           /* Straight assign is OK. */
2580           return TRUE;
2581         }
2582     }
2583
2584   return FALSE;
2585 }
2586
2587
2588 /* Some optimisation cases:
2589
2590    1. Part of memcpy
2591 ;       genPointerGet
2592         ld      l,-4(ix)
2593         ld      h,-3(ix)
2594         ld      c,(hl)
2595 ;       genPlus
2596         inc     -4(ix)
2597         jp      nz,00108$
2598         inc     -3(ix)
2599 00108$:
2600 ;       genAssign (pointer)
2601         ld      a,c
2602         ld      (de),a
2603  
2604       want to optimise down to:
2605         ld       hl,-4(ix) ...
2606         ld       a,(hl)
2607         inc      -4(ix).w  ...
2608         ld       (de),a
2609
2610       So genPointer get is OK
2611       genPlus where the right is constant, left is iTemp, and result is same as left
2612       genAssign (pointer) is OK
2613
2614     2. Part of _strcpy
2615 ;       genPointerGet
2616         ld      a,(de)
2617         ld      c,a
2618 ;       genIfx
2619         xor     a,a
2620         or      a,c
2621         jp      z,00103$
2622 ;       _strcpy.c 40
2623 ;       genAssign (pointer)
2624 ;       AOP_STK for _strcpy_to_1_1
2625         ld      l,-2(ix)
2626         ld      h,-1(ix)
2627         ld      (hl),c
2628
2629       want to optimise down to:
2630         ld      a,(de)
2631         or      a,a
2632         jp      z,00103$
2633         ld      (bc),a
2634       
2635       So genIfx where IC_COND has size of 1 and is a constant.
2636 */
2637
2638 /** Pack registers for acc use.
2639     When the result of this operation is small and short lived it may
2640     be able to be stored in the accumulator.
2641
2642     Note that the 'A preserving' list is currently emperical :)
2643  */
2644 static void 
2645 packRegsForAccUse2 (iCode * ic)
2646 {
2647   iCode *uic;
2648
2649   D (D_ACCUSE2, ("packRegsForAccUse2: running on ic %p line %u\n", ic, ic->lineno));
2650
2651   /* Filter out all but those 'good' commands */
2652   if (
2653        !POINTER_GET (ic) &&
2654        ic->op != '+' &&
2655        !IS_BITWISE_OP (ic) &&
2656        ic->op != '=' &&
2657        ic->op != EQ_OP &&
2658        ic->op != '<' &&
2659        ic->op != '>' &&
2660        ic->op != CAST &&
2661        ic->op != GETHBIT &&
2662        1)
2663     {
2664       D (D_ACCUSE2, ("  + Dropping as not a 'good' source command\n"));
2665       return;
2666     }
2667
2668   /* if + or - then it has to be one byte result.
2669      MLH: Ok.
2670    */
2671   if ((ic->op == '+' || ic->op == '-')
2672       && getSize (operandType (IC_RESULT (ic))) > 1)
2673     {
2674       D (D_ACCUSE2, ("  + Dropping as it's a big + or -\n"));
2675       return;
2676     }
2677
2678   /* has only one definition */
2679   if (bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) > 1)
2680     {
2681       D (D_ACCUSE2, ("  + Dropping as it has more than one definition\n"));
2682       return;
2683     }
2684
2685   /* Right.  We may be able to propagate it through if:
2686      For each in the chain of uses the intermediate is OK.
2687    */
2688   /* Get next with 'uses result' bit on
2689      If this->next == next
2690      Validate use of next
2691      If OK, increase count
2692    */
2693   /* and the usage immediately follows this iCode */
2694   if (!(uic = hTabItemWithKey (iCodehTab,
2695                                bitVectFirstBit (OP_USES (IC_RESULT (ic))))))
2696     {
2697       D (D_ACCUSE2, ("  + Dropping as usage does not follow first\n"));
2698       return;
2699     }
2700
2701   {
2702     /* Create a copy of the OP_USES bit vect */
2703     bitVect *uses = bitVectCopy (OP_USES (IC_RESULT (ic)));
2704     int setBit;
2705     iCode *scan = ic, *next;
2706
2707     do
2708       {
2709         setBit = bitVectFirstBit (uses);
2710         next = hTabItemWithKey (iCodehTab, setBit);
2711         if (scan->next == next)
2712           {
2713             D (D_ACCUSE2_VERBOSE, ("  ! Is next in line\n"));
2714
2715             bitVectUnSetBit (uses, setBit);
2716             /* Still contigous. */
2717             if (!opPreservesA (next))
2718               {
2719                 D (D_ACCUSE2, ("  + Dropping as operation doesn't preserve A\n"));
2720                 return;
2721               }
2722             D (D_ACCUSE2_VERBOSE, ("  ! Preserves A, so continue scanning\n"));
2723             scan = next;
2724           }
2725         else if (scan->next == NULL && bitVectnBitsOn (uses) == 1 && next != NULL)
2726           {
2727             if (next->prev == NULL)
2728               {
2729                 if (!opPreservesA (next))
2730                   {
2731                     D (D_ACCUSE2, ("  + Dropping as operation doesn't preserve A #2\n"));
2732                     return;
2733                   }
2734                 bitVectUnSetBit (uses, setBit);
2735                 scan = next;
2736               }
2737             else 
2738               {
2739                 D (D_ACCUSE2, ("  + Dropping as last in list and next doesn't start a block\n"));
2740                 return;
2741               }
2742           }
2743         else if (scan->next == NULL)
2744           {
2745             D (D_ACCUSE2, ("  + Dropping as hit the end of the list\n"));
2746             D (D_ACCUSE2, ("  + Next in htab: %p\n", next));
2747             return;
2748           }
2749         else
2750           {
2751             if (opIgnoresA (ic, scan->next))
2752               {
2753                 /* Safe for now. */
2754                 scan = scan->next;
2755                 D (D_ACCUSE2_VERBOSE, ("  ! Op ignores A, so continue scanning\n"));
2756               }
2757             else
2758               {
2759                 D (D_ACCUSE2, ("  + Dropping as parts are not consecuitive and intermediate might use A\n"));
2760                 return;
2761               }
2762           }
2763       }
2764     while (!bitVectIsZero (uses));
2765
2766     OP_SYMBOL (IC_RESULT (ic))->accuse = ACCUSE_A;
2767     return;
2768   }
2769 }
2770
2771 /** Does some transformations to reduce register pressure.
2772  */
2773 static void 
2774 packRegisters (eBBlock * ebp)
2775 {
2776   iCode *ic;
2777   int change = 0;
2778
2779   D (D_ALLOC, ("packRegisters: entered.\n"));
2780
2781   while (1 && !DISABLE_PACK_ASSIGN)
2782     {
2783       change = 0;
2784       /* look for assignments of the form */
2785       /* iTempNN = TRueSym (someoperation) SomeOperand */
2786       /*       ....                       */
2787       /* TrueSym := iTempNN:1             */
2788       for (ic = ebp->sch; ic; ic = ic->next)
2789         {
2790           /* find assignment of the form TrueSym := iTempNN:1 */
2791           if (ic->op == '=' && !POINTER_SET (ic))
2792             change += packRegsForAssign (ic, ebp);
2793         }
2794       if (!change)
2795         break;
2796     }
2797
2798   for (ic = ebp->sch; ic; ic = ic->next)
2799     {
2800       /* Safe: address of a true sym is always constant. */
2801       /* if this is an itemp & result of a address of a true sym 
2802          then mark this as rematerialisable   */
2803       D (D_ALLOC, ("packRegisters: looping on ic %p\n", ic));
2804
2805       if (ic->op == ADDRESS_OF &&
2806           IS_ITEMP (IC_RESULT (ic)) &&
2807           IS_TRUE_SYMOP (IC_LEFT (ic)) &&
2808           bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) == 1 &&
2809           !OP_SYMBOL (IC_LEFT (ic))->onStack)
2810         {
2811
2812           OP_SYMBOL (IC_RESULT (ic))->remat = 1;
2813           OP_SYMBOL (IC_RESULT (ic))->rematiCode = ic;
2814           OP_SYMBOL (IC_RESULT (ic))->usl.spillLoc = NULL;
2815         }
2816
2817       /* Safe: just propagates the remat flag */
2818       /* if straight assignment then carry remat flag if this is the
2819          only definition */
2820       if (ic->op == '=' &&
2821           !POINTER_SET (ic) &&
2822           IS_SYMOP (IC_RIGHT (ic)) &&
2823           OP_SYMBOL (IC_RIGHT (ic))->remat &&
2824           bitVectnBitsOn (OP_SYMBOL (IC_RESULT (ic))->defs) <= 1)
2825         {
2826
2827           OP_SYMBOL (IC_RESULT (ic))->remat =
2828             OP_SYMBOL (IC_RIGHT (ic))->remat;
2829           OP_SYMBOL (IC_RESULT (ic))->rematiCode =
2830             OP_SYMBOL (IC_RIGHT (ic))->rematiCode;
2831         }
2832
2833       /* if the condition of an if instruction is defined in the
2834          previous instruction then mark the itemp as a conditional */
2835       if ((IS_CONDITIONAL (ic) ||
2836            ((ic->op == BITWISEAND ||
2837              ic->op == '|' ||
2838              ic->op == '^') &&
2839             isBitwiseOptimizable (ic))) &&
2840           ic->next && ic->next->op == IFX &&
2841           bitVectnBitsOn (OP_USES(IC_RESULT(ic)))==1 &&
2842           isOperandEqual (IC_RESULT (ic), IC_COND (ic->next)) &&
2843           OP_SYMBOL (IC_RESULT (ic))->liveTo <= ic->next->seq)
2844         {
2845
2846           OP_SYMBOL (IC_RESULT (ic))->regType = REG_CND;
2847           continue;
2848         }
2849
2850 #if 0
2851       /* reduce for support function calls */
2852       if (ic->supportRtn || ic->op == '+' || ic->op == '-')
2853         packRegsForSupport (ic, ebp);
2854 #endif
2855
2856       /* some cases the redundant moves can
2857          can be eliminated for return statements */
2858       if (ic->op == RETURN || ic->op == SEND)
2859         {
2860           packRegsForOneuse (ic, IC_LEFT (ic), ebp);
2861         }
2862
2863       /* if pointer set & left has a size more than
2864          one and right is not in far space */
2865       if (!DISABLE_PACK_ONE_USE &&
2866           POINTER_SET (ic) &&
2867           /* MLH: no such thing.
2868              !isOperandInFarSpace(IC_RIGHT(ic)) && */
2869           !OP_SYMBOL (IC_RESULT (ic))->remat &&
2870           !IS_OP_RUONLY (IC_RIGHT (ic)) &&
2871           getSize (aggrToPtr (operandType (IC_RESULT (ic)), FALSE)) > 1)
2872         {
2873
2874           packRegsForOneuse (ic, IC_RESULT (ic), ebp);
2875         }
2876
2877       /* if pointer get */
2878       if (!DISABLE_PACK_ONE_USE &&
2879           POINTER_GET (ic) &&
2880       /* MLH: dont have far space
2881          !isOperandInFarSpace(IC_RESULT(ic))&& */
2882           !OP_SYMBOL (IC_LEFT (ic))->remat &&
2883           !IS_OP_RUONLY (IC_RESULT (ic)) &&
2884           getSize (aggrToPtr (operandType (IC_LEFT (ic)), FALSE)) > 1)
2885         {
2886
2887           packRegsForOneuse (ic, IC_LEFT (ic), ebp);
2888         }
2889
2890       /* pack registers for accumulator use, when the result of an
2891          arithmetic or bit wise operation has only one use, that use is
2892          immediately following the defintion and the using iCode has
2893          only one operand or has two operands but one is literal & the
2894          result of that operation is not on stack then we can leave the
2895          result of this operation in acc:b combination */
2896
2897       if (!DISABLE_PACK_HL && IS_ITEMP (IC_RESULT (ic)))
2898         {
2899           if (IS_GB)
2900             packRegsForHLUse (ic);
2901           else
2902             packRegsForHLUse3 (ic, IC_RESULT (ic), ebp);
2903         }
2904
2905       if (!DISABLE_PACK_HL && IS_ITEMP (IC_RESULT (ic)) && IS_Z80)
2906         {
2907           packRegsForIYUse (ic, IC_RESULT (ic), ebp);
2908         }
2909
2910       if (!DISABLE_PACK_ACC && IS_ITEMP (IC_RESULT (ic)) &&
2911           getSize (operandType (IC_RESULT (ic))) == 1)
2912         {
2913           packRegsForAccUse2 (ic);
2914         }
2915     }
2916 }
2917
2918 /** Joins together two byte constant pushes into one word push.
2919  */
2920 static iCode *
2921 joinPushes (iCode *lic)
2922 {
2923   iCode *ic, *uic;
2924
2925   for (ic = lic; ic; ic = ic->next)
2926     {
2927       int first, second;
2928       value *val;
2929
2930       uic = ic->next;
2931
2932       /* Anything past this? */
2933       if (uic == NULL)
2934         {
2935           continue;
2936         }
2937       /* This and the next pushes? */
2938       if (ic->op != IPUSH || uic->op != IPUSH)
2939         {
2940           continue;
2941         }
2942       /* Both literals? */
2943       if ( !IS_OP_LITERAL (IC_LEFT (ic)) || !IS_OP_LITERAL (IC_LEFT (uic)))
2944         {
2945           continue;
2946         }
2947       /* Both characters? */
2948       if ( getSize (operandType (IC_LEFT (ic))) != 1 || getSize (operandType (IC_LEFT (uic))) != 1)
2949         {
2950           continue;
2951         }
2952       /* Pull out the values, make a new type, and create the new iCode for it.
2953        */
2954       first = (int)operandLitValue ( IC_LEFT (ic));
2955       second = (int)operandLitValue ( IC_LEFT (uic));
2956
2957       sprintf (buffer, "%u", ((first << 8) | (second & 0xFF)) & 0xFFFFU);
2958       val = constVal (buffer);
2959       SPEC_NOUN (val->type) = V_INT;
2960       IC_LEFT (ic)->operand.valOperand = val;
2961       
2962       /* Now remove the second one from the list. */
2963       ic->next = uic->next;
2964       if (uic->next)
2965         {
2966           /* Patch up the reverse link */
2967           uic->next->prev = ic;
2968         }
2969     }
2970
2971   return lic;
2972 }
2973
2974 /*-----------------------------------------------------------------*/
2975 /* assignRegisters - assigns registers to each live range as need  */
2976 /*-----------------------------------------------------------------*/
2977 void 
2978 z80_assignRegisters (eBBlock ** ebbs, int count)
2979 {
2980   iCode *ic;
2981   int i;
2982
2983   D (D_ALLOC, ("\n-> z80_assignRegisters: entered.\n"));
2984
2985   setToNull ((void *) &_G.funcrUsed);
2986   setToNull ((void *) &_G.totRegAssigned);  
2987   _G.stackExtend = _G.dataExtend = 0;
2988
2989   if (IS_GB)
2990     {
2991       /* DE is required for the code gen. */
2992       _G.nRegs = GBZ80_MAX_REGS;
2993       regsZ80 = _gbz80_regs;
2994     }
2995   else
2996     {
2997       _G.nRegs = Z80_MAX_REGS;
2998       regsZ80 = _z80_regs;
2999     }
3000
3001   /* change assignments this will remove some
3002      live ranges reducing some register pressure */
3003   for (i = 0; i < count; i++)
3004     packRegisters (ebbs[i]);
3005
3006   if (options.dump_pack)
3007     dumpEbbsToFileExt (DUMP_PACK, ebbs, count);
3008
3009   /* first determine for each live range the number of 
3010      registers & the type of registers required for each */
3011   regTypeNum ();
3012
3013   /* and serially allocate registers */
3014   serialRegAssign (ebbs, count);
3015
3016   freeAllRegs ();
3017   fillGaps();
3018
3019   /* if stack was extended then tell the user */
3020   if (_G.stackExtend)
3021     {
3022 /*      werror(W_TOOMANY_SPILS,"stack", */
3023 /*             _G.stackExtend,currFunc->name,""); */
3024       _G.stackExtend = 0;
3025     }
3026
3027   if (_G.dataExtend)
3028     {
3029 /*      werror(W_TOOMANY_SPILS,"data space", */
3030 /*             _G.dataExtend,currFunc->name,""); */
3031       _G.dataExtend = 0;
3032     }
3033
3034   if (options.dump_rassgn) {
3035     dumpEbbsToFileExt (DUMP_RASSGN, ebbs, count);
3036     dumpLiveRanges (DUMP_LRANGE, liveRanges);
3037   }
3038
3039   /* after that create the register mask
3040      for each of the instruction */
3041   createRegMask (ebbs, count);
3042
3043   /* now get back the chain */
3044   ic = iCodeLabelOptimize (iCodeFromeBBlock (ebbs, count));
3045
3046   ic = joinPushes (ic);
3047
3048   /* redo that offsets for stacked automatic variables */
3049   redoStackOffsets ();
3050
3051   genZ80Code (ic);
3052
3053   /* free up any stackSpil locations allocated */
3054   applyToSet (_G.stackSpil, deallocStackSpil);
3055   _G.slocNum = 0;
3056   setToNull ((void **) &_G.stackSpil);
3057   setToNull ((void **) &_G.spiltSet);
3058   /* mark all registers as free */
3059   freeAllRegs ();
3060
3061   return;
3062 }