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