Fixed the range computation for SEND iCode
[fw/sdcc] / src / SDCClrange.c
1 /*-------------------------------------------------------------------------
2
3   SDCClrange.c - source file for live range computations
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 "limits.h"
28
29 int iCodeSeq = 0;
30 hTab *liveRanges = NULL;
31 hTab *iCodehTab = NULL;
32
33 /*-----------------------------------------------------------------*/
34 /* sequenceiCode - creates a sequence number for the iCode & add   */
35 /*-----------------------------------------------------------------*/
36 void 
37 sequenceiCode (eBBlock ** ebbs, int count)
38 {
39   int i;
40
41   for (i = 0; i < count; i++)
42     {
43
44       iCode *ic;
45       ebbs[i]->fSeq = iCodeSeq + 1;
46       for (ic = ebbs[i]->sch; ic; ic = ic->next)
47         {
48           ic->seq = ++iCodeSeq;
49           ic->depth = ebbs[i]->depth;
50           hTabAddItem (&iCodehTab, ic->key, ic);
51         }
52       ebbs[i]->lSeq = iCodeSeq;
53     }
54 }
55
56 /*-----------------------------------------------------------------*/
57 /* markVisited - will set the visited flag for the given Block     */
58 /*-----------------------------------------------------------------*/
59 DEFSETFUNC (markVisited)
60 {
61   eBBlock *ebp = item;
62
63   if (ebp->visited)
64     return 0;
65   ebp->visited = 1;
66   applyToSet (ebp->succList, markVisited);
67   return 0;
68 }
69
70 /*-----------------------------------------------------------------*/
71 /* isOpAlive - checks to see if the usage in this block is the     */
72 /*             uses the same definitions as this one               */
73 /*-----------------------------------------------------------------*/
74 DEFSETFUNC (isOpAlive)
75 {
76   eBBlock *ebp = item;
77   V_ARG (operand *, op);
78   V_ARG (eBBlock *, orig);
79   V_ARG (iCode *, ic);
80
81   if (ebp->visited)
82     return 0;
83
84   ebp->visited = 1;
85
86   /* if we have reached the originating block */
87   /* or this block has some definiton for it  */
88   /* then check if it is used between start & */
89   /* this point */
90   if (ebp == orig ||
91       bitVectBitsInCommon (OP_DEFS (op), ebp->defSet))
92     if (usedBetweenPoints (op, ebp->sch, ic))
93       return 1;
94     else
95       {
96         applyToSet (ebp->succList, markVisited);
97         return 0;
98       }
99   else
100     /* choosing this more expensive one since 
101        killDeadCode will take away some definitions
102        but there is not way right now to take away
103        the usage information for the corresponding
104        usages, this will lead to longer live ranges */
105   if (usedInRemaining (op, ebp->sch))
106     return 1;
107
108
109   return (applyToSet (ebp->succList, isOpAlive, op, orig, ic));
110 }
111
112 /*-----------------------------------------------------------------*/
113 /* isLastUse - return TRUE if no usage of this operand after this  */
114 /*-----------------------------------------------------------------*/
115 int 
116 isLastUse (operand * op, eBBlock * ebp, iCode * ic,
117            eBBlock ** ebbs, int count)
118 {
119   int i;
120
121   /* if this is used in the remaining */
122   if (usedInRemaining (op, ic))
123     return 0;
124
125   /* if not then check any of the successor blocks use it */
126   for (i = 0; i < count; ebbs[i++]->visited = 0);
127   if (applyToSet (ebp->succList, isOpAlive, op, ebp, ic))
128     return 0;
129
130   /* this is the last use */
131   return 1;
132 }
133
134 /*-----------------------------------------------------------------*/
135 /* unionDefsUsed - unions the defsUsed in a block                  */
136 /*-----------------------------------------------------------------*/
137 DEFSETFUNC (unionDefsUsed)
138 {
139   eBBlock *ebp = item;
140   V_ARG (bitVect **, bvp);
141
142   if (ebp->visited)
143     return 0;
144
145   ebp->visited = 1;
146
147   *bvp = bitVectUnion (*bvp, ebp->usesDefs);
148   applyToSet (ebp->succList, unionDefsUsed, bvp);
149   return 0;
150 }
151
152 /*-----------------------------------------------------------------*/
153 /* setFromRange - sets the from range of a given operand           */
154 /*-----------------------------------------------------------------*/
155 void 
156 setFromRange (operand * op, int from)
157 {
158   /* only for compiler defined temporaries */
159   if (!IS_ITEMP (op))
160     return;
161
162   hTabAddItemIfNotP (&liveRanges, op->key, OP_SYMBOL (op));
163
164   if (op->isaddr)
165     OP_SYMBOL (op)->isptr = 1;
166
167   if (!OP_LIVEFROM (op) ||
168       OP_LIVEFROM (op) > from)
169     OP_LIVEFROM (op) = from;
170 }
171
172 /*-----------------------------------------------------------------*/
173 /* setToRange - set the range to for an operand                    */
174 /*-----------------------------------------------------------------*/
175 void 
176 setToRange (operand * op, int to, bool check)
177 {
178   /* only for compiler defined temps */
179   if (!IS_ITEMP (op))
180     return;
181
182   OP_SYMBOL (op)->key = op->key;
183   hTabAddItemIfNotP (&liveRanges, op->key, OP_SYMBOL (op));
184
185   if (op->isaddr)
186     OP_SYMBOL (op)->isptr = 1;
187
188   if (check)
189     if (!OP_LIVETO (op))
190       OP_LIVETO (op) = to;
191     else;
192   else
193     OP_LIVETO (op) = to;
194 }
195
196 /*-----------------------------------------------------------------*/
197 /* firstDeOf - finds the first definition in seq for op            */
198 /*-----------------------------------------------------------------*/
199 static iCode *
200 firstDefOf (operand * op)
201 {
202   int i;
203   iCode *ric = NULL, *lic = NULL;
204   int fSeq = INT_MAX;
205
206   if (!OP_DEFS (op))
207     return NULL;
208
209   for (i = 0; i < OP_DEFS (op)->size; i++)
210     {
211       if (bitVectBitValue (OP_DEFS (op), i) &&
212           (lic = hTabItemWithKey (iCodehTab, i)) &&
213           lic->seq < fSeq)
214         {
215
216           fSeq = lic->seq;
217           ric = lic;
218         }
219     }
220   return ric;
221 }
222 /*-----------------------------------------------------------------*/
223 /* useDefLoopCheck - check for uses before init inside loops       */
224 /*-----------------------------------------------------------------*/
225 static void 
226 useDefLoopCheck (operand * op, iCode * ic)
227 {
228   /* this is for situations like the following
229      int a,b;
230
231      while (...) {
232      a = ... ;
233      ...
234      _some_usage_of_b_;
235      ...
236      b = ... ;
237      } 
238      in this case the definition of 'b' will flow to the usages
239      but register allocator cannot handle these situations.so
240      will mark as spilt */
241
242   int i = 0, fdSeq;
243   int er = 0;
244   iCode *tic;
245
246   /* get the first definition */
247   if (!(tic = firstDefOf (op)))
248     return;
249
250   fdSeq = tic->seq;
251   /* now go thru the usages & make sure they follow
252      the first definition */
253   for (i = 0; i <= OP_USES (op)->size; i++)
254     {
255       if (bitVectBitValue (OP_USES (op), i) &&
256           (tic = hTabItemWithKey (iCodehTab, i)) &&
257           tic->seq < fdSeq)
258         {
259           er = 1;
260           break;
261         }
262     }
263
264   /* found a usage without definition */
265   if (er)
266     {
267       if (OP_SYMBOL (op)->isreqv && SPIL_LOC (op))
268         {
269
270           werror (W_LOCAL_NOINIT,
271                   SPIL_LOC (op)->name,
272                   ic->filename, ic->lineno);
273         }
274       else
275         {
276
277           werror (W_LOCAL_NOINIT,
278                   OP_SYMBOL (op)->name,
279                   ic->filename, ic->lineno);
280         }
281       OP_SYMBOL (op)->isspilt = 1;
282     }
283 }
284
285
286 /*-----------------------------------------------------------------*/
287 /* operandLUse - check and set the last use for a given operand    */
288 /*-----------------------------------------------------------------*/
289 operand *
290 operandLUse (operand * op, eBBlock ** ebbs,
291              int count, iCode * ic, eBBlock * ebp)
292 {
293   setFromRange (op, ic->seq);
294   if (ic->depth)
295     OP_SYMBOL (op)->used += (((unsigned int) 1 << ic->depth) + 1);
296   else
297     OP_SYMBOL (op)->used += 1;
298
299   if (isLastUse (op, ebp, ic->next, ebbs, count) ||
300       (OP_LIVETO (op) && OP_LIVETO (op) < ic->seq))
301     {
302       int torange = ic->seq;
303
304       /* if this is a SEND then the toRange should be extended
305          to the call */
306       if (ic->op == SEND) {
307           iCode *lic ;
308           for (lic = ic->next ; lic ; lic = lic->next) {
309               if (lic->op == CALL || lic->op == PCALL) break;
310           }
311           /* found it : mark */
312           if (lic) torange = lic->seq;
313       }
314       /* if this is the last use then if this block belongs 
315          to a  loop &  some definition  comes into the loop 
316          then extend the live range to  the end of the loop */
317       if (ebp->partOfLoop 
318           && hasIncomingDefs (ebp->partOfLoop, op))
319         {
320           torange = findLoopEndSeq (ebp->partOfLoop);
321         }
322       
323       op = operandFromOperand (op);
324       setToRange (op, torange, FALSE);
325     }
326   ic->uses = bitVectSetBit (ic->uses, op->key);
327
328   if (!OP_SYMBOL (op)->udChked)
329     {
330       sym_link *type = operandType (op);
331       sym_link *etype = getSpec (type);
332
333       OP_SYMBOL (op)->udChked = 1;
334       /* good place to check if unintialised */
335       if ((IS_TRUE_SYMOP (op) || OP_SYMBOL (op)->isreqv) &&
336           OP_SYMBOL (op)->islocal &&
337           !IS_AGGREGATE (type) &&
338           !IS_FUNC (type) &&
339           ic->op != ADDRESS_OF &&
340           !IS_STATIC (etype))
341         {
342
343           if (bitVectIsZero (op->usesDefs))
344             {
345               OP_SYMBOL (op)->isspilt = 1;
346
347               if (OP_SYMBOL (op)->isreqv &&
348                   !OP_SYMBOL (op)->_isparm && SPIL_LOC (op))
349                 {
350
351                   werror (W_LOCAL_NOINIT,
352                           SPIL_LOC (op)->name,
353                           ic->filename, ic->lineno);
354                 }
355               else
356                 {
357
358                   werror (W_LOCAL_NOINIT,
359                           OP_SYMBOL (op)->name,
360                           ic->filename, ic->lineno);
361                 }
362             }
363           else
364             {
365               if (ebp->depth && op->usesDefs &&
366                   !OP_SYMBOL (op)->_isparm)
367                 {
368                   /* check non-inits inside loops */
369                   useDefLoopCheck (op, ic);
370                 }
371             }
372         }
373     }
374   return op;
375 }
376
377 /*-----------------------------------------------------------------*/
378 /* killAllAlive - mark all the definitions living with this seq    */
379 /*-----------------------------------------------------------------*/
380 void 
381 killAllAlive (int seq)
382 {
383   symbol *sym;
384   int k;
385
386   for (sym = hTabFirstItem (liveRanges, &k); sym;
387        sym = hTabNextItem (liveRanges, &k))
388     if (!sym->liveTo || (sym->liveTo < sym->liveFrom))
389       sym->liveTo = seq;
390 }
391 /*-----------------------------------------------------------------*/
392 /* defUsedAfterLoop - all definitions & usages before sequence num */
393 /*-----------------------------------------------------------------*/
394 bool 
395 defUsedAfterLoop (operand * op, int seq)
396 {
397   int i;
398   iCode *ic;
399
400   /* check for the usages first */
401   if (OP_SYMBOL (op)->uses && !bitVectIsZero (OP_SYMBOL (op)->uses))
402     {
403       for (i = 0; i < OP_SYMBOL (op)->uses->size; i++)
404         {
405
406           if (bitVectBitValue (OP_SYMBOL (op)->uses, i) &&      /* usage found */
407               (ic = hTabItemWithKey (iCodehTab, i)) &&  /*    ""       */
408               ic->seq > seq)    /* & is after the seq */
409             return TRUE;
410         }
411     }
412
413   return FALSE;
414 }
415
416 /*-----------------------------------------------------------------*/
417 /* markLiveRanges - for each operand mark the liveFrom & liveTo    */
418 /*-----------------------------------------------------------------*/
419 void 
420 markLiveRanges (eBBlock * ebp, eBBlock ** ebbs, int count)
421 {
422   iCode *ic;
423   bitVect *defsUsed = NULL;
424   bitVect *defsNotUsed = NULL;
425   int i;
426   /* for all the instructions */
427   for (ic = ebp->sch; ic; ic = ic->next)
428     {
429
430       if (ic->op == CALL || ic->op == PCALL)
431         {
432           setFromRange (IC_RESULT (ic), ic->seq);
433           /* if the result has no usage then 
434              mark this as the end of its life too 
435              and take it away from the defs for the block */
436           if (bitVectIsZero (OP_SYMBOL (IC_RESULT (ic))->uses))
437             {
438               setToRange (IC_RESULT (ic), ic->seq, FALSE);
439               bitVectUnSetBit (ebp->defSet, ic->key);
440             }
441         }
442
443       if (SKIP_IC2 (ic))
444         continue;
445
446       /* take care of the special icodes first */
447       if (ic->op == JUMPTABLE && IS_SYMOP (IC_JTCOND (ic)))
448         {
449           operandLUse (IC_JTCOND (ic), ebbs, count, ic, ebp);
450           continue;
451         }
452
453       if (ic->op == IFX && IS_SYMOP (IC_COND (ic)))
454         {
455           operandLUse (IC_COND (ic), ebbs, count, ic, ebp);
456           continue;
457         }
458
459       if (IS_SYMOP (IC_LEFT (ic)))
460         operandLUse (IC_LEFT (ic), ebbs, count, ic, ebp);
461
462       if (IS_SYMOP (IC_RIGHT (ic)))
463         operandLUse (IC_RIGHT (ic), ebbs, count, ic, ebp);
464
465       if (POINTER_SET (ic))
466         operandLUse (IC_RESULT (ic), ebbs, count, ic, ebp);
467       else if (IC_RESULT (ic))
468         ic->defKey = IC_RESULT (ic)->key;
469     }
470
471
472   /* for all the definitions in the block */
473   /* compute and set the live from        */
474   if (ebp->ldefs && !bitVectIsZero (ebp->ldefs))
475     {
476       for (i = 0; i < ebp->ldefs->size; i++)
477         {
478           iCode *dic;
479
480           if (bitVectBitValue (ebp->ldefs, i) &&
481               (dic = hTabItemWithKey (iCodehTab, i)))
482             {
483
484               /* if the definition has a from & it is greater */
485               /* than the defininng iCode->seq then change it */
486               setFromRange (IC_RESULT (dic), dic->seq);
487             }
488         }
489     }
490
491   /* special case for lastBlock in a loop: here we
492      mark the end of all the induction variables for the
493      loop */
494   if (ebp->isLastInLoop && !bitVectIsZero (ebp->linds))
495     {
496       for (i = 0; i <= ebp->linds->size; i++)
497         {
498           iCode *dic;
499
500           if (bitVectBitValue (ebp->linds, i) &&
501               (dic = hTabItemWithKey (iCodehTab, i)))
502             {
503
504               /* if this is a register equvalent make sure
505                  it is not defined or used anywhere after the loop */
506               if (OP_SYMBOL (IC_RESULT (dic))->isreqv &&
507                   defUsedAfterLoop (IC_RESULT (dic), ebp->lSeq))
508                 continue;
509
510               setToRange (IC_RESULT (dic), (ebp->lSeq), FALSE);
511             }
512         }
513     }
514
515   /* for defnitions coming into the block if they */
516   /* not used by itself & any of its successors   */
517   /* they are dead */
518   /* first union the definitions used in all successors
519      and itself */
520   for (i = 0; i < count; ebbs[i++]->visited = 0);
521   applyToSet (ebp->succList, unionDefsUsed, &defsUsed);
522   defsUsed = bitVectUnion (defsUsed, ebp->usesDefs);
523
524   /* now subract the result of these unions from */
525   /* the incoming definitions this will give the */
526   /* definitions that are never used in the future */
527   defsNotUsed = bitVectCplAnd (bitVectCopy (ebp->inDefs),
528                                defsUsed);
529
530   /* mark the end of the defintions */
531   if (!bitVectIsZero (defsNotUsed) && ebp->sch)
532     {
533       for (i = 0; i < defsNotUsed->size; i++)
534         {
535           iCode *dic;
536
537           if (bitVectBitValue (defsNotUsed, i) &&
538               (dic = hTabItemWithKey (iCodehTab, i)))
539             {
540
541               setToRange (IC_RESULT (dic), (ebp->fSeq - 1), TRUE);
542             }
543         }
544     }
545
546
547   /* if we reach a lock with noPath to it then kill all
548      the live ranges alive at this point */
549 /*     if (ebp->noPath || ebp->entryLabel == returnLabel) */
550   if (ebp->entryLabel == returnLabel)
551     killAllAlive (ebp->fSeq);
552 }
553
554 /*-----------------------------------------------------------------*/
555 /* rlivePoint - for each point compute the ranges that are alive   */
556 /*-----------------------------------------------------------------*/
557 void 
558 rlivePoint (eBBlock ** ebbs, int count)
559 {
560     int i;
561     
562     /* for all blocks do */
563     for (i = 0; i < count; i++) {
564         iCode *ic;
565         
566         /* for all instruction in the block do */
567         for (ic = ebbs[i]->sch; ic; ic = ic->next) {
568             symbol *lrange;
569             int k;
570             
571             ic->rlive = newBitVect (operandKey);
572             /* for all symbols in the liverange table */
573             for (lrange = hTabFirstItem (liveRanges, &k); lrange;
574                  lrange = hTabNextItem (liveRanges, &k)) {
575                 
576                 /* if it is live then add the lrange to ic->rlive */
577                 if (lrange->liveFrom <= ic->seq &&
578                     lrange->liveTo >= ic->seq) {
579                     lrange->isLiveFcall |= (ic->op == CALL || ic->op == PCALL || ic->op == SEND);
580                     ic->rlive = bitVectSetBit (ic->rlive, lrange->key);
581                 }
582             }
583             /* overlapping live ranges should be eliminated */
584             if (ASSIGN_ITEMP_TO_ITEMP (ic)) {
585                 if (SPIL_LOC(IC_RIGHT(ic)) == SPIL_LOC(IC_RESULT(ic))   && /* left & right share the same spil location */
586                     OP_SYMBOL(IC_RESULT(ic))->isreqv                    && /* left of assign is a register requivalent */
587                     !OP_SYMBOL(IC_RIGHT(ic))->isreqv                    && /* right side is not */
588                     OP_SYMBOL(IC_RIGHT(ic))->liveTo > ic->key           && /* right side live beyond this point */
589                     bitVectnBitsOn(OP_DEFS(IC_RESULT(ic))) > 1 )        {  /* left has multiple definitions */
590                     SPIL_LOC(IC_RIGHT(ic)) = NULL; /* then cannot share */
591                 }
592             }
593         }
594     }
595 }
596
597 /*-----------------------------------------------------------------*/
598 /* computeClash - find out which live ranges collide with others   */
599 /*-----------------------------------------------------------------*/
600 static void computeClash ()
601 {
602     hTab *lRangeCopy = newHashTable(hTabMaxKey(liveRanges));
603     void *item;
604     symbol *outer, *inner;
605     int key, key1;
606
607     /* have to make a copy of the liveRanges hashTable :: UGHH .*/
608     for (item = hTabFirstItem(liveRanges,&key); item ; 
609          item = hTabNextItem(liveRanges,&key)) {
610         hTabAddItem(&lRangeCopy,key,item);
611     }
612    
613     /* outerloop : for each liverange do */
614     for (outer = hTabFirstItem(liveRanges,&key); outer ; 
615          outer = hTabNextItem(liveRanges,&key)) {
616
617         /* if the liveFrom & To are the same then skip, 
618            could happen for unused return values from functions */
619         if (outer->liveFrom == outer->liveTo) continue;
620
621         /* innerloop : for the inner loop we can start from the
622            item after the outer loop */
623         inner = hTabFirstItemWK (lRangeCopy,outer->key);
624         inner = hTabNextItem (lRangeCopy,&key1 );
625         for (; inner ; inner = hTabNextItem( lRangeCopy ,&key1)) {
626
627             if (inner->liveFrom == inner->liveTo) continue;
628             if (inner->liveTo < outer->liveFrom)  continue;
629             if (inner->liveFrom > outer->liveTo)  continue;
630             
631             /* if one of them are being defined where the other
632                one end , then no overlap (i.e. they can goto same registers */
633             if (inner->liveFrom == outer->liveTo ||
634                 outer->liveFrom == inner->liveTo) continue;
635
636             /* so they overlap : set both their clashes */
637             inner->clashes = bitVectSetBit(inner->clashes,outer->key);
638             outer->clashes = bitVectSetBit(outer->clashes,inner->key);
639
640             /* check if they share the same spillocation */
641             if (SYM_SPIL_LOC(inner) && SYM_SPIL_LOC(outer) && 
642                 SYM_SPIL_LOC(inner) == SYM_SPIL_LOC(outer)) {
643                 if (inner->reqv && !outer->reqv) SYM_SPIL_LOC(outer)=NULL;
644                 else if (outer->reqv && !inner->reqv) SYM_SPIL_LOC(inner)=NULL;
645                 else if (inner->used > outer->used) SYM_SPIL_LOC(outer)=NULL;
646                 else SYM_SPIL_LOC(inner)=NULL;
647             }
648
649         }
650     }
651 }
652
653 /*-----------------------------------------------------------------*/
654 /* computeLiveRanges - computes the live ranges for variables      */
655 /*-----------------------------------------------------------------*/
656 void 
657 computeLiveRanges (eBBlock ** ebbs, int count)
658 {
659   int i = 0;
660   /* sequence the code the live ranges are computed 
661      in terms of this sequence additionally the   
662      routine will also create a hashtable of instructions */
663   iCodeSeq = 0;
664   setToNull ((void **) &iCodehTab);
665   iCodehTab = newHashTable (iCodeKey);
666   sequenceiCode (ebbs, count);
667
668   /* call routine to mark the from & to live ranges for
669      variables used */
670   setToNull ((void **) &liveRanges);
671   for (i = 0; i < count; i++)
672     markLiveRanges (ebbs[i], ebbs, count);
673
674   /* mark the ranges live for each point */
675   rlivePoint (ebbs, count);
676
677   /* compute which overlaps with what */
678   computeClash();
679 }