Wed Feb 24 15:47:16 CET 2010 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / mini / liveness.c
1 /*
2  * liveness.c: liveness analysis
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *
7  * (C) 2002 Ximian, Inc.
8  */
9
10 #include "mini.h"
11
12 #define SPILL_COST_INCREMENT (1 << (bb->nesting << 1))
13
14 #define DEBUG_LIVENESS
15
16 #define BITS_PER_CHUNK MONO_BITSET_BITS_PER_CHUNK
17
18 /* 
19  * The liveness2 pass can't handle long vars on 32 bit platforms because the component
20  * vars have the same 'idx'.
21  */
22 #if SIZEOF_REGISTER == 8
23 #define ENABLE_LIVENESS2
24 #endif
25
26 #ifdef ENABLE_LIVENESS2
27 static void mono_analyze_liveness2 (MonoCompile *cfg);
28 #endif
29
30 static void
31 optimize_initlocals (MonoCompile *cfg);
32
33 /* mono_bitset_mp_new:
34  * 
35  * allocates a MonoBitSet inside a memory pool
36  */
37 static inline MonoBitSet* 
38 mono_bitset_mp_new (MonoMemPool *mp, guint32 size, guint32 max_size)
39 {
40         guint8 *mem = mono_mempool_alloc0 (mp, size);
41         return mono_bitset_mem_new (mem, max_size, MONO_BITSET_DONT_FREE);
42 }
43
44 static inline MonoBitSet* 
45 mono_bitset_mp_new_noinit (MonoMemPool *mp, guint32 size, guint32 max_size)
46 {
47         guint8 *mem = mono_mempool_alloc (mp, size);
48         return mono_bitset_mem_new (mem, max_size, MONO_BITSET_DONT_FREE);
49 }
50
51 G_GNUC_UNUSED static void
52 mono_bitset_print (MonoBitSet *set)
53 {
54         int i;
55         gboolean first = TRUE;
56
57         printf ("{");
58         for (i = 0; i < mono_bitset_size (set); i++) {
59
60                 if (mono_bitset_test (set, i)) {
61                         if (!first)
62                                 printf (", ");
63                         printf ("%d", i);
64                         first = FALSE;
65                 }
66         }
67         printf ("}\n");
68 }
69
70 static void
71 visit_bb (MonoCompile *cfg, MonoBasicBlock *bb, GSList **visited)
72 {
73         int i;
74         MonoInst *ins;
75
76         if (g_slist_find (*visited, bb))
77                 return;
78
79         for (ins = bb->code; ins; ins = ins->next) {
80                 const char *spec = INS_INFO (ins->opcode);
81                 int regtype, srcindex, sreg, num_sregs;
82                 int sregs [MONO_MAX_SRC_REGS];
83
84                 if (ins->opcode == OP_NOP)
85                         continue;
86
87                 /* DREG */
88                 regtype = spec [MONO_INST_DEST];
89                 g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
90                                 
91                 if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
92                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
93                         int idx = var->inst_c0;
94                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
95
96                         cfg->varinfo [vi->idx]->flags |= MONO_INST_VOLATILE;
97                 }
98                         
99                 /* SREGS */
100                 num_sregs = mono_inst_get_src_registers (ins, sregs);
101                 for (srcindex = 0; srcindex < num_sregs; ++srcindex) {
102                         sreg = sregs [srcindex];
103
104                         g_assert (sreg != -1);
105                         if (get_vreg_to_inst (cfg, sreg)) {
106                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
107                                 int idx = var->inst_c0;
108                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
109
110                                 cfg->varinfo [vi->idx]->flags |= MONO_INST_VOLATILE;
111                         }
112                 }
113         }
114
115         *visited = g_slist_append (*visited, bb);
116
117         /* 
118          * Need to visit all bblocks reachable from this one since they can be
119          * reached during exception handling.
120          */
121         for (i = 0; i < bb->out_count; ++i) {
122                 visit_bb (cfg, bb->out_bb [i], visited);
123         }
124 }
125
126 void
127 mono_liveness_handle_exception_clauses (MonoCompile *cfg)
128 {
129         MonoBasicBlock *bb;
130         GSList *visited = NULL;
131
132         /*
133          * Variables in exception handler register cannot be allocated to registers
134          * so make them volatile. See bug #42136. This will not be neccessary when
135          * the back ends could guarantee that the variables will be in the
136          * correct registers when a handler is called.
137          * This includes try blocks too, since a variable in a try block might be
138          * accessed after an exception handler has been run.
139          */
140         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
141
142                 if (bb->region == -1 || MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
143                         continue;
144
145                 visit_bb (cfg, bb, &visited);
146         }
147         g_slist_free (visited);
148 }
149
150 static inline void
151 update_live_range (MonoMethodVar *var, int abs_pos)
152 {
153         if (var->range.first_use.abs_pos > abs_pos)
154                 var->range.first_use.abs_pos = abs_pos;
155
156         if (var->range.last_use.abs_pos < abs_pos)
157                 var->range.last_use.abs_pos = abs_pos;
158 }
159
160 static void
161 analyze_liveness_bb (MonoCompile *cfg, MonoBasicBlock *bb)
162 {
163         MonoInst *ins;
164         int sreg, inst_num;
165         MonoMethodVar *vars = cfg->vars;
166         guint32 abs_pos = (bb->dfn << 16);
167         
168         for (inst_num = 0, ins = bb->code; ins; ins = ins->next, inst_num += 2) {
169                 const char *spec = INS_INFO (ins->opcode);
170                 int num_sregs, i;
171                 int sregs [MONO_MAX_SRC_REGS];
172
173 #ifdef DEBUG_LIVENESS
174                 if (cfg->verbose_level > 1) {
175                         printf ("\t");
176                         mono_print_ins (ins);
177                 }
178 #endif
179
180                 if (ins->opcode == OP_NOP)
181                         continue;
182
183                 if (ins->opcode == OP_LDADDR) {
184                         MonoInst *var = ins->inst_p0;
185                         int idx = var->inst_c0;
186                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
187
188 #ifdef DEBUG_LIVENESS
189                         if (cfg->verbose_level > 1)
190                                 printf ("\tGEN: R%d(%d)\n", var->dreg, idx);
191 #endif
192                         update_live_range (&vars [idx], abs_pos + inst_num); 
193                         if (!mono_bitset_test_fast (bb->kill_set, idx))
194                                 mono_bitset_set_fast (bb->gen_set, idx);
195                         vi->spill_costs += SPILL_COST_INCREMENT;
196                 }                               
197
198                 /* SREGs must come first, so MOVE r <- r is handled correctly */
199                 num_sregs = mono_inst_get_src_registers (ins, sregs);
200                 for (i = 0; i < num_sregs; ++i) {
201                         sreg = sregs [i];
202                         if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
203                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
204                                 int idx = var->inst_c0;
205                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
206
207 #ifdef DEBUG_LIVENESS
208                                 if (cfg->verbose_level > 1)
209                                         printf ("\tGEN: R%d(%d)\n", sreg, idx);
210 #endif
211                                 update_live_range (&vars [idx], abs_pos + inst_num); 
212                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
213                                         mono_bitset_set_fast (bb->gen_set, idx);
214                                 vi->spill_costs += SPILL_COST_INCREMENT;
215                         }
216                 }
217
218                 /* DREG */
219                 if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
220                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
221                         int idx = var->inst_c0;
222                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
223
224                         if (MONO_IS_STORE_MEMBASE (ins)) {
225                                 update_live_range (&vars [idx], abs_pos + inst_num); 
226                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
227                                         mono_bitset_set_fast (bb->gen_set, idx);
228                                 vi->spill_costs += SPILL_COST_INCREMENT;
229                         } else {
230 #ifdef DEBUG_LIVENESS
231                                 if (cfg->verbose_level > 1)
232                                         printf ("\tKILL: R%d(%d)\n", ins->dreg, idx);
233 #endif
234                                 update_live_range (&vars [idx], abs_pos + inst_num + 1); 
235                                 mono_bitset_set_fast (bb->kill_set, idx);
236                                 vi->spill_costs += SPILL_COST_INCREMENT;
237                         }
238                 }
239         }
240 }
241
242 /* generic liveness analysis code. CFG specific parts are 
243  * in update_gen_kill_set()
244  */
245 void
246 mono_analyze_liveness (MonoCompile *cfg)
247 {
248         MonoBitSet *old_live_out_set;
249         int i, j, max_vars = cfg->num_varinfo;
250         int out_iter;
251         gboolean *in_worklist;
252         MonoBasicBlock **worklist;
253         guint32 l_end;
254         int bitsize;
255
256 #ifdef DEBUG_LIVENESS
257         if (cfg->verbose_level > 1)
258                 printf ("\nLIVENESS:\n");
259 #endif
260
261         g_assert (!(cfg->comp_done & MONO_COMP_LIVENESS));
262
263         cfg->comp_done |= MONO_COMP_LIVENESS;
264         
265         if (max_vars == 0)
266                 return;
267
268         bitsize = mono_bitset_alloc_size (max_vars, 0);
269
270         for (i = 0; i < max_vars; i ++) {
271                 MONO_VARINFO (cfg, i)->range.first_use.abs_pos = ~ 0;
272                 MONO_VARINFO (cfg, i)->range.last_use .abs_pos =   0;
273                 MONO_VARINFO (cfg, i)->spill_costs = 0;
274         }
275
276         for (i = 0; i < cfg->num_bblocks; ++i) {
277                 MonoBasicBlock *bb = cfg->bblocks [i];
278
279                 bb->gen_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
280                 bb->kill_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
281
282 #ifdef DEBUG_LIVENESS
283                 if (cfg->verbose_level > 1) {
284                         printf ("BLOCK BB%d (", bb->block_num);
285                         for (j = 0; j < bb->out_count; j++) 
286                                 printf ("BB%d, ", bb->out_bb [j]->block_num);
287                 
288                         printf ("):\n");
289                 }
290 #endif
291
292                 analyze_liveness_bb (cfg, bb);
293
294 #ifdef DEBUG_LIVENESS
295                 if (cfg->verbose_level > 1) {
296                         printf ("GEN  BB%d: ", bb->block_num); mono_bitset_print (bb->gen_set);
297                         printf ("KILL BB%d: ", bb->block_num); mono_bitset_print (bb->kill_set);
298                 }
299 #endif
300         }
301
302         old_live_out_set = mono_bitset_new (max_vars, 0);
303         in_worklist = g_new0 (gboolean, cfg->num_bblocks + 1);
304
305         worklist = g_new (MonoBasicBlock *, cfg->num_bblocks + 1);
306         l_end = 0;
307
308         /*
309          * This is a backward dataflow analysis problem, so we process blocks in
310          * decreasing dfn order, this speeds up the iteration.
311          */
312         for (i = 0; i < cfg->num_bblocks; i ++) {
313                 MonoBasicBlock *bb = cfg->bblocks [i];
314
315                 worklist [l_end ++] = bb;
316                 in_worklist [bb->dfn] = TRUE;
317
318                 /* Initialized later */
319                 bb->live_in_set = NULL;
320                 bb->live_out_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
321         }
322
323         out_iter = 0;
324
325         if (cfg->verbose_level > 1)
326                 printf ("\nITERATION:\n");
327
328         while (l_end != 0) {
329                 MonoBasicBlock *bb = worklist [--l_end];
330                 MonoBasicBlock *out_bb;
331                 gboolean changed;
332
333                 in_worklist [bb->dfn] = FALSE;
334
335 #ifdef DEBUG_LIVENESS
336                 if (cfg->verbose_level > 1) {
337                         printf ("P: BB%d(%d): IN: ", bb->block_num, bb->dfn);
338                         for (j = 0; j < bb->in_count; ++j) 
339                                 printf ("BB%d ", bb->in_bb [j]->block_num);
340                         printf ("OUT:");
341                         for (j = 0; j < bb->out_count; ++j) 
342                                 printf ("BB%d ", bb->out_bb [j]->block_num);
343                         printf ("\n");
344                 }
345 #endif
346
347
348                 if (bb->out_count == 0)
349                         continue;
350
351                 out_iter ++;
352
353                 if (!bb->live_in_set) {
354                         /* First pass over this bblock */
355                         changed = TRUE;
356                 }
357                 else {
358                         changed = FALSE;
359                         mono_bitset_copyto_fast (bb->live_out_set, old_live_out_set);
360                 }
361  
362                 for (j = 0; j < bb->out_count; j++) {
363                         out_bb = bb->out_bb [j];
364
365                         if (!out_bb->live_in_set) {
366                                 out_bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
367
368                                 mono_bitset_copyto_fast (out_bb->live_out_set, out_bb->live_in_set);
369                                 mono_bitset_sub_fast (out_bb->live_in_set, out_bb->kill_set);
370                                 mono_bitset_union_fast (out_bb->live_in_set, out_bb->gen_set);
371                         }
372
373                         // FIXME: Do this somewhere else
374                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
375                         } else {
376                                 mono_bitset_union_fast (bb->live_out_set, out_bb->live_in_set);
377                         }
378                 }
379                                 
380                 if (changed || !mono_bitset_equal (old_live_out_set, bb->live_out_set)) {
381                         if (!bb->live_in_set)
382                                 bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
383                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
384                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
385                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
386
387                         for (j = 0; j < bb->in_count; j++) {
388                                 MonoBasicBlock *in_bb = bb->in_bb [j];
389                                 /* 
390                                  * Some basic blocks do not seem to be in the 
391                                  * cfg->bblocks array...
392                                  */
393                                 if (in_bb->gen_set && !in_worklist [in_bb->dfn]) {
394 #ifdef DEBUG_LIVENESS
395                                         if (cfg->verbose_level > 1)
396                                                 printf ("\tADD: %d\n", in_bb->block_num);
397 #endif
398                                         /*
399                                          * Put the block at the top of the stack, so it
400                                          * will be processed right away.
401                                          */
402                                         worklist [l_end ++] = in_bb;
403                                         in_worklist [in_bb->dfn] = TRUE;
404                                 }
405                         }
406                 }
407
408                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
409                         printf ("\tLIVE IN  BB%d: ", bb->block_num); 
410                         mono_bitset_print (bb->live_in_set); 
411                 }                       
412         }
413
414 #ifdef DEBUG_LIVENESS
415         if (cfg->verbose_level > 1)
416                 printf ("IT: %d %d.\n", cfg->num_bblocks, out_iter);
417 #endif
418
419         mono_bitset_free (old_live_out_set);
420
421         g_free (worklist);
422         g_free (in_worklist);
423
424         /* Compute live_in_set for bblocks skipped earlier */
425         for (i = 0; i < cfg->num_bblocks; ++i) {
426                 MonoBasicBlock *bb = cfg->bblocks [i];
427
428                 if (!bb->live_in_set) {
429                         bb->live_in_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
430
431                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
432                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
433                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
434                 }
435         }
436
437         for (i = 0; i < cfg->num_bblocks; ++i) {
438                 MonoBasicBlock *bb = cfg->bblocks [i];
439                 guint32 rem, max;
440                 guint32 abs_pos = (bb->dfn << 16);
441                 MonoMethodVar *vars = cfg->vars;
442
443                 if (!bb->live_out_set)
444                         continue;
445
446                 rem = max_vars % BITS_PER_CHUNK;
447                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
448                 for (j = 0; j < max; ++j) {
449                         gsize bits_in;
450                         gsize bits_out;
451                         int k;
452
453                         bits_in = mono_bitset_get_fast (bb->live_in_set, j);
454                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
455
456                         k = (j * BITS_PER_CHUNK);
457                         while ((bits_in || bits_out)) {
458                                 if (bits_in & 1)
459                                         update_live_range (&vars [k], abs_pos + 0);
460                                 if (bits_out & 1)
461                                         update_live_range (&vars [k], abs_pos + 0xffff);
462                                 bits_in >>= 1;
463                                 bits_out >>= 1;
464                                 k ++;
465                         }
466                 }
467         }
468
469         /*
470          * Arguments need to have their live ranges extended to the beginning of
471          * the method to account for the arg reg/memory -> global register copies
472          * in the prolog (bug #74992).
473          */
474
475         for (i = 0; i < max_vars; i ++) {
476                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
477                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG) {
478                         if (vi->range.last_use.abs_pos == 0 && !(cfg->varinfo [vi->idx]->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
479                                 /* 
480                                  * Can't eliminate the this variable in gshared code, since
481                                  * it is needed during exception handling to identify the
482                                  * method.
483                                  * It is better to check for this here instead of marking the variable
484                                  * VOLATILE, since that would prevent it from being allocated to
485                                  * registers.
486                                  */
487                                  if (!cfg->disable_deadce_vars && !(cfg->generic_sharing_context && mono_method_signature (cfg->method)->hasthis && cfg->varinfo [vi->idx] == cfg->args [0]))
488                                          cfg->varinfo [vi->idx]->flags |= MONO_INST_IS_DEAD;
489                         }
490                         vi->range.first_use.abs_pos = 0;
491                 }
492         }
493
494 #ifdef DEBUG_LIVENESS
495         if (cfg->verbose_level > 1) {
496                 for (i = cfg->num_bblocks - 1; i >= 0; i--) {
497                         MonoBasicBlock *bb = cfg->bblocks [i];
498                 
499                         printf ("LIVE IN  BB%d: ", bb->block_num); 
500                         mono_bitset_print (bb->live_in_set); 
501                         printf ("LIVE OUT BB%d: ", bb->block_num); 
502                         mono_bitset_print (bb->live_out_set); 
503                 }
504
505                 for (i = 0; i < max_vars; i ++) {
506                         MonoMethodVar *vi = MONO_VARINFO (cfg, i);
507
508                         printf ("V%d: [0x%x - 0x%x]\n", i, vi->range.first_use.abs_pos, vi->range.last_use.abs_pos);
509                 }
510         }
511 #endif
512
513         if (!cfg->disable_initlocals_opt)
514                 optimize_initlocals (cfg);
515
516 #ifdef ENABLE_LIVENESS2
517         /* This improves code size by about 5% but slows down compilation too much */
518         if (cfg->compile_aot)
519                 mono_analyze_liveness2 (cfg);
520 #endif
521 }
522
523 /**
524  * optimize_initlocals:
525  *
526  * Try to optimize away some of the redundant initialization code inserted because of
527  * 'locals init' using the liveness information.
528  */
529 static void
530 optimize_initlocals (MonoCompile *cfg)
531 {
532         MonoBitSet *used;
533         MonoInst *ins;
534         MonoBasicBlock *initlocals_bb;
535
536         used = mono_bitset_new (cfg->next_vreg + 1, 0);
537
538         mono_bitset_clear_all (used);
539         initlocals_bb = cfg->bb_entry->next_bb;
540         for (ins = initlocals_bb->code; ins; ins = ins->next) {
541                 int num_sregs, i;
542                 int sregs [MONO_MAX_SRC_REGS];
543
544                 num_sregs = mono_inst_get_src_registers (ins, sregs);
545                 for (i = 0; i < num_sregs; ++i)
546                         mono_bitset_set_fast (used, sregs [i]);
547
548                 if (MONO_IS_STORE_MEMBASE (ins))
549                         mono_bitset_set_fast (used, ins->dreg);
550         }
551
552         for (ins = initlocals_bb->code; ins; ins = ins->next) {
553                 const char *spec = INS_INFO (ins->opcode);
554
555                 /* Look for statements whose dest is not used in this bblock and not live on exit. */
556                 if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
557                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
558
559                         if (var && !mono_bitset_test_fast (used, ins->dreg) && !mono_bitset_test_fast (initlocals_bb->live_out_set, var->inst_c0) && (var != cfg->ret) && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
560                                 //printf ("DEAD: "); mono_print_ins (ins);
561                                 if (cfg->disable_initlocals_opt_refs && var->type == STACK_OBJ)
562                                         continue;
563                                 if ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST)) {
564                                         NULLIFY_INS (ins);
565                                         MONO_VARINFO (cfg, var->inst_c0)->spill_costs -= 1;
566                                         /* 
567                                          * We should shorten the liveness interval of these vars as well, but
568                                          * don't have enough info to do that.
569                                          */
570                                 }
571                         }
572                 }
573         }
574
575         g_free (used);
576 }
577
578 void
579 mono_linterval_add_range (MonoCompile *cfg, MonoLiveInterval *interval, int from, int to)
580 {
581         MonoLiveRange2 *prev_range, *next_range, *new_range;
582
583         g_assert (to >= from);
584
585         /* Optimize for extending the first interval backwards */
586         if (G_LIKELY (interval->range && (interval->range->from > from) && (interval->range->from == to))) {
587                 interval->range->from = from;
588                 return;
589         }
590
591         /* Find a place in the list for the new range */
592         prev_range = NULL;
593         next_range = interval->range;
594         while ((next_range != NULL) && (next_range->from <= from)) {
595                 prev_range = next_range;
596                 next_range = next_range->next;
597         }
598
599         if (prev_range && prev_range->to == from) {
600                 /* Merge with previous */
601                 prev_range->to = to;
602         } else if (next_range && next_range->from == to) {
603                 /* Merge with previous */
604                 next_range->from = from;
605         } else {
606                 /* Insert it */
607                 new_range = mono_mempool_alloc (cfg->mempool, sizeof (MonoLiveRange2));
608                 new_range->from = from;
609                 new_range->to = to;
610                 new_range->next = NULL;
611
612                 if (prev_range)
613                         prev_range->next = new_range;
614                 else
615                         interval->range = new_range;
616                 if (next_range)
617                         new_range->next = next_range;
618                 else
619                         interval->last_range = new_range;
620         }
621
622         /* FIXME: Merge intersecting ranges */
623 }
624
625 void
626 mono_linterval_print (MonoLiveInterval *interval)
627 {
628         MonoLiveRange2 *range;
629
630         for (range = interval->range; range != NULL; range = range->next)
631                 printf ("[%x-%x] ", range->from, range->to);
632 }
633
634 void
635 mono_linterval_print_nl (MonoLiveInterval *interval)
636 {
637         mono_linterval_print (interval);
638         printf ("\n");
639 }
640
641 /**
642  * mono_linterval_convers:
643  *
644  *   Return whenever INTERVAL covers the position POS.
645  */
646 gboolean
647 mono_linterval_covers (MonoLiveInterval *interval, int pos)
648 {
649         MonoLiveRange2 *range;
650
651         for (range = interval->range; range != NULL; range = range->next) {
652                 if (pos >= range->from && pos <= range->to)
653                         return TRUE;
654                 if (range->from > pos)
655                         return FALSE;
656         }
657
658         return FALSE;
659 }
660
661 /**
662  * mono_linterval_get_intersect_pos:
663  *
664  *   Determine whenever I1 and I2 intersect, and if they do, return the first
665  * point of intersection. Otherwise, return -1.
666  */
667 gint32
668 mono_linterval_get_intersect_pos (MonoLiveInterval *i1, MonoLiveInterval *i2)
669 {
670         MonoLiveRange2 *r1, *r2;
671
672         /* FIXME: Optimize this */
673         for (r1 = i1->range; r1 != NULL; r1 = r1->next) {
674                 for (r2 = i2->range; r2 != NULL; r2 = r2->next) {
675                         if (r2->to > r1->from && r2->from < r1->to) {
676                                 if (r2->from <= r1->from)
677                                         return r1->from;
678                                 else
679                                         return r2->from;
680                         }
681                 }
682         }
683
684         return -1;
685 }
686  
687 /**
688  * mono_linterval_split
689  *
690  *   Split L at POS and store the newly created intervals into L1 and L2. POS becomes
691  * part of L2.
692  */
693 void
694 mono_linterval_split (MonoCompile *cfg, MonoLiveInterval *interval, MonoLiveInterval **i1, MonoLiveInterval **i2, int pos)
695 {
696         MonoLiveRange2 *r;
697
698         g_assert (pos > interval->range->from && pos <= interval->last_range->to);
699
700         *i1 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
701         *i2 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
702
703         for (r = interval->range; r; r = r->next) {
704                 if (pos > r->to) {
705                         /* Add it to the first child */
706                         mono_linterval_add_range (cfg, *i1, r->from, r->to);
707                 } else if (pos > r->from && pos <= r->to) {
708                         /* Split at pos */
709                         mono_linterval_add_range (cfg, *i1, r->from, pos - 1);
710                         mono_linterval_add_range (cfg, *i2, pos, r->to);
711                 } else {
712                         /* Add it to the second child */
713                         mono_linterval_add_range (cfg, *i2, r->from, r->to);
714                 }
715         }
716 }
717
718 #ifdef ENABLE_LIVENESS2
719
720 #if 0
721 #define LIVENESS_DEBUG(a) do { a; } while (0)
722 #else
723 #define LIVENESS_DEBUG(a)
724 #endif
725
726 static inline void
727 update_liveness2 (MonoCompile *cfg, MonoInst *ins, gboolean set_volatile, int inst_num, gint32 *last_use)
728 {
729         const char *spec = INS_INFO (ins->opcode);
730         int sreg;
731         int num_sregs, i;
732         int sregs [MONO_MAX_SRC_REGS];
733
734         LIVENESS_DEBUG (printf ("\t%x: ", inst_num); mono_print_ins (ins));
735
736         if (ins->opcode == OP_NOP)
737                 return;
738
739         /* DREG */
740         if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
741                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
742                 int idx = var->inst_c0;
743                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
744
745                 if (MONO_IS_STORE_MEMBASE (ins)) {
746                         if (last_use [idx] == 0) {
747                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", ins->dreg, inst_num));
748                                 last_use [idx] = inst_num;
749                         }
750                 } else {
751                         if (last_use [idx] > 0) {
752                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", ins->dreg, inst_num, last_use [idx]));
753                                 mono_linterval_add_range (cfg, vi->interval, inst_num, last_use [idx]);
754                                 last_use [idx] = 0;
755                         }
756                         else {
757                                 /* Try dead code elimination */
758                                 if ((var != cfg->ret) && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) && ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST)) && !(var->flags & MONO_INST_VOLATILE)) {
759                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, eliminated\n", ins->dreg));
760                                         ins->opcode = OP_NOP;
761                                         ins->dreg = -1;
762                                         MONO_INST_NULLIFY_SREGS (ins);
763                                         return;
764                                 }
765
766                                 LIVENESS_DEBUG (printf ("\tdead def of R%d, add range to R%d: [%x, %x]\n", ins->dreg, ins->dreg, inst_num, inst_num + 1));
767                                 mono_linterval_add_range (cfg, vi->interval, inst_num, inst_num + 1);
768                         }
769                 }
770         }
771
772         /* SREGs */
773         num_sregs = mono_inst_get_src_registers (ins, sregs);
774         for (i = 0; i < num_sregs; ++i) {
775                 sreg = sregs [i];
776                 if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
777                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
778                         int idx = var->inst_c0;
779
780                         if (last_use [idx] == 0) {
781                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
782                                 last_use [idx] = inst_num;
783                         }
784                 }
785         }
786 }
787
788 static void
789 mono_analyze_liveness2 (MonoCompile *cfg)
790 {
791         int bnum, idx, i, j, nins, rem, max, max_vars, block_from, block_to, pos, reverse_len;
792         gint32 *last_use;
793         static guint32 disabled = -1;
794         MonoInst **reverse;
795
796         if (disabled == -1)
797                 disabled = getenv ("DISABLED") != NULL;
798
799         if (disabled)
800                 return;
801
802         LIVENESS_DEBUG (printf ("LIVENESS 2 %s\n", mono_method_full_name (cfg->method, TRUE)));
803
804         /*
805         if (strstr (cfg->method->name, "test_") != cfg->method->name)
806                 return;
807         */
808
809         max_vars = cfg->num_varinfo;
810         last_use = g_new0 (gint32, max_vars);
811
812         reverse_len = 1024;
813         reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
814
815         for (idx = 0; idx < max_vars; ++idx) {
816                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
817
818                 vi->interval = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
819         }
820
821         /*
822          * Process bblocks in reverse order, so the addition of new live ranges
823          * to the intervals is faster.
824          */
825         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
826                 MonoBasicBlock *bb = cfg->bblocks [bnum];
827                 MonoInst *ins;
828
829                 block_from = (bb->dfn << 16) + 1; /* so pos > 0 */
830                 if (bnum < cfg->num_bblocks - 1)
831                         /* Beginning of the next bblock */
832                         block_to = (cfg->bblocks [bnum + 1]->dfn << 16) + 1;
833                 else
834                         block_to = (bb->dfn << 16) + 0xffff;
835
836                 LIVENESS_DEBUG (printf ("LIVENESS BLOCK BB%d:\n", bb->block_num));
837
838                 memset (last_use, 0, max_vars * sizeof (gint32));
839                 
840                 /* For variables in bb->live_out, set last_use to block_to */
841
842                 rem = max_vars % BITS_PER_CHUNK;
843                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
844                 for (j = 0; j < max; ++j) {
845                         gsize bits_out;
846                         int k;
847
848                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
849                         k = (j * BITS_PER_CHUNK);       
850                         while (bits_out) {
851                                 if (bits_out & 1) {
852                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, set last_use to %x\n", cfg->varinfo [k]->dreg, block_to));
853                                         last_use [k] = block_to;
854                                 }
855                                 bits_out >>= 1;
856                                 k ++;
857                         }
858                 }
859
860                 if (cfg->ret)
861                         last_use [cfg->ret->inst_c0] = block_to;
862
863                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
864                         if (nins >= reverse_len) {
865                                 int new_reverse_len = reverse_len * 2;
866                                 MonoInst **new_reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
867                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
868                                 reverse = new_reverse;
869                                 reverse_len = new_reverse_len;
870                         }
871
872                         reverse [nins] = ins;
873                 }
874
875                 /* Process instructions backwards */
876                 for (i = nins - 1; i >= 0; --i) {
877                         MonoInst *ins = (MonoInst*)reverse [i];
878
879                         update_liveness2 (cfg, ins, FALSE, pos, last_use);
880
881                         pos --;
882                 }
883
884                 for (idx = 0; idx < max_vars; ++idx) {
885                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
886
887                         if (last_use [idx] != 0) {
888                                 /* Live at exit, not written -> live on enter */
889                                 LIVENESS_DEBUG (printf ("Var R%d live at enter, add range to R%d: [%x, %x)\n", cfg->varinfo [idx]->dreg, cfg->varinfo [idx]->dreg, block_from, last_use [idx]));
890                                 mono_linterval_add_range (cfg, vi->interval, block_from, last_use [idx]);
891                         }
892                 }
893         }
894
895         /*
896          * Arguments need to have their live ranges extended to the beginning of
897          * the method to account for the arg reg/memory -> global register copies
898          * in the prolog (bug #74992).
899          */
900         for (i = 0; i < max_vars; i ++) {
901                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
902                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG)
903                         mono_linterval_add_range (cfg, vi->interval, 0, 1);
904         }
905
906 #if 0
907         for (idx = 0; idx < max_vars; ++idx) {
908                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
909                 
910                 LIVENESS_DEBUG (printf ("LIVENESS R%d: ", cfg->varinfo [idx]->dreg));
911                 LIVENESS_DEBUG (mono_linterval_print (vi->interval));
912                 LIVENESS_DEBUG (printf ("\n"));
913         }
914 #endif
915
916         g_free (last_use);
917 }
918
919 #endif