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