Imported initial.
[fw/sdcc] / src / izt / ralloc.c
1 /** @file izt/ralloc.c
2  */
3 #include "izt.h"
4
5 /// Static data.
6 static struct {
7     struct {
8         /// Used to generate a unique name for the spill location.
9         int loc;
10         /// Set of all iTemps spilt onto the stack.
11         set *set;
12         /// Similar to stackSpill
13         bitVect *vect;
14     } spill;
15     /// Bitvector of all registers used in this function.
16     bitVect *funcUsedRegs;
17     /// If a bit is set in this then the iCode at that sequence has had
18     /// registers allocated.
19     bitVect *regAssigned;
20     int blockSpill;
21     int stackExtend;
22 } _G;
23
24 static REG *_findRegById(REG_ID id)
25 {
26     REG *r = port_data.regs;
27     
28     while (r->size) {
29         if (r->id == id)
30             return r;
31         r++;
32     }
33     wassert(0);
34     return NULL;
35 }
36
37 static REG *_getSubReg(REG *r, int size, int offset)
38 {
39     wassert(r->size >= size);
40     
41     if (r->size == size) {
42         wassert(offset == 0);
43         return r;
44     }
45     // We use the hiding table to get the parts of the register.
46     else if (size == 1) {
47         wassert(offset == 0 || offset == 1);
48         return _findRegById(r->hides[offset]);
49     }
50     else if (size == 2) {
51         wassert(offset == 0);
52         return _findRegById(r->hides[2]);
53     }
54     // Cant.
55     wassert(0);
56     return NULL;
57 }
58
59 static int _numRegsAvailable(int size)
60 {
61     REG *r = port_data.regs;
62     int ret = 0;
63
64     while (r->size) {
65         if (r->size == size && r->used == 0)
66             ret++;
67         r++;
68     }
69     
70     return ret;
71 }
72
73 static void _setClearUsed(REG_ID id, int clear)
74 {
75     REG *r = _findRegById(id);
76     wassert(r);
77
78     if (!clear) {
79         // The parent shouldnt be able to be allocated if this child
80         // is already.
81         wassert((r->used & REG_USED_HIDDEN) == 0);
82         r->used |= REG_USED_HIDDEN;
83     }
84     else {
85         wassert((r->used & REG_USED_HIDDEN) != 0);
86         r->used &= ~REG_USED_HIDDEN;
87     }
88 }
89
90 static void _markAsUsed(REG_ID id)
91 {
92     _setClearUsed(id, FALSE);
93 }
94
95 static void _markAsFree(REG_ID id)
96 {
97     _setClearUsed(id, TRUE);
98 }
99
100 static REG *_allocateReg(int size)
101 {
102     REG *r = port_data.regs;
103     
104     while (r->size) {
105         if (r->size == size && r->used == 0) {
106             // Now go through the interference table and mark all other
107             // registers as used.
108             int i;
109             for (i=0; i < NUM_OF(r->hides); i++) {
110                 if (r->hides[i] == REG_ID_NONE) {
111                     break;
112                 }
113                 _markAsUsed(r->hides[i]);
114             }
115             r->used |= REG_USED;
116             return r;
117         }
118         r++;
119     }
120     return NULL;
121 }
122
123 static bitVect *_markRegBits(bitVect *v, REG *r)
124 {
125     int i;
126
127     // Mark the primary register.
128     v = bitVectSetBit(v, r->id);
129
130     // Now add all the hidden registers.
131     for (i=0; i < NUM_OF(r->hides); i++) {
132         if (r->hides[i] == REG_ID_NONE) {
133             break;
134         }
135         v = bitVectSetBit(v, r->hides[i]);
136     }
137
138     return v;
139 }
140
141 static void _freeReg(REG *r)
142 {
143     int i;
144     wassert(r->used == REG_USED);
145     
146     r->used = 0;
147
148     for (i=0; i < NUM_OF(r->hides); i++) {
149         if (r->hides[i] == REG_ID_NONE) {
150             break;
151         }
152         _markAsFree(r->hides[i]);
153     }
154 }
155
156 static void _freeAllRegs(viod)
157 {
158     REG *r = port_data.regs;
159
160     while (r->size) {
161         r->used = 0;
162         r++;
163     }
164 }
165
166 static void _dumpRegs(void)
167 {
168     REG *r = port_data.regs;
169
170     while (r->size) {
171         printf("%u\t%u\t%s\t%u\n", r->size, r->id, r->name, r->used);
172         r++;
173     }
174 }
175
176 void izt_init(REG *regs)
177 {
178     wassert(regs);
179     port_data.regs = regs;
180 }
181
182 /// Lower register pressure by packing iTemps where possible.
183 static void _packRegisters(eBBlock *ebp)
184 {
185     // PENDING: Assignment packing
186     // PENDING: Mark address of a true symbol as remat.
187     // PENDING: Propagate remat through equals.
188     // PENDING: Assign bitwise which is followed by a conditional into carry.
189     // PENDING: Pack for one use on pointer get or set.  Assumes that the pointer
190     //  is stored in the scratch register.
191     // PENDING: Pack short use iTemps into ACC or the scratch register.
192 }
193
194 static void _computeRequiredRegs(void)
195 {
196     symbol *sym;
197     int k;
198
199     // Iterate over each live range.
200     for (sym = hTabFirstItem(liveRanges, &k); sym ;
201          sym = hTabNextItem(liveRanges, &k)) {
202
203         sym->nRegs = 0;
204
205         // If the symbol is never used, then next.
206         if ((sym->liveTo - sym->liveFrom) == 0)
207             continue;
208
209         // Only temporaries need registers.
210         if (!sym->isitmp)
211             continue;
212
213         // Conditionals live in carry and dont need registers.
214         if (sym->regType == REG_TYPE_CND)
215             continue;
216
217         
218 #if 0 // PENDING.  Currently we dont compute ruonly or accuse.
219         if (sym->ruonly || sym->accuse) {
220             if (IS_AGGREGATE(sym->type) || sym->isptr)
221                 sym->type = aggrToPtr(sym->type,FALSE);
222             continue ;
223         }
224 #endif
225         // We need registers.
226         if (IS_AGGREGATE(sym->type) || sym->isptr) {
227             // Turn an aggregate into something real.
228             sym->type = aggrToPtr(sym->type, FALSE);
229         }
230
231         sym->nRegs = getSize(sym->type);
232         wassert(sym->nRegs <= 4);
233     }
234 }
235
236 static bool _doesntNeedRegs(iCode *ic)
237 {
238     // Some types of instructions dont need registers.
239     // PENDING: Flush out the types and make processor specific.
240     if (SKIP_IC2(ic) ||
241         ic->op == JUMPTABLE ||
242         ic->op == IFX ||
243         ic->op == IPUSH ||
244         ic->op == IPOP ||
245         ic->op == RETURN) {
246         return TRUE;
247     }
248     return FALSE;
249 }
250
251 static bool _willCauseSpill(int size)
252 {
253     return _numRegsAvailable(size) == 0;
254 }
255
256 static void _deassignLRs(iCode *ic, eBBlock *ebp)
257 {
258     symbol *sym;
259     int ignored;
260     symbol *result;
261
262     // For each symbol
263     for (sym = hTabFirstItem(liveRanges, &ignored); sym; sym = hTabNextItem(liveRanges, &ignored)) {
264         
265         // Has this symbol expired yet?
266         if (sym->liveTo > ic->seq) {
267             // No.  Cant deassign.
268             continue;
269         }
270
271         // It has expired.  Free up the resources.
272         
273         // If it was spilt, then free up the stack spill location.
274         if (sym->isspilt) {
275             if (sym->stackSpil) {
276                 sym->usl.spillLoc->isFree = 1;
277                 sym->stackSpil = 0;
278             }
279             continue;
280         }
281
282         // If it currently has no registers assigned, then continue.
283         if (bitVectBitValue(_G.regAssigned, sym->key) == 0) {
284             continue;
285         }
286         
287         // If it has no registers assigned to it, then continue.
288         if (sym->nRegs == 0) {
289             continue;
290         }
291
292         // Mark this sym as not having registers assigned.
293         bitVectUnSetBit(_G.regAssigned, sym->key);
294         
295         // Free the registers.
296         _freeReg(sym->regs[0]);
297
298         // If deallocating will free up enough registers for this iCode
299         // then steal them immediatly.
300         if (IC_RESULT(ic) && !_doesntNeedRegs(ic)) {
301             result = OP_SYMBOL(IC_RESULT(ic));
302             if (result &&                       // Has a result
303                 result->liveTo > ic->seq &&     // and lives past this instruction
304                 result->liveTo <= ebp->lSeq &&  // and doesnt go past this block
305                 result->nRegs &&                // and actually needs registers
306                 !result->isspilt &&             // and doesnt have them yet
307                 !result->remat &&               // and wouldnt waste them
308                 !bitVectBitValue(_G.regAssigned, result->key) && // doesnt have them yet
309                 !_willCauseSpill(result->nRegs)
310                 ) {
311                 result->regs[0] = _allocateReg(result->nRegs);
312             }
313         }
314     }
315 }
316
317 /// Returns true if the live range of the given symbol doesnt overlap
318 /// with any of the live ranges in the set.
319 static bool _noOverlap (set *itmpStack, symbol *fsym)
320 {
321     symbol *sym;
322    
323     for (sym = setFirstItem(itmpStack); sym; sym = setNextItem(itmpStack)) {
324         if (sym->liveTo > fsym->liveFrom) {
325             return FALSE;
326         }
327     }
328     return TRUE;
329 }
330
331 /// Set operator that returns 1 if a free spill location is found.
332 DEFSETFUNC(_stackIsFree)
333 {
334     symbol *sym = item;
335     V_ARG(symbol **,sloc);
336     V_ARG(symbol *,fsym);
337
338     // Dont bother if one has already been found.
339     if (*sloc)
340         return 0;
341
342     if (sym->isFree &&                                  // This location is free...
343         _noOverlap(sym->usl.itmpStack, fsym) &&         // and its usage doesnt overlap with the usage of this sym
344         getSize(sym->type) >= getSize(fsym->type) &&    // and the location is big enough to hold the sym
345         1) {
346         // All good.  Take this location.
347         *sloc = sym;
348         return 1;
349     }
350     else {
351         // No match.
352         return 0;
353     }
354 }
355
356 /// Create a new spill location on the stack for this symbol.
357 symbol *_createStackSpill(symbol *sym)
358 {
359     symbol *sloc= NULL;
360
361     // Try to reuse an exisiting spill location.
362     if (applyToSet(_G.spill.set, _stackIsFree, &sloc, sym)) {
363         // Found one.  Take it over.
364         sym->usl.spillLoc = sloc;
365         sym->stackSpil = TRUE;
366         sloc->isFree = 0;
367         addSetHead(&sloc->usl.itmpStack, sym);
368         return sym;
369     }
370
371     // No existing location.  Time to create one.
372     // Give it a pretty name.
373     sprintf(buffer, "sloc%d", ++_G.spill.loc);
374     // And create.
375     sloc = newiTemp(buffer);
376
377     // Setup the type.
378     sloc->type = copyLinkChain(sym->type);
379     sloc->etype = getSpec(sloc->type);
380     SPEC_SCLS(sloc->etype) = S_AUTO ;    
381
382     allocLocal(sloc);
383
384     // "To prevent compiler warning"
385     sloc->isref = 1;
386
387     // Increase the local variable stack size on this function.
388     if (IN_STACK(sloc->etype)) {
389         currFunc->stack += getSize(sloc->type);
390         _G.stackExtend += getSize(sloc->type);
391     } else {
392         // The IZT port currently doesnt support loading locals into data space.
393         wassert(0);
394     }
395
396     // And add it to the spill set.
397     addSetHead(&_G.spill.set, sloc);
398     sym->usl.spillLoc = sloc;
399     sym->stackSpil = TRUE;
400     
401     // "Add it to the set of itempStack set of the spill location
402     addSetHead(&sloc->usl.itmpStack,sym);
403
404     return sym;
405 }
406
407 static void _spillThis(symbol *sym)
408 {
409     // Create a spill location if it needs one and doesnt have one yet.
410     if (!(sym->remat || sym->usl.spillLoc)) {
411         _createStackSpill(sym);
412     }
413
414     sym->isspilt = TRUE;
415     // Add it to the spilt set.
416     _G.spill.vect = bitVectSetBit(_G.spill.vect, sym->key);
417     // and remove it from the 'has registers' set.
418     bitVectUnSetBit(_G.regAssigned, sym->key);
419
420     // Free up any registers that were assigned to this.
421     if (sym->regs[0]) {
422         _freeReg(sym->regs[0]);
423         sym->regs[0] = NULL;
424     }
425
426     // CHECK: If this sym now has a spill location, mark it as allocated
427     // so that the stack packing later doesnt remove it.
428     if (sym->usl.spillLoc && !sym->remat) {
429         sym->usl.spillLoc->allocreq = TRUE;
430     }
431
432     return;
433 }
434
435 static bitVect *_findSpillable(iCode *ic)
436 {
437     bitVect *spillable;
438
439     // First create a copy of the currently live ranges.
440     spillable = bitVectCopy(ic->rlive);
441     // Remove those which are already spilt.
442     spillable = bitVectCplAnd(spillable, _G.spill.vect);
443     // Remove those that this iCode uses.
444     spillable = bitVectCplAnd(spillable, ic->uses);
445     // Remove those that this iCode defines.
446     bitVectUnSetBit(spillable, ic->defKey);
447
448     // Only those that have registers assigned can actually be spilt :)
449     spillable = bitVectIntersect(spillable, _G.regAssigned);
450
451     return spillable;
452 }
453
454 /// Finds the least used live range
455 static symbol *_leastUsedLR(set *sset)
456 {
457     // sym is the currently least used symbol.
458     symbol *sym;
459     // walk walks the list of symbols in the scan set.
460     symbol *walk;
461     
462     // Use the first as the seed.
463     sym = walk = setFirstItem(sset);
464
465     while (walk) {
466         // Prefer spilling the symbol with the least allocated registers.
467         // PENDING: Why?
468         if (walk->used == sym->used) {
469             if (getSize(walk->type) < getSize(sym->type)) {
470                 sym = walk;
471             }
472         }
473         else if (walk->used < sym->used) {
474             // This is used less than the current best.  It looses.
475             sym = walk;
476         }
477         
478         walk = setNextItem(sset);
479    }
480
481     setToNull((void **)&sset);
482     sym->blockSpil = 0;
483
484     return sym;
485 }
486
487 /// Applies a function to a given set of live ranges.
488 static set *_liveRangesWith(bitVect *lrs, int (func)(symbol *,eBBlock *, iCode *),
489                      eBBlock *ebp, iCode *ic)
490 {
491     set *rset = NULL;
492     int i;
493
494     // Dont do anything if the bitVect is empty.
495     if (!lrs || !lrs->size)
496         return NULL;
497
498     for (i = 1; i < lrs->size; i++ ) {
499         symbol *sym;
500
501         // If this bit isnt turned on, skip.
502         if (!bitVectBitValue(lrs, i))
503             continue ;
504
505         // If we don't find it in the live range hash table we are in serious trouble.
506         if (!(sym = hTabItemWithKey(liveRanges, i))) {
507             werror(E_INTERNAL_ERROR,__FILE__,__LINE__,
508                    "liveRangesWith could not find liveRange");
509             exit(1);
510         }
511         
512         // If the function likes it, and it has registers assigned to
513         // it, add it to the return set.
514         if (func(sym, ebp, ic) && bitVectBitValue(_G.regAssigned, sym->key)) {
515             addSetHead(&rset,sym);
516         }
517     }
518
519     return rset;
520 }
521
522 /// Returns TRUE always.  Used to fetch all live ranges.
523 static int _allLRs(symbol *sym, eBBlock *ebp, iCode *ic)
524 {
525     return 1;
526 }
527
528 static void _serialRegAssign(eBBlock **ebbs, int count)
529 {
530     int i;
531
532     // For each block, do...
533     for (i=0; i<count; i++) {
534         iCode *ic;
535
536         if (ebbs[i]->noPath &&
537             (ebbs[i]->entryLabel != entryLabel &&
538              ebbs[i]->entryLabel != returnLabel )) {
539             // PENDING:  Dont understand.
540             continue;
541         }
542         
543         
544         // For each iCode in this block, do...
545         for (ic = ebbs[i]->sch; ic; ic = ic->next) {
546             symbol *sym;
547             bitVect *spillable;
548             int willCauseSpill;
549
550             // Dont support IPOP
551             wassert(ic->op != IPOP);
552
553             // if result is present && is a true symbol
554             if (IC_RESULT(ic) && ic->op != IFX &&
555                 IS_TRUE_SYMOP(IC_RESULT(ic)))
556                 OP_SYMBOL(IC_RESULT(ic))->allocreq = 1;
557
558             // Take away registers from live ranges that end at this
559             // instruction.
560             _deassignLRs(ic, ebbs[i]);
561             
562             // Some instructions dont need registers.
563             if (_doesntNeedRegs(ic)) {
564                 continue;
565             }
566
567             // If there is no result, then it doesnt need registers.
568             if (!IC_RESULT(ic)) {
569                 continue;
570             }
571
572             sym = OP_SYMBOL(IC_RESULT(ic));
573
574             // Does it need any registers?
575             if (sym->nRegs == 0) {
576                 continue;
577             }
578
579             // Is it already split?
580             if (sym->isspilt) {
581                 continue;
582             }
583
584             // Does it already have registers assigned?
585             if (bitVectBitValue(_G.regAssigned,sym->key)) {
586                 continue;
587             }
588
589             // Will it live past this instruction?
590             if (sym->liveTo <= ic->seq) {
591                 continue;
592             }
593
594             // MLH Doesnt understand this.
595             /* "Iif some liverange has been spilt at the block level
596                and this one live beyond this block then spil this
597                to be safe" */
598             if (_G.blockSpill && sym->liveTo > ebbs[i]->lSeq) {
599                 _spillThis(sym);
600                 continue;
601             }
602             
603             // Seems that this symbol needs registers.  See if 
604             // allocating will cause a spill.
605             willCauseSpill = _willCauseSpill(sym->nRegs);
606             spillable = _findSpillable(ic);
607
608             // If this is remat., then dont waste any regsiters on it.
609             if (sym->remat) {
610                 _spillThis(sym);
611                 continue;
612             }
613
614             // If trying to allocate will cause a spill, and nothing
615             // else is spillable then this sym looses.
616             if (willCauseSpill && bitVectIsZero(spillable)) {
617                 _spillThis(sym);
618                 continue;
619             }
620
621             // If this will cause a spill, and it already has a spill
622             // location then spill this if it is the least used.
623             if (willCauseSpill && sym->usl.spillLoc) {
624                 symbol *leastUsed = _leastUsedLR(_liveRangesWith(spillable, _allLRs, ebbs[i], ic));
625                 if (leastUsed && leastUsed->used > sym->used) {
626                     _spillThis(sym);
627                     continue;
628                 }
629             }
630
631             // Hmm.  Here we could have no registers available but
632             // we'll still try to allocate.  MLH wonders how this will
633             // work.
634             
635             // Mark this iCode as having registers assigned to it.
636             _G.regAssigned = bitVectSetBit(_G.regAssigned, sym->key);
637
638             // And do it.
639             sym->regs[0] = _allocateReg(sym->nRegs);
640         }
641     }
642 }
643
644 static void izt_gen(iCode *ic)
645 {
646     printf("izt_gen\n");    
647 }
648
649 static DEFSETFUNC(_deallocStackSpil)
650 {
651     symbol *sym = item;
652
653     deallocLocal(sym);
654     return 0;
655 }
656
657 /// Compute the register mask for an operand.
658 bitVect *_rUmaskForOp(operand *op)
659 {
660     bitVect *rumask;
661     symbol *sym;
662     
663     // "Only temporaries are assigned registers"
664     if (!IS_ITEMP(op)) 
665         return NULL;
666
667     sym = OP_SYMBOL(op);
668     
669     // If its spilt or no registers are needed, then no regs are assigned.
670     if (sym->isspilt || !sym->nRegs)
671         return NULL;
672
673     rumask = newBitVect(REG_ID_MAX);
674
675     if (sym->regs[0]) {
676         rumask = _markRegBits(rumask, sym->regs[0]);
677     }
678
679     return rumask;
680 }
681
682 /// Returns bit vector of registers used in iCode.
683 bitVect *_regsUsedIniCode (iCode *ic)
684 {
685     bitVect *rmask = newBitVect(REG_ID_MAX);
686
687     do {
688         // Special cases first.
689         if (ic->op == IFX ) {
690             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_COND(ic)));
691             break;
692         }
693
694         if (ic->op == JUMPTABLE) {
695             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_JTCOND(ic)));
696             break;
697         }
698
699         // Now the good old left, right, and result.
700         if (IC_LEFT(ic)) {
701             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_LEFT(ic)));
702         }
703         
704         if (IC_RIGHT(ic)) {
705             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_RIGHT(ic)));
706         }
707
708         if (IC_RESULT(ic)) {
709             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_RESULT(ic)));
710         }
711     } while (0);
712
713     return rmask;
714 }
715
716 /// Compute the helper bitVect that contains the register used mask.
717 static void _createRegMask(eBBlock **ebbs, int count)
718 {
719     int i;
720
721     /* for all blocks */
722     for (i = 0; i < count; i++) {
723         iCode *ic ;
724
725         // If this code is unused, skip it.
726         if ( ebbs[i]->noPath &&
727              ( ebbs[i]->entryLabel != entryLabel &&
728                ebbs[i]->entryLabel != returnLabel )) {
729             continue;
730         }
731
732         /* for all instructions */
733         for (ic = ebbs[i]->sch; ic; ic = ic->next) {
734             int j;
735
736             if (SKIP_IC2(ic) || !ic->rlive)
737                 continue ;
738             
739             // Mark the registers used in this instruction.
740             ic->rUsed = _regsUsedIniCode(ic);
741             // Mark them as used at least once in the function.
742             _G.funcUsedRegs = bitVectUnion(_G.funcUsedRegs, ic->rUsed);
743
744             /* now create the register mask for those 
745                registers that are in use : this is a
746                super set of ic->rUsed */
747             ic->rMask = newBitVect(REG_ID_MAX+1);
748
749             // "For all live Ranges alive at this point"
750             for (j = 1; j < ic->rlive->size; j++) {
751                 symbol *sym;
752
753                 // "If if not alive then continue"
754                 if (!bitVectBitValue(ic->rlive,j)) {
755                     continue;
756                 }
757
758                 // "Find the live range we are interested in"
759                 if (!(sym = hTabItemWithKey(liveRanges,j))) {
760                     werror (E_INTERNAL_ERROR,__FILE__,__LINE__,
761                             "createRegMask cannot find live range");
762                     exit(0);
763                 }
764
765                 // "If no register assigned to it"
766                 if (!sym->nRegs || sym->isspilt) {
767                     continue;
768                 }
769
770                 // If this has any registers allocated, mark them as such.
771                 if (sym->regs[0]) {
772                     ic->rMask = _markRegBits(ic->rMask, sym->regs[0]);
773                 }
774             }
775         }
776     }
777 }
778
779 void izt_assignRegisters(eBBlock **ebbs, int count)
780 {
781     // Contains a flat version of ebbs used in code generation.
782     iCode *chain;
783
784     // Clear the bit vector of registers used in this function.
785     // Assumes that assignRegisters is called once per function.
786     setToNull((void *)&_G.funcUsedRegs);
787
788     // First scan each live range, and figure out what registers
789     // are required.
790     _computeRequiredRegs();
791
792     // Now allocate the registers.
793     _serialRegAssign(ebbs, count);
794
795     // And create the helper register used mask.
796     _createRegMask(ebbs, count);
797
798     // Turn the bblock array into an optimised list of iCode entries.
799     chain = iCodeLabelOptimize(iCodeFromeBBlock(ebbs,count));
800
801     // Redo the stack offsets.  This will remove any redundent stack
802     // locations ie iTemps that exist only in registers.
803     redoStackOffsets();
804
805     izt_gen(chain);
806
807     // Deallocate any stack spill locations.
808     applyToSet(_G.spill.set, _deallocStackSpil);
809
810     _G.spill.loc = 0;
811     setToNull((void **)&_G.spill.set);
812     setToNull((void **)&_G.spill.vect);
813
814     // And free all registers.
815     _freeAllRegs();
816 }