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