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