1d0b68f66843c20a16dbff6921d88199ed83a45d
[mono.git] / mono / mini / ssa.c
1 /*
2  * ssa.c: Static single assign form support for the JIT compiler.
3  *
4  * Author:
5  *    Dietmar Maurer (dietmar@ximian.com)
6  *
7  * (C) 2003 Ximian, Inc.
8  */
9 #include <string.h>
10 #include <mono/metadata/debug-helpers.h>
11
12 #include "mini.h"
13
14 extern guint8 mono_burg_arity [];
15
16 #define USE_ORIGINAL_VARS
17 #define CREATE_PRUNED_SSA
18
19 //#define DEBUG_SSA 1
20
21 #define NEW_PHI(cfg,dest,val) do {      \
22                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
23                 (dest)->opcode = OP_PHI;        \
24                 (dest)->inst_c0 = (val);        \
25         } while (0)
26
27 #define NEW_ICONST(cfg,dest,val) do {   \
28                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
29                 (dest)->opcode = OP_ICONST;     \
30                 (dest)->inst_c0 = (val);        \
31                 (dest)->type = STACK_I4;        \
32         } while (0)
33
34
35 static void 
36 unlink_target (MonoBasicBlock *bb, MonoBasicBlock *target)
37 {
38         int i;
39
40         for (i = 0; i < bb->out_count; i++) {
41                 if (bb->out_bb [i] == target) {
42                         bb->out_bb [i] = bb->out_bb [--bb->out_count];
43                         break;
44                 }
45         }
46         for (i = 0; i < target->in_count; i++) {
47                 if (target->in_bb [i] == bb) {
48                         target->in_bb [i] = target->in_bb [--target->in_count];
49                         break;
50                         
51                 }
52         }
53 }
54
55 static void
56 unlink_unused_bblocks (MonoCompile *cfg) 
57 {
58         int i, j;
59         MonoBasicBlock *bb;
60
61         g_assert (cfg->comp_done & MONO_COMP_REACHABILITY);
62
63         for (bb = cfg->bb_entry; bb && bb->next_bb;) {
64                 if (!(bb->next_bb->flags & BB_REACHABLE)) {
65                         bb->next_bb = bb->next_bb->next_bb;
66                 } else 
67                         bb = bb->next_bb;
68         }
69
70         for (i = 1; i < cfg->num_bblocks; i++) {
71                 bb = cfg->bblocks [i];
72                
73                 if (!(bb->flags & BB_REACHABLE)) {
74                         for (j = 0; j < bb->in_count; j++) {
75                                 unlink_target (bb->in_bb [j], bb);      
76                         }
77                         for (j = 0; j < bb->out_count; j++) {
78                                 unlink_target (bb, bb->out_bb [j]);     
79                         }
80                 }
81  
82         }
83 }
84
85
86
87 static void
88 replace_usage (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *inst, MonoInst **stack)
89 {
90         int arity;
91
92         if (!inst)
93                 return;
94
95         arity = mono_burg_arity [inst->opcode];
96
97         if ((inst->ssa_op == MONO_SSA_LOAD || inst->ssa_op == MONO_SSA_MAYBE_LOAD) && 
98             (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG)) {
99                 MonoInst *new_var;
100                 int idx = inst->inst_i0->inst_c0;
101                         
102                 if (stack [idx]) {
103                         new_var = stack [idx];
104                 } else {
105                         new_var = cfg->varinfo [idx];
106
107                         if (new_var->opcode != OP_ARG) {
108                                 /* uninitialized variable ? */
109                                 g_warning ("using uninitialized variables %d in BB%d (%s)", idx, bb->block_num,
110                                            mono_method_full_name (cfg->method, TRUE));
111                                 //g_assert_not_reached ();
112                         }
113                 }
114 #ifdef DEBUG_SSA
115                 printf ("REPLACE BB%d %d %d\n", bb->block_num, idx, new_var->inst_c0);
116 #endif
117                 inst->inst_i0 = new_var;
118         } else {
119
120                 if (arity) {
121                         if (inst->ssa_op != MONO_SSA_STORE)
122                                 replace_usage (cfg, bb, inst->inst_left, stack);
123                         if (arity > 1)
124                                 replace_usage (cfg, bb, inst->inst_right, stack);
125                 }
126         }
127 }
128
129 static int
130 extends_live (MonoInst *inst)
131 {
132         int arity;
133
134         if (!inst)
135                 return 0;
136
137         arity = mono_burg_arity [inst->opcode];
138
139         if (inst->ssa_op == MONO_SSA_LOAD && 
140             (inst->inst_i0->opcode == OP_LOCAL /*|| inst->inst_i0->opcode == OP_ARG*/)) {
141                 return 1;
142         } else {
143                 if (arity) {
144                         if (inst->ssa_op != MONO_SSA_STORE)
145                                 if (extends_live (inst->inst_left))
146                                         return 1;
147                         if (arity > 1)
148                                 if (extends_live (inst->inst_right))
149                                         return 1;
150                 }
151         }
152
153         return 0;
154 }
155
156 static int
157 replace_usage_new (MonoCompile *cfg, MonoInst *inst, int varnum, MonoInst *rep)
158 {
159         int arity;
160
161         if (!inst)
162                 return 0;
163
164         arity = mono_burg_arity [inst->opcode];
165
166         if ((inst->ssa_op == MONO_SSA_LOAD) && 
167             (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG) &&
168             inst->inst_i0->inst_c0 == varnum && rep->type == inst->type) {
169                 *inst = *rep;
170                 return 1;
171         } else {
172                 if (arity) {
173                         if (inst->ssa_op != MONO_SSA_STORE)
174                                 if (replace_usage_new (cfg, inst->inst_left, varnum, rep))
175                                         return 1;
176                         if (arity > 1)
177                                 if (replace_usage_new (cfg, inst->inst_right, varnum, rep))
178                                         return 1;
179                 }
180         }
181
182         return 0;
183 }
184
185 static void
186 mono_ssa_rename_vars (MonoCompile *cfg, int max_vars, MonoBasicBlock *bb, MonoInst **stack) 
187 {
188         MonoInst *inst, *new_var;
189         int i, j, idx;
190         GList *tmp;
191         MonoInst *new_stack [max_vars];
192
193 #ifdef DEBUG_SSA
194         printf ("RENAME VARS BB%d %s\n", bb->block_num, mono_method_full_name (cfg->method, TRUE));
195 #endif
196
197         for (inst = bb->code; inst; inst = inst->next) {
198                 if (inst->opcode != OP_PHI)
199                         replace_usage (cfg, bb, inst, stack);
200
201                 if (inst->ssa_op == MONO_SSA_STORE && 
202                     (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG)) {
203                         idx = inst->inst_i0->inst_c0;
204                         g_assert (idx < max_vars);
205
206                         if (!stack [idx] && bb == cfg->bb_init) {
207                                 new_var = cfg->varinfo [idx];
208                         } else {
209                                 new_var = mono_compile_create_var (cfg, inst->inst_i0->inst_vtype,  inst->inst_i0->opcode);
210                                 new_var->flags = inst->inst_i0->flags;
211                         }
212 #ifdef DEBUG_SSA
213                         printf ("DEF %d %d\n", idx, new_var->inst_c0);
214 #endif
215                         inst->inst_i0 = new_var;
216
217 #ifdef USE_ORIGINAL_VARS
218                         cfg->vars [new_var->inst_c0]->reg = idx;
219 #endif
220
221                         stack [idx] = new_var;
222                 }
223         }
224
225         for (i = 0; i < bb->out_count; i++) {
226                 MonoBasicBlock *n = bb->out_bb [i];
227
228                 for (j = 0; j < n->in_count; j++)
229                         if (n->in_bb [j] == bb)
230                                 break;
231                 
232                 for (inst = n->code; inst; inst = inst->next) {
233                         if (inst->ssa_op == MONO_SSA_STORE && inst->inst_i1->opcode == OP_PHI) {
234                                 idx = inst->inst_i1->inst_c0;
235                                 if (stack [idx])
236                                         new_var = stack [idx];
237                                 else
238                                         new_var = cfg->varinfo [idx];
239 #ifdef DEBUG_SSA
240                                 printf ("FOUND PHI %d (%d, %d)\n", idx, j, new_var->inst_c0);
241 #endif
242                                 inst->inst_i1->inst_phi_args [j + 1] = new_var->inst_c0;
243                                 
244                         }
245                 }
246         }
247
248         for (tmp = bb->dominated; tmp; tmp = tmp->next) {
249                 memcpy (new_stack, stack, sizeof (MonoInst *) * max_vars); 
250                 mono_ssa_rename_vars (cfg, max_vars, (MonoBasicBlock *)tmp->data, new_stack);
251         }
252 }
253
254 void
255 mono_ssa_compute (MonoCompile *cfg)
256 {
257         int i, idx;
258         MonoBitSet *set;
259         MonoMethodVar *vinfo = g_new0 (MonoMethodVar, cfg->num_varinfo);
260         MonoInst *inst, *store, **stack;
261
262         g_assert (!(cfg->comp_done & MONO_COMP_SSA));
263
264         /* we dont support methods containing exception clauses */
265         g_assert (((MonoMethodNormal *)cfg->method)->header->num_clauses == 0);
266         g_assert (!cfg->disable_ssa);
267
268         //printf ("COMPUTS SSA %s %d\n", mono_method_full_name (cfg->method, TRUE), cfg->num_varinfo);
269
270 #ifdef CREATE_PRUNED_SSA
271         /* we need liveness for pruned SSA */
272         if (!(cfg->comp_done & MONO_COMP_LIVENESS))
273                 mono_analyze_liveness (cfg);
274 #endif
275
276         mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM | MONO_COMP_DFRONTIER);
277
278         for (i = 0; i < cfg->num_varinfo; ++i) {
279                 vinfo [i].def_in = mono_bitset_new (cfg->num_bblocks, 0);
280                 vinfo [i].idx = i;
281                 /* implizit reference at start */
282                 mono_bitset_set (vinfo [i].def_in, 0);
283         }
284         for (i = 0; i < cfg->num_bblocks; ++i) {
285                 for (inst = cfg->bblocks [i]->code; inst; inst = inst->next) {
286                         if (inst->ssa_op == MONO_SSA_STORE) {
287                                 idx = inst->inst_i0->inst_c0;
288                                 g_assert (idx < cfg->num_varinfo);
289                                 mono_bitset_set (vinfo [idx].def_in, i);
290                         } 
291                 }
292         }
293
294         /* insert phi functions */
295         for (i = 0; i < cfg->num_varinfo; ++i) {
296                 set = mono_compile_iterated_dfrontier (cfg, vinfo [i].def_in);
297                 vinfo [i].dfrontier = set;
298                 mono_bitset_foreach_bit (set, idx, cfg->num_bblocks) {
299                         MonoBasicBlock *bb = cfg->bblocks [idx];
300
301                         /* fixme: create pruned SSA? we would need liveness information for that */
302
303                         if (bb == cfg->bb_exit)
304                                 continue;
305
306                         if ((cfg->comp_done & MONO_COMP_LIVENESS) && !mono_bitset_test_fast (bb->live_in_set, i)) {
307                                 //printf ("%d is not live in BB%d %s\n", i, bb->block_num, mono_method_full_name (cfg->method, TRUE));
308                                 continue;
309                         }
310
311                         NEW_PHI (cfg, inst, i);
312
313                         inst->inst_phi_args =  mono_mempool_alloc0 (cfg->mempool, sizeof (int) * (cfg->bblocks [idx]->in_count + 1));
314                         inst->inst_phi_args [0] = cfg->bblocks [idx]->in_count;
315
316                         store = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));
317                         if (!cfg->varinfo [i]->inst_vtype->type)
318                                 g_assert_not_reached ();
319                         store->opcode = mono_type_to_stind (cfg->varinfo [i]->inst_vtype);
320                         store->ssa_op = MONO_SSA_STORE;
321                         store->inst_i0 = cfg->varinfo [i];
322                         store->inst_i1 = inst;
323                         store->klass = store->inst_i0->klass;
324              
325                         store->next = bb->code;
326                         bb->code = store;
327
328 #ifdef DEBUG_SSA
329                         printf ("ADD PHI BB%d %s\n", cfg->bblocks [idx]->block_num, mono_method_full_name (cfg->method, TRUE));
330 #endif
331                 }
332         }
333
334         /* free the stuff */
335         for (i = 0; i < cfg->num_varinfo; ++i)
336                 mono_bitset_free (vinfo [i].def_in);
337         g_free (vinfo);
338
339
340         stack = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
341                 
342         for (i = 0; i < cfg->num_varinfo; i++)
343                 stack [i] = NULL;
344
345         mono_ssa_rename_vars (cfg, cfg->num_varinfo, cfg->bb_entry, stack);
346
347         cfg->comp_done |= MONO_COMP_SSA;
348 }
349
350 #ifndef USE_ORIGINAL_VARS
351 static GPtrArray *
352 mono_ssa_get_allocatable_vars (MonoCompile *cfg)
353 {
354         GHashTable *type_hash;
355         GPtrArray *varlist_array = g_ptr_array_new ();
356         int tidx, i;
357
358         g_assert (cfg->comp_done & MONO_COMP_LIVENESS);
359
360         type_hash = g_hash_table_new (NULL, NULL);
361
362         for (i = 0; i < cfg->num_varinfo; i++) {
363                 MonoInst *ins = cfg->varinfo [i];
364                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
365
366                 /* unused vars */
367                 if (vmv->range.first_use.abs_pos > vmv->range.last_use.abs_pos)
368                         continue;
369
370                 if (ins->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT) || 
371                     (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG) || vmv->reg != -1)
372                         continue;
373
374                 g_assert (ins->inst_vtype);
375                 g_assert (vmv->reg == -1);
376                 g_assert (i == vmv->idx);
377
378                 if (!(tidx = (int)g_hash_table_lookup (type_hash, ins->inst_vtype))) {
379                         GList *vars = g_list_append (NULL, vmv);
380                         g_ptr_array_add (varlist_array, vars);
381                         g_hash_table_insert (type_hash, ins->inst_vtype, (gpointer)varlist_array->len);
382                 } else {
383                         tidx--;
384                         g_ptr_array_index (varlist_array, tidx) =
385                                 mono_varlist_insert_sorted (cfg, g_ptr_array_index (varlist_array, tidx), vmv, FALSE);
386                 }
387         }
388
389         g_hash_table_destroy (type_hash);
390
391         return varlist_array;
392 }
393 #endif
394
395 static void
396 mono_ssa_replace_copies (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *inst, char *is_live)
397 {
398         int arity;
399
400         if (!inst)
401                 return;
402
403         arity = mono_burg_arity [inst->opcode];
404
405         if ((inst->ssa_op == MONO_SSA_LOAD || inst->ssa_op == MONO_SSA_MAYBE_LOAD || inst->ssa_op == MONO_SSA_STORE) && 
406             (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG)) {
407                 MonoInst *new_var;
408                 int idx = inst->inst_i0->inst_c0;
409                 MonoMethodVar *mv = cfg->vars [idx];
410
411                 if (mv->reg != -1 && mv->reg != mv->idx) {
412                        
413                         is_live [mv->reg] = 1;
414
415                         new_var = cfg->varinfo [mv->reg];
416
417 #if 0
418                         printf ("REPLACE COPY BB%d %d %d\n", bb->block_num, idx, new_var->inst_c0);
419                         g_assert (cfg->varinfo [mv->reg]->inst_vtype == cfg->varinfo [idx]->inst_vtype);
420 #endif
421                         inst->inst_i0 = new_var;
422                 } else {
423                         is_live [mv->idx] = 1;
424                 }
425         }
426
427
428         if (arity) {
429                 mono_ssa_replace_copies (cfg, bb, inst->inst_left, is_live);
430                 if (arity > 1)
431                         mono_ssa_replace_copies (cfg, bb, inst->inst_right, is_live);
432         }
433
434         if (inst->ssa_op == MONO_SSA_STORE && inst->inst_i1->ssa_op == MONO_SSA_LOAD &&
435             inst->inst_i0->inst_c0 == inst->inst_i1->inst_i0->inst_c0) {
436                 inst->ssa_op = MONO_SSA_NOP;
437                 inst->opcode = CEE_NOP;
438         }
439
440 }
441
442 void
443 mono_ssa_remove (MonoCompile *cfg)
444 {
445         MonoInst *inst, *phi;
446         char *is_live;
447         int i, j;
448 #ifndef USE_ORIGINAL_VARS
449         GPtrArray *varlist_array;
450         GList *active;
451 #endif
452         g_assert (cfg->comp_done & MONO_COMP_SSA);
453
454         for (i = 0; i < cfg->num_bblocks; ++i) {
455                 MonoBasicBlock *bb = cfg->bblocks [i];
456                 for (inst = bb->code; inst; inst = inst->next) {
457                         if (inst->ssa_op == MONO_SSA_STORE && inst->inst_i1->opcode == OP_PHI) {
458                                 
459                                 phi = inst->inst_i1;
460                                 g_assert (phi->inst_phi_args [0] == bb->in_count);
461
462                                 for (j = 0; j < bb->in_count; j++) {
463                                         MonoBasicBlock *pred = bb->in_bb [j];
464                                         int idx = phi->inst_phi_args [j + 1];
465                                         MonoMethodVar *mv = cfg->vars [idx];
466
467                                         if (mv->reg != -1 && mv->reg != mv->idx) {
468                                                 //printf ("PHICOPY %d %d -> %d\n", idx, mv->reg, inst->inst_i0->inst_c0);
469                                                 idx = mv->reg;
470                                         }
471
472                                         
473                                         if (idx != inst->inst_i0->inst_c0) {
474 #ifdef DEBUG_SSA
475                                                 printf ("MOVE %d to %d in BB%d\n", idx, inst->inst_i0->inst_c0, pred->block_num);
476 #endif
477                                                 mono_add_varcopy_to_end (cfg, pred, idx, inst->inst_i0->inst_c0);
478                                         }
479                                 }
480
481                                 /* remove the phi functions */
482                                 inst->opcode = CEE_NOP;
483                                 inst->ssa_op = MONO_SSA_NOP;
484                         } 
485                 }
486         }
487         
488 #ifndef USE_ORIGINAL_VARS
489         /* we compute liveness again */
490         cfg->comp_done &= ~MONO_COMP_LIVENESS;
491         mono_analyze_liveness (cfg);
492
493         varlist_array = mono_ssa_get_allocatable_vars (cfg);
494
495         for (i = 0; i < varlist_array->len; i++) {
496                 GList *l, *regs, *vars = g_ptr_array_index (varlist_array, i);
497                 MonoMethodVar *vmv, *amv;
498                 
499                 if (g_list_length (vars) <= 1) {
500                         continue;
501                 }
502
503                 active = NULL;
504                 regs = NULL;
505
506                 for (l = vars; l; l = l->next) {
507                         vmv = l->data;
508
509                         /* expire old intervals in active */
510                         while (active) {
511                                 amv = (MonoMethodVar *)active->data;
512
513                                 if (amv->range.last_use.abs_pos >= vmv->range.first_use.abs_pos)
514                                         break;
515
516                                 active = g_list_remove_link (active, active);
517                                 regs = g_list_prepend (regs, (gpointer)amv->reg);
518                         }
519
520                         if (!regs)
521                                 regs = g_list_prepend (regs, (gpointer)vmv->idx);
522
523                         vmv->reg = (int)regs->data;
524                         regs = g_list_remove_link (regs, regs);
525                         active = mono_varlist_insert_sorted (cfg, active, vmv, TRUE);           
526                 }
527
528                 g_list_free (active);
529                 g_list_free (regs);
530                 g_list_free (vars);
531         }
532
533         g_ptr_array_free (varlist_array, TRUE);
534
535 #endif
536
537         is_live = alloca (cfg->num_varinfo);
538         memset (is_live, 0, cfg->num_varinfo);
539
540         for (i = 0; i < cfg->num_bblocks; ++i) {
541                 MonoBasicBlock *bb = cfg->bblocks [i];
542
543                 for (inst = bb->code; inst; inst = inst->next)
544                         mono_ssa_replace_copies (cfg, bb, inst, is_live);
545         }
546
547         for (i = 0; i < cfg->num_varinfo; ++i) {
548                 cfg->vars [i]->reg = -1;
549                 if (!is_live [i]) {
550                         cfg->varinfo [i]->flags |= MONO_INST_IS_DEAD;
551                 }
552         }
553
554         if (cfg->comp_done & MONO_COMP_REACHABILITY)
555                 unlink_unused_bblocks (cfg);
556
557         cfg->comp_done &= ~MONO_COMP_SSA;
558 }
559
560
561 #define IS_CALL(op) (op == CEE_CALLI || op == CEE_CALL || op == CEE_CALLVIRT || (op >= OP_VOIDCALL && op <= OP_CALL_MEMBASE))
562
563 typedef struct {
564         MonoBasicBlock *bb;
565         MonoInst *inst;
566 } MonoVarUsageInfo;
567
568 static void
569 analyze_dev_use (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *root, MonoInst *inst)
570 {
571         MonoMethodVar *info;
572         int i, idx, arity;
573
574         if (!inst)
575                 return;
576
577         arity = mono_burg_arity [inst->opcode];
578
579         if ((inst->ssa_op == MONO_SSA_STORE) && 
580             (inst->inst_i0->opcode == OP_LOCAL /*|| inst->inst_i0->opcode == OP_ARG */)) {
581                 idx = inst->inst_i0->inst_c0;
582                 info = cfg->vars [idx];
583                 //printf ("%d defined in BB%d %p\n", idx, bb->block_num, root);
584                 if (info->def) {
585                         g_warning ("more than one definition of variable %d in %s", idx,
586                                    mono_method_full_name (cfg->method, TRUE));
587                         g_assert_not_reached ();
588                 }
589                 if (!IS_CALL (inst->inst_i1->opcode) /* && inst->inst_i1->opcode == OP_ICONST */) {
590                         g_assert (inst == root);
591                         info->def = root;
592                         info->def_bb = bb;
593                 }
594
595                 if (inst->inst_i1->opcode == OP_PHI) {
596                         for (i = inst->inst_i1->inst_phi_args [0]; i > 0; i--) {
597                                 MonoVarUsageInfo *ui = mono_mempool_alloc (cfg->mempool, sizeof (MonoVarUsageInfo));
598                                 idx = inst->inst_i1->inst_phi_args [i]; 
599                                 info = cfg->vars [idx];
600                                 //printf ("FOUND %d\n", idx);
601                                 ui->bb = bb;
602                                 ui->inst = root;
603                                 info->uses = g_list_prepend (info->uses, ui);
604                         }
605                 }
606         }
607
608         if ((inst->ssa_op == MONO_SSA_LOAD || inst->ssa_op == MONO_SSA_MAYBE_LOAD) && 
609             (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG)) {
610                 MonoVarUsageInfo *ui = mono_mempool_alloc (cfg->mempool, sizeof (MonoVarUsageInfo));
611                 idx = inst->inst_i0->inst_c0;   
612                 info = cfg->vars [idx];
613                 //printf ("FOUND %d\n", idx);
614                 ui->bb = bb;
615                 ui->inst = root;
616                 info->uses = g_list_prepend (info->uses, ui);
617         } else {
618                 if (arity) {
619                         //if (inst->ssa_op != MONO_SSA_STORE)
620                         analyze_dev_use (cfg, bb, root, inst->inst_left);
621                         if (arity > 1)
622                                 analyze_dev_use (cfg, bb, root, inst->inst_right);
623                 }
624         }
625 }
626
627
628 /* avoid unnecessary copies of variables:
629  * Y <= X; Z = Y; is translated to Z = X;
630  */
631 static void
632 mono_ssa_avoid_copies (MonoCompile *cfg)
633 {
634         MonoInst *inst, *next, *u;
635         MonoBasicBlock *bb;
636         MonoMethodVar *i1, *i2;
637
638         g_assert ((cfg->comp_done & MONO_COMP_SSA_DEF_USE));
639
640         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
641                 for (inst = bb->code; inst; inst = inst->next) {
642                         if (inst->ssa_op == MONO_SSA_STORE && inst->inst_i0->opcode == OP_LOCAL &&
643                             !IS_CALL (inst->inst_i1->opcode) && inst->inst_i1->opcode != OP_PHI && !inst->flags) {
644                                 i1 = cfg->vars [inst->inst_i0->inst_c0];
645
646 /* fixme: compiling mcs does not work when I enable this */
647 #if 0
648                                 if (g_list_length (i1->uses) == 1 && !extends_live (inst->inst_i1)) {
649                                         MonoVarUsageInfo *vi = (MonoVarUsageInfo *)i1->uses->data;
650                                         u = vi->inst;
651
652                                         //printf ("VAR %d %s\n", i1->idx, mono_method_full_name (cfg->method, TRUE));
653                                         //mono_print_tree (inst); printf ("\n");
654                                         //mono_print_tree (u); printf ("\n");
655
656                                         if (replace_usage_new (cfg, u, inst->inst_i0->inst_c0,  inst->inst_i1)) {
657                                                                                                                 
658                                                 //mono_print_tree (u); printf ("\n");
659                                                         
660                                                 inst->opcode = CEE_NOP;
661                                                 inst->ssa_op = MONO_SSA_NOP;
662                                         }
663                                 }
664 #endif                  
665                                 if ((next = inst->next) && next->ssa_op == MONO_SSA_STORE && next->inst_i0->opcode == OP_LOCAL &&
666                                     next->inst_i1->ssa_op == MONO_SSA_LOAD &&  next->inst_i1->inst_i0->opcode == OP_LOCAL &&
667                                     next->inst_i1->inst_i0->inst_c0 == inst->inst_i0->inst_c0 && g_list_length (i1->uses) == 1 &&
668                                     inst->opcode == next->opcode && inst->inst_i0->type == next->inst_i0->type) {
669                                         i2 = cfg->vars [next->inst_i0->inst_c0];
670                                         //printf ("ELIM. COPY in BB%d %s\n", bb->block_num, mono_method_full_name (cfg->method, TRUE));
671                                         inst->inst_i0 = next->inst_i0;
672                                         i2->def = inst;
673                                         i1->def = NULL;
674                                         g_list_free (i1->uses);
675                                         i1->uses = NULL;
676                                         next->opcode = CEE_NOP;
677                                         next->ssa_op = MONO_SSA_NOP;
678                                 }
679                         }
680                 }
681         }
682 }
683
684 static void
685 mono_ssa_create_def_use (MonoCompile *cfg) 
686 {
687         MonoBasicBlock *bb;
688
689         g_assert (!(cfg->comp_done & MONO_COMP_SSA_DEF_USE));
690
691         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
692                 MonoInst *inst;
693                 for (inst = bb->code; inst; inst = inst->next) {
694                         analyze_dev_use (cfg, bb, inst, inst);
695                 }
696         }
697
698         cfg->comp_done |= MONO_COMP_SSA_DEF_USE;
699 }
700
701 static int
702 simulate_compare (int opcode, int a, int b)
703 {
704         switch (opcode) {
705         case CEE_BEQ:
706                 return a == b;
707         case CEE_BGE:
708                 return a >= b;
709         case CEE_BGT:
710                 return a > b;
711         case CEE_BLE:
712                 return a <= b;
713         case CEE_BLT:
714                 return a < b;
715         case CEE_BNE_UN:
716                 return a != b;
717         case CEE_BGE_UN:
718                 return (unsigned)a >= (unsigned)b;
719         case CEE_BGT_UN:
720                 return (unsigned)a > (unsigned)b;
721         case CEE_BLE_UN:
722                 return (unsigned)a <= (unsigned)b;
723         case CEE_BLT_UN:
724                 return (unsigned)a < (unsigned)b;
725         default:
726                 g_assert_not_reached ();
727         }
728
729         return 0;
730 }
731
732 #define EVAL_CXX(name,op,cast)  \
733         case name:      \
734                 if (inst->inst_i0->opcode == OP_COMPARE) { \
735                         r1 = evaluate_const_tree (cfg, inst->inst_i0->inst_i0, &a, carray); \
736                         r2 = evaluate_const_tree (cfg, inst->inst_i0->inst_i1, &b, carray); \
737                         if (r1 == 1 && r2 == 1) { \
738                                 *res = ((cast)a op (cast)b); \
739                                 return 1; \
740                         } else { \
741                                 return MAX (r1, r2); \
742                         } \
743                 } \
744                 break;
745
746 #define EVAL_BINOP(name,op)     \
747         case name:      \
748                 r1 = evaluate_const_tree (cfg, inst->inst_i0, &a, carray); \
749                 r2 = evaluate_const_tree (cfg, inst->inst_i1, &b, carray); \
750                 if (r1 == 1 && r2 == 1) { \
751                         *res = (a op b); \
752                         return 1; \
753                 } else { \
754                         return MAX (r1, r2); \
755                 } \
756                 break;
757
758
759 static int
760 evaluate_const_tree (MonoCompile *cfg, MonoInst *inst, int *res, MonoInst **carray)
761 {
762         MonoInst *c0;
763         int a, b, r1, r2;
764
765         if (!inst)
766                 return 0;
767
768         if (inst->ssa_op == MONO_SSA_LOAD && 
769             (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG) &&
770             (c0 = carray [inst->inst_i0->inst_c0])) {
771                 *res = c0->inst_c0;
772                 return 1;
773         }
774
775         switch (inst->opcode) {
776         case OP_ICONST:
777                 *res = inst->inst_c0;
778                 return 1;
779
780         EVAL_CXX (OP_CEQ,==,gint32)
781         EVAL_CXX (OP_CGT,>,gint32)
782         EVAL_CXX (OP_CGT_UN,>,guint32)
783         EVAL_CXX (OP_CLT,<,gint32)
784         EVAL_CXX (OP_CLT_UN,<,guint32)
785
786         EVAL_BINOP (CEE_ADD,+)
787         EVAL_BINOP (CEE_SUB,-)
788         EVAL_BINOP (CEE_MUL,*)
789         EVAL_BINOP (CEE_AND,&)
790         EVAL_BINOP (CEE_OR,|)
791         EVAL_BINOP (CEE_XOR,^)
792         EVAL_BINOP (CEE_SHL,<<)
793         EVAL_BINOP (CEE_SHR,>>)
794
795         default:
796                 return 2;
797         }
798
799         return 2;
800 }
801
802 static void
803 fold_tree (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *inst, MonoInst **carray)
804 {
805         MonoInst *c0;
806         int arity, a, b;
807
808         if (!inst)
809                 return;
810
811         arity = mono_burg_arity [inst->opcode];
812
813         if (inst->ssa_op == MONO_SSA_STORE && 
814             (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG) &&
815             inst->inst_i1->opcode == OP_PHI && (c0 = carray [inst->inst_i0->inst_c0])) {
816                 //{static int cn = 0; printf ("PHICONST %d %d %s\n", cn++, c0->inst_c0, mono_method_full_name (cfg->method, TRUE));}
817                 *inst->inst_i1 = *c0;           
818         } else if (inst->ssa_op == MONO_SSA_LOAD && 
819             (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG) &&
820             (c0 = carray [inst->inst_i0->inst_c0])) {
821                 //{static int cn = 0; printf ("YCCOPY %d %d %s\n", cn++, c0->inst_c0, mono_method_full_name (cfg->method, TRUE));}
822                 *inst = *c0;
823         } else {
824
825                 if (arity) {
826                         fold_tree (cfg, bb, inst->inst_left, carray);
827                         if (arity > 1)
828                                 fold_tree (cfg, bb, inst->inst_right, carray);
829                         mono_constant_fold_inst (inst, NULL); 
830                 }
831         }
832
833         if ((inst->opcode >= CEE_BEQ && inst->opcode <= CEE_BLT_UN) &&
834             inst->inst_i0->opcode == OP_COMPARE) {
835                 MonoInst *v0 = inst->inst_i0->inst_i0;
836                 MonoInst *v1 = inst->inst_i0->inst_i1;
837
838                 if (evaluate_const_tree (cfg, v0, &a, carray) == 1 &&
839                     evaluate_const_tree (cfg, v1, &b, carray) == 1) {
840                         MonoBasicBlock *target;
841                                 
842                         if (simulate_compare (inst->opcode, a, b)) {
843                                 //unlink_target (bb, inst->inst_false_bb);
844                                 target = inst->inst_true_bb;
845                         } else {
846                                 //unlink_target (bb, inst->inst_true_bb);
847                                 target = inst->inst_false_bb;
848                         }
849                         
850                         bb->out_bb [0] = target;
851                         bb->out_count = 1;
852                         inst->opcode = CEE_BR;
853                         inst->inst_target_bb = target;
854                 }
855         } else if (inst->opcode == CEE_SWITCH && evaluate_const_tree (cfg, inst->inst_left, &a, carray) == 1) {
856                 bb->out_bb [0] = inst->inst_many_bb [a];
857                 bb->out_count = 1;
858                 inst->inst_target_bb = bb->out_bb [0];
859                 inst->opcode = CEE_BR;
860         }
861
862 }
863
864 static void
865 change_varstate (MonoCompile *cfg, GList **cvars, MonoMethodVar *info, int state, MonoInst *c0, MonoInst **carray)
866 {
867         if (info->cpstate >= state)
868                 return;
869
870         info->cpstate = state;
871
872         //printf ("SETSTATE %d to %d\n", info->idx, info->cpstate);
873
874         if (state == 1)
875                 carray [info->idx] = c0;
876         else
877                 carray [info->idx] = NULL;
878
879         if (!g_list_find (*cvars, info)) {
880                 *cvars = g_list_prepend (*cvars, info);
881         }
882 }
883
884 static void
885 visit_inst (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *inst, GList **cvars, GList **bblist, MonoInst **carray)
886 {
887         g_assert (inst);
888
889         if (inst->opcode == CEE_SWITCH) {
890                 int r1, i, a;
891
892                 r1 = evaluate_const_tree (cfg, inst->inst_left, &a, carray);
893                 if (r1 == 1) {
894                         MonoBasicBlock *tb = inst->inst_many_bb [a];
895                         if (!(tb->flags &  BB_REACHABLE)) {
896                                 tb->flags |= BB_REACHABLE;
897                                 *bblist = g_list_prepend (*bblist, tb);
898                         }
899                 } else if (r1 == 2) {
900                         for (i = (int)inst->klass; i >= 0; i--) {
901                                 MonoBasicBlock *tb = inst->inst_many_bb [i];
902                                 if (!(tb->flags &  BB_REACHABLE)) {
903                                         tb->flags |= BB_REACHABLE;
904                                         *bblist = g_list_prepend (*bblist, tb);
905                                 }
906                         }
907                 }
908         } else if ((inst->opcode >= CEE_BEQ && inst->opcode <= CEE_BLT_UN) &&
909             inst->inst_i0->opcode == OP_COMPARE) {
910                 int a, b, r1, r2;
911                 MonoInst *v0 = inst->inst_i0->inst_i0;
912                 MonoInst *v1 = inst->inst_i0->inst_i1;
913
914                 r1 = evaluate_const_tree (cfg, v0, &a, carray);
915                 r2 = evaluate_const_tree (cfg, v1, &b, carray);
916
917                 if (r1 == 1 && r2 == 1) {
918                         MonoBasicBlock *target;
919                                 
920                         if (simulate_compare (inst->opcode, a, b)) {
921                                 target = inst->inst_true_bb;
922                         } else {
923                                 target = inst->inst_false_bb;
924                         }
925                         if (!(target->flags &  BB_REACHABLE)) {
926                                 target->flags |= BB_REACHABLE;
927                                 *bblist = g_list_prepend (*bblist, target);
928                         }
929                 } else if (r1 == 2 || r2 == 2) {
930                         if (!(inst->inst_true_bb->flags &  BB_REACHABLE)) {
931                                 inst->inst_true_bb->flags |= BB_REACHABLE;
932                                 *bblist = g_list_prepend (*bblist, inst->inst_true_bb);
933                         }
934                         if (!(inst->inst_false_bb->flags &  BB_REACHABLE)) {
935                                 inst->inst_false_bb->flags |= BB_REACHABLE;
936                                 *bblist = g_list_prepend (*bblist, inst->inst_false_bb);
937                         }
938                 }       
939         } else if (inst->ssa_op == MONO_SSA_STORE && 
940                    (inst->inst_i0->opcode == OP_LOCAL || inst->inst_i0->opcode == OP_ARG)) {
941                 MonoMethodVar *info = cfg->vars [inst->inst_i0->inst_c0];
942                 MonoInst *i1 = inst->inst_i1;
943                 int res;
944                 
945                 if (info->cpstate < 2) {
946                         if (i1->opcode == OP_ICONST) { 
947                                 change_varstate (cfg, cvars, info, 1, i1, carray);
948                         } else if (i1->opcode == OP_PHI) {
949                                 MonoInst *c0 = NULL;
950                                 int j;
951
952                                 for (j = 1; j <= i1->inst_phi_args [0]; j++) {
953                                         MonoMethodVar *mv = cfg->vars [i1->inst_phi_args [j]];
954                                         MonoInst *src = mv->def;
955
956                                         if (mv->def_bb && !(mv->def_bb->flags & BB_REACHABLE)) {
957                                                 continue;
958                                         }
959
960                                         if (!mv->def || !src || src->ssa_op != MONO_SSA_STORE ||
961                                             !(src->inst_i0->opcode == OP_LOCAL || src->inst_i0->opcode == OP_ARG) ||
962                                             mv->cpstate == 2) {
963                                                 change_varstate (cfg, cvars, info, 2, NULL, carray);
964                                                 break;
965                                         }
966                                         
967                                         if (mv->cpstate == 0)
968                                                 continue;
969
970                                         //g_assert (src->inst_i1->opcode == OP_ICONST);
971                                         g_assert (carray [mv->idx]);
972
973                                         if (!c0) {
974                                                 c0 = carray [mv->idx];
975                                         }
976                                         
977                                         if (carray [mv->idx]->inst_c0 != c0->inst_c0) {
978                                                 change_varstate (cfg, cvars, info, 2, NULL, carray);
979                                                 break;
980                                         }
981                                 }
982                                 
983                                 if (c0 && info->cpstate < 1) {
984                                         change_varstate (cfg, cvars, info, 1, c0, carray);
985                                 }
986                         } else {
987                                 int state = evaluate_const_tree (cfg, i1, &res, carray);
988                                 if (state == 1) {
989                                         NEW_ICONST (cfg, i1, res);
990                                         change_varstate (cfg, cvars, info, 1, i1, carray);
991                                 } else {
992                                         change_varstate (cfg, cvars, info, 2, NULL, carray);
993                                 }
994                         }
995                 }
996         }
997 }
998
999 void
1000 mono_ssa_cprop (MonoCompile *cfg) 
1001 {
1002         MonoInst *carray [cfg->num_varinfo];
1003         MonoBasicBlock *bb;
1004         GList *bblock_list, *cvars;
1005         GList *tmp;
1006         int i;
1007         //printf ("SIMPLE OPTS BB%d %s\n", bb->block_num, mono_method_full_name (cfg->method, TRUE));
1008
1009         if (!(cfg->comp_done & MONO_COMP_SSA_DEF_USE))
1010                 mono_ssa_create_def_use (cfg);
1011
1012         bblock_list = g_list_prepend (NULL, cfg->bb_entry);
1013         cfg->bb_entry->flags |= BB_REACHABLE;
1014
1015         memset (carray, 0, sizeof (MonoInst *) * cfg->num_varinfo);
1016
1017         for (i = 0; i < cfg->num_varinfo; i++) {
1018                 MonoMethodVar *info = cfg->vars [i];
1019                 if (!info->def)
1020                         info->cpstate = 2;
1021         }
1022
1023         cvars = NULL;
1024
1025         while (bblock_list) {
1026                 MonoInst *inst;
1027
1028                 bb = (MonoBasicBlock *)bblock_list->data;
1029
1030                 bblock_list = g_list_remove_link (bblock_list, bblock_list);
1031
1032                 g_assert (bb->flags &  BB_REACHABLE);
1033
1034                 if (bb->out_count == 1) {
1035                         if (!(bb->out_bb [0]->flags &  BB_REACHABLE)) {
1036                                 bb->out_bb [0]->flags |= BB_REACHABLE;
1037                                 bblock_list = g_list_prepend (bblock_list, bb->out_bb [0]);
1038                         }
1039                 }
1040
1041                 for (inst = bb->code; inst; inst = inst->next) {
1042                         visit_inst (cfg, bb, inst, &cvars, &bblock_list, carray);
1043                 }
1044
1045                 while (cvars) {
1046                         MonoMethodVar *info = (MonoMethodVar *)cvars->data;                     
1047                         cvars = g_list_remove_link (cvars, cvars);
1048
1049                         for (tmp = info->uses; tmp; tmp = tmp->next) {
1050                                 MonoVarUsageInfo *ui = (MonoVarUsageInfo *)tmp->data;
1051                                 if (!(ui->bb->flags & BB_REACHABLE))
1052                                         continue;
1053                                 visit_inst (cfg, ui->bb, ui->inst, &cvars, &bblock_list, carray);
1054                         }
1055                 }
1056         }
1057
1058         for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
1059                 MonoInst *inst;
1060                 for (inst = bb->code; inst; inst = inst->next) {
1061                         fold_tree (cfg, bb, inst, carray);
1062                 }
1063         }
1064
1065         cfg->comp_done |= MONO_COMP_REACHABILITY;
1066 }
1067
1068 static void
1069 add_to_dce_worklist (MonoCompile *cfg, MonoMethodVar *var, MonoMethodVar *use, GList **wl)
1070 {
1071         GList *tmp;
1072
1073         *wl = g_list_prepend (*wl, use);
1074
1075         for (tmp = use->uses; tmp; tmp = tmp->next) {
1076                 MonoVarUsageInfo *ui = (MonoVarUsageInfo *)tmp->data;
1077                 if (ui->inst == var->def) {
1078                         use->uses = g_list_remove_link (use->uses, tmp);
1079                         break;
1080                 }
1081         }       
1082 }
1083
1084 void
1085 mono_ssa_deadce (MonoCompile *cfg) 
1086 {
1087         int i;
1088         GList *work_list;
1089
1090         g_assert (cfg->comp_done & MONO_COMP_SSA);
1091
1092         //printf ("DEADCE %s\n", mono_method_full_name (cfg->method, TRUE));
1093
1094         /* fixme: we should update usage infos during cprop, instead of computing it again */
1095         cfg->comp_done &=  ~MONO_COMP_SSA_DEF_USE;
1096         for (i = 0; i < cfg->num_varinfo; i++) {
1097                 MonoMethodVar *info = cfg->vars [i];
1098                 info->def = NULL;
1099                 info->uses = NULL;
1100         }
1101
1102         if (!(cfg->comp_done & MONO_COMP_SSA_DEF_USE))
1103                 mono_ssa_create_def_use (cfg);
1104
1105         mono_ssa_avoid_copies (cfg);
1106
1107         work_list = NULL;
1108         for (i = 0; i < cfg->num_varinfo; i++) {
1109                 MonoMethodVar *info = cfg->vars [i];
1110                 work_list = g_list_prepend (work_list, info);
1111         }
1112
1113         while (work_list) {
1114                 MonoMethodVar *info = (MonoMethodVar *)work_list->data;
1115                 work_list = g_list_remove_link (work_list, work_list);
1116
1117                 if (!info->uses && info->def) {
1118                         MonoInst *i1;
1119                         //printf ("ELIMINATE %s: ", mono_method_full_name (cfg->method, TRUE)); mono_print_tree (info->def); printf ("\n");
1120
1121                         i1 = info->def->inst_i1;
1122                         if (i1->opcode == OP_PHI) {
1123                                 int j;
1124                                 for (j = i1->inst_phi_args [0]; j > 0; j--) {
1125                                         MonoMethodVar *u = cfg->vars [i1->inst_phi_args [j]];
1126                                         add_to_dce_worklist (cfg, info, u, &work_list);
1127                                 }
1128                         } else if (i1->ssa_op == MONO_SSA_LOAD &&
1129                                    (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG)) {
1130                                         MonoMethodVar *u = cfg->vars [i1->inst_i0->inst_c0];
1131                                         add_to_dce_worklist (cfg, info, u, &work_list);
1132                         }
1133
1134                         info->def->opcode = CEE_NOP;
1135                         info->def->ssa_op = MONO_SSA_NOP;
1136                 }
1137
1138         }
1139 }
1140
1141 #if 0
1142 void
1143 mono_ssa_strength_reduction (MonoCompile *cfg)
1144 {
1145         MonoBasicBlock *bb;
1146         int i;
1147
1148         g_assert (cfg->comp_done & MONO_COMP_SSA);
1149         g_assert (cfg->comp_done & MONO_COMP_LOOPS);
1150         g_assert (cfg->comp_done & MONO_COMP_SSA_DEF_USE);
1151
1152         for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
1153                 GList *lp = bb->loop_blocks;
1154
1155                 if (lp) {
1156                         MonoBasicBlock *h = (MonoBasicBlock *)lp->data;
1157
1158                         /* we only consider loops with 2 in bblocks */
1159                         if (!h->in_count == 2)
1160                                 continue;
1161
1162                         for (i = 0; i < cfg->num_varinfo; i++) {
1163                                 MonoMethodVar *info = cfg->vars [i];
1164                         
1165                                 if (info->def && info->def->ssa_op == MONO_SSA_STORE &&
1166                                     info->def->inst_i0->opcode == OP_LOCAL && g_list_find (lp, info->def_bb)) {
1167                                         MonoInst *v = info->def->inst_i1;
1168
1169
1170                                         printf ("FOUND %d in %s\n", info->idx, mono_method_full_name (cfg->method, TRUE));
1171                                 }
1172                         }
1173                 }
1174         }
1175 }
1176 #endif