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