* Added common.h
[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, ix, iy, and a are reserved for the code generator,
11     leaving bc and de for allocation.  The extra register pressure
12     from reserving hl is made up for by how much easier the sub
13     operations become.  You could swap hl for iy if the undocumented
14     iyl/iyh instructions are available.
15
16     The stack frame is the common ix-bp style.  Basically:
17
18     ix+4+n:     param 1 
19     ix+4:       param 0 
20     ix+2:       return address 
21     ix+0:       calling functions ix 
22     ix-n:       local varibles 
23     ...  
24     sp:         end of local varibles
25
26     There is currently no support for bit spaces or banked functions.
27     
28     This program is free software; you can redistribute it and/or
29     modify it under the terms of the GNU General Public License as
30     published by the Free Software Foundation; either version 2, or (at
31     your option) any later version.  This program is distributed in the
32     hope that it will be useful, but WITHOUT ANY WARRANTY; without even
33     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
34     PURPOSE.  See the GNU General Public License for more details.
35     
36     You should have received a copy of the GNU General Public License
37     along with this program; if not, write to the Free Software
38     Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
39     USA.  In other words, you are welcome to use, share and improve
40     this program.  You are forbidden to forbid anyone else to use,
41     share and improve what you give them.  Help stamp out
42     software-hoarding!  
43 */
44
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include "SDCCglobl.h"
48 #include "SDCCast.h"
49 #include "SDCCmem.h"
50 #include "SDCCy.h" 
51 #include "SDCChasht.h"
52 #include "SDCCbitv.h"
53 #include "SDCCset.h"
54 #include "SDCCicode.h"
55 #include "SDCClabel.h"
56 #include "SDCCBBlock.h"
57 #include "SDCCloop.h"
58 #include "SDCCcse.h"
59 #include "SDCCcflow.h"
60 #include "SDCCdflow.h"
61 #include "SDCClrange.h"
62 #include "ralloc.h"
63
64 /*-----------------------------------------------------------------*/
65 /* At this point we start getting processor specific although      */
66 /* some routines are non-processor specific & can be reused when   */
67 /* targetting other processors. The decision for this will have    */
68 /* to be made on a routine by routine basis                        */
69 /* routines used to pack registers are most definitely not reusable*/
70 /* since the pack the registers depending strictly on the MCU      */
71 /*-----------------------------------------------------------------*/
72
73 bitVect *spiltSet = NULL ; 
74 set *stackSpil = NULL;
75 bitVect *regAssigned = NULL;
76 short blockSpil = 0;
77 int slocNum = 0 ;
78 extern void genZ80Code(iCode *);
79 int ptrRegReq = 0; /* one byte pointer register required */
80 bitVect *funcrUsed = NULL; /* registers used in a function */
81 int stackExtend = 0;
82 int dataExtend  = 0;
83
84 /** Set to help debug register pressure related problems */
85 #define DEBUG_FAKE_EXTRA_REGS   0
86
87 regs regsZ80[] = 
88 {
89     { REG_GPR, C_IDX , "c", 1 },
90     { REG_GPR, B_IDX , "b", 1 },
91     { REG_GPR, E_IDX , "e", 1 },
92     { REG_GPR, D_IDX , "d", 1 },
93     /*    { REG_GPR, L_IDX , "l", 1 },
94     { REG_GPR, H_IDX , "h", 1 },*/
95 #if DEBUG_FAKE_EXTRA_REGS
96     { REG_GPR, M_IDX , "m", 1 },
97     { REG_GPR, N_IDX , "n", 1 },
98     { REG_GPR, O_IDX , "o", 1 },
99     { REG_GPR, P_IDX , "p", 1 },
100     { REG_GPR, Q_IDX , "q", 1 },
101     { REG_GPR, R_IDX , "r", 1 },
102     { REG_GPR, S_IDX , "s", 1 },
103     { REG_GPR, T_IDX , "t", 1 },
104 #endif
105     { REG_CND, CND_IDX, "c", 1}
106 };
107
108 /** Number of usable registers (all but C) */
109 #define MAX_REGS ((sizeof(regsZ80)/sizeof(regs))-1)
110
111 int nRegs = MAX_REGS;
112
113 void spillThis (symbol *);
114
115 /** Allocates register of given type.
116     'type' is not used on the z80 version.  It was used to select
117     between pointer and general purpose registers on the mcs51 version.
118
119     @return             Pointer to the newly allocated register.
120  */
121 regs *allocReg (short type)
122 {
123     int i;
124
125     for ( i = 0 ; i < nRegs ; i++ ) {
126         /* For now we allocate from any free */
127         if (regsZ80[i].isFree ) {
128             regsZ80[i].isFree = 0;
129             if (currFunc)
130                 currFunc->regsUsed = 
131                     bitVectSetBit(currFunc->regsUsed,i);
132             return &regsZ80[i];
133         }
134     }
135     return NULL;
136 }
137
138 /** Returns pointer to register wit index number
139  */
140 regs *regWithIdx (int idx)
141 {
142     int i;
143     
144     for (i=0;i < nRegs;i++)
145         if (regsZ80[i].rIdx == idx)
146             return &regsZ80[i];
147
148     werror(E_INTERNAL_ERROR,__FILE__,__LINE__,
149            "regWithIdx not found");
150     exit(1);
151 }
152
153 /** Frees a register.
154  */
155 void freeReg (regs *reg)
156 {
157     assert(!reg->isFree);
158     reg->isFree = 1;
159 }
160
161
162 /** Returns number of free registers.
163  */
164 int nFreeRegs (int type)
165 {
166     int i;
167     int nfr=0;
168     
169     for (i = 0 ; i < nRegs; i++ ) {
170         /* For now only one reg type */
171         if (regsZ80[i].isFree)
172             nfr++;
173     }
174     return nfr;
175 }
176
177 /** Free registers with type.
178  */
179 int nfreeRegsType (int type)
180 {
181     int nfr ;
182     if (type == REG_PTR) {
183         if ((nfr = nFreeRegs(type)) == 0)
184             return nFreeRegs(REG_GPR);
185     } 
186     
187     return nFreeRegs(type);
188 }
189
190
191 /*-----------------------------------------------------------------*/
192 /* allDefsOutOfRange - all definitions are out of a range          */
193 /*-----------------------------------------------------------------*/
194 bool allDefsOutOfRange (bitVect *defs,int fseq, int toseq) 
195 {
196     int i ;
197
198     if (!defs)
199         return TRUE ;
200
201     for ( i = 0 ;i < defs->size ; i++ ) {
202         iCode *ic;
203
204         if (bitVectBitValue(defs,i)             &&
205             (ic = hTabItemWithKey(iCodehTab,i)) &&
206             ( ic->seq >= fseq  && ic->seq <= toseq))
207             
208             return FALSE;
209         
210     }
211     
212     return TRUE;
213 }
214   
215 /*-----------------------------------------------------------------*/
216 /* computeSpillable - given a point find the spillable live ranges */
217 /*-----------------------------------------------------------------*/
218 bitVect *computeSpillable (iCode *ic)
219 {
220     bitVect *spillable ;
221
222     /* spillable live ranges are those that are live at this 
223        point . the following categories need to be subtracted
224        from this set. 
225        a) - those that are already spilt
226        b) - if being used by this one
227        c) - defined by this one */
228     
229     spillable = bitVectCopy(ic->rlive);
230     spillable = 
231         bitVectCplAnd(spillable,spiltSet); /* those already spilt */
232     spillable = 
233         bitVectCplAnd(spillable,ic->uses); /* used in this one */    
234     bitVectUnSetBit(spillable,ic->defKey);
235     spillable = bitVectIntersect(spillable,regAssigned);
236     return spillable;
237     
238 }
239
240 /*-----------------------------------------------------------------*/
241 /* noSpilLoc - return true if a variable has no spil location      */
242 /*-----------------------------------------------------------------*/
243 int noSpilLoc (symbol *sym, eBBlock *ebp,iCode *ic)
244 {
245     return (sym->usl.spillLoc ? 0 : 1);
246 }
247
248 /*-----------------------------------------------------------------*/
249 /* hasSpilLoc - will return 1 if the symbol has spil location      */
250 /*-----------------------------------------------------------------*/
251 int hasSpilLoc (symbol *sym, eBBlock *ebp, iCode *ic)
252 {
253     return (sym->usl.spillLoc ? 1 : 0);
254 }
255
256 /*-----------------------------------------------------------------*/
257 /* directSpilLoc - will return 1 if the splilocation is in direct  */
258 /*-----------------------------------------------------------------*/
259 int directSpilLoc (symbol *sym, eBBlock *ebp, iCode *ic)
260 {
261     /* No such thing as direct space */
262     return 0;
263 }
264
265 /*-----------------------------------------------------------------*/
266 /* hasSpilLocnoUptr - will return 1 if the symbol has spil location*/
267 /*                    but is not used as a pointer                 */
268 /*-----------------------------------------------------------------*/
269 int hasSpilLocnoUptr (symbol *sym, eBBlock *ebp, iCode *ic)
270 {
271 #if 0
272     return sym->usl.spillLoc ? 1:0;
273 #else
274     return ((sym->usl.spillLoc && !sym->uptr) ? 1 : 0);
275 #endif
276 }
277
278 /** Will return 1 if the remat flag is set.
279     A symbol is rematerialisable if it doesnt need to be allocated
280     into registers at creation as it can be re-created at any time -
281     i.e. it's constant in some way.
282 */
283 int rematable (symbol *sym, eBBlock *ebp, iCode *ic)
284 {
285     return sym->remat;
286 }
287
288 /*-----------------------------------------------------------------*/
289 /* notUsedInBlock - not used in this block                         */
290 /*-----------------------------------------------------------------*/
291 int notUsedInBlock (symbol *sym, eBBlock *ebp, iCode *ic)
292 {   
293     return (!bitVectBitsInCommon(sym->defs,ebp->usesDefs) &&
294             allDefsOutOfRange (sym->defs,ebp->fSeq,ebp->lSeq));
295 /*     return (!bitVectBitsInCommon(sym->defs,ebp->usesDefs)); */
296 }
297
298 /*-----------------------------------------------------------------*/
299 /* notUsedInRemaining - not used or defined in remain of the block */
300 /*-----------------------------------------------------------------*/
301 int notUsedInRemaining (symbol *sym, eBBlock *ebp, iCode *ic)
302 {
303     return ((usedInRemaining (operandFromSymbol(sym),ic) ? 0 : 1) &&
304             allDefsOutOfRange (sym->defs,ic->seq,ebp->lSeq));
305 }
306
307 /*-----------------------------------------------------------------*/
308 /* allLRs - return true for all                                    */
309 /*-----------------------------------------------------------------*/
310 int allLRs (symbol *sym, eBBlock *ebp, iCode *ic)
311 {
312     return 1;
313 }
314
315 /*-----------------------------------------------------------------*/
316 /* liveRangesWith - applies function to a given set of live range  */
317 /*-----------------------------------------------------------------*/
318 set *liveRangesWith (bitVect *lrs, int (func)(symbol *,eBBlock *, iCode *),
319                      eBBlock *ebp, iCode *ic)
320 {
321     set *rset = NULL;
322     int i;
323
324     if (!lrs || !lrs->size)
325         return NULL;
326
327     for ( i = 1 ; i < lrs->size ; i++ ) {
328         symbol *sym;
329         if (!bitVectBitValue(lrs,i))
330             continue ;
331
332         /* if we don't find it in the live range 
333            hash table we are in serious trouble */
334         if (!(sym = hTabItemWithKey(liveRanges,i))) {
335             werror(E_INTERNAL_ERROR,__FILE__,__LINE__,
336                    "liveRangesWith could not find liveRange");
337             exit(1);
338         }
339         
340         if (func(sym,ebp,ic) && bitVectBitValue(regAssigned,sym->key))
341             addSetHead(&rset,sym);
342     }
343
344     return rset;
345 }
346
347
348 /*-----------------------------------------------------------------*/
349 /* leastUsedLR - given a set determines which is the least used    */
350 /*-----------------------------------------------------------------*/
351 symbol *leastUsedLR (set *sset)
352 {
353     symbol *sym = NULL, *lsym = NULL ;
354     
355     sym = lsym = setFirstItem(sset);
356
357     if (!lsym)
358         return NULL;
359
360     for (; lsym; lsym = setNextItem(sset)) {
361         
362         /* if usage is the same then prefer
363            the spill the smaller of the two */
364         if ( lsym->used == sym->used )
365             if (getSize(lsym->type) < getSize(sym->type))
366                 sym = lsym;
367
368         /* if less usage */
369         if (lsym->used < sym->used )
370             sym = lsym;
371         
372    }
373
374     setToNull((void **)&sset);
375     sym->blockSpil = 0;
376     return sym;
377 }
378
379 /*-----------------------------------------------------------------*/
380 /* noOverLap - will iterate through the list looking for over lap  */
381 /*-----------------------------------------------------------------*/
382 int noOverLap (set *itmpStack, symbol *fsym)
383 {
384     symbol *sym;
385    
386
387     for (sym = setFirstItem(itmpStack); sym;
388          sym = setNextItem(itmpStack)) {
389         if (sym->liveTo > fsym->liveFrom )
390             return 0;
391             
392     }
393
394     return 1;
395 }
396
397 /*-----------------------------------------------------------------*/
398 /* isFree - will return 1 if the a free spil location is found     */
399 /*-----------------------------------------------------------------*/
400 DEFSETFUNC(isFree)
401 {
402     symbol *sym = item;
403     V_ARG(symbol **,sloc);
404     V_ARG(symbol *,fsym);
405
406     /* if already found */
407     if (*sloc)
408         return 0;
409
410     /* if it is free && and the itmp assigned to
411        this does not have any overlapping live ranges
412        with the one currently being assigned and
413        the size can be accomodated  */
414     if (sym->isFree                        && 
415         noOverLap(sym->usl.itmpStack,fsym) &&
416         getSize(sym->type) >= getSize(fsym->type)) {
417         *sloc = sym;
418         return 1;
419     }
420
421     return 0;
422 }
423
424 /*-----------------------------------------------------------------*/
425 /* spillLRWithPtrReg :- will spil those live ranges which use PTR  */
426 /*-----------------------------------------------------------------*/
427 void spillLRWithPtrReg (symbol *forSym)
428 {
429     /* Always just return */
430 }
431
432 /*-----------------------------------------------------------------*/
433 /* createStackSpil - create a location on the stack to spil        */
434 /*-----------------------------------------------------------------*/
435 symbol *createStackSpil (symbol *sym)
436 {
437     symbol *sloc= NULL;
438
439     /* first go try and find a free one that is already 
440        existing on the stack */
441     if (applyToSet(stackSpil,isFree,&sloc, sym)) {
442         /* found a free one : just update & return */
443         sym->usl.spillLoc = sloc;
444         sym->stackSpil= 1;
445         sloc->isFree = 0;
446         addSetHead(&sloc->usl.itmpStack,sym);
447         return sym;
448     }
449
450     /* could not then have to create one , this is the hard part
451        we need to allocate this on the stack : this is really a
452        hack!! but cannot think of anything better at this time */
453         
454     sprintf(buffer,"sloc%d",slocNum++);
455     sloc = newiTemp(buffer);
456
457     /* set the type to the spilling symbol */
458     sloc->type = copyLinkChain(sym->type);
459     sloc->etype = getSpec(sloc->type);
460     SPEC_SCLS(sloc->etype) = S_AUTO ;    
461
462     /* we don't allow it to be allocated`
463        onto the external stack since : so we
464        temporarily turn it off ; we also
465        turn off memory model to prevent
466        the spil from going to the external storage
467        and turn off overlaying 
468     */
469     allocLocal(sloc);
470
471     sloc->isref = 1; /* to prevent compiler warning */
472     
473     /* if it is on the stack then update the stack */
474     if (IN_STACK(sloc->etype)) {
475         currFunc->stack += getSize(sloc->type);
476         stackExtend += getSize(sloc->type);
477     } else
478         dataExtend += getSize(sloc->type);
479
480     /* add it to the stackSpil set */
481     addSetHead(&stackSpil,sloc);
482     sym->usl.spillLoc = sloc;
483     sym->stackSpil = 1;
484     
485     /* add it to the set of itempStack set 
486        of the spill location */
487     addSetHead(&sloc->usl.itmpStack,sym);
488     return sym;
489 }
490
491 /*-----------------------------------------------------------------*/
492 /* isSpiltOnStack - returns true if the spil location is on stack  */
493 /*-----------------------------------------------------------------*/
494 bool isSpiltOnStack (symbol *sym)
495 {
496     link *etype;
497
498     if (!sym)
499         return FALSE ;
500     
501     if (!sym->isspilt)
502         return FALSE ;
503
504 /*     if (sym->stackSpil) */
505 /*      return TRUE; */
506     
507     if (!sym->usl.spillLoc)
508         return FALSE;
509
510     etype = getSpec(sym->usl.spillLoc->type);
511     if (IN_STACK(etype))
512         return TRUE;
513
514     return FALSE ;
515 }
516
517 /*-----------------------------------------------------------------*/
518 /* spillThis - spils a specific operand                            */
519 /*-----------------------------------------------------------------*/
520 void spillThis (symbol *sym)
521 {
522     int i;
523     /* if this is rematerializable or has a spillLocation
524        we are okay, else we need to create a spillLocation
525        for it */
526     if (!(sym->remat || sym->usl.spillLoc)) 
527         createStackSpil (sym);
528     
529
530     /* mark it has spilt & put it in the spilt set */
531     sym->isspilt = 1;
532     spiltSet = bitVectSetBit(spiltSet,sym->key);
533        
534     bitVectUnSetBit(regAssigned,sym->key);
535
536     for (i = 0 ; i < sym->nRegs ; i++)
537
538         if (sym->regs[i]) {
539             freeReg(sym->regs[i]);
540             sym->regs[i] = NULL;
541         }
542     
543     /* if spilt on stack then free up r0 & r1 
544        if they could have been assigned to some
545        LIVE ranges */
546     if (!ptrRegReq && isSpiltOnStack(sym)) {
547         ptrRegReq++ ;
548         spillLRWithPtrReg(sym);
549     }
550
551     if (sym->usl.spillLoc && !sym->remat)
552         sym->usl.spillLoc->allocreq = 1;
553     return;
554 }
555
556 /** Select a iTemp to spil : rather a simple procedure.
557  */
558 symbol *selectSpil (iCode *ic, eBBlock *ebp, symbol *forSym)
559 {
560     bitVect *lrcs= NULL ; 
561     set *selectS ;
562     symbol *sym;
563
564     /* get the spillable live ranges */
565     lrcs = computeSpillable (ic);
566
567     /* get all live ranges that are rematerizable */
568     if ((selectS = liveRangesWith(lrcs,rematable,ebp,ic))) {
569
570         /* return the least used of these */
571         return leastUsedLR(selectS);
572     }
573
574 #if 0
575     /* get live ranges with spillLocations in direct space */
576     if ((selectS = liveRangesWith(lrcs,directSpilLoc,ebp,ic))) {
577         sym = leastUsedLR(selectS);
578         strcpy(sym->rname,(sym->usl.spillLoc->rname[0] ? 
579                            sym->usl.spillLoc->rname : 
580                            sym->usl.spillLoc->name)); 
581         sym->spildir = 1;
582         /* mark it as allocation required */
583         sym->usl.spillLoc->allocreq = 1;
584         return sym;
585     }
586
587     /* if the symbol is local to the block then */        
588     if (forSym->liveTo < ebp->lSeq ) {       
589
590         /* check if there are any live ranges allocated
591            to registers that are not used in this block */
592         if (!blockSpil && (selectS = liveRangesWith(lrcs,notUsedInBlock,ebp,ic))) {
593             sym = leastUsedLR(selectS);
594             /* if this is not rematerializable */
595             if (!sym->remat) {
596                 blockSpil++;
597                 sym->blockSpil = 1;
598             }
599             return sym;
600         } 
601
602         /* check if there are any live ranges that not
603            used in the remainder of the block */
604         if (!blockSpil && (selectS = liveRangesWith(lrcs,notUsedInRemaining,ebp,ic))) {
605             sym = leastUsedLR (selectS);
606             if (!sym->remat) {
607                 sym->remainSpil = 1;
608                 blockSpil++;
609             }
610             return sym;
611         }
612     }
613     /* find live ranges with spillocation && not used as pointers */
614     if ((selectS = liveRangesWith(lrcs,hasSpilLocnoUptr,ebp,ic))) {
615        
616         sym =  leastUsedLR(selectS);
617         /* mark this as allocation required */
618         sym->usl.spillLoc->allocreq = 1;
619         return sym;
620     }
621 #endif   
622
623     /* find live ranges with spillocation */
624     if ((selectS = liveRangesWith(lrcs,hasSpilLoc,ebp,ic))) {
625         
626         sym = leastUsedLR(selectS);
627         sym->usl.spillLoc->allocreq = 1;
628         return sym;
629     }
630
631     /* couldn't find then we need to create a spil
632        location on the stack , for which one? the least
633        used ofcourse */
634     if ((selectS = liveRangesWith(lrcs,noSpilLoc,ebp,ic))) {
635         /* return a created spil location */
636         sym = createStackSpil(leastUsedLR(selectS));
637         sym->usl.spillLoc->allocreq = 1;
638         return sym;
639     }
640     
641     /* this is an extreme situation we will spill
642        this one : happens very rarely but it does happen */
643     spillThis ( forSym );
644     return forSym;
645    
646 }
647
648 /** Spil some variable & mark registers as free.
649     A spill occurs when an iTemp wont fit into the available registers.
650  */
651 bool spilSomething (iCode *ic, eBBlock *ebp, symbol *forSym)
652 {
653     symbol *ssym;
654     int i ;
655
656     /* get something we can spil */
657     ssym = selectSpil(ic,ebp,forSym);
658     
659     /* mark it as spilt */
660     ssym->isspilt = 1;
661     spiltSet = bitVectSetBit(spiltSet,ssym->key);
662     
663     /* mark it as not register assigned &
664        take it away from the set */   
665     bitVectUnSetBit(regAssigned,ssym->key);
666  
667     /* mark the registers as free */    
668     for (i = 0 ; i < ssym->nRegs ;i++ )
669         if (ssym->regs[i])
670             freeReg(ssym->regs[i]);
671      
672 #if 0
673     /* if spilt on stack then free up r0 & r1 
674        if they could have been assigned to as gprs */
675     if (!ptrRegReq && isSpiltOnStack(ssym) ) {
676         ptrRegReq++ ;
677         spillLRWithPtrReg(ssym);
678     }
679
680     /* if this was a block level spil then insert push & pop 
681        at the start & end of block respectively */
682     if (ssym->blockSpil) {
683         iCode *nic = newiCode(IPUSH,operandFromSymbol(ssym),NULL);
684         /* add push to the start of the block */
685         addiCodeToeBBlock(ebp,nic,( ebp->sch->op == LABEL ? 
686                                     ebp->sch->next : ebp->sch));
687         nic = newiCode(IPOP,operandFromSymbol(ssym),NULL);
688         /* add pop to the end of the block */
689         addiCodeToeBBlock(ebp,nic,NULL);
690     }       
691
692     /* if spilt because not used in the remainder of the
693        block then add a push before this instruction and
694        a pop at the end of the block */
695     if (ssym->remainSpil) {
696
697         iCode *nic = newiCode(IPUSH,operandFromSymbol(ssym),NULL);
698         /* add push just before this instruction */
699         addiCodeToeBBlock(ebp,nic,ic);
700                                     
701         nic = newiCode(IPOP,operandFromSymbol(ssym),NULL);
702         /* add pop to the end of the block */
703         addiCodeToeBBlock(ebp,nic,NULL);    
704     }
705 #endif
706
707     if (ssym == forSym )
708         return FALSE ;
709     else
710         return TRUE ;
711 }
712
713 /** Will try for GPR if not spil.
714  */
715 regs *getRegGpr (iCode *ic, eBBlock *ebp,symbol *sym)
716 {
717     regs *reg;
718
719  tryAgain:
720     /* try for gpr type */
721     if ((reg = allocReg(REG_GPR)))        
722         return reg;    
723
724     if (!ptrRegReq)
725         if ((reg = allocReg(REG_PTR)))
726             return reg ;
727
728     /* we have to spil */
729     if (!spilSomething (ic,ebp,sym))
730         return NULL ;
731
732     /* this looks like an infinite loop but 
733        in really selectSpil will abort  */
734     goto tryAgain ;    
735 }
736
737 /** Symbol has a given register.
738  */
739 static bool symHasReg(symbol *sym,regs *reg)
740 {
741     int i;
742
743     for ( i = 0 ; i < sym->nRegs ; i++)
744         if (sym->regs[i] == reg)
745             return TRUE;
746             
747     return FALSE;
748 }
749
750 /** Check the live to and if they have registers & are not spilt then
751     free up the registers 
752 */
753 void deassignLRs (iCode *ic, eBBlock *ebp)
754 {
755     symbol *sym;
756     int k;
757     symbol *result;
758
759     for (sym = hTabFirstItem(liveRanges,&k); sym;
760          sym = hTabNextItem(liveRanges,&k)) {
761         
762         symbol *psym= NULL;
763         /* if it does not end here */
764         if (sym->liveTo > ic->seq )
765             continue ;
766
767         /* if it was spilt on stack then we can 
768            mark the stack spil location as free */
769         if (sym->isspilt ) {
770             if (sym->stackSpil) {
771                 sym->usl.spillLoc->isFree = 1;
772                 sym->stackSpil = 0;
773             }
774             continue ;
775         }
776         
777         if (!bitVectBitValue(regAssigned,sym->key))
778             continue;
779         
780         /* special case check if this is an IFX &
781            the privious one was a pop and the 
782            previous one was not spilt then keep track
783            of the symbol */     
784         if (ic->op == IFX && ic->prev &&
785             ic->prev->op == IPOP && 
786             !ic->prev->parmPush  &&
787             !OP_SYMBOL(IC_LEFT(ic->prev))->isspilt) 
788             psym = OP_SYMBOL(IC_LEFT(ic->prev));
789
790         if (sym->nRegs) {
791             int i = 0;
792             
793             bitVectUnSetBit(regAssigned,sym->key);
794
795             /* if the result of this one needs registers
796                and does not have it then assign it right
797                away */
798             if (IC_RESULT(ic) &&
799                 !  (SKIP_IC2(ic) ||               /* not a special icode */
800                     ic->op == JUMPTABLE ||
801                     ic->op == IFX ||
802                     ic->op == IPUSH ||
803                     ic->op == IPOP ||
804                     ic->op == RETURN)   &&
805                 (result = OP_SYMBOL(IC_RESULT(ic))) && /* has a result */
806                 result->liveTo > ic->seq &&            /* and will live beyond this */
807                 result->liveTo <= ebp->lSeq &&         /* does not go beyond this block */
808                 result->regType == sym->regType &&     /* same register types */
809                 result->nRegs            &&            /* which needs registers */
810                 ! result->isspilt        &&            /* and does not already have them */
811                 ! result->remat          &&
812                 ! bitVectBitValue(regAssigned,result->key) &&
813                 /* the number of free regs + number of regs in this LR
814                    can accomodate the what result Needs */
815                 ((nfreeRegsType(result->regType) +
816                   sym->nRegs) >= result->nRegs)
817                 ) {
818                 
819                 for (i = 0 ; i < max(sym->nRegs,result->nRegs) ; i++)
820                     if (i < sym->nRegs )
821                         result->regs[i] = sym->regs[i] ;
822                     else
823                         result->regs[i] = getRegGpr (ic,ebp,result);
824
825                 regAssigned = bitVectSetBit(regAssigned,result->key);
826             }                   
827             
828             /* free the remaining */
829             for (; i < sym->nRegs ; i++) {
830                 if (psym) {
831                     if (!symHasReg(psym,sym->regs[i]))
832                         freeReg(sym->regs[i]);
833                 } else
834                     freeReg(sym->regs[i]);
835             }
836         }
837     }
838 }
839
840
841 /** Reassign this to registers.
842  */
843 void reassignLR (operand *op)
844 {
845     symbol *sym = OP_SYMBOL(op);
846     int i;
847
848     /* not spilt any more */     
849     sym->isspilt = sym->blockSpil  = sym->remainSpil = 0;
850     bitVectUnSetBit(spiltSet,sym->key);
851       
852     regAssigned = bitVectSetBit(regAssigned,sym->key);
853
854     blockSpil--;
855
856     for (i=0;i<sym->nRegs;i++)
857         sym->regs[i]->isFree = 0;
858 }
859
860 /** Determines if allocating will cause a spill.
861  */
862 int willCauseSpill ( int nr, int rt)
863 {
864     /* first check if there are any avlb registers
865        of te type required */
866     if (nFreeRegs(0) >= nr)
867         return 0;
868
869     /* it will cause a spil */
870     return 1;
871 }
872
873 /** The allocator can allocate same registers to result and operand,
874     if this happens make sure they are in the same position as the operand
875     otherwise chaos results.
876 */
877 static void positionRegs (symbol *result, symbol *opsym, int lineno)
878 {
879         int count = min(result->nRegs,opsym->nRegs);
880         int i , j = 0, shared = 0;
881
882         /* if the result has been spilt then cannot share */
883         if (opsym->isspilt)
884                 return ;
885  again:
886         shared = 0;
887         /* first make sure that they actually share */
888         for ( i = 0 ; i < count; i++ ) {
889                 for (j = 0 ; j < count ; j++ ) {
890                         if (result->regs[i] == opsym->regs[j] && i !=j) {
891                                 shared = 1;
892                                 goto xchgPositions;
893                         }
894                 }
895         }
896  xchgPositions:
897         if (shared) {
898                 regs *tmp = result->regs[i];
899                 result->regs[i] = result->regs[j];
900                 result->regs[j] = tmp;          
901                 goto again;
902         }
903 }
904
905 /** Try to allocate a pair of registers to the symbol.
906  */
907 bool tryAllocatingRegPair(symbol *sym)
908 {
909     int i;
910     assert(sym->nRegs == 2);
911     for ( i = 0 ; i < nRegs ; i+=2 ) {
912         if ((regsZ80[i].isFree)&&(regsZ80[i+1].isFree)) {
913             regsZ80[i].isFree = 0;
914             sym->regs[0] = &regsZ80[i];
915             regsZ80[i+1].isFree = 0;
916             sym->regs[1] = &regsZ80[i+1];
917             if (currFunc) {
918                 currFunc->regsUsed = 
919                     bitVectSetBit(currFunc->regsUsed,i);
920                 currFunc->regsUsed = 
921                     bitVectSetBit(currFunc->regsUsed,i+1);
922             }
923             return TRUE;
924         }
925     }
926     return FALSE;
927 }
928
929 /** Serially allocate registers to the variables.
930     This is the main register allocation function.  It is called after
931     packing.
932  */
933 void serialRegAssign (eBBlock **ebbs, int count)
934 {
935     int i;
936
937     /* for all blocks */
938     for (i = 0; i < count ; i++ ) {
939         
940         iCode *ic;
941         
942         if (ebbs[i]->noPath &&
943             (ebbs[i]->entryLabel != entryLabel &&
944              ebbs[i]->entryLabel != returnLabel ))
945             continue ;
946
947         /* of all instructions do */
948         for (ic = ebbs[i]->sch ; ic ; ic = ic->next) {
949          
950             /* if this is an ipop that means some live
951                range will have to be assigned again */
952             if (ic->op == IPOP)
953                 reassignLR (IC_LEFT(ic));
954
955             /* if result is present && is a true symbol */
956             if (IC_RESULT(ic) && ic->op != IFX &&
957                 IS_TRUE_SYMOP(IC_RESULT(ic)))
958                 OP_SYMBOL(IC_RESULT(ic))->allocreq = 1;
959
960             /* take away registers from live
961                ranges that end at this instruction */      
962             deassignLRs (ic, ebbs[i]) ;         
963                     
964             /* some don't need registers */
965             /* MLH: removed RESULT and POINTER_SET condition */
966             if (SKIP_IC2(ic) ||
967                 ic->op == JUMPTABLE ||
968                 ic->op == IFX ||
969                 ic->op == IPUSH ||
970                 ic->op == IPOP)
971                 continue;   
972             
973             /* now we need to allocate registers only for the result */
974             if (IC_RESULT(ic)) {
975                 symbol *sym = OP_SYMBOL(IC_RESULT(ic));
976                 bitVect *spillable;
977                 int willCS ;
978                 int j;
979
980                 /* if it does not need or is spilt 
981                    or is already assigned to registers
982                    or will not live beyond this instructions */
983                 if (!sym->nRegs      || 
984                     sym->isspilt     || 
985                     bitVectBitValue(regAssigned,sym->key) ||
986                     sym->liveTo <= ic->seq)
987                     continue ;
988
989                 /* if some liverange has been spilt at the block level
990                    and this one live beyond this block then spil this
991                    to be safe */
992                 if (blockSpil && sym->liveTo > ebbs[i]->lSeq) {
993                     spillThis (sym);
994                     continue ;
995                 }
996                 /* if trying to allocate this will cause
997                    a spill and there is nothing to spill 
998                    or this one is rematerializable then
999                    spill this one */
1000                 willCS = willCauseSpill(sym->nRegs,sym->regType);
1001                 spillable = computeSpillable(ic);
1002                 if ( sym->remat ||                  
1003                     (willCS  && bitVectIsZero(spillable) ) ) {
1004
1005                     spillThis (sym) ;
1006                     continue ;
1007
1008                 }
1009
1010                 /* if it has a spillocation & is used less than
1011                    all other live ranges then spill this */
1012                 if ( willCS && sym->usl.spillLoc ) {
1013
1014                     symbol *leastUsed = 
1015                         leastUsedLR(liveRangesWith (spillable ,
1016                                                     allLRs,
1017                                                     ebbs[i],
1018                                                     ic));
1019                     if (leastUsed && 
1020                         leastUsed->used > sym->used) {
1021                         spillThis (sym);
1022                         continue;
1023                     }
1024                 }               
1025
1026                 /* else we assign registers to it */            
1027                 regAssigned = bitVectSetBit(regAssigned,sym->key);
1028
1029                 /* Special case:  Try to fit into a reg pair if
1030                    available */
1031                 if ((sym->nRegs == 2)&&tryAllocatingRegPair(sym)) {
1032                 }
1033                 else {
1034                     for (j = 0 ; j < sym->nRegs ;j++ ) {
1035                         sym->regs[j] = getRegGpr(ic,ebbs[i],sym);
1036                         
1037                         /* if the allocation falied which means
1038                            this was spilt then break */
1039                         if (!sym->regs[j]) {
1040                             break;
1041                         }
1042                     }
1043                 }
1044                 /* if it shares registers with operands make sure
1045                    that they are in the same position */
1046                 if (IC_LEFT(ic) && IS_SYMOP(IC_LEFT(ic)) &&
1047                     OP_SYMBOL(IC_LEFT(ic))->nRegs  && ic->op != '=')
1048                         positionRegs(OP_SYMBOL(IC_RESULT(ic)),
1049                                      OP_SYMBOL(IC_LEFT(ic)),ic->lineno);
1050                 /* do the same for the right operand */
1051                 if (IC_RIGHT(ic) && IS_SYMOP(IC_RIGHT(ic)) &&
1052                     OP_SYMBOL(IC_RIGHT(ic))->nRegs && ic->op != '=')
1053                         positionRegs(OP_SYMBOL(IC_RESULT(ic)),
1054                                      OP_SYMBOL(IC_RIGHT(ic)),ic->lineno);
1055                 
1056             }       
1057         }
1058     }
1059 }
1060
1061 /*-----------------------------------------------------------------*/
1062 /* rUmaskForOp :- returns register mask for an operand             */
1063 /*-----------------------------------------------------------------*/
1064 bitVect *rUmaskForOp (operand *op)
1065 {
1066     bitVect *rumask;
1067     symbol *sym;
1068     int j;
1069     
1070     /* only temporaries are assigned registers */
1071     if (!IS_ITEMP(op)) 
1072         return NULL;
1073
1074     sym = OP_SYMBOL(op);
1075     
1076     /* if spilt or no registers assigned to it
1077        then nothing */
1078     if (sym->isspilt || !sym->nRegs)
1079         return NULL;
1080
1081     rumask = newBitVect(nRegs);
1082
1083     for (j = 0; j < sym->nRegs; j++) {
1084         rumask = bitVectSetBit(rumask,
1085                                sym->regs[j]->rIdx);
1086     }
1087
1088     return rumask;
1089 }
1090
1091 /** Returns bit vector of registers used in iCode.
1092  */
1093 bitVect *regsUsedIniCode (iCode *ic)
1094 {
1095     bitVect *rmask = newBitVect(nRegs);
1096
1097     /* do the special cases first */
1098     if (ic->op == IFX ) {
1099         rmask = bitVectUnion(rmask,
1100                              rUmaskForOp(IC_COND(ic)));
1101         goto ret;
1102     }
1103
1104     /* for the jumptable */
1105     if (ic->op == JUMPTABLE) {
1106         rmask = bitVectUnion(rmask,
1107                              rUmaskForOp(IC_JTCOND(ic)));
1108
1109         goto ret;
1110     }
1111
1112     /* of all other cases */
1113     if (IC_LEFT(ic)) 
1114         rmask = bitVectUnion(rmask,
1115                              rUmaskForOp(IC_LEFT(ic)));
1116         
1117     
1118     if (IC_RIGHT(ic))
1119         rmask = bitVectUnion(rmask,
1120                              rUmaskForOp(IC_RIGHT(ic)));
1121
1122     if (IC_RESULT(ic))
1123         rmask = bitVectUnion(rmask,
1124                              rUmaskForOp(IC_RESULT(ic)));
1125
1126  ret:
1127     return rmask;
1128 }
1129
1130 /** For each instruction will determine the regsUsed.
1131  */
1132 void createRegMask (eBBlock **ebbs, int count)
1133 {
1134     int i;
1135
1136     /* for all blocks */
1137     for (i = 0; i < count ; i++ ) {
1138         iCode *ic ;
1139
1140         if ( ebbs[i]->noPath &&
1141              ( ebbs[i]->entryLabel != entryLabel &&
1142                ebbs[i]->entryLabel != returnLabel ))
1143             continue ;
1144
1145         /* for all instructions */
1146         for ( ic = ebbs[i]->sch ; ic ; ic = ic->next ) {
1147             
1148             int j;
1149
1150             if (SKIP_IC2(ic) || !ic->rlive)
1151                 continue ;
1152             
1153             /* first mark the registers used in this
1154                instruction */
1155             ic->rUsed = regsUsedIniCode(ic);
1156             funcrUsed = bitVectUnion(funcrUsed,ic->rUsed);
1157
1158             /* now create the register mask for those 
1159                registers that are in use : this is a
1160                super set of ic->rUsed */
1161             ic->rMask = newBitVect(nRegs+1);
1162
1163             /* for all live Ranges alive at this point */
1164             for (j = 1; j < ic->rlive->size; j++ ) {
1165                 symbol *sym;
1166                 int k;
1167
1168                 /* if not alive then continue */
1169                 if (!bitVectBitValue(ic->rlive,j))
1170                     continue ;
1171
1172                 /* find the live range we are interested in */
1173                 if (!(sym = hTabItemWithKey(liveRanges,j))) {
1174                     werror (E_INTERNAL_ERROR,__FILE__,__LINE__,
1175                             "createRegMask cannot find live range");
1176                     exit(0);
1177                 }
1178
1179                 /* if no register assigned to it */
1180                 if (!sym->nRegs || sym->isspilt)
1181                     continue ;
1182
1183                 /* for all the registers allocated to it */
1184                 for (k = 0 ; k < sym->nRegs ;k++)
1185                     if (sym->regs[k])
1186                         ic->rMask =
1187                             bitVectSetBit(ic->rMask,sym->regs[k]->rIdx);
1188             }
1189         }
1190     }
1191 }
1192
1193 /** Returns the rematerialized string for a remat var.
1194  */
1195 char *rematStr (symbol *sym)
1196 {
1197     char *s = buffer;   
1198     iCode *ic = sym->rematiCode;    
1199
1200     while (1) {
1201
1202         /* if plus or minus print the right hand side */
1203         if (ic->op == '+' || ic->op == '-') {
1204             sprintf(s,"0x%04x %c ",(int) operandLitValue(IC_RIGHT(ic)),
1205                     ic->op );
1206             s += strlen(s);
1207             ic = OP_SYMBOL(IC_LEFT(ic))->rematiCode;
1208             continue ;
1209         }
1210         /* we reached the end */
1211         sprintf(s,"%s",OP_SYMBOL(IC_LEFT(ic))->rname);
1212         break;
1213     }
1214
1215     return buffer ;
1216 }
1217
1218 /*-----------------------------------------------------------------*/
1219 /* regTypeNum - computes the type & number of registers required   */
1220 /*-----------------------------------------------------------------*/
1221 void regTypeNum ()
1222 {
1223     symbol *sym;
1224     int k;
1225
1226     /* for each live range do */
1227     for ( sym = hTabFirstItem(liveRanges,&k); sym ;
1228           sym = hTabNextItem(liveRanges,&k)) {
1229
1230         /* if used zero times then no registers needed */
1231         if ((sym->liveTo - sym->liveFrom) == 0)
1232             continue ;
1233
1234         /* if the live range is a temporary */
1235         if (sym->isitmp) {
1236
1237             /* if the type is marked as a conditional */
1238             if (sym->regType == REG_CND)
1239                 continue ;
1240
1241             /* if used in return only then we don't 
1242                need registers */
1243             if (sym->ruonly || sym->accuse) {
1244                 if (IS_AGGREGATE(sym->type) || sym->isptr)
1245                     sym->type = aggrToPtr(sym->type,FALSE);
1246                 continue ;
1247             }
1248
1249             /* if not then we require registers */
1250             sym->nRegs = ((IS_AGGREGATE(sym->type) || sym->isptr ) ?
1251                           getSize(sym->type = aggrToPtr(sym->type,FALSE)) :
1252                           getSize(sym->type));
1253
1254             if (sym->nRegs > 4) {
1255                 fprintf(stderr,"allocated more than 4 or 0 registers for type ");
1256                 printTypeChain(sym->type,stderr);fprintf(stderr,"\n");
1257             }
1258             
1259             /* determine the type of register required */
1260             /* Always general purpose */
1261             sym->regType = REG_GPR ;
1262             
1263         } else 
1264             /* for the first run we don't provide */
1265             /* registers for true symbols we will */
1266             /* see how things go                  */
1267             sym->nRegs = 0 ;    
1268     }
1269     
1270 }
1271
1272 /** Mark all registers as free.
1273  */
1274 void freeAllRegs()
1275 {
1276     int i;
1277
1278     for (i=0;i< nRegs;i++ )
1279         regsZ80[i].isFree = 1;
1280 }
1281
1282 /*-----------------------------------------------------------------*/
1283 /* deallocStackSpil - this will set the stack pointer back         */
1284 /*-----------------------------------------------------------------*/
1285 DEFSETFUNC(deallocStackSpil)
1286 {
1287     symbol *sym = item;
1288
1289     deallocLocal(sym);
1290     return 0;
1291 }
1292
1293 /** Register reduction for assignment.
1294  */
1295 int packRegsForAssign (iCode *ic,eBBlock *ebp)
1296 {
1297     iCode *dic, *sic;
1298     
1299     if (
1300         !IS_TRUE_SYMOP(IC_RESULT(ic)) ||
1301         !IS_ITEMP(IC_RIGHT(ic))       ||        
1302         OP_LIVETO(IC_RIGHT(ic)) > ic->seq ||
1303         OP_SYMBOL(IC_RIGHT(ic))->isind)
1304         return 0;
1305
1306 #if 0        
1307     /* if the true symbol is defined in far space or on stack
1308        then we should not since this will increase register pressure */
1309     if (isOperandInFarSpace(IC_RESULT(ic))) {
1310         if ((dic = farSpacePackable(ic)))
1311             goto pack;
1312         else
1313             return 0;
1314     }
1315 #endif
1316
1317     /* find the definition of iTempNN scanning backwards if we find a 
1318        a use of the true symbol in before we find the definition then 
1319        we cannot */     
1320     for ( dic = ic->prev ; dic ; dic = dic->prev) {
1321
1322         /* if there is a function call and this is
1323            a parameter & not my parameter then don't pack it */
1324         if ( (dic->op == CALL || dic->op == PCALL) &&
1325              (OP_SYMBOL(IC_RESULT(ic))->_isparm &&
1326               !OP_SYMBOL(IC_RESULT(ic))->ismyparm)) {
1327             dic = NULL;
1328             break;
1329         }
1330
1331         if (SKIP_IC2(dic))
1332             continue;
1333
1334 #if 0   
1335         if (IS_SYMOP(IC_RESULT(dic)) &&
1336             IC_RESULT(dic)->key == IC_RIGHT(ic)->key) {
1337             if (POINTER_SET(dic))
1338                 dic = NULL;
1339             break;          
1340         }
1341
1342         if (IS_SYMOP(IC_RIGHT(dic)) && 
1343             (IC_RIGHT(dic)->key == IC_RESULT(ic)->key ||
1344              IC_RIGHT(dic)->key == IC_RIGHT(ic)->key)) {
1345             dic = NULL;
1346             break;
1347         }
1348         
1349         if (IS_SYMOP(IC_LEFT(dic)) && 
1350             (IC_LEFT(dic)->key == IC_RESULT(ic)->key ||
1351              IC_LEFT(dic)->key == IC_RIGHT(ic)->key)) {
1352             dic = NULL;
1353             break;
1354         }
1355         if (POINTER_SET(dic) && 
1356             IC_RESULT(dic)->key == IC_RESULT(ic)->key ) {
1357             dic = NULL ;
1358             break;
1359         }
1360 #endif
1361     }
1362     
1363     if (!dic)
1364         return 0 ; /* did not find */
1365             
1366     /* if the result is on stack or iaccess then it must be
1367        the same atleast one of the operands */
1368     if (OP_SYMBOL(IC_RESULT(ic))->onStack  || 
1369         OP_SYMBOL(IC_RESULT(ic))->iaccess ) {
1370         
1371         /* the operation has only one symbol
1372            operator then we can pack */
1373         if ((IC_LEFT(dic) && !IS_SYMOP(IC_LEFT(dic))) ||
1374             (IC_RIGHT(dic) && !IS_SYMOP(IC_RIGHT(dic))))
1375             goto pack;
1376
1377         if (!((IC_LEFT(dic) &&
1378              IC_RESULT(ic)->key == IC_LEFT(dic)->key) ||
1379               (IC_RIGHT(dic) &&
1380                IC_RESULT(ic)->key == IC_RIGHT(dic)->key)))
1381             return 0;                
1382     }
1383 pack:
1384     /* found the definition */
1385     /* replace the result with the result of */
1386     /* this assignment and remove this assignment */
1387     IC_RESULT(dic) = IC_RESULT(ic) ;
1388
1389     if (IS_ITEMP(IC_RESULT(dic)) && OP_SYMBOL(IC_RESULT(dic))->liveFrom > dic->seq) {
1390             OP_SYMBOL(IC_RESULT(dic))->liveFrom = dic->seq;
1391     }
1392     /* delete from liverange table also 
1393        delete from all the points inbetween and the new
1394        one */
1395     for ( sic = dic; sic != ic ; sic = sic->next ) {    
1396         bitVectUnSetBit(sic->rlive,IC_RESULT(ic)->key);
1397         if (IS_ITEMP(IC_RESULT(dic)))
1398             bitVectSetBit(sic->rlive,IC_RESULT(dic)->key);
1399     }
1400         
1401     remiCodeFromeBBlock(ebp,ic);
1402     return 1;
1403     
1404 }
1405
1406 /** Scanning backwards looks for first assig found.
1407  */
1408 iCode *findAssignToSym (operand *op,iCode *ic)
1409 {
1410     iCode *dic;
1411
1412     for (dic = ic->prev ; dic ; dic = dic->prev) {
1413         
1414         /* if definition by assignment */
1415         if (dic->op == '='                 && 
1416             !POINTER_SET(dic)              &&
1417             IC_RESULT(dic)->key == op->key)
1418             /*      &&  IS_TRUE_SYMOP(IC_RIGHT(dic))*/
1419             {      
1420
1421             /* we are interested only if defined in far space */
1422             /* or in stack space in case of + & - */
1423
1424             /* if assigned to a non-symbol then return
1425                true */
1426             if (!IS_SYMOP(IC_RIGHT(dic)))
1427                 break ;
1428
1429             /* if the symbol is in far space then
1430                we should not */
1431             if (isOperandInFarSpace(IC_RIGHT(dic)))
1432                 return NULL ;
1433
1434             /* for + & - operations make sure that
1435                if it is on the stack it is the same
1436                as one of the three operands */
1437             if ((ic->op == '+' || ic->op == '-') &&
1438                 OP_SYMBOL(IC_RIGHT(dic))->onStack) {
1439
1440                 if ( IC_RESULT(ic)->key != IC_RIGHT(dic)->key &&
1441                      IC_LEFT(ic)->key   != IC_RIGHT(dic)->key &&
1442                      IC_RIGHT(ic)->key  != IC_RIGHT(dic)->key)
1443                     return NULL;
1444             }           
1445
1446             break ;
1447                 
1448         }
1449
1450         /* if we find an usage then we cannot delete it */
1451         if (IC_LEFT(dic) && IC_LEFT(dic)->key == op->key)
1452             return NULL;
1453             
1454         if (IC_RIGHT(dic) && IC_RIGHT(dic)->key == op->key)
1455             return NULL;
1456
1457         if (POINTER_SET(dic) && IC_RESULT(dic)->key == op->key)
1458             return NULL;
1459     }
1460
1461     /* now make sure that the right side of dic
1462        is not defined between ic & dic */       
1463     if (dic) {
1464         iCode *sic = dic->next ;
1465
1466         for (; sic != ic ; sic = sic->next)
1467             if (IC_RESULT(sic) &&
1468                 IC_RESULT(sic)->key == IC_RIGHT(dic)->key)
1469                 return NULL;
1470     }
1471
1472     return dic;
1473         
1474         
1475 }
1476
1477 /*-----------------------------------------------------------------*/
1478 /* packRegsForSupport :- reduce some registers for support calls   */
1479 /*-----------------------------------------------------------------*/
1480 int packRegsForSupport (iCode *ic, eBBlock *ebp)
1481 {
1482     int change = 0 ;
1483     /* for the left & right operand :- look to see if the
1484        left was assigned a true symbol in far space in that
1485        case replace them */
1486     if (IS_ITEMP(IC_LEFT(ic)) && 
1487         OP_SYMBOL(IC_LEFT(ic))->liveTo <= ic->seq) {
1488         iCode *dic = findAssignToSym(IC_LEFT(ic),ic);
1489         iCode *sic;
1490
1491         if (!dic)
1492             goto right ;
1493
1494         /* found it we need to remove it from the
1495            block */
1496         for ( sic = dic; sic != ic ; sic = sic->next )
1497             bitVectUnSetBit(sic->rlive,IC_LEFT(ic)->key);
1498
1499         IC_LEFT(ic)->operand.symOperand =
1500             IC_RIGHT(dic)->operand.symOperand;
1501         IC_LEFT(ic)->key = IC_RIGHT(dic)->operand.symOperand->key;
1502         remiCodeFromeBBlock(ebp,dic);   
1503         change++;      
1504     }
1505     
1506     /* do the same for the right operand */
1507  right:    
1508     if (!change && 
1509         IS_ITEMP(IC_RIGHT(ic)) &&
1510         OP_SYMBOL(IC_RIGHT(ic))->liveTo <= ic->seq) {
1511         iCode *dic = findAssignToSym(IC_RIGHT(ic),ic);
1512         iCode *sic;
1513         
1514         if (!dic)
1515             return change ;
1516
1517         /* found it we need to remove it from the block */
1518         for ( sic = dic; sic != ic ; sic = sic->next )
1519             bitVectUnSetBit(sic->rlive,IC_RIGHT(ic)->key);
1520         
1521         IC_RIGHT(ic)->operand.symOperand =
1522             IC_RIGHT(dic)->operand.symOperand;
1523         IC_RIGHT(ic)->key = IC_RIGHT(dic)->operand.symOperand->key;
1524         
1525         remiCodeFromeBBlock(ebp,dic);
1526         change ++;
1527     }
1528    
1529     return change ;
1530 }
1531
1532 #define IS_OP_RUONLY(x) (x && IS_SYMOP(x) && OP_SYMBOL(x)->ruonly)
1533
1534 /** Will reduce some registers for single use.
1535  */
1536 static iCode *packRegsForOneuse (iCode *ic, operand *op , eBBlock *ebp)
1537 {
1538     bitVect *uses ;
1539     iCode *dic, *sic;
1540
1541     /* if returning a literal then do nothing */
1542     if (!IS_SYMOP(op))
1543         return NULL;
1544     
1545     /* only upto 2 bytes since we cannot predict
1546        the usage of b, & acc */
1547     if (getSize(operandType(op)) > 2 && 
1548         ic->op != RETURN             &&
1549         ic->op != SEND)
1550         return NULL;
1551
1552     /* this routine will mark the a symbol as used in one 
1553        instruction use only && if the defintion is local 
1554        (ie. within the basic block) && has only one definition &&
1555        that definiion is either a return value from a 
1556        function or does not contain any variables in
1557        far space */
1558     uses = bitVectCopy(OP_USES(op));
1559     bitVectUnSetBit(uses,ic->key); /* take away this iCode */
1560     if (!bitVectIsZero(uses)) /* has other uses */
1561         return NULL ;
1562     
1563     /* if it has only one defintion */
1564     if (bitVectnBitsOn(OP_DEFS(op)) > 1)
1565         return NULL ; /* has more than one definition */
1566
1567     /* get the that definition */
1568     if (!(dic = 
1569           hTabItemWithKey(iCodehTab,
1570                           bitVectFirstBit(OP_DEFS(op)))))
1571         return NULL ;
1572
1573     /* found the definition now check if it is local */
1574     if (dic->seq < ebp->fSeq ||
1575         dic->seq > ebp->lSeq)
1576         return NULL ; /* non-local */
1577
1578     /* now check if it is the return from a function call */
1579     if (dic->op == CALL || dic->op == PCALL ) {
1580         if (ic->op != SEND && ic->op != RETURN) {
1581             OP_SYMBOL(op)->ruonly = 1;
1582             return dic;
1583         }
1584         dic = dic->next ;
1585     }
1586         
1587     /* otherwise check that the definition does
1588        not contain any symbols in far space */
1589     if (isOperandInFarSpace(IC_LEFT(dic))  ||
1590         isOperandInFarSpace(IC_RIGHT(dic)) ||
1591         IS_OP_RUONLY(IC_LEFT(ic))          ||
1592         IS_OP_RUONLY(IC_RIGHT(ic)) )        {
1593         return NULL;
1594     }
1595     
1596     /* if pointer set then make sure the pointer is one byte */
1597     if (POINTER_SET(dic))
1598       return NULL;
1599
1600     if (POINTER_GET(dic))
1601       return NULL;
1602     
1603     sic = dic;
1604
1605     /* also make sure the intervenening instructions
1606        don't have any thing in far space */
1607     for (dic = dic->next ; dic && dic != ic ; dic = dic->next) {
1608         /* if there is an intervening function call then no */
1609         if (dic->op == CALL || dic->op == PCALL)
1610                 return NULL;
1611         /* if pointer set then make sure the pointer
1612            is one byte */
1613         if (POINTER_SET(dic))
1614             return NULL ;
1615         
1616         if (POINTER_GET(dic))
1617             return NULL ;
1618
1619         /* if address of & the result is remat the okay */
1620         if (dic->op == ADDRESS_OF &&
1621             OP_SYMBOL(IC_RESULT(dic))->remat)
1622             continue ;
1623            
1624         /* if left or right or result is in far space */
1625         if (isOperandInFarSpace(IC_LEFT(dic))   ||
1626             isOperandInFarSpace(IC_RIGHT(dic))  ||
1627             isOperandInFarSpace(IC_RESULT(dic)) ||
1628             IS_OP_RUONLY(IC_LEFT(dic))          ||
1629             IS_OP_RUONLY(IC_RIGHT(dic))         ||
1630             IS_OP_RUONLY(IC_RESULT(dic))            ) {
1631             return NULL;
1632         }
1633     }
1634                 
1635     OP_SYMBOL(op)->ruonly = 1;
1636     return sic;
1637 }
1638
1639 /*-----------------------------------------------------------------*/
1640 /* isBitwiseOptimizable - requirements of JEAN LOUIS VERN          */
1641 /*-----------------------------------------------------------------*/
1642 static bool isBitwiseOptimizable (iCode *ic)
1643 {
1644     link *rtype = getSpec(operandType(IC_RIGHT(ic)));
1645
1646     /* bitwise operations are considered optimizable
1647        under the following conditions (Jean-Louis VERN) 
1648        
1649        x & lit
1650        bit & bit
1651        bit & x
1652        bit ^ bit
1653        bit ^ x
1654        x   ^ lit
1655        x   | lit
1656        bit | bit
1657        bit | x
1658     */    
1659     if (IS_LITERAL(rtype))
1660         return TRUE;
1661     return FALSE; 
1662 }
1663
1664 /** Pack registers for acc use.
1665     When the result of this operation is small and short lived it may
1666     be able to be stored in the accumelator.
1667  */
1668 void packRegsForAccUse (iCode *ic)
1669 {
1670     iCode *uic;
1671     
1672     /* if + or - then it has to be one byte result */
1673     if ((ic->op == '+' || ic->op == '-')
1674         && getSize(operandType(IC_RESULT(ic))) > 1)
1675         return ;
1676     
1677     /* if shift operation make sure right side is not a literal */
1678     if (ic->op == RIGHT_OP  &&
1679         (isOperandLiteral(IC_RIGHT(ic)) ||
1680           getSize(operandType(IC_RESULT(ic))) > 1))
1681         return ;
1682         
1683     if (ic->op == LEFT_OP &&        
1684         ( isOperandLiteral(IC_RIGHT(ic)) ||
1685           getSize(operandType(IC_RESULT(ic))) > 1))
1686         return ;
1687         
1688     /* has only one definition */
1689     if (bitVectnBitsOn(OP_DEFS(IC_RESULT(ic))) > 1)
1690         return ;
1691
1692     /* has only one use */
1693     if (bitVectnBitsOn(OP_USES(IC_RESULT(ic))) > 1)
1694         return ;
1695
1696     /* and the usage immediately follows this iCode */
1697     if (!(uic = hTabItemWithKey(iCodehTab,
1698                                 bitVectFirstBit(OP_USES(IC_RESULT(ic))))))
1699         return ;
1700
1701     if (ic->next != uic)
1702         return ;
1703     
1704     /* if it is a conditional branch then we definitely can */
1705     if (uic->op == IFX  ) 
1706         goto accuse;
1707
1708     if ( uic->op == JUMPTABLE )
1709         return ;
1710
1711 #if 0
1712     /* if the usage is not is an assignment or an 
1713        arithmetic / bitwise / shift operation then not */
1714     if (POINTER_SET(uic) && 
1715         getSize(aggrToPtr(operandType(IC_RESULT(uic)),FALSE)) > 1)
1716         return;
1717 #endif
1718
1719     if (uic->op != '=' && 
1720         !IS_ARITHMETIC_OP(uic) &&
1721         !IS_BITWISE_OP(uic)    &&
1722         uic->op != LEFT_OP &&
1723         uic->op != RIGHT_OP )
1724         return;
1725
1726     /* if used in ^ operation then make sure right is not a 
1727        literl */
1728     if (uic->op == '^' && isOperandLiteral(IC_RIGHT(uic)))
1729         return ;
1730
1731     /* if shift operation make sure right side is not a literal */
1732     if (uic->op == RIGHT_OP  &&
1733         ( isOperandLiteral(IC_RIGHT(uic)) ||
1734           getSize(operandType(IC_RESULT(uic))) > 1))
1735         return ;
1736
1737     if (uic->op == LEFT_OP &&        
1738         ( isOperandLiteral(IC_RIGHT(uic)) ||
1739           getSize(operandType(IC_RESULT(uic))) > 1))
1740         return ;
1741             
1742 #if 0
1743     /* make sure that the result of this icode is not on the
1744        stack, since acc is used to compute stack offset */
1745     if (IS_TRUE_SYMOP(IC_RESULT(uic)) &&
1746         OP_SYMBOL(IC_RESULT(uic))->onStack)
1747         return ;
1748 #endif
1749
1750 #if 0
1751     /* if either one of them in far space then we cannot */
1752     if ((IS_TRUE_SYMOP(IC_LEFT(uic)) &&
1753          isOperandInFarSpace(IC_LEFT(uic))) ||
1754         (IS_TRUE_SYMOP(IC_RIGHT(uic)) &&
1755          isOperandInFarSpace(IC_RIGHT(uic))))
1756         return ;
1757 #endif
1758
1759     /* if the usage has only one operand then we can */
1760     if (IC_LEFT(uic) == NULL ||
1761         IC_RIGHT(uic) == NULL) 
1762         goto accuse;
1763
1764     /* make sure this is on the left side if not
1765        a '+' since '+' is commutative */
1766     if (ic->op != '+' &&
1767         IC_LEFT(uic)->key != IC_RESULT(ic)->key)
1768         return;
1769
1770     /* if one of them is a literal then we can */
1771     if ((IC_LEFT(uic) && IS_OP_LITERAL(IC_LEFT(uic))) ||
1772         (IC_RIGHT(uic) && IS_OP_LITERAL(IC_RIGHT(uic)))) {
1773         OP_SYMBOL(IC_RESULT(ic))->accuse = 1;
1774         return ;
1775     }
1776
1777     /** This is confusing :)  Guess for now */
1778     if (IC_LEFT(uic)->key == IC_RESULT(ic)->key &&
1779         (IS_ITEMP(IC_RIGHT(uic)) ||
1780          (IS_TRUE_SYMOP(IC_RIGHT(uic)))))
1781         goto accuse;
1782     
1783     if (IC_RIGHT(uic)->key == IC_RESULT(ic)->key &&
1784         (IS_ITEMP(IC_LEFT(uic)) ||
1785          (IS_TRUE_SYMOP(IC_LEFT(uic)))))
1786         goto accuse ;
1787     return ;
1788  accuse:
1789     OP_SYMBOL(IC_RESULT(ic))->accuse = 1;
1790 }
1791
1792 /** Does some transformations to reduce register pressure.
1793  */
1794 void packRegisters (eBBlock *ebp)
1795 {
1796     iCode *ic ;
1797     int change = 0 ;
1798     
1799     while (1) {
1800         change = 0;
1801         /* look for assignments of the form */
1802         /* iTempNN = TRueSym (someoperation) SomeOperand */
1803         /*       ....                       */
1804         /* TrueSym := iTempNN:1             */
1805         for ( ic = ebp->sch ; ic ; ic = ic->next ) {
1806             /* find assignment of the form TrueSym := iTempNN:1 */
1807             if (ic->op == '=' && !POINTER_SET(ic))
1808                 change += packRegsForAssign(ic,ebp);
1809         }
1810         if (!change)
1811             break;
1812     }
1813
1814     for ( ic = ebp->sch ; ic ; ic = ic->next ) {
1815         /* Safe: address of a true sym is always constant. */
1816         /* if this is an itemp & result of a address of a true sym 
1817            then mark this as rematerialisable   */
1818         if (ic->op == ADDRESS_OF && 
1819             IS_ITEMP(IC_RESULT(ic)) &&
1820             IS_TRUE_SYMOP(IC_LEFT(ic)) &&
1821             bitVectnBitsOn(OP_DEFS(IC_RESULT(ic))) == 1 &&
1822             !OP_SYMBOL(IC_LEFT(ic))->onStack ) {
1823
1824             OP_SYMBOL(IC_RESULT(ic))->remat = 1;
1825             OP_SYMBOL(IC_RESULT(ic))->rematiCode = ic;
1826             OP_SYMBOL(IC_RESULT(ic))->usl.spillLoc = NULL;
1827         }
1828
1829         /* Safe: just propagates the remat flag */
1830         /* if straight assignment then carry remat flag if this is the
1831            only definition */
1832         if (ic->op == '='    && 
1833             !POINTER_SET(ic) &&
1834             IS_SYMOP(IC_RIGHT(ic)) && 
1835             OP_SYMBOL(IC_RIGHT(ic))->remat &&
1836             bitVectnBitsOn(OP_SYMBOL(IC_RESULT(ic))->defs) <= 1) {
1837
1838             OP_SYMBOL(IC_RESULT(ic))->remat = 
1839                 OP_SYMBOL(IC_RIGHT(ic))->remat;
1840             OP_SYMBOL(IC_RESULT(ic))->rematiCode = 
1841                 OP_SYMBOL(IC_RIGHT(ic))->rematiCode ;
1842         }
1843
1844         /* if the condition of an if instruction is defined in the
1845            previous instruction then mark the itemp as a conditional */
1846         if ((IS_CONDITIONAL(ic) ||
1847              ( ( ic->op == BITWISEAND      ||
1848                  ic->op == '|'             ||
1849                  ic->op == '^' ) &&
1850                isBitwiseOptimizable(ic))) &&        
1851             ic->next && ic->next->op == IFX &&
1852             isOperandEqual(IC_RESULT(ic),IC_COND(ic->next)) &&
1853             OP_SYMBOL(IC_RESULT(ic))->liveTo <= ic->next->seq) {
1854             
1855             OP_SYMBOL(IC_RESULT(ic))->regType = REG_CND;            
1856             continue ;
1857         }
1858
1859 #if 0
1860         /* reduce for support function calls */
1861         if (ic->supportRtn || ic->op == '+' || ic->op == '-' )
1862             packRegsForSupport(ic,ebp); 
1863 #endif
1864
1865 #if 0
1866         /* some cases the redundant moves can
1867            can be eliminated for return statements */
1868         if ((ic->op == RETURN || ic->op == SEND) &&
1869             !isOperandInFarSpace(IC_LEFT(ic))    &&
1870             !options.model)
1871             packRegsForOneuse (ic,IC_LEFT(ic),ebp);     
1872 #endif
1873
1874 #if 0
1875         /* if pointer set & left has a size more than
1876            one and right is not in far space */
1877         if (POINTER_SET(ic)                    &&
1878             !isOperandInFarSpace(IC_RIGHT(ic)) &&
1879             !OP_SYMBOL(IC_RESULT(ic))->remat   &&
1880             !IS_OP_RUONLY(IC_RIGHT(ic))        &&
1881             getSize(aggrToPtr(operandType(IC_RESULT(ic)),FALSE)) > 1 )
1882
1883             packRegsForOneuse (ic,IC_RESULT(ic),ebp);
1884 #endif
1885
1886 #if 0
1887         /* if pointer get */
1888         if (POINTER_GET(ic)                    &&
1889             !isOperandInFarSpace(IC_RESULT(ic))&&
1890             !OP_SYMBOL(IC_LEFT(ic))->remat     &&
1891             !IS_OP_RUONLY(IC_RESULT(ic))         &&
1892             getSize(aggrToPtr(operandType(IC_LEFT(ic)),FALSE)) > 1 )
1893
1894             packRegsForOneuse (ic,IC_LEFT(ic),ebp);
1895 #endif
1896
1897         /* pack registers for accumulator use, when the result of an
1898            arithmetic or bit wise operation has only one use, that use is
1899            immediately following the defintion and the using iCode has
1900            only one operand or has two operands but one is literal & the
1901            result of that operation is not on stack then we can leave the
1902            result of this operation in acc:b combination */
1903         if ((IS_ARITHMETIC_OP(ic) 
1904              || IS_BITWISE_OP(ic) 
1905              || ic->op == LEFT_OP || ic->op == RIGHT_OP
1906              ) &&
1907             IS_ITEMP(IC_RESULT(ic)) &&
1908             getSize(operandType(IC_RESULT(ic))) <= 2)
1909             packRegsForAccUse (ic);
1910     }
1911 }
1912   
1913 /*-----------------------------------------------------------------*/
1914 /* assignRegisters - assigns registers to each live range as need  */
1915 /*-----------------------------------------------------------------*/
1916 void z80_assignRegisters (eBBlock **ebbs, int count)
1917 {
1918     iCode *ic;
1919     int i ;
1920
1921     setToNull((void *)&funcrUsed);
1922     ptrRegReq = stackExtend = dataExtend = 0;
1923     /* if not register extentions then reduce number
1924        of registers */
1925     nRegs = MAX_REGS;
1926
1927     /* change assignments this will remove some
1928        live ranges reducing some register pressure */
1929     for (i = 0 ; i < count ;i++ )
1930         packRegisters (ebbs[i]);
1931
1932     if (options.dump_pack)
1933         dumpEbbsToFileExt(".dumppack",ebbs,count);
1934
1935     /* first determine for each live range the number of 
1936        registers & the type of registers required for each */
1937     regTypeNum ();
1938     
1939     /* and serially allocate registers */ 
1940     serialRegAssign(ebbs,count);
1941
1942     /* if stack was extended then tell the user */
1943     if (stackExtend) {
1944 /*      werror(W_TOOMANY_SPILS,"stack", */
1945 /*             stackExtend,currFunc->name,""); */
1946         stackExtend = 0 ;
1947     }
1948
1949     if (dataExtend) {
1950 /*      werror(W_TOOMANY_SPILS,"data space", */
1951 /*             dataExtend,currFunc->name,""); */
1952         dataExtend = 0 ;
1953     }
1954
1955     if (options.dump_rassgn)
1956         dumpEbbsToFileExt(".dumprassgn",ebbs,count);
1957
1958     /* after that create the register mask
1959        for each of the instruction */
1960     createRegMask (ebbs,count);
1961
1962     /* now get back the chain */
1963     ic = iCodeLabelOptimize(iCodeFromeBBlock (ebbs,count));
1964
1965     /* redo that offsets for stacked automatic variables */
1966     redoStackOffsets ();
1967
1968     genZ80Code(ic);
1969
1970     /* free up any stackSpil locations allocated */   
1971     applyToSet(stackSpil,deallocStackSpil);
1972     slocNum = 0;
1973     setToNull((void **)&stackSpil);
1974     setToNull((void **)&spiltSet);
1975     /* mark all registers as free */
1976     freeAllRegs();
1977
1978     return ;
1979 }