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