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