added code to detect loops in unreachable code, these would cause
[libfirm] / ir / opt / scalar_replace.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/scalar_replace.c
4  * Purpose:     scalar replacement of arrays and compounds
5  * Author:      Beyhan Veliev
6  * Modified by: Michael Beck
7  * Created:
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 1998-2005 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12 #ifdef HAVE_CONFIG_H
13 #include "config.h"
14 #endif
15
16 #ifdef HAVE_ALLOCA_H
17 #include <alloca.h>
18 #endif
19
20 #ifdef HAVE_MALLOC_H
21 #include <malloc.h>
22 #endif
23
24 #ifdef HAVE_STRING_H
25 #include <string.h>
26 #endif
27
28 #include "scalar_replace.h"
29 #include "irflag_t.h"
30 #include "irouts.h"
31 #include "set.h"
32 #include "pset.h"
33 #include "array.h"
34 #include "tv.h"
35 #include "ircons_t.h"
36 #include "hashptr.h"
37 #include "irgwalk.h"
38 #include "irgmod.h"
39 #include "irnode_t.h"
40 #include "irtools.h"
41
42 #define SET_VNUM(node, vnum) set_irn_link(node, INT_TO_PTR(vnum))
43 #define GET_VNUM(node)       (unsigned)PTR_TO_INT(get_irn_link(node))
44
45 /**
46  * A path element entry: it is either an entity
47  * or a tarval, because we evaluate only constant array
48  * accesses like a.b.c[8].d
49  */
50 typedef union {
51   entity *ent;
52   tarval *tv;
53 } path_elem_t;
54
55 /**
56  * An access path, used to assign value numbers
57  * to variables that will be scalar replaced
58  */
59 typedef struct _path_t {
60   unsigned    vnum;      /**< the value number */
61   unsigned    path_len;  /**< the length of the access path */
62   path_elem_t path[1];   /**< the path */
63 } path_t;
64
65 typedef struct _scalars_t {
66   entity *ent;                 /**< A entity for scalar replacement. */
67   type *ent_owner;             /**< The owner of this entity. */
68 } scalars_t;
69
70
71 /**
72  * Compare two pathes.
73  *
74  * @return 0 if they are identically
75  */
76 static int path_cmp(const void *elt, const void *key, size_t size)
77 {
78   const path_t *p1 = elt;
79   const path_t *p2 = key;
80
81   /* we can use memcmp here, because identical tarvals should have identical addresses */
82   return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
83 }
84
85 /**
86  * Compare two elements of the scalars_t set.
87  *
88  * @return 0 if they are identically
89  */
90 static int ent_cmp(const void *elt, const void *key, size_t size)
91 {
92   const scalars_t *c1 = elt;
93   const scalars_t *c2 = key;
94
95   return c1->ent != c2->ent;
96 }
97
98 /**
99  * Calculate a hash value for a path.
100  */
101 static unsigned path_hash(const path_t *path)
102 {
103   unsigned hash = 0;
104   unsigned i;
105
106   for (i = 0; i < path->path_len; ++i)
107     hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
108
109   return hash >> 4;
110 }
111
112 /**
113  * Returns non-zero, if all indeces of a Sel node are constants.
114  *
115  * @param sel  the Sel node that will be checked
116  */
117 static int is_const_sel(ir_node *sel) {
118   int i, n = get_Sel_n_indexs(sel);
119
120   for (i = 0; i < n; ++i) {
121     ir_node *idx = get_Sel_index(sel, i);
122
123     if (get_irn_op(idx) != op_Const)
124       return 0;
125   }
126   return 1;
127 }
128
129 /*
130  * Returns non-zero, if the address of an entity
131  * represented by a Sel node (or it's successor Sels) is taken.
132  */
133 int is_address_taken(ir_node *sel)
134 {
135   int i, n;
136
137   if (! is_const_sel(sel))
138     return 1;
139
140   n = get_irn_n_outs(sel);
141   for (i = 0; i < n; ++i) {
142     ir_node *succ = get_irn_out(sel, i);
143
144     switch (get_irn_opcode(succ)) {
145     case iro_Load:
146       /* ok, we just load from that entity */
147       break;
148
149     case iro_Store:
150       /* check that Sel is not the Store's value */
151       if (get_Store_value(succ) == sel)
152         return 1;
153       break;
154
155     case iro_Sel: {
156       /* Check the Sel successor of Sel */
157       int res = is_address_taken(succ);
158
159       if (res)
160         return 1;
161       break;
162     }
163
164     case iro_Call:
165       /* The address of an entity is given as a parameter.
166        * As long as we do not have analyses that can tell what
167        * is done with parameters, think is taken.
168        */
169       return 1;
170
171     default:
172       /* another op, the address is taken */
173       return 1;
174     }
175   }
176   return 0;
177 }
178
179 /**
180  * Link all leave Sels with the entity.
181  *
182  * @param ent  the entity that will be scalar replaced
183  * @param sel  a Sel node that selects some fields of this entity
184  */
185 static void link_all_leave_sels(entity *ent, ir_node *sel)
186 {
187   int i, n, flag = 1;
188
189   n = get_irn_n_outs(sel);
190   for (i = 0; i < n; ++i) {
191     ir_node *succ = get_irn_out(sel, i);
192
193     if (get_irn_op(succ) == op_Sel) {
194       link_all_leave_sels(ent, succ);
195       flag = 0;
196     }
197   }
198
199   if (flag) {
200     /* if Sel nodes with memory inputs are used, a entity can be
201      * visited more than once causing a ring here, so we use the
202      * node flag to mark linked nodes
203      */
204     if (irn_visited(sel))
205       return;
206
207     /* we know we are at a leave, because this function is only
208      * called if the address is NOT taken, so succ must be a Load
209      * or a Store node
210      */
211     set_irn_link(sel, get_entity_link(ent));
212     set_entity_link(ent, sel);
213
214     mark_irn_visited(sel);
215   }
216 }
217
218 /* we need a special address that serves as an address taken marker */
219 static char _x;
220 static void *ADDRESS_TAKEN = &_x;
221
222 /**
223  * Find possible scalar replacements.
224  *
225  * @param irg  an IR graph
226  *
227  * This function finds variables on the (members of the) frame type
228  * that can be scalar replaced, because their address is never taken.
229  * If such a variable is found, it's entity link will hold a list of all
230  * Sel nodes, that selects the atomic fields of this entity.
231  * Otherwise, the link will be ADDRESS_TAKEN or NULL.
232  *
233  * @return  non-zero if at least one entity could be replaced
234  *          potentially
235  */
236 static int find_possible_replacements(ir_graph *irg)
237 {
238   ir_node *irg_frame = get_irg_frame(irg);
239   int i, n;
240   int res = 0;
241
242   inc_irg_visited(irg);
243
244   n = get_irn_n_outs(irg_frame);
245
246   /*
247    * First, clear the link field of all interesting entities.
248    * Note that we did not rely on the fact that there is only
249    * one Sel node per entity, so we might access one entity
250    * more than once here.
251    * That's why we have need two loops.
252    */
253   for (i = 0; i < n; ++i) {
254     ir_node *succ = get_irn_out(irg_frame, i);
255
256     if (get_irn_op(succ) == op_Sel) {
257       entity *ent = get_Sel_entity(succ);
258       set_entity_link(ent, NULL);
259     }
260   }
261
262   /*
263    * Check the ir_graph for Sel nodes. If the entity of Sel
264    * isn't a scalar replacement set the link of this entity
265    * equal ADDRESS_TAKEN.
266    */
267   for (i = 0; i < n; ++i) {
268     ir_node *succ = get_irn_out(irg_frame, i);
269
270     if (get_irn_op(succ) == op_Sel) {
271       entity *ent = get_Sel_entity(succ);
272       type *ent_type;
273
274       if (get_entity_link(ent) == ADDRESS_TAKEN)
275         continue;
276
277       ent_type = get_entity_type(ent);
278
279       /* we can handle arrays, structs and atomic types yet */
280       if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
281         if (is_address_taken(succ)) {
282           if (get_entity_link(ent)) /* killing one */
283             --res;
284           set_entity_link(ent, ADDRESS_TAKEN);
285         }
286         else {
287           /* possible found one */
288           if (get_entity_link(ent) == NULL)
289             ++res;
290           link_all_leave_sels(ent, succ);
291         }
292       }
293     }
294   }
295
296   return res;
297 }
298
299 /**
300  * Return a path from the Sel node sel to it's root.
301  *
302  * @param sel  the Sel node
303  * @param len  the length of the path so far
304  */
305 static path_t *find_path(ir_node *sel, unsigned len)
306 {
307   int pos, i, n;
308   path_t *res;
309   ir_node *pred = get_Sel_ptr(sel);
310
311   /* the current Sel node will add some path elements */
312   n    = get_Sel_n_indexs(sel);
313   len += n + 1;
314
315   if (get_irn_op(pred) != op_Sel) {
316     /* we found the root */
317
318     res = xmalloc(sizeof(*res) + (len - 1) * sizeof(res->path));
319     res->path_len = len;
320   }
321   else
322     res = find_path(pred, len);
323
324   pos = res->path_len - len;
325
326   res->path[pos++].ent = get_Sel_entity(sel);
327   for (i = 0; i < n; ++i) {
328     ir_node *index = get_Sel_index(sel, i);
329
330     res->path[pos++].tv = get_Const_tarval(index);
331   }
332   return res;
333 }
334
335
336 /**
337  * Allocate value numbers for the leaves
338  * in our found entities.
339  *
340  * @param sels  a set that will contain all Sels that have a value number
341  * @param ent   the entity that will be scalar replaced
342  * @param vnum  the first value number we can assign
343  * @param modes a flexible array, containing all the modes of
344  *              the value numbers.
345  *
346  * @return the next free value number
347  */
348 static unsigned allocate_value_numbers(pset *sels, entity *ent, unsigned vnum, ir_mode ***modes)
349 {
350   ir_node *sel, *next;
351   path_t *key, *path;
352   set *pathes = new_set(path_cmp, 8);
353
354   /* visit all Sel nodes in the chain of the entity */
355   for (sel = get_entity_link(ent); sel; sel = next) {
356     next = get_irn_link(sel);
357
358     /* we must mark this sel for later */
359     pset_insert_ptr(sels, sel);
360
361     key  = find_path(sel, 0);
362     path = set_find(pathes, key, sizeof(*key) + sizeof(key->path[0]) * key->path_len, path_hash(key));
363
364     if (path)
365       SET_VNUM(sel, path->vnum);
366     else {
367       unsigned i;
368
369       key->vnum = vnum++;
370
371       set_insert(pathes, key, sizeof(*key) + sizeof(key->path[0]) * key->path_len, path_hash(key));
372
373       SET_VNUM(sel, key->vnum);
374       ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
375
376       (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
377
378       assert((*modes)[key->vnum] && "Value is not atomic");
379
380 #ifdef DEBUG_libfirm
381       /* Debug output */
382       if (get_opt_scalar_replacement_verbose() && get_firm_verbosity() > 1) {
383         printf("  %s", get_entity_name(ent));
384         for (i = 1; i < key->path_len; ++i) {
385           if (is_entity(key->path[i].ent))
386             printf(".%s", get_entity_name(key->path[i].ent));
387           else
388             printf("[%ld]", get_tarval_long(key->path[i].tv));
389         }
390         printf(" = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum]));
391       }
392 #endif /* DEBUG_libfirm */
393     }
394     free(key);
395   }
396
397   del_set(pathes);
398   set_entity_link(ent, NULL);
399   return vnum;
400 }
401
402 /**
403  * A list entry for the fixing lists
404  */
405 typedef struct _list_entry_t {
406   ir_node  *node;   /**< the node that must be fixed */
407   unsigned vnum;    /**< the value number of this node */
408 } list_entry_t;
409
410 /**
411  * environment for memory walker
412  */
413 typedef struct _env_t {
414   struct obstack obst;      /**< a obstack for the value blocks */
415   int          nvals;       /**< number of values */
416   ir_mode      **modes;     /**< the modes of the values */
417   list_entry_t *fix_phis;   /**< list of all Phi nodes that must be fixed */
418   list_entry_t *fix_loads;  /**< list of all Load nodes that must be fixed */
419   pset         *sels;       /**< A set of all Sel nodes that have a value number */
420 } env_t;
421
422 /**
423  * Walker
424  */
425 static void handle_first(ir_node *node, void *ctx)
426 {
427   env_t        *env = ctx;
428   ir_op        *op = get_irn_op(node);
429   ir_node      *adr, *block, *mem, *unk, **value_arr, **in;
430   unsigned     vnum;
431   int          i, j, n;
432   list_entry_t *l;
433
434   if (op == op_Load) {
435     /* a load, check if we can resolve it */
436     adr = get_Load_ptr(node);
437
438     if (get_irn_op(adr) != op_Sel)
439       return;
440
441     if (! pset_find_ptr(env->sels, adr))
442       return;
443
444     /* ok, we have a Load that will be replaced */
445     vnum = GET_VNUM(adr);
446
447     assert(vnum < (unsigned)env->nvals);
448
449     block     = get_nodes_block(node);
450     value_arr = get_irn_link(block);
451
452     /* check, if we can replace this Load */
453     if (value_arr[vnum]) {
454       mem = get_Load_mem(node);
455
456       turn_into_tuple(node, pn_Load_max);
457       set_Tuple_pred(node, pn_Load_M,        mem);
458       set_Tuple_pred(node, pn_Load_res,      value_arr[vnum]);
459       set_Tuple_pred(node, pn_Load_X_except, new_Bad());
460     }
461     else {
462       l = obstack_alloc(&env->obst, sizeof(*l));
463       l->node = node;
464       l->vnum = vnum;
465
466       set_irn_link(node, env->fix_loads);
467       env->fix_loads = l;
468     }
469   }
470   else if (op == op_Store) {
471     /* a Store always can be replaced */
472     adr = get_Store_ptr(node);
473
474     if (get_irn_op(adr) != op_Sel)
475       return;
476
477     if (! pset_find_ptr(env->sels, adr))
478       return;
479
480     vnum = GET_VNUM(adr);
481
482     assert(vnum < (unsigned)env->nvals);
483
484     block     = get_nodes_block(node);
485     value_arr = get_irn_link(block);
486
487     value_arr[vnum] = get_Store_value(node);
488
489     mem = get_Store_mem(node);
490
491     turn_into_tuple(node, pn_Store_max);
492     set_Tuple_pred(node, pn_Store_M,        mem);
493     set_Tuple_pred(node, pn_Store_X_except, new_Bad());
494   }
495   else if (op == op_Phi && get_irn_mode(node) == mode_M) {
496     /*
497      * found a memory Phi: Here, we must create new Phi nodes
498      */
499     block     = get_nodes_block(node);
500     value_arr = get_irn_link(block);
501
502     n = get_Block_n_cfgpreds(block);
503
504     in = alloca(sizeof(*in) * n);
505
506     for (i = env->nvals - 1; i >= 0; --i) {
507       unk = new_Unknown(env->modes[i]);
508       for (j = n - 1; j >= 0; --j)
509         in[j] = unk;
510
511       value_arr[i] = new_r_Phi(current_ir_graph, block, n, in, env->modes[i]);
512
513       l = obstack_alloc(&env->obst, sizeof(*l));
514       l->node = value_arr[i];
515       l->vnum = i;
516
517       set_irn_link(value_arr[i], env->fix_phis);
518       env->fix_phis = l;
519     }
520   }
521 }
522
523 /**
524  * Walker: allocate the value array for every block.
525  */
526 static void alloc_value_arr(ir_node *block, void *ctx)
527 {
528   env_t *env = ctx;
529   ir_node **var_arr = obstack_alloc(&env->obst, sizeof(*var_arr) * env->nvals);
530
531   /* the value array is empty at start */
532   memset(var_arr, 0, sizeof(*var_arr) * env->nvals);
533   set_irn_link(block, var_arr);
534 }
535
536 /**
537  * searches through blocks beginning from block for value
538  * vnum and return it.
539  */
540 static ir_node *find_value(ir_node *block, unsigned vnum)
541 {
542   ir_node **value_arr;
543   int i;
544   ir_node *res;
545
546   if (Block_not_block_visited(block)) {
547     mark_Block_block_visited(block);
548
549     value_arr = get_irn_link(block);
550
551     if (value_arr[vnum])
552       return value_arr[vnum];
553
554     for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
555       ir_node *pred = get_Block_cfgpred(block, i);
556
557       res = find_value(get_nodes_block(pred), vnum);
558       if (res)
559         return res;
560     }
561   }
562   return NULL;
563 }
564
565 /**
566  * fix the Phi list
567  */
568 static void fix_phis(env_t *env)
569 {
570   list_entry_t *l;
571   ir_node      *phi, *block, *pred, *val;
572   int          i;
573
574   for (l = env->fix_phis; l; l = get_irn_link(phi)) {
575     phi = l->node;
576
577     block = get_nodes_block(phi);
578     for (i = get_irn_arity(phi) - 1; i >= 0; --i) {
579       pred = get_Block_cfgpred(block, i);
580       pred = get_nodes_block(pred);
581
582       inc_irg_block_visited(current_ir_graph);
583       val = find_value(pred, l->vnum);
584
585       if (val)
586         set_irn_n(phi, i, val);
587     }
588   }
589 }
590
591 /**
592  * fix the Load list
593  */
594 static void fix_loads(env_t *env)
595 {
596   list_entry_t *l;
597   ir_node      *load, *block, *pred, *val, *mem;
598   int          i;
599
600   for (l = env->fix_loads; l; l = get_irn_link(load)) {
601     load = l->node;
602
603     block = get_nodes_block(load);
604     for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
605       pred = get_Block_cfgpred(block, i);
606       pred = get_nodes_block(pred);
607
608       inc_irg_block_visited(current_ir_graph);
609       val = find_value(pred, l->vnum);
610
611       if (val)
612         break;
613     }
614
615     if (! val) {
616       /* access of an uninitialized value */
617       val = new_Unknown(env->modes[l->vnum]);
618     }
619
620     mem = get_Load_mem(load);
621
622     turn_into_tuple(load, pn_Load_max);
623     set_Tuple_pred(load, pn_Load_M,        mem);
624     set_Tuple_pred(load, pn_Load_res,      val);
625     set_Tuple_pred(load, pn_Load_X_except, new_Bad());
626   }
627 }
628
629 /**
630  *  Make scalar replacement.
631  *
632  * @param sels    A set containing all Sel nodes that have a value number
633  * @param nvals   The number of scalars.
634  * @param modes   A flexible array, containing all the modes of
635  *                the value numbers.
636  */
637 static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes)
638 {
639   env_t env;
640
641   obstack_init(&env.obst);
642   env.nvals     = nvals;
643   env.modes     = modes;
644   env.fix_phis  = NULL;
645   env.fix_loads = NULL;
646   env.sels      = sels;
647
648   /* first step: allocate the value arrays for every block */
649   irg_block_walk_graph(current_ir_graph, NULL, alloc_value_arr, &env);
650
651   /*
652    * second step: walk over the graph blockwise in topological order
653    * and fill the array as much as possible.
654    */
655   irg_walk_blkwise_graph(current_ir_graph, NULL, handle_first, &env);
656
657   /* third, fix the list of Phis, then the list of Loads */
658   fix_phis(&env);
659   fix_loads(&env);
660
661   obstack_free(&env.obst, NULL);
662 }
663
664 /*
665  * Find possible scalar replacements
666  *
667  * @param irg  The current ir graph.
668  */
669 void scalar_replacement_opt(ir_graph *irg)
670 {
671   unsigned  nvals;
672   int       i;
673   scalars_t key, *value;
674   ir_node   *irg_frame;
675   ir_mode   **modes;
676   set       *set_ent;
677   pset      *sels;
678   type      *ent_type;
679   ir_graph  *rem;
680
681   if (! get_opt_scalar_replacement())
682     return;
683
684   rem = current_ir_graph;
685
686   /* Call algorithm that computes the out edges */
687   if (get_irg_outs_state(irg) != outs_consistent)
688     compute_irg_outs(irg);
689
690   /* Find possible scalar replacements */
691   if (find_possible_replacements(irg)) {
692
693     if (get_opt_scalar_replacement_verbose()) {
694       printf("Scalar Replacement: %s\n", get_entity_name(get_irg_entity(irg)));
695     }
696
697     /* Insert in set the scalar replacements. */
698     irg_frame = get_irg_frame(irg);
699     nvals = 0;
700     modes = NEW_ARR_F(ir_mode *, 16);
701     set_ent = new_set(ent_cmp, 8);
702     sels    = pset_new_ptr(8);
703
704     for (i = 0 ; i < get_irn_n_outs(irg_frame); i++) {
705       ir_node *succ = get_irn_out(irg_frame, i);
706
707       if (get_irn_op(succ) == op_Sel) {
708         entity *ent = get_Sel_entity(succ);
709
710         if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
711           continue;
712
713         ent_type = get_entity_type(ent);
714
715         key.ent       = ent;
716         key.ent_owner = get_entity_owner(ent);
717         set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
718
719         if (get_opt_scalar_replacement_verbose()) {
720           if (is_Array_type(ent_type)) {
721             printf("  found array %s\n", get_entity_name(ent));
722           }
723           else if (is_Struct_type(ent_type)) {
724             printf("  found struct %s\n", get_entity_name(ent));
725           }
726           else if (is_atomic_type(ent_type))
727             printf("  found atomic value %s\n", get_entity_name(ent));
728           else {
729             assert(0 && "Neither an array nor a struct or atomic value");
730           }
731         }
732
733         nvals = allocate_value_numbers(sels, ent, nvals, &modes);
734       }
735     }
736
737     if (get_opt_scalar_replacement_verbose()) {
738       printf("  %u values will be needed\n", nvals);
739     }
740
741     /* If scalars were found. */
742     if (nvals) {
743       do_scalar_replacements(sels, nvals, modes);
744
745       for (value = set_first(set_ent); value; value = set_next(set_ent)) {
746         remove_class_member(value->ent_owner, value->ent);
747       }
748     }
749
750     del_pset(sels);
751     del_set(set_ent);
752     DEL_ARR_F(modes);
753
754     if (nvals) {
755       /*
756        * We changed the graph, but did NOT introduce new blocks
757        * neither changed control flow, cf-backedges should be still
758        * consistent.
759        */
760       set_irg_outs_inconsistent(irg);
761       set_irg_loopinfo_inconsistent(irg);
762     }
763   }
764
765   current_ir_graph = rem;
766 }