2009-03-02 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 #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;
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                                 /* 
462                                  * Can't eliminate the this variable in gshared code, since
463                                  * it is needed during exception handling to identify the
464                                  * method.
465                                  * It is better to check for this here instead of marking the variable
466                                  * VOLATILE, since that would prevent it from being allocated to
467                                  * registers.
468                                  */
469                                  if (!cfg->disable_deadce_vars && !(cfg->generic_sharing_context && mono_method_signature (cfg->method)->hasthis && cfg->varinfo [vi->idx] == cfg->args [0]))
470                                          cfg->varinfo [vi->idx]->flags |= MONO_INST_IS_DEAD;
471                         }
472                         vi->range.first_use.abs_pos = 0;
473                 }
474         }
475
476 #ifdef DEBUG_LIVENESS
477         for (i = cfg->num_bblocks - 1; i >= 0; i--) {
478                 MonoBasicBlock *bb = cfg->bblocks [i];
479                 
480                 printf ("LIVE IN  BB%d: ", bb->block_num); 
481                 mono_bitset_print (bb->live_in_set); 
482                 printf ("LIVE OUT BB%d: ", bb->block_num); 
483                 mono_bitset_print (bb->live_out_set); 
484         }
485 #endif
486
487         if (!cfg->disable_initlocals_opt)
488                 optimize_initlocals (cfg);
489
490 #ifdef ENABLE_LIVENESS2
491         /* This improves code size by about 5% but slows down compilation too much */
492         if (cfg->compile_aot)
493                 mono_analyze_liveness2 (cfg);
494 #endif
495 }
496
497 /**
498  * optimize_initlocals:
499  *
500  * Try to optimize away some of the redundant initialization code inserted because of
501  * 'locals init' using the liveness information.
502  */
503 static void
504 optimize_initlocals (MonoCompile *cfg)
505 {
506         MonoBitSet *used;
507         MonoInst *ins;
508         MonoBasicBlock *initlocals_bb;
509
510         used = mono_bitset_new (cfg->next_vreg + 1, 0);
511
512         mono_bitset_clear_all (used);
513         initlocals_bb = cfg->bb_entry->next_bb;
514         for (ins = initlocals_bb->code; ins; ins = ins->next) {
515                 const char *spec = INS_INFO (ins->opcode);
516
517                 if (spec [MONO_INST_SRC1] != ' ')
518                         mono_bitset_set_fast (used, ins->sreg1);
519                 if (spec [MONO_INST_SRC2] != ' ')
520                         mono_bitset_set_fast (used, ins->sreg2);
521                 if (MONO_IS_STORE_MEMBASE (ins))
522                         mono_bitset_set_fast (used, ins->dreg);
523         }
524
525         for (ins = initlocals_bb->code; ins; ins = ins->next) {
526                 const char *spec = INS_INFO (ins->opcode);
527
528                 /* Look for statements whose dest is not used in this bblock and not live on exit. */
529                 if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
530                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
531
532                         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))) {
533                                 //printf ("DEAD: "); mono_print_ins (ins);
534                                 if ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST)) {
535                                         NULLIFY_INS (ins);
536                                         MONO_VARINFO (cfg, var->inst_c0)->spill_costs -= 1;
537                                         /* 
538                                          * We should shorten the liveness interval of these vars as well, but
539                                          * don't have enough info to do that.
540                                          */
541                                 }
542                         }
543                 }
544         }
545
546         g_free (used);
547 }
548
549 void
550 mono_linterval_add_range (MonoCompile *cfg, MonoLiveInterval *interval, int from, int to)
551 {
552         MonoLiveRange2 *prev_range, *next_range, *new_range;
553
554         g_assert (to >= from);
555
556         /* Optimize for extending the first interval backwards */
557         if (G_LIKELY (interval->range && (interval->range->from > from) && (interval->range->from == to))) {
558                 interval->range->from = from;
559                 return;
560         }
561
562         /* Find a place in the list for the new range */
563         prev_range = NULL;
564         next_range = interval->range;
565         while ((next_range != NULL) && (next_range->from <= from)) {
566                 prev_range = next_range;
567                 next_range = next_range->next;
568         }
569
570         if (prev_range && prev_range->to == from) {
571                 /* Merge with previous */
572                 prev_range->to = to;
573         } else if (next_range && next_range->from == to) {
574                 /* Merge with previous */
575                 next_range->from = from;
576         } else {
577                 /* Insert it */
578                 new_range = mono_mempool_alloc (cfg->mempool, sizeof (MonoLiveRange2));
579                 new_range->from = from;
580                 new_range->to = to;
581                 new_range->next = NULL;
582
583                 if (prev_range)
584                         prev_range->next = new_range;
585                 else
586                         interval->range = new_range;
587                 if (next_range)
588                         new_range->next = next_range;
589                 else
590                         interval->last_range = new_range;
591         }
592
593         /* FIXME: Merge intersecting ranges */
594 }
595
596 void
597 mono_linterval_print (MonoLiveInterval *interval)
598 {
599         MonoLiveRange2 *range;
600
601         for (range = interval->range; range != NULL; range = range->next)
602                 printf ("[%x-%x] ", range->from, range->to);
603 }
604
605 void
606 mono_linterval_print_nl (MonoLiveInterval *interval)
607 {
608         mono_linterval_print (interval);
609         printf ("\n");
610 }
611
612 /**
613  * mono_linterval_convers:
614  *
615  *   Return whenever INTERVAL covers the position POS.
616  */
617 gboolean
618 mono_linterval_covers (MonoLiveInterval *interval, int pos)
619 {
620         MonoLiveRange2 *range;
621
622         for (range = interval->range; range != NULL; range = range->next) {
623                 if (pos >= range->from && pos <= range->to)
624                         return TRUE;
625                 if (range->from > pos)
626                         return FALSE;
627         }
628
629         return FALSE;
630 }
631
632 /**
633  * mono_linterval_get_intersect_pos:
634  *
635  *   Determine whenever I1 and I2 intersect, and if they do, return the first
636  * point of intersection. Otherwise, return -1.
637  */
638 gint32
639 mono_linterval_get_intersect_pos (MonoLiveInterval *i1, MonoLiveInterval *i2)
640 {
641         MonoLiveRange2 *r1, *r2;
642
643         /* FIXME: Optimize this */
644         for (r1 = i1->range; r1 != NULL; r1 = r1->next) {
645                 for (r2 = i2->range; r2 != NULL; r2 = r2->next) {
646                         if (r2->to > r1->from && r2->from < r1->to) {
647                                 if (r2->from <= r1->from)
648                                         return r1->from;
649                                 else
650                                         return r2->from;
651                         }
652                 }
653         }
654
655         return -1;
656 }
657  
658 /**
659  * mono_linterval_split
660  *
661  *   Split L at POS and store the newly created intervals into L1 and L2. POS becomes
662  * part of L2.
663  */
664 void
665 mono_linterval_split (MonoCompile *cfg, MonoLiveInterval *interval, MonoLiveInterval **i1, MonoLiveInterval **i2, int pos)
666 {
667         MonoLiveRange2 *r;
668
669         g_assert (pos > interval->range->from && pos <= interval->last_range->to);
670
671         *i1 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
672         *i2 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
673
674         for (r = interval->range; r; r = r->next) {
675                 if (pos > r->to) {
676                         /* Add it to the first child */
677                         mono_linterval_add_range (cfg, *i1, r->from, r->to);
678                 } else if (pos > r->from && pos <= r->to) {
679                         /* Split at pos */
680                         mono_linterval_add_range (cfg, *i1, r->from, pos - 1);
681                         mono_linterval_add_range (cfg, *i2, pos, r->to);
682                 } else {
683                         /* Add it to the second child */
684                         mono_linterval_add_range (cfg, *i2, r->from, r->to);
685                 }
686         }
687 }
688
689 #ifdef ENABLE_LIVENESS2
690
691 #if 0
692 #define LIVENESS_DEBUG(a) do { a; } while (0)
693 #else
694 #define LIVENESS_DEBUG(a)
695 #endif
696
697 static inline void
698 update_liveness2 (MonoCompile *cfg, MonoInst *ins, gboolean set_volatile, int inst_num, gint32 *last_use)
699 {
700         const char *spec = INS_INFO (ins->opcode);
701         int sreg;
702
703         LIVENESS_DEBUG (printf ("\t%x: ", inst_num); mono_print_ins (ins));
704
705         if (ins->opcode == OP_NOP)
706                 return;
707
708         /* DREG */
709         if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
710                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
711                 int idx = var->inst_c0;
712                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
713
714                 if (MONO_IS_STORE_MEMBASE (ins)) {
715                         if (last_use [idx] == 0) {
716                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", ins->dreg, inst_num));
717                                 last_use [idx] = inst_num;
718                         }
719                 } else {
720                         if (last_use [idx] > 0) {
721                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", ins->dreg, inst_num, last_use [idx]));
722                                 mono_linterval_add_range (cfg, vi->interval, inst_num, last_use [idx]);
723                                 last_use [idx] = 0;
724                         }
725                         else {
726                                 /* Try dead code elimination */
727                                 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)) {
728                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, eliminated\n", ins->dreg));
729                                         ins->opcode = OP_NOP;
730                                         ins->dreg = ins->sreg1 = ins->sreg2 = -1;
731                                         return;
732                                 }
733
734                                 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));
735                                 mono_linterval_add_range (cfg, vi->interval, inst_num, inst_num + 1);
736                         }
737                 }
738         }
739
740         /* SREG1 */
741         sreg = ins->sreg1;
742         if ((spec [MONO_INST_SRC1] != ' ') && get_vreg_to_inst (cfg, sreg)) {
743                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
744                 int idx = var->inst_c0;
745
746                 if (last_use [idx] == 0) {
747                         LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
748                         last_use [idx] = inst_num;
749                 }
750         }
751
752         /* SREG2 */
753         sreg = ins->sreg2;
754         if ((spec [MONO_INST_SRC2] != ' ') && get_vreg_to_inst (cfg, sreg)) {
755                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
756                 int idx = var->inst_c0;
757
758                 if (last_use [idx] == 0) {
759                         LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
760                         last_use [idx] = inst_num;
761                 }
762         }
763 }
764
765 static void
766 mono_analyze_liveness2 (MonoCompile *cfg)
767 {
768         int bnum, idx, i, j, nins, rem, max, max_vars, block_from, block_to, pos, reverse_len;
769         gint32 *last_use;
770         static guint32 disabled = -1;
771         MonoInst **reverse;
772
773         if (disabled == -1)
774                 disabled = getenv ("DISABLED") != NULL;
775
776         if (disabled)
777                 return;
778
779         LIVENESS_DEBUG (printf ("LIVENESS 2 %s\n", mono_method_full_name (cfg->method, TRUE)));
780
781         /*
782         if (strstr (cfg->method->name, "test_") != cfg->method->name)
783                 return;
784         */
785
786         max_vars = cfg->num_varinfo;
787         last_use = g_new0 (gint32, max_vars);
788
789         reverse_len = 1024;
790         reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
791
792         for (idx = 0; idx < max_vars; ++idx) {
793                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
794
795                 vi->interval = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
796         }
797
798         /*
799          * Process bblocks in reverse order, so the addition of new live ranges
800          * to the intervals is faster.
801          */
802         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
803                 MonoBasicBlock *bb = cfg->bblocks [bnum];
804                 MonoInst *ins;
805
806                 block_from = (bb->dfn << 16) + 1; /* so pos > 0 */
807                 if (bnum < cfg->num_bblocks - 1)
808                         /* Beginning of the next bblock */
809                         block_to = (cfg->bblocks [bnum + 1]->dfn << 16) + 1;
810                 else
811                         block_to = (bb->dfn << 16) + 0xffff;
812
813                 LIVENESS_DEBUG (printf ("LIVENESS BLOCK BB%d:\n", bb->block_num));
814
815                 memset (last_use, 0, max_vars * sizeof (gint32));
816                 
817                 /* For variables in bb->live_out, set last_use to block_to */
818
819                 rem = max_vars % BITS_PER_CHUNK;
820                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
821                 for (j = 0; j < max; ++j) {
822                         gsize bits_out;
823                         int k;
824
825                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
826                         k = (j * BITS_PER_CHUNK);       
827                         while (bits_out) {
828                                 if (bits_out & 1) {
829                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, set last_use to %x\n", cfg->varinfo [k]->dreg, block_to));
830                                         last_use [k] = block_to;
831                                 }
832                                 bits_out >>= 1;
833                                 k ++;
834                         }
835                 }
836
837                 if (cfg->ret)
838                         last_use [cfg->ret->inst_c0] = block_to;
839
840                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
841                         if (nins >= reverse_len) {
842                                 int new_reverse_len = reverse_len * 2;
843                                 MonoInst **new_reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
844                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
845                                 reverse = new_reverse;
846                                 reverse_len = new_reverse_len;
847                         }
848
849                         reverse [nins] = ins;
850                 }
851
852                 /* Process instructions backwards */
853                 for (i = nins - 1; i >= 0; --i) {
854                         MonoInst *ins = (MonoInst*)reverse [i];
855
856                         update_liveness2 (cfg, ins, FALSE, pos, last_use);
857
858                         pos --;
859                 }
860
861                 for (idx = 0; idx < max_vars; ++idx) {
862                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
863
864                         if (last_use [idx] != 0) {
865                                 /* Live at exit, not written -> live on enter */
866                                 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]));
867                                 mono_linterval_add_range (cfg, vi->interval, block_from, last_use [idx]);
868                         }
869                 }
870         }
871
872         /*
873          * Arguments need to have their live ranges extended to the beginning of
874          * the method to account for the arg reg/memory -> global register copies
875          * in the prolog (bug #74992).
876          */
877         for (i = 0; i < max_vars; i ++) {
878                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
879                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG)
880                         mono_linterval_add_range (cfg, vi->interval, 0, 1);
881         }
882
883 #if 0
884         for (idx = 0; idx < max_vars; ++idx) {
885                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
886                 
887                 LIVENESS_DEBUG (printf ("LIVENESS R%d: ", cfg->varinfo [idx]->dreg));
888                 LIVENESS_DEBUG (mono_linterval_print (vi->interval));
889                 LIVENESS_DEBUG (printf ("\n"));
890         }
891 #endif
892
893         g_free (last_use);
894 }
895
896 #endif