2010-01-18 Zoltan Varga <vargaz@gmail.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 ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST)) {
562                                         NULLIFY_INS (ins);
563                                         MONO_VARINFO (cfg, var->inst_c0)->spill_costs -= 1;
564                                         /* 
565                                          * We should shorten the liveness interval of these vars as well, but
566                                          * don't have enough info to do that.
567                                          */
568                                 }
569                         }
570                 }
571         }
572
573         g_free (used);
574 }
575
576 void
577 mono_linterval_add_range (MonoCompile *cfg, MonoLiveInterval *interval, int from, int to)
578 {
579         MonoLiveRange2 *prev_range, *next_range, *new_range;
580
581         g_assert (to >= from);
582
583         /* Optimize for extending the first interval backwards */
584         if (G_LIKELY (interval->range && (interval->range->from > from) && (interval->range->from == to))) {
585                 interval->range->from = from;
586                 return;
587         }
588
589         /* Find a place in the list for the new range */
590         prev_range = NULL;
591         next_range = interval->range;
592         while ((next_range != NULL) && (next_range->from <= from)) {
593                 prev_range = next_range;
594                 next_range = next_range->next;
595         }
596
597         if (prev_range && prev_range->to == from) {
598                 /* Merge with previous */
599                 prev_range->to = to;
600         } else if (next_range && next_range->from == to) {
601                 /* Merge with previous */
602                 next_range->from = from;
603         } else {
604                 /* Insert it */
605                 new_range = mono_mempool_alloc (cfg->mempool, sizeof (MonoLiveRange2));
606                 new_range->from = from;
607                 new_range->to = to;
608                 new_range->next = NULL;
609
610                 if (prev_range)
611                         prev_range->next = new_range;
612                 else
613                         interval->range = new_range;
614                 if (next_range)
615                         new_range->next = next_range;
616                 else
617                         interval->last_range = new_range;
618         }
619
620         /* FIXME: Merge intersecting ranges */
621 }
622
623 void
624 mono_linterval_print (MonoLiveInterval *interval)
625 {
626         MonoLiveRange2 *range;
627
628         for (range = interval->range; range != NULL; range = range->next)
629                 printf ("[%x-%x] ", range->from, range->to);
630 }
631
632 void
633 mono_linterval_print_nl (MonoLiveInterval *interval)
634 {
635         mono_linterval_print (interval);
636         printf ("\n");
637 }
638
639 /**
640  * mono_linterval_convers:
641  *
642  *   Return whenever INTERVAL covers the position POS.
643  */
644 gboolean
645 mono_linterval_covers (MonoLiveInterval *interval, int pos)
646 {
647         MonoLiveRange2 *range;
648
649         for (range = interval->range; range != NULL; range = range->next) {
650                 if (pos >= range->from && pos <= range->to)
651                         return TRUE;
652                 if (range->from > pos)
653                         return FALSE;
654         }
655
656         return FALSE;
657 }
658
659 /**
660  * mono_linterval_get_intersect_pos:
661  *
662  *   Determine whenever I1 and I2 intersect, and if they do, return the first
663  * point of intersection. Otherwise, return -1.
664  */
665 gint32
666 mono_linterval_get_intersect_pos (MonoLiveInterval *i1, MonoLiveInterval *i2)
667 {
668         MonoLiveRange2 *r1, *r2;
669
670         /* FIXME: Optimize this */
671         for (r1 = i1->range; r1 != NULL; r1 = r1->next) {
672                 for (r2 = i2->range; r2 != NULL; r2 = r2->next) {
673                         if (r2->to > r1->from && r2->from < r1->to) {
674                                 if (r2->from <= r1->from)
675                                         return r1->from;
676                                 else
677                                         return r2->from;
678                         }
679                 }
680         }
681
682         return -1;
683 }
684  
685 /**
686  * mono_linterval_split
687  *
688  *   Split L at POS and store the newly created intervals into L1 and L2. POS becomes
689  * part of L2.
690  */
691 void
692 mono_linterval_split (MonoCompile *cfg, MonoLiveInterval *interval, MonoLiveInterval **i1, MonoLiveInterval **i2, int pos)
693 {
694         MonoLiveRange2 *r;
695
696         g_assert (pos > interval->range->from && pos <= interval->last_range->to);
697
698         *i1 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
699         *i2 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
700
701         for (r = interval->range; r; r = r->next) {
702                 if (pos > r->to) {
703                         /* Add it to the first child */
704                         mono_linterval_add_range (cfg, *i1, r->from, r->to);
705                 } else if (pos > r->from && pos <= r->to) {
706                         /* Split at pos */
707                         mono_linterval_add_range (cfg, *i1, r->from, pos - 1);
708                         mono_linterval_add_range (cfg, *i2, pos, r->to);
709                 } else {
710                         /* Add it to the second child */
711                         mono_linterval_add_range (cfg, *i2, r->from, r->to);
712                 }
713         }
714 }
715
716 #ifdef ENABLE_LIVENESS2
717
718 #if 0
719 #define LIVENESS_DEBUG(a) do { a; } while (0)
720 #else
721 #define LIVENESS_DEBUG(a)
722 #endif
723
724 static inline void
725 update_liveness2 (MonoCompile *cfg, MonoInst *ins, gboolean set_volatile, int inst_num, gint32 *last_use)
726 {
727         const char *spec = INS_INFO (ins->opcode);
728         int sreg;
729         int num_sregs, i;
730         int sregs [MONO_MAX_SRC_REGS];
731
732         LIVENESS_DEBUG (printf ("\t%x: ", inst_num); mono_print_ins (ins));
733
734         if (ins->opcode == OP_NOP)
735                 return;
736
737         /* DREG */
738         if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
739                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
740                 int idx = var->inst_c0;
741                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
742
743                 if (MONO_IS_STORE_MEMBASE (ins)) {
744                         if (last_use [idx] == 0) {
745                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", ins->dreg, inst_num));
746                                 last_use [idx] = inst_num;
747                         }
748                 } else {
749                         if (last_use [idx] > 0) {
750                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", ins->dreg, inst_num, last_use [idx]));
751                                 mono_linterval_add_range (cfg, vi->interval, inst_num, last_use [idx]);
752                                 last_use [idx] = 0;
753                         }
754                         else {
755                                 /* Try dead code elimination */
756                                 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)) {
757                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, eliminated\n", ins->dreg));
758                                         ins->opcode = OP_NOP;
759                                         ins->dreg = -1;
760                                         MONO_INST_NULLIFY_SREGS (ins);
761                                         return;
762                                 }
763
764                                 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));
765                                 mono_linterval_add_range (cfg, vi->interval, inst_num, inst_num + 1);
766                         }
767                 }
768         }
769
770         /* SREGs */
771         num_sregs = mono_inst_get_src_registers (ins, sregs);
772         for (i = 0; i < num_sregs; ++i) {
773                 sreg = sregs [i];
774                 if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
775                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
776                         int idx = var->inst_c0;
777
778                         if (last_use [idx] == 0) {
779                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
780                                 last_use [idx] = inst_num;
781                         }
782                 }
783         }
784 }
785
786 static void
787 mono_analyze_liveness2 (MonoCompile *cfg)
788 {
789         int bnum, idx, i, j, nins, rem, max, max_vars, block_from, block_to, pos, reverse_len;
790         gint32 *last_use;
791         static guint32 disabled = -1;
792         MonoInst **reverse;
793
794         if (disabled == -1)
795                 disabled = getenv ("DISABLED") != NULL;
796
797         if (disabled)
798                 return;
799
800         LIVENESS_DEBUG (printf ("LIVENESS 2 %s\n", mono_method_full_name (cfg->method, TRUE)));
801
802         /*
803         if (strstr (cfg->method->name, "test_") != cfg->method->name)
804                 return;
805         */
806
807         max_vars = cfg->num_varinfo;
808         last_use = g_new0 (gint32, max_vars);
809
810         reverse_len = 1024;
811         reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
812
813         for (idx = 0; idx < max_vars; ++idx) {
814                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
815
816                 vi->interval = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
817         }
818
819         /*
820          * Process bblocks in reverse order, so the addition of new live ranges
821          * to the intervals is faster.
822          */
823         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
824                 MonoBasicBlock *bb = cfg->bblocks [bnum];
825                 MonoInst *ins;
826
827                 block_from = (bb->dfn << 16) + 1; /* so pos > 0 */
828                 if (bnum < cfg->num_bblocks - 1)
829                         /* Beginning of the next bblock */
830                         block_to = (cfg->bblocks [bnum + 1]->dfn << 16) + 1;
831                 else
832                         block_to = (bb->dfn << 16) + 0xffff;
833
834                 LIVENESS_DEBUG (printf ("LIVENESS BLOCK BB%d:\n", bb->block_num));
835
836                 memset (last_use, 0, max_vars * sizeof (gint32));
837                 
838                 /* For variables in bb->live_out, set last_use to block_to */
839
840                 rem = max_vars % BITS_PER_CHUNK;
841                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
842                 for (j = 0; j < max; ++j) {
843                         gsize bits_out;
844                         int k;
845
846                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
847                         k = (j * BITS_PER_CHUNK);       
848                         while (bits_out) {
849                                 if (bits_out & 1) {
850                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, set last_use to %x\n", cfg->varinfo [k]->dreg, block_to));
851                                         last_use [k] = block_to;
852                                 }
853                                 bits_out >>= 1;
854                                 k ++;
855                         }
856                 }
857
858                 if (cfg->ret)
859                         last_use [cfg->ret->inst_c0] = block_to;
860
861                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
862                         if (nins >= reverse_len) {
863                                 int new_reverse_len = reverse_len * 2;
864                                 MonoInst **new_reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
865                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
866                                 reverse = new_reverse;
867                                 reverse_len = new_reverse_len;
868                         }
869
870                         reverse [nins] = ins;
871                 }
872
873                 /* Process instructions backwards */
874                 for (i = nins - 1; i >= 0; --i) {
875                         MonoInst *ins = (MonoInst*)reverse [i];
876
877                         update_liveness2 (cfg, ins, FALSE, pos, last_use);
878
879                         pos --;
880                 }
881
882                 for (idx = 0; idx < max_vars; ++idx) {
883                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
884
885                         if (last_use [idx] != 0) {
886                                 /* Live at exit, not written -> live on enter */
887                                 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]));
888                                 mono_linterval_add_range (cfg, vi->interval, block_from, last_use [idx]);
889                         }
890                 }
891         }
892
893         /*
894          * Arguments need to have their live ranges extended to the beginning of
895          * the method to account for the arg reg/memory -> global register copies
896          * in the prolog (bug #74992).
897          */
898         for (i = 0; i < max_vars; i ++) {
899                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
900                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG)
901                         mono_linterval_add_range (cfg, vi->interval, 0, 1);
902         }
903
904 #if 0
905         for (idx = 0; idx < max_vars; ++idx) {
906                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
907                 
908                 LIVENESS_DEBUG (printf ("LIVENESS R%d: ", cfg->varinfo [idx]->dreg));
909                 LIVENESS_DEBUG (mono_linterval_print (vi->interval));
910                 LIVENESS_DEBUG (printf ("\n"));
911         }
912 #endif
913
914         g_free (last_use);
915 }
916
917 #endif