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