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