c897893074057b178071b619e5420ae7a36b5b6e
[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  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
10  */
11
12 #include <config.h>
13
14 #ifndef DISABLE_JIT
15
16 #include "mini.h"
17
18 #define SPILL_COST_INCREMENT (1 << (bb->nesting << 1))
19
20 #define DEBUG_LIVENESS
21
22 #define BITS_PER_CHUNK MONO_BITSET_BITS_PER_CHUNK
23
24 #define BB_ID_SHIFT 18
25
26 /* 
27  * The liveness2 pass can't handle long vars on 32 bit platforms because the component
28  * vars have the same 'idx'.
29  */
30 #if SIZEOF_REGISTER == 8
31 #define ENABLE_LIVENESS2
32 #endif
33
34 #ifdef ENABLE_LIVENESS2
35 static void mono_analyze_liveness2 (MonoCompile *cfg);
36 #endif
37
38 static void
39 optimize_initlocals (MonoCompile *cfg);
40
41 /* mono_bitset_mp_new:
42  * 
43  * allocates a MonoBitSet inside a memory pool
44  */
45 static inline MonoBitSet* 
46 mono_bitset_mp_new (MonoMemPool *mp, guint32 size, guint32 max_size)
47 {
48         guint8 *mem = (guint8 *)mono_mempool_alloc0 (mp, size);
49         return mono_bitset_mem_new (mem, max_size, MONO_BITSET_DONT_FREE);
50 }
51
52 static inline MonoBitSet* 
53 mono_bitset_mp_new_noinit (MonoMemPool *mp, guint32 size, guint32 max_size)
54 {
55         guint8 *mem = (guint8 *)mono_mempool_alloc (mp, size);
56         return mono_bitset_mem_new (mem, max_size, MONO_BITSET_DONT_FREE);
57 }
58
59 G_GNUC_UNUSED static void
60 mono_bitset_print (MonoBitSet *set)
61 {
62         int i;
63         gboolean first = TRUE;
64
65         printf ("{");
66         for (i = 0; i < mono_bitset_size (set); i++) {
67
68                 if (mono_bitset_test (set, i)) {
69                         if (!first)
70                                 printf (", ");
71                         printf ("%d", i);
72                         first = FALSE;
73                 }
74         }
75         printf ("}\n");
76 }
77
78 static void
79 visit_bb (MonoCompile *cfg, MonoBasicBlock *bb, GSList **visited)
80 {
81         int i;
82         MonoInst *ins;
83
84         if (g_slist_find (*visited, bb))
85                 return;
86
87         for (ins = bb->code; ins; ins = ins->next) {
88                 const char *spec = INS_INFO (ins->opcode);
89                 int regtype, srcindex, sreg, num_sregs;
90                 int sregs [MONO_MAX_SRC_REGS];
91
92                 if (ins->opcode == OP_NOP)
93                         continue;
94
95                 /* DREG */
96                 regtype = spec [MONO_INST_DEST];
97                 g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
98                                 
99                 if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
100                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
101                         int idx = var->inst_c0;
102                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
103
104                         cfg->varinfo [vi->idx]->flags |= MONO_INST_VOLATILE;
105                         if (SIZEOF_REGISTER == 4 && (var->type == STACK_I8 || (var->type == STACK_R8 && COMPILE_SOFT_FLOAT (cfg)))) {
106                                 /* Make the component vregs volatile as well (#612206) */
107                                 get_vreg_to_inst (cfg, MONO_LVREG_LS (var->dreg))->flags |= MONO_INST_VOLATILE;
108                                 get_vreg_to_inst (cfg, MONO_LVREG_MS (var->dreg))->flags |= MONO_INST_VOLATILE;
109                         }
110                 }
111                         
112                 /* SREGS */
113                 num_sregs = mono_inst_get_src_registers (ins, sregs);
114                 for (srcindex = 0; srcindex < num_sregs; ++srcindex) {
115                         sreg = sregs [srcindex];
116
117                         g_assert (sreg != -1);
118                         if (get_vreg_to_inst (cfg, sreg)) {
119                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
120                                 int idx = var->inst_c0;
121                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
122
123                                 cfg->varinfo [vi->idx]->flags |= MONO_INST_VOLATILE;
124                                 if (SIZEOF_REGISTER == 4 && (var->type == STACK_I8 || (var->type == STACK_R8 && COMPILE_SOFT_FLOAT (cfg)))) {
125                                         /* Make the component vregs volatile as well (#612206) */
126                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (var->dreg))->flags |= MONO_INST_VOLATILE;
127                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (var->dreg))->flags |= MONO_INST_VOLATILE;
128                                 }
129                         }
130                 }
131         }
132
133         *visited = g_slist_append (*visited, bb);
134
135         /* 
136          * Need to visit all bblocks reachable from this one since they can be
137          * reached during exception handling.
138          */
139         for (i = 0; i < bb->out_count; ++i) {
140                 visit_bb (cfg, bb->out_bb [i], visited);
141         }
142 }
143
144 void
145 mono_liveness_handle_exception_clauses (MonoCompile *cfg)
146 {
147         MonoBasicBlock *bb;
148         GSList *visited = NULL;
149         MonoMethodHeader *header = cfg->header;
150         MonoExceptionClause *clause, *clause2;
151         int i, j;
152         gboolean *outer_try;
153
154         /* 
155          * Determine which clauses are outer try clauses, i.e. they are not contained in any
156          * other non-try clause.
157          */
158         outer_try = (gboolean *)mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * header->num_clauses);
159         for (i = 0; i < header->num_clauses; ++i)
160                 outer_try [i] = TRUE;
161         /* Iterate over the clauses backward, so outer clauses come first */
162         /* This avoids doing an O(2) search, since we can determine when inner clauses end */
163         for (i = header->num_clauses - 1; i >= 0; --i) {
164                 clause = &header->clauses [i];
165
166                 if (clause->flags != 0) {
167                         outer_try [i] = TRUE;
168                         /* Iterate over inner clauses */
169                         for (j = i - 1; j >= 0; --j) {
170                                 clause2 = &header->clauses [j];
171
172                                 if (clause2->flags == 0 && MONO_OFFSET_IN_HANDLER (clause, clause2->try_offset)) {
173                                         outer_try [j] = FALSE;
174                                         break;
175                                 }
176                                 if (clause2->try_offset < clause->try_offset)
177                                         /* End of inner clauses */
178                                         break;
179                         }
180                 }
181         }
182
183         /*
184          * Variables in exception handler register cannot be allocated to registers
185          * so make them volatile. See bug #42136. This will not be neccessary when
186          * the back ends could guarantee that the variables will be in the
187          * correct registers when a handler is called.
188          * This includes try blocks too, since a variable in a try block might be
189          * accessed after an exception handler has been run.
190          */
191         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
192
193                 if (bb->region == -1)
194                         continue;
195
196                 if (MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY) && outer_try [MONO_REGION_CLAUSE_INDEX (bb->region)])
197                         continue;
198
199                 if (cfg->verbose_level > 2)
200                         printf ("pessimize variables in bb %d.\n", bb->block_num);
201
202                 visit_bb (cfg, bb, &visited);
203         }
204         g_slist_free (visited);
205 }
206
207 static inline void
208 update_live_range (MonoMethodVar *var, int abs_pos)
209 {
210         if (var->range.first_use.abs_pos > abs_pos)
211                 var->range.first_use.abs_pos = abs_pos;
212
213         if (var->range.last_use.abs_pos < abs_pos)
214                 var->range.last_use.abs_pos = abs_pos;
215 }
216
217 static void
218 analyze_liveness_bb (MonoCompile *cfg, MonoBasicBlock *bb)
219 {
220         MonoInst *ins;
221         int sreg, inst_num;
222         MonoMethodVar *vars = cfg->vars;
223         guint32 abs_pos = (bb->dfn << BB_ID_SHIFT);
224         
225         /* Start inst_num from > 0, so last_use.abs_pos is only 0 for dead variables */
226         for (inst_num = 2, ins = bb->code; ins; ins = ins->next, inst_num += 2) {
227                 const char *spec = INS_INFO (ins->opcode);
228                 int num_sregs, i;
229                 int sregs [MONO_MAX_SRC_REGS];
230
231 #ifdef DEBUG_LIVENESS
232                 if (cfg->verbose_level > 1) {
233                         printf ("\t");
234                         mono_print_ins (ins);
235                 }
236 #endif
237
238                 if (ins->opcode == OP_NOP)
239                         continue;
240
241                 if (ins->opcode == OP_LDADDR) {
242                         MonoInst *var = (MonoInst *)ins->inst_p0;
243                         int idx = var->inst_c0;
244                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
245
246 #ifdef DEBUG_LIVENESS
247                         if (cfg->verbose_level > 1)
248                                 printf ("\tGEN: R%d(%d)\n", var->dreg, idx);
249 #endif
250                         update_live_range (&vars [idx], abs_pos + inst_num); 
251                         if (!mono_bitset_test_fast (bb->kill_set, idx))
252                                 mono_bitset_set_fast (bb->gen_set, idx);
253                         vi->spill_costs += SPILL_COST_INCREMENT;
254                 }                               
255
256                 /* SREGs must come first, so MOVE r <- r is handled correctly */
257                 num_sregs = mono_inst_get_src_registers (ins, sregs);
258                 for (i = 0; i < num_sregs; ++i) {
259                         sreg = sregs [i];
260                         if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
261                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
262                                 int idx = var->inst_c0;
263                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
264
265 #ifdef DEBUG_LIVENESS
266                                 if (cfg->verbose_level > 1)
267                                         printf ("\tGEN: R%d(%d)\n", sreg, idx);
268 #endif
269                                 update_live_range (&vars [idx], abs_pos + inst_num); 
270                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
271                                         mono_bitset_set_fast (bb->gen_set, idx);
272                                 vi->spill_costs += SPILL_COST_INCREMENT;
273                         }
274                 }
275
276                 /* DREG */
277                 if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
278                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
279                         int idx = var->inst_c0;
280                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
281
282                         if (MONO_IS_STORE_MEMBASE (ins)) {
283                                 update_live_range (&vars [idx], abs_pos + inst_num); 
284                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
285                                         mono_bitset_set_fast (bb->gen_set, idx);
286                                 vi->spill_costs += SPILL_COST_INCREMENT;
287                         } else {
288 #ifdef DEBUG_LIVENESS
289                                 if (cfg->verbose_level > 1)
290                                         printf ("\tKILL: R%d(%d)\n", ins->dreg, idx);
291 #endif
292                                 update_live_range (&vars [idx], abs_pos + inst_num + 1); 
293                                 mono_bitset_set_fast (bb->kill_set, idx);
294                                 vi->spill_costs += SPILL_COST_INCREMENT;
295                         }
296                 }
297         }
298 }
299
300 /* generic liveness analysis code. CFG specific parts are 
301  * in update_gen_kill_set()
302  */
303 void
304 mono_analyze_liveness (MonoCompile *cfg)
305 {
306         MonoBitSet *old_live_out_set;
307         int i, j, max_vars = cfg->num_varinfo;
308         int out_iter;
309         gboolean *in_worklist;
310         MonoBasicBlock **worklist;
311         guint32 l_end;
312         int bitsize;
313
314 #ifdef DEBUG_LIVENESS
315         if (cfg->verbose_level > 1)
316                 printf ("\nLIVENESS:\n");
317 #endif
318
319         g_assert (!(cfg->comp_done & MONO_COMP_LIVENESS));
320
321         cfg->comp_done |= MONO_COMP_LIVENESS;
322         
323         if (max_vars == 0)
324                 return;
325
326         bitsize = mono_bitset_alloc_size (max_vars, 0);
327
328         for (i = 0; i < max_vars; i ++) {
329                 MONO_VARINFO (cfg, i)->range.first_use.abs_pos = ~ 0;
330                 MONO_VARINFO (cfg, i)->range.last_use .abs_pos =   0;
331                 MONO_VARINFO (cfg, i)->spill_costs = 0;
332         }
333
334         for (i = 0; i < cfg->num_bblocks; ++i) {
335                 MonoBasicBlock *bb = cfg->bblocks [i];
336
337                 bb->gen_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
338                 bb->kill_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
339
340 #ifdef DEBUG_LIVENESS
341                 if (cfg->verbose_level > 1) {
342                         printf ("BLOCK BB%d (", bb->block_num);
343                         for (j = 0; j < bb->out_count; j++) 
344                                 printf ("BB%d, ", bb->out_bb [j]->block_num);
345                 
346                         printf ("):\n");
347                 }
348 #endif
349
350                 analyze_liveness_bb (cfg, bb);
351
352 #ifdef DEBUG_LIVENESS
353                 if (cfg->verbose_level > 1) {
354                         printf ("GEN  BB%d: ", bb->block_num); mono_bitset_print (bb->gen_set);
355                         printf ("KILL BB%d: ", bb->block_num); mono_bitset_print (bb->kill_set);
356                 }
357 #endif
358         }
359
360         old_live_out_set = mono_bitset_new (max_vars, 0);
361         in_worklist = g_new0 (gboolean, cfg->num_bblocks + 1);
362
363         worklist = g_new (MonoBasicBlock *, cfg->num_bblocks + 1);
364         l_end = 0;
365
366         /*
367          * This is a backward dataflow analysis problem, so we process blocks in
368          * decreasing dfn order, this speeds up the iteration.
369          */
370         for (i = 0; i < cfg->num_bblocks; i ++) {
371                 MonoBasicBlock *bb = cfg->bblocks [i];
372
373                 worklist [l_end ++] = bb;
374                 in_worklist [bb->dfn] = TRUE;
375
376                 /* Initialized later */
377                 bb->live_in_set = NULL;
378                 bb->live_out_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
379         }
380
381         out_iter = 0;
382
383         if (cfg->verbose_level > 1)
384                 printf ("\nITERATION:\n");
385
386         while (l_end != 0) {
387                 MonoBasicBlock *bb = worklist [--l_end];
388                 MonoBasicBlock *out_bb;
389                 gboolean changed;
390
391                 in_worklist [bb->dfn] = FALSE;
392
393 #ifdef DEBUG_LIVENESS
394                 if (cfg->verbose_level > 1) {
395                         printf ("P: BB%d(%d): IN: ", bb->block_num, bb->dfn);
396                         for (j = 0; j < bb->in_count; ++j) 
397                                 printf ("BB%d ", bb->in_bb [j]->block_num);
398                         printf ("OUT:");
399                         for (j = 0; j < bb->out_count; ++j) 
400                                 printf ("BB%d ", bb->out_bb [j]->block_num);
401                         printf ("\n");
402                 }
403 #endif
404
405
406                 if (bb->out_count == 0)
407                         continue;
408
409                 out_iter ++;
410
411                 if (!bb->live_in_set) {
412                         /* First pass over this bblock */
413                         changed = TRUE;
414                 }
415                 else {
416                         changed = FALSE;
417                         mono_bitset_copyto_fast (bb->live_out_set, old_live_out_set);
418                 }
419  
420                 for (j = 0; j < bb->out_count; j++) {
421                         out_bb = bb->out_bb [j];
422
423                         if (!out_bb->live_in_set) {
424                                 out_bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
425
426                                 mono_bitset_copyto_fast (out_bb->live_out_set, out_bb->live_in_set);
427                                 mono_bitset_sub_fast (out_bb->live_in_set, out_bb->kill_set);
428                                 mono_bitset_union_fast (out_bb->live_in_set, out_bb->gen_set);
429                         }
430
431                         // FIXME: Do this somewhere else
432                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
433                         } else {
434                                 mono_bitset_union_fast (bb->live_out_set, out_bb->live_in_set);
435                         }
436                 }
437                                 
438                 if (changed || !mono_bitset_equal (old_live_out_set, bb->live_out_set)) {
439                         if (!bb->live_in_set)
440                                 bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
441                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
442                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
443                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
444
445                         for (j = 0; j < bb->in_count; j++) {
446                                 MonoBasicBlock *in_bb = bb->in_bb [j];
447                                 /* 
448                                  * Some basic blocks do not seem to be in the 
449                                  * cfg->bblocks array...
450                                  */
451                                 if (in_bb->gen_set && !in_worklist [in_bb->dfn]) {
452 #ifdef DEBUG_LIVENESS
453                                         if (cfg->verbose_level > 1)
454                                                 printf ("\tADD: %d\n", in_bb->block_num);
455 #endif
456                                         /*
457                                          * Put the block at the top of the stack, so it
458                                          * will be processed right away.
459                                          */
460                                         worklist [l_end ++] = in_bb;
461                                         in_worklist [in_bb->dfn] = TRUE;
462                                 }
463                         }
464                 }
465
466                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
467                         printf ("\tLIVE IN  BB%d: ", bb->block_num); 
468                         mono_bitset_print (bb->live_in_set); 
469                 }                       
470         }
471
472 #ifdef DEBUG_LIVENESS
473         if (cfg->verbose_level > 1)
474                 printf ("IT: %d %d.\n", cfg->num_bblocks, out_iter);
475 #endif
476
477         mono_bitset_free (old_live_out_set);
478
479         g_free (worklist);
480         g_free (in_worklist);
481
482         /* Compute live_in_set for bblocks skipped earlier */
483         for (i = 0; i < cfg->num_bblocks; ++i) {
484                 MonoBasicBlock *bb = cfg->bblocks [i];
485
486                 if (!bb->live_in_set) {
487                         bb->live_in_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
488
489                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
490                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
491                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
492                 }
493         }
494
495         for (i = 0; i < cfg->num_bblocks; ++i) {
496                 MonoBasicBlock *bb = cfg->bblocks [i];
497                 guint32 max;
498                 guint32 abs_pos = (bb->dfn << BB_ID_SHIFT);
499                 MonoMethodVar *vars = cfg->vars;
500
501                 if (!bb->live_out_set)
502                         continue;
503
504                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
505                 for (j = 0; j < max; ++j) {
506                         gsize bits_in;
507                         gsize bits_out;
508                         int k;
509
510                         bits_in = mono_bitset_get_fast (bb->live_in_set, j);
511                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
512
513                         k = (j * BITS_PER_CHUNK);
514                         while ((bits_in || bits_out)) {
515                                 if (bits_in & 1)
516                                         update_live_range (&vars [k], abs_pos + 0);
517                                 if (bits_out & 1)
518                                         update_live_range (&vars [k], abs_pos + ((1 << BB_ID_SHIFT) - 1));
519                                 bits_in >>= 1;
520                                 bits_out >>= 1;
521                                 k ++;
522                         }
523                 }
524         }
525
526         /*
527          * Arguments need to have their live ranges extended to the beginning of
528          * the method to account for the arg reg/memory -> global register copies
529          * in the prolog (bug #74992).
530          */
531
532         for (i = 0; i < max_vars; i ++) {
533                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
534                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG) {
535                         if (vi->range.last_use.abs_pos == 0 && !(cfg->varinfo [vi->idx]->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
536                                 /* 
537                                  * Can't eliminate the this variable in gshared code, since
538                                  * it is needed during exception handling to identify the
539                                  * method.
540                                  * It is better to check for this here instead of marking the variable
541                                  * VOLATILE, since that would prevent it from being allocated to
542                                  * registers.
543                                  */
544                                  if (!cfg->disable_deadce_vars && !(cfg->gshared && mono_method_signature (cfg->method)->hasthis && cfg->varinfo [vi->idx] == cfg->args [0]))
545                                          cfg->varinfo [vi->idx]->flags |= MONO_INST_IS_DEAD;
546                         }
547                         vi->range.first_use.abs_pos = 0;
548                 }
549         }
550
551 #ifdef DEBUG_LIVENESS
552         if (cfg->verbose_level > 1) {
553                 for (i = cfg->num_bblocks - 1; i >= 0; i--) {
554                         MonoBasicBlock *bb = cfg->bblocks [i];
555                 
556                         printf ("LIVE IN  BB%d: ", bb->block_num); 
557                         mono_bitset_print (bb->live_in_set); 
558                         printf ("LIVE OUT BB%d: ", bb->block_num); 
559                         mono_bitset_print (bb->live_out_set); 
560                 }
561
562                 for (i = 0; i < max_vars; i ++) {
563                         MonoMethodVar *vi = MONO_VARINFO (cfg, i);
564
565                         printf ("V%d: [0x%x - 0x%x]\n", i, vi->range.first_use.abs_pos, vi->range.last_use.abs_pos);
566                 }
567         }
568 #endif
569
570         if (!cfg->disable_initlocals_opt)
571                 optimize_initlocals (cfg);
572
573 #ifdef ENABLE_LIVENESS2
574         /* This improves code size by about 5% but slows down compilation too much */
575         if (cfg->compile_aot)
576                 mono_analyze_liveness2 (cfg);
577 #endif
578 }
579
580 /**
581  * optimize_initlocals:
582  *
583  * Try to optimize away some of the redundant initialization code inserted because of
584  * 'locals init' using the liveness information.
585  */
586 static void
587 optimize_initlocals (MonoCompile *cfg)
588 {
589         MonoBitSet *used;
590         MonoInst *ins;
591         MonoBasicBlock *initlocals_bb;
592
593         used = mono_bitset_new (cfg->next_vreg + 1, 0);
594
595         mono_bitset_clear_all (used);
596         initlocals_bb = cfg->bb_entry->next_bb;
597         for (ins = initlocals_bb->code; ins; ins = ins->next) {
598                 int num_sregs, i;
599                 int sregs [MONO_MAX_SRC_REGS];
600
601                 num_sregs = mono_inst_get_src_registers (ins, sregs);
602                 for (i = 0; i < num_sregs; ++i)
603                         mono_bitset_set_fast (used, sregs [i]);
604
605                 if (MONO_IS_STORE_MEMBASE (ins))
606                         mono_bitset_set_fast (used, ins->dreg);
607         }
608
609         for (ins = initlocals_bb->code; ins; ins = ins->next) {
610                 const char *spec = INS_INFO (ins->opcode);
611
612                 /* Look for statements whose dest is not used in this bblock and not live on exit. */
613                 if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
614                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
615
616                         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))) {
617                                 //printf ("DEAD: "); mono_print_ins (ins);
618                                 if (cfg->disable_initlocals_opt_refs && var->type == STACK_OBJ)
619                                         continue;
620                                 if ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST) || (ins->opcode == OP_R4CONST)) {
621                                         NULLIFY_INS (ins);
622                                         MONO_VARINFO (cfg, var->inst_c0)->spill_costs -= 1;
623                                         /* 
624                                          * We should shorten the liveness interval of these vars as well, but
625                                          * don't have enough info to do that.
626                                          */
627                                 }
628                         }
629                 }
630         }
631
632         g_free (used);
633 }
634
635 void
636 mono_linterval_add_range (MonoCompile *cfg, MonoLiveInterval *interval, int from, int to)
637 {
638         MonoLiveRange2 *prev_range, *next_range, *new_range;
639
640         g_assert (to >= from);
641
642         /* Optimize for extending the first interval backwards */
643         if (G_LIKELY (interval->range && (interval->range->from > from) && (interval->range->from == to))) {
644                 interval->range->from = from;
645                 return;
646         }
647
648         /* Find a place in the list for the new range */
649         prev_range = NULL;
650         next_range = interval->range;
651         while ((next_range != NULL) && (next_range->from <= from)) {
652                 prev_range = next_range;
653                 next_range = next_range->next;
654         }
655
656         if (prev_range && prev_range->to == from) {
657                 /* Merge with previous */
658                 prev_range->to = to;
659         } else if (next_range && next_range->from == to) {
660                 /* Merge with previous */
661                 next_range->from = from;
662         } else {
663                 /* Insert it */
664                 new_range = (MonoLiveRange2 *)mono_mempool_alloc (cfg->mempool, sizeof (MonoLiveRange2));
665                 new_range->from = from;
666                 new_range->to = to;
667                 new_range->next = NULL;
668
669                 if (prev_range)
670                         prev_range->next = new_range;
671                 else
672                         interval->range = new_range;
673                 if (next_range)
674                         new_range->next = next_range;
675                 else
676                         interval->last_range = new_range;
677         }
678
679         /* FIXME: Merge intersecting ranges */
680 }
681
682 void
683 mono_linterval_print (MonoLiveInterval *interval)
684 {
685         MonoLiveRange2 *range;
686
687         for (range = interval->range; range != NULL; range = range->next)
688                 printf ("[%x-%x] ", range->from, range->to);
689 }
690
691 void
692 mono_linterval_print_nl (MonoLiveInterval *interval)
693 {
694         mono_linterval_print (interval);
695         printf ("\n");
696 }
697
698 /**
699  * mono_linterval_convers:
700  *
701  *   Return whenever INTERVAL covers the position POS.
702  */
703 gboolean
704 mono_linterval_covers (MonoLiveInterval *interval, int pos)
705 {
706         MonoLiveRange2 *range;
707
708         for (range = interval->range; range != NULL; range = range->next) {
709                 if (pos >= range->from && pos <= range->to)
710                         return TRUE;
711                 if (range->from > pos)
712                         return FALSE;
713         }
714
715         return FALSE;
716 }
717
718 /**
719  * mono_linterval_get_intersect_pos:
720  *
721  *   Determine whenever I1 and I2 intersect, and if they do, return the first
722  * point of intersection. Otherwise, return -1.
723  */
724 gint32
725 mono_linterval_get_intersect_pos (MonoLiveInterval *i1, MonoLiveInterval *i2)
726 {
727         MonoLiveRange2 *r1, *r2;
728
729         /* FIXME: Optimize this */
730         for (r1 = i1->range; r1 != NULL; r1 = r1->next) {
731                 for (r2 = i2->range; r2 != NULL; r2 = r2->next) {
732                         if (r2->to > r1->from && r2->from < r1->to) {
733                                 if (r2->from <= r1->from)
734                                         return r1->from;
735                                 else
736                                         return r2->from;
737                         }
738                 }
739         }
740
741         return -1;
742 }
743  
744 /**
745  * mono_linterval_split
746  *
747  *   Split L at POS and store the newly created intervals into L1 and L2. POS becomes
748  * part of L2.
749  */
750 void
751 mono_linterval_split (MonoCompile *cfg, MonoLiveInterval *interval, MonoLiveInterval **i1, MonoLiveInterval **i2, int pos)
752 {
753         MonoLiveRange2 *r;
754
755         g_assert (pos > interval->range->from && pos <= interval->last_range->to);
756
757         *i1 = (MonoLiveInterval *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
758         *i2 = (MonoLiveInterval *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
759
760         for (r = interval->range; r; r = r->next) {
761                 if (pos > r->to) {
762                         /* Add it to the first child */
763                         mono_linterval_add_range (cfg, *i1, r->from, r->to);
764                 } else if (pos > r->from && pos <= r->to) {
765                         /* Split at pos */
766                         mono_linterval_add_range (cfg, *i1, r->from, pos - 1);
767                         mono_linterval_add_range (cfg, *i2, pos, r->to);
768                 } else {
769                         /* Add it to the second child */
770                         mono_linterval_add_range (cfg, *i2, r->from, r->to);
771                 }
772         }
773 }
774
775 #if 1
776 #define LIVENESS_DEBUG(a) do { if (cfg->verbose_level > 1) do { a; } while (0); } while (0)
777 #define ENABLE_LIVENESS_DEBUG 1
778 #else
779 #define LIVENESS_DEBUG(a)
780 #endif
781
782 #ifdef ENABLE_LIVENESS2
783
784 static inline void
785 update_liveness2 (MonoCompile *cfg, MonoInst *ins, gboolean set_volatile, int inst_num, gint32 *last_use)
786 {
787         const char *spec = INS_INFO (ins->opcode);
788         int sreg;
789         int num_sregs, i;
790         int sregs [MONO_MAX_SRC_REGS];
791
792         LIVENESS_DEBUG (printf ("\t%x: ", inst_num); mono_print_ins (ins));
793
794         if (ins->opcode == OP_NOP || ins->opcode == OP_IL_SEQ_POINT)
795                 return;
796
797         /* DREG */
798         if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
799                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
800                 int idx = var->inst_c0;
801                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
802
803                 if (MONO_IS_STORE_MEMBASE (ins)) {
804                         if (last_use [idx] == 0) {
805                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", ins->dreg, inst_num));
806                                 last_use [idx] = inst_num;
807                         }
808                 } else {
809                         if (last_use [idx] > 0) {
810                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", ins->dreg, inst_num, last_use [idx]));
811                                 mono_linterval_add_range (cfg, vi->interval, inst_num, last_use [idx]);
812                                 last_use [idx] = 0;
813                         }
814                         else {
815                                 /* Try dead code elimination */
816                                 if (!cfg->disable_deadce_vars && (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)) {
817                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, eliminated\n", ins->dreg));
818                                         NULLIFY_INS (ins);
819                                         return;
820                                 } else {
821                                         int inst_num_add = 1;
822                                         MonoInst *next = ins->next;
823                                         while (next && next->opcode == OP_IL_SEQ_POINT) {
824                                                 inst_num_add++;
825                                                 next = next->next;
826                                         }
827
828                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, add range to R%d: [%x, %x]\n", ins->dreg, ins->dreg, inst_num, inst_num + inst_num_add));
829                                         mono_linterval_add_range (cfg, vi->interval, inst_num, inst_num + inst_num_add);
830                                 }
831                         }
832                 }
833         }
834
835         /* SREGs */
836         num_sregs = mono_inst_get_src_registers (ins, sregs);
837         for (i = 0; i < num_sregs; ++i) {
838                 sreg = sregs [i];
839                 if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
840                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
841                         int idx = var->inst_c0;
842
843                         if (last_use [idx] == 0) {
844                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
845                                 last_use [idx] = inst_num;
846                         }
847                 }
848         }
849 }
850
851 static void
852 mono_analyze_liveness2 (MonoCompile *cfg)
853 {
854         int bnum, idx, i, j, nins, max, max_vars, block_from, block_to, pos, reverse_len;
855         gint32 *last_use;
856         static guint32 disabled = -1;
857         MonoInst **reverse;
858
859         if (disabled == -1)
860                 disabled = g_getenv ("DISABLED") != NULL;
861
862         if (disabled)
863                 return;
864
865         if (cfg->num_bblocks >= (1 << (32 - BB_ID_SHIFT - 1)))
866                 /* Ranges would overflow */
867                 return;
868
869         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
870                 MonoBasicBlock *bb = cfg->bblocks [bnum];
871                 MonoInst *ins;
872
873                 nins = 0;
874                 for (nins = 0, ins = bb->code; ins; ins = ins->next, ++nins)
875                         nins ++;
876
877                 if (nins >= ((1 << BB_ID_SHIFT) - 1))
878                         /* Ranges would overflow */
879                         return;
880         }
881
882         LIVENESS_DEBUG (printf ("LIVENESS 2 %s\n", mono_method_full_name (cfg->method, TRUE)));
883
884         /*
885         if (strstr (cfg->method->name, "test_") != cfg->method->name)
886                 return;
887         */
888
889         max_vars = cfg->num_varinfo;
890         last_use = g_new0 (gint32, max_vars);
891
892         reverse_len = 1024;
893         reverse = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
894
895         for (idx = 0; idx < max_vars; ++idx) {
896                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
897
898                 vi->interval = (MonoLiveInterval *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
899         }
900
901         /*
902          * Process bblocks in reverse order, so the addition of new live ranges
903          * to the intervals is faster.
904          */
905         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
906                 MonoBasicBlock *bb = cfg->bblocks [bnum];
907                 MonoInst *ins;
908
909                 block_from = (bb->dfn << BB_ID_SHIFT) + 1; /* so pos > 0 */
910                 if (bnum < cfg->num_bblocks - 1)
911                         /* Beginning of the next bblock */
912                         block_to = (cfg->bblocks [bnum + 1]->dfn << BB_ID_SHIFT) + 1;
913                 else
914                         block_to = (bb->dfn << BB_ID_SHIFT) + ((1 << BB_ID_SHIFT) - 1);
915
916                 LIVENESS_DEBUG (printf ("LIVENESS BLOCK BB%d:\n", bb->block_num));
917
918                 memset (last_use, 0, max_vars * sizeof (gint32));
919                 
920                 /* For variables in bb->live_out, set last_use to block_to */
921
922                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
923                 for (j = 0; j < max; ++j) {
924                         gsize bits_out;
925                         int k;
926
927                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
928                         k = (j * BITS_PER_CHUNK);       
929                         while (bits_out) {
930                                 if (bits_out & 1) {
931                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, set last_use to %x\n", cfg->varinfo [k]->dreg, block_to));
932                                         last_use [k] = block_to;
933                                 }
934                                 bits_out >>= 1;
935                                 k ++;
936                         }
937                 }
938
939                 if (cfg->ret)
940                         last_use [cfg->ret->inst_c0] = block_to;
941
942                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
943                         if (nins >= reverse_len) {
944                                 int new_reverse_len = reverse_len * 2;
945                                 MonoInst **new_reverse = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
946                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
947                                 reverse = new_reverse;
948                                 reverse_len = new_reverse_len;
949                         }
950
951                         reverse [nins] = ins;
952                 }
953
954                 /* Process instructions backwards */
955                 for (i = nins - 1; i >= 0; --i) {
956                         MonoInst *ins = (MonoInst*)reverse [i];
957
958                         update_liveness2 (cfg, ins, FALSE, pos, last_use);
959
960                         pos --;
961                 }
962
963                 for (idx = 0; idx < max_vars; ++idx) {
964                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
965
966                         if (last_use [idx] != 0) {
967                                 /* Live at exit, not written -> live on enter */
968                                 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]));
969                                 mono_linterval_add_range (cfg, vi->interval, block_from, last_use [idx]);
970                         }
971                 }
972         }
973
974         /*
975          * Arguments need to have their live ranges extended to the beginning of
976          * the method to account for the arg reg/memory -> global register copies
977          * in the prolog (bug #74992).
978          */
979         for (i = 0; i < max_vars; i ++) {
980                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
981                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG)
982                         mono_linterval_add_range (cfg, vi->interval, 0, 1);
983         }
984
985 #if 0
986         for (idx = 0; idx < max_vars; ++idx) {
987                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
988                 
989                 LIVENESS_DEBUG (printf ("LIVENESS R%d: ", cfg->varinfo [idx]->dreg));
990                 LIVENESS_DEBUG (mono_linterval_print (vi->interval));
991                 LIVENESS_DEBUG (printf ("\n"));
992         }
993 #endif
994
995         g_free (last_use);
996 }
997
998 #endif
999
1000 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
1001
1002 static inline void
1003 update_liveness_gc (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, gint32 *last_use, MonoMethodVar **vreg_to_varinfo, GSList **callsites)
1004 {
1005         if (ins->opcode == OP_GC_LIVENESS_DEF || ins->opcode == OP_GC_LIVENESS_USE) {
1006                 int vreg = ins->inst_c1;
1007                 MonoMethodVar *vi = vreg_to_varinfo [vreg];
1008                 int idx = vi->idx;
1009                 int pc_offset = ins->backend.pc_offset;
1010
1011                 LIVENESS_DEBUG (printf ("\t%x: ", pc_offset); mono_print_ins (ins));
1012
1013                 if (ins->opcode == OP_GC_LIVENESS_DEF) {
1014                         if (last_use [idx] > 0) {
1015                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", vreg, pc_offset, last_use [idx]));
1016                                 last_use [idx] = 0;
1017                         }
1018                 } else {
1019                         if (last_use [idx] == 0) {
1020                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", vreg, pc_offset));
1021                                 last_use [idx] = pc_offset;
1022                         }
1023                 }
1024         } else if (ins->opcode == OP_GC_PARAM_SLOT_LIVENESS_DEF) {
1025                 GCCallSite *last;
1026
1027                 /* Add it to the last callsite */
1028                 g_assert (*callsites);
1029                 last = (GCCallSite *)(*callsites)->data;
1030                 last->param_slots = g_slist_prepend_mempool (cfg->mempool, last->param_slots, ins);
1031         } else if (ins->flags & MONO_INST_GC_CALLSITE) {
1032                 GCCallSite *callsite = (GCCallSite *)mono_mempool_alloc0 (cfg->mempool, sizeof (GCCallSite));
1033                 int i;
1034
1035                 LIVENESS_DEBUG (printf ("\t%x: ", ins->backend.pc_offset); mono_print_ins (ins));
1036                 LIVENESS_DEBUG (printf ("\t\tlive: "));
1037
1038                 callsite->bb = bb;
1039                 callsite->liveness = (guint8 *)mono_mempool_alloc0 (cfg->mempool, ALIGN_TO (cfg->num_varinfo, 8) / 8);
1040                 callsite->pc_offset = ins->backend.pc_offset;
1041                 for (i = 0; i < cfg->num_varinfo; ++i) {
1042                         if (last_use [i] != 0) {
1043                                 LIVENESS_DEBUG (printf ("R%d", MONO_VARINFO (cfg, i)->vreg));
1044                                 callsite->liveness [i / 8] |= (1 << (i % 8));
1045                         }
1046                 }
1047                 LIVENESS_DEBUG (printf ("\n"));
1048                 *callsites = g_slist_prepend_mempool (cfg->mempool, *callsites, callsite);
1049         }
1050 }
1051
1052 static inline int
1053 get_vreg_from_var (MonoCompile *cfg, MonoInst *var)
1054 {
1055         if (var->opcode == OP_REGVAR)
1056                 /* dreg contains a hreg, but inst_c0 still contains the var index */
1057                 return MONO_VARINFO (cfg, var->inst_c0)->vreg;
1058         else
1059                 /* dreg still contains the vreg */
1060                 return var->dreg;
1061 }
1062
1063 /*
1064  * mono_analyze_liveness_gc:
1065  *
1066  *   Compute liveness bitmaps for each call site.
1067  * This function is a modified version of mono_analyze_liveness2 ().
1068  */
1069 void
1070 mono_analyze_liveness_gc (MonoCompile *cfg)
1071 {
1072         int idx, i, j, nins, max, max_vars, block_from, block_to, pos, reverse_len;
1073         gint32 *last_use;
1074         MonoInst **reverse;
1075         MonoMethodVar **vreg_to_varinfo = NULL;
1076         MonoBasicBlock *bb;
1077         GSList *callsites;
1078
1079         LIVENESS_DEBUG (printf ("\n------------ GC LIVENESS: ----------\n"));
1080
1081         max_vars = cfg->num_varinfo;
1082         last_use = g_new0 (gint32, max_vars);
1083
1084         /*
1085          * var->inst_c0 no longer contains the variable index, so compute a mapping now.
1086          */
1087         vreg_to_varinfo = g_new0 (MonoMethodVar*, cfg->next_vreg);
1088         for (idx = 0; idx < max_vars; ++idx) {
1089                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
1090
1091                 vreg_to_varinfo [vi->vreg] = vi;
1092         }
1093
1094         reverse_len = 1024;
1095         reverse = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
1096
1097         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1098                 MonoInst *ins;
1099
1100                 block_from = bb->real_native_offset;
1101                 block_to = bb->native_offset + bb->native_length;
1102
1103                 LIVENESS_DEBUG (printf ("GC LIVENESS BB%d:\n", bb->block_num));
1104
1105                 if (!bb->code)
1106                         continue;
1107
1108                 memset (last_use, 0, max_vars * sizeof (gint32));
1109                 
1110                 /* For variables in bb->live_out, set last_use to block_to */
1111
1112                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
1113                 for (j = 0; j < max; ++j) {
1114                         gsize bits_out;
1115                         int k;
1116
1117                         if (!bb->live_out_set)
1118                                 /* The variables used in this bblock are volatile anyway */
1119                                 continue;
1120
1121                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
1122                         k = (j * BITS_PER_CHUNK);       
1123                         while (bits_out) {
1124                                 if ((bits_out & 1) && cfg->varinfo [k]->flags & MONO_INST_GC_TRACK) {
1125                                         int vreg = get_vreg_from_var (cfg, cfg->varinfo [k]);
1126                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, last_use set to %x.\n", vreg, block_to));
1127                                         last_use [k] = block_to;
1128                                 }
1129                                 bits_out >>= 1;
1130                                 k ++;
1131                         }
1132                 }
1133
1134                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
1135                         if (nins >= reverse_len) {
1136                                 int new_reverse_len = reverse_len * 2;
1137                                 MonoInst **new_reverse = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
1138                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
1139                                 reverse = new_reverse;
1140                                 reverse_len = new_reverse_len;
1141                         }
1142
1143                         reverse [nins] = ins;
1144                 }
1145
1146                 /* Process instructions backwards */
1147                 callsites = NULL;
1148                 for (i = nins - 1; i >= 0; --i) {
1149                         MonoInst *ins = (MonoInst*)reverse [i];
1150
1151                         update_liveness_gc (cfg, bb, ins, last_use, vreg_to_varinfo, &callsites);
1152                 }
1153                 /* The callsites should already be sorted by pc offset because we added them backwards */
1154                 bb->gc_callsites = callsites;
1155         }
1156
1157         g_free (last_use);
1158         g_free (vreg_to_varinfo);
1159 }
1160
1161 #endif /* DISABLE_JIT */