- do not clean up keep-alives here
[libfirm] / ir / ana / irmemory.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief    Memory disambiguator
23  * @author   Michael Beck
24  * @date     27.12.2006
25  * @version  $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <stdlib.h>
32 #include <stdbool.h>
33
34 #include "adt/pmap.h"
35 #include "irnode_t.h"
36 #include "irgraph_t.h"
37 #include "irprog_t.h"
38 #include "irmemory_t.h"
39 #include "irmemory.h"
40 #include "irflag.h"
41 #include "hashptr.h"
42 #include "irflag.h"
43 #include "irouts.h"
44 #include "irgwalk.h"
45 #include "irprintf.h"
46 #include "debug.h"
47 #include "error.h"
48 #include "typerep.h"
49
50 /** The debug handle. */
51 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
52 DEBUG_ONLY(static firm_dbg_module_t *dbgcall = NULL;)
53
54 /** The source language specific language disambiguator function. */
55 static DISAMBIGUATOR_FUNC language_disambuigator = NULL;
56
57 /** The global memory disambiguator options. */
58 static unsigned global_mem_disamgig_opt = aa_opt_no_opt;
59
60 /* Returns a human readable name for an alias relation. */
61 const char *get_ir_alias_relation_name(ir_alias_relation rel) {
62 #define X(a) case a: return #a
63         switch (rel) {
64         X(ir_no_alias);
65         X(ir_may_alias);
66         X(ir_sure_alias);
67         default: assert(0); return "UNKNOWN";
68         }
69 #undef X
70 }
71
72 /* Get the memory disambiguator options for a graph. */
73 unsigned get_irg_memory_disambiguator_options(ir_graph *irg) {
74         unsigned opt = irg->mem_disambig_opt;
75         if (opt & aa_opt_inherited)
76                 return global_mem_disamgig_opt;
77         return opt;
78 }  /* get_irg_memory_disambiguator_options */
79
80 /*  Set the memory disambiguator options for a graph. */
81 void set_irg_memory_disambiguator_options(ir_graph *irg, unsigned options) {
82         irg->mem_disambig_opt = options & ~aa_opt_inherited;
83 }  /* set_irg_memory_disambiguator_options */
84
85 /* Set the global disambiguator options for all graphs not having local options. */
86 void set_irp_memory_disambiguator_options(unsigned options) {
87         global_mem_disamgig_opt = options;
88 }  /* set_irp_memory_disambiguator_options */
89
90 /**
91  * Find the base address and entity of an Sel node.
92  *
93  * @param sel  the node
94  * @param pEnt after return points to the base entity.
95  *
96  * @return the base address.
97  */
98 static ir_node *find_base_adr(ir_node *sel, ir_entity **pEnt) {
99         ir_node *ptr = get_Sel_ptr(sel);
100
101         while (is_Sel(ptr)) {
102                 sel = ptr;
103                 ptr = get_Sel_ptr(sel);
104         }
105         *pEnt = get_Sel_entity(sel);
106         return ptr;
107 }  /* find_base_adr */
108
109 /**
110  * Check if a given Const node is greater or equal a given size.
111  *
112  * @param cns   a Const node
113  * @param size  a integer size
114  *
115  * @return ir_no_alias if the Const is greater, ir_may_alias else
116  */
117 static ir_alias_relation check_const(ir_node *cns, int size) {
118         tarval *tv = get_Const_tarval(cns);
119         tarval *tv_size;
120
121         if (size == 0)
122                 return tarval_is_null(tv) ? ir_may_alias : ir_no_alias;
123         tv_size = new_tarval_from_long(size, get_tarval_mode(tv));
124         return tarval_cmp(tv_size, tv) & (pn_Cmp_Eq|pn_Cmp_Lt) ? ir_no_alias : ir_may_alias;
125 }  /* check_const */
126
127 /**
128  * Treat idx1 and idx2 as integer indexes and check if they differ always more than size.
129  *
130  * @param idx1  a node representing the first index
131  * @param idx2  a node representing the second index
132  * @param size  an integer size
133  *
134  * @return ir_sure_alias iff idx1 == idx2
135  *         ir_no_alias iff they ALWAYS differ more than size
136  *         ir_may_alias else
137  */
138 static ir_alias_relation different_index(ir_node *idx1, ir_node *idx2, int size) {
139         if (idx1 == idx2)
140                 return ir_sure_alias;
141         if (is_Const(idx1) && is_Const(idx2)) {
142                 /* both are const, we can compare them */
143                 tarval *tv1 = get_Const_tarval(idx1);
144                 tarval *tv2 = get_Const_tarval(idx2);
145                 tarval *tv, *tv_size;
146                 ir_mode *m1, *m2;
147
148                 if (size == 0)
149                         return tv1 == tv2 ? ir_sure_alias : ir_no_alias;
150
151                 /* arg, modes may be different */
152                 m1 = get_tarval_mode(tv1);
153                 m2 = get_tarval_mode(tv2);
154                 if (m1 != m2) {
155                         int size = get_mode_size_bits(m1) - get_mode_size_bits(m2);
156
157                         if (size < 0) {
158                                 /* m1 is a small mode, cast up */
159                                 m1 = mode_is_signed(m1) ? find_signed_mode(m2) : find_unsigned_mode(m2);
160                                 if (m1 == NULL) {
161                                         /* should NOT happen, but if it does we give up here */
162                                         return ir_may_alias;
163                                 }
164                                 tv1 = tarval_convert_to(tv1, m1);
165                         } else if (size > 0) {
166                                 /* m2 is a small mode, cast up */
167                                 m2 = mode_is_signed(m2) ? find_signed_mode(m1) : find_unsigned_mode(m1);
168                                 if (m2 == NULL) {
169                                         /* should NOT happen, but if it does we give up here */
170                                         return ir_may_alias;
171                                 }
172                                 tv2 = tarval_convert_to(tv2, m2);
173                         }
174                         /* here the size should be identical, check for signed */
175                         if (get_mode_sign(m1) != get_mode_sign(m2)) {
176                                 /* find the signed */
177                                 if (mode_is_signed(m2)) {
178                                         tarval *t = tv1;
179                                         ir_mode *tm = m1;
180                                         tv1 = tv2; m1 = m2;
181                                         tv2 = t;   m2 = tm;
182                                 }
183
184                                 /* m1 is now the signed one */
185                                 if (tarval_cmp(tv1, get_tarval_null(m1)) & (pn_Cmp_Eq|pn_Cmp_Gt)) {
186                                         /* tv1 is signed, but >= 0, simply cast into unsigned */
187                                         tv1 = tarval_convert_to(tv1, m2);
188                                 } else {
189                                         tv_size = new_tarval_from_long(size, m2);
190
191                                         if (tarval_cmp(tv2, tv_size) & (pn_Cmp_Eq|pn_Cmp_Gt)) {
192                                                 /* tv1 is negative and tv2 >= tv_size, so the difference is bigger than size */
193                                                 return ir_no_alias;
194                                         }
195                                         /* tv_size > tv2, so we can subtract without overflow */
196                                         tv2 = tarval_sub(tv_size, tv2, NULL);
197
198                                         /* tv1 is < 0, so we can negate it */
199                                         tv1 = tarval_neg(tv1);
200
201                                         /* cast it into unsigned. for two-complement it does the right thing for MIN_INT */
202                                         tv1 = tarval_convert_to(tv1, m2);
203
204                                         /* now we can compare without overflow */
205                                         return tarval_cmp(tv1, tv2) & (pn_Cmp_Eq|pn_Cmp_Gt) ? ir_no_alias : ir_may_alias;
206                                 }
207                         }
208                 }
209                 if (tarval_cmp(tv1, tv2) == pn_Cmp_Gt) {
210                         tarval *t = tv1;
211                         tv1 = tv2;
212                         tv2 = t;
213                 }
214                 /* tv1 is now the "smaller" one */
215                 tv      = tarval_sub(tv2, tv1, NULL);
216                 tv_size = new_tarval_from_long(size, get_tarval_mode(tv));
217                 return tarval_cmp(tv_size, tv) & (pn_Cmp_Eq|pn_Cmp_Lt) ? ir_no_alias : ir_may_alias;
218         }
219
220         /* Note: we rely here on the fact that normalization puts constants on the RIGHT side */
221         if (is_Add(idx1)) {
222                 ir_node *l1 = get_Add_left(idx1);
223                 ir_node *r1 = get_Add_right(idx1);
224
225                 if (l1 == idx2) {
226                         /* x + c == y */
227                         if (is_Const(r1))
228                                 return check_const(r1, size);
229                 }
230                 if (is_Add(idx2)) {
231                         /* both are Adds, check if they are of x + a == x + b kind */
232                         ir_node *l2 = get_Add_left(idx2);
233                         ir_node *r2 = get_Add_right(idx2);
234
235                         if (l1 == l2)
236                                 return different_index(r1, r2, size);
237                         else if (l1 == r2)
238                                 return different_index(r1, l2, size);
239                         else if (r1 == r2)
240                                 return different_index(l1, l2, size);
241                         else if (r1 == l2)
242                                 return different_index(l1, r2, size);
243                 }
244         }
245         if (is_Add(idx2)) {
246                 ir_node *l2 = get_Add_left(idx2);
247                 ir_node *r2 = get_Add_right(idx2);
248
249                 if (l2 == idx1) {
250                         /* x + c == y */
251                         if (is_Const(r2))
252                                 return check_const(r2, size);
253                 }
254         }
255
256         if (is_Sub(idx1)) {
257                 ir_node *l1 = get_Sub_left(idx1);
258                 ir_node *r1 = get_Sub_right(idx1);
259
260                 if (l1 == idx2) {
261                         /* x - c == y */
262                         if (is_Const(r1))
263                                 return check_const(r1, size);
264                 }
265
266                 if (is_Sub(idx2)) {
267                         /* both are Subs, check if they are of x - a == x - b kind */
268                         ir_node *l2 = get_Sub_left(idx2);
269
270                         if (l1 == l2) {
271                                 ir_node *r2 = get_Sub_right(idx2);
272                                 return different_index(r1, r2, size);
273                         }
274                 }
275         }
276         if (is_Sub(idx2)) {
277                 ir_node *l2 = get_Sub_left(idx2);
278                 ir_node *r2 = get_Sub_right(idx2);
279
280                 if (l2 == idx1) {
281                         /* x - c == y */
282                         if (is_Const(r2))
283                                 return check_const(r2, size);
284                 }
285
286         }
287         return ir_may_alias;
288 }  /* different_index */
289
290 /**
291  * Two Sel addresses have the same base address, check if there offsets are
292  * different.
293  *
294  * @param adr1  The first address.
295  * @param adr2  The second address.
296  */
297 static ir_alias_relation different_sel_offsets(ir_node *sel1, ir_node *sel2) {
298         /* seems to be broken */
299         (void) sel1;
300         (void) sel2;
301 #if 0
302         ir_entity *ent1 = get_Sel_entity(sel1);
303         ir_entity *ent2 = get_Sel_entity(sel2);
304         int i, check_arr = 0;
305
306         if (ent1 == ent2)
307                 check_arr = 1;
308         else {
309                 ir_type *tp1 = get_entity_type(ent1);
310                 ir_type *tp2 = get_entity_type(ent2);
311
312                 if (tp1 == tp2)
313                         check_arr = 1;
314                 else if (get_type_state(tp1) == layout_fixed && get_type_state(tp2) == layout_fixed &&
315                          get_type_size_bits(tp1) == get_type_size_bits(tp2))
316                         check_arr = 1;
317         }
318         if (check_arr) {
319                 /* we select an entity of same size, check for indexes */
320                 int n = get_Sel_n_indexs(sel1);
321                 int have_no = 0;
322
323                 if (n > 0 && n == get_Sel_n_indexs(sel2)) {
324                         /* same non-zero number of indexes, an array access, check */
325                         for (i = 0; i < n; ++i) {
326                                 ir_node *idx1 = get_Sel_index(sel1, i);
327                                 ir_node *idx2 = get_Sel_index(sel2, i);
328                                 ir_alias_relation res = different_index(idx1, idx2, 0); /* we can safely IGNORE the size here if it's at least >0 */
329
330                                 if (res == may_alias)
331                                         return may_alias;
332                                 else if (res == no_alias)
333                                         have_no = 1;
334                         }
335                         /* if we have at least one no_alias, there is no alias relation, else we have sure */
336                         return have_no > 0 ? no_alias : sure_alias;
337                 }
338         }
339 #endif
340         return ir_may_alias;
341 }  /* different_sel_offsets */
342
343 /**
344  * Determine the alias relation by checking if adr1 and adr2 are pointer
345  * to different type.
346  *
347  * @param adr1    The first address.
348  * @param adr2    The second address.
349  */
350 static ir_alias_relation different_types(ir_node *adr1, ir_node *adr2)
351 {
352         ir_entity *ent1 = NULL, *ent2 = NULL;
353
354         if (is_Global(adr1))
355                 ent1 = get_Global_entity(adr1);
356         else if (is_Sel(adr1))
357                 ent1 = get_Sel_entity(adr1);
358
359         if (is_Global(adr2))
360                 ent2 = get_Global_entity(adr2);
361         else if (is_Sel(adr2))
362                 ent2 = get_Sel_entity(adr2);
363
364         if (ent1 != NULL && ent2 != NULL) {
365                 ir_type *tp1 = get_entity_type(ent1);
366                 ir_type *tp2 = get_entity_type(ent2);
367
368                 if (tp1 != tp2) {
369                         /* do deref until no pointer types are found */
370                         while (is_Pointer_type(tp1) && is_Pointer_type(tp2)) {
371                                 tp1 = get_pointer_points_to_type(tp1);
372                                 tp2 = get_pointer_points_to_type(tp2);
373                         }
374
375                         if (get_type_tpop(tp1) != get_type_tpop(tp2)) {
376                                 /* different type structure */
377                                 return ir_no_alias;
378                         }
379                         if (is_Class_type(tp1)) {
380                                 /* check class hierarchy */
381                                 if (! is_SubClass_of(tp1, tp2) &&
382                                         ! is_SubClass_of(tp2, tp1))
383                                         return ir_no_alias;
384                         } else {
385                                 /* different types */
386                                 return ir_no_alias;
387                         }
388                 }
389         }
390         return ir_may_alias;
391 }  /* different_types */
392
393 /**
394  * Returns non-zero if a node is a result on a malloc-like routine.
395  *
396  * @param node  the Proj node to test
397  */
398 static int is_malloc_Result(ir_node *node) {
399         node = get_Proj_pred(node);
400         if (! is_Proj(node))
401                 return 0;
402         node = get_Proj_pred(node);
403         if (! is_Call(node))
404                 return 0;
405         node = get_Call_ptr(node);
406         if (is_Global(node)) {
407                 ir_entity *ent = get_Global_entity(node);
408
409                 if (get_entity_additional_properties(ent) & mtp_property_malloc)
410                         return 1;
411                 return 0;
412         }
413         return 0;
414 }  /* is_malloc_Result */
415
416 /**
417  * Classify a base pointer.
418  *
419  * @param irg  the graph of the pointer
420  * @param irn  the node representing the base address
421  * @param ent  the base entity of the base address iff any
422  */
423 ir_storage_class_class_t classify_pointer(ir_graph *irg, ir_node *irn, ir_entity *ent)
424 {
425         ir_storage_class_class_t res = ir_sc_pointer;
426         if (is_Global(irn)) {
427                 ir_entity *entity = get_Global_entity(irn);
428                 res = ir_sc_globalvar;
429                 if (! (get_entity_usage(entity) & ir_usage_address_taken))
430                         res |= ir_sc_modifier_nottaken;
431         } else if (irn == get_irg_frame(irg)) {
432                 res = ir_sc_localvar;
433                 if (ent != NULL && !(get_entity_usage(ent) & ir_usage_address_taken))
434                         res |= ir_sc_modifier_nottaken;
435         } else if (is_arg_Proj(irn)) {
436                 return ir_sc_argument;
437         } else if (irn == get_irg_tls(irg)) {
438                 res = ir_sc_tls;
439                 if (ent != NULL && !(get_entity_usage(ent) & ir_usage_address_taken))
440                         res |= ir_sc_modifier_nottaken;
441         } else if (is_Proj(irn) && is_malloc_Result(irn)) {
442                 return ir_sc_malloced;
443         }
444
445         return res;
446 }
447
448 /**
449  * If adr represents a Bitfield Sel, skip it
450  */
451 static ir_node *skip_Bitfield_Sels(ir_node *adr) {
452         if (is_Sel(adr)) {
453                 ir_entity *ent     = get_Sel_entity(adr);
454                 ir_type   *bf_type = get_entity_type(ent);
455
456                 /* is it a bitfield type? */
457                 if (is_Primitive_type(bf_type) && get_primitive_base_type(bf_type) != NULL)
458                         adr = get_Sel_ptr(adr);
459         }
460         return adr;
461 }
462
463 /**
464  * Determine the alias relation between two addresses.
465  *
466  * @param irg    the graph of both memory operations
467  * @param addr1  pointer address of the first memory operation
468  * @param mode1  the mode of the accessed data through addr1
469  * @param addr2  pointer address of the second memory operation
470  * @param mode2  the mode of the accessed data through addr2
471  *
472  * @return found memory relation
473  */
474 static ir_alias_relation _get_alias_relation(
475         ir_graph *irg,
476         ir_node *adr1, ir_mode *mode1,
477         ir_node *adr2, ir_mode *mode2)
478 {
479         ir_entity             *ent1, *ent2;
480         unsigned              options;
481         long                  offset1 = 0;
482         long                  offset2 = 0;
483         ir_node               *base1;
484         ir_node               *base2;
485         ir_node               *orig_adr1 = adr1;
486         ir_node               *orig_adr2 = adr2;
487         unsigned              mode_size;
488         ir_storage_class_class_t class1, class2;
489         int                   have_const_offsets;
490
491         if (! get_opt_alias_analysis())
492                 return ir_may_alias;
493
494         if (adr1 == adr2)
495                 return ir_sure_alias;
496
497         options = get_irg_memory_disambiguator_options(irg);
498
499         /* The Armageddon switch */
500         if (options & aa_opt_no_alias)
501                 return ir_no_alias;
502
503         /* do the addresses have constants offsets?
504          *  Note: nodes are normalized to have constants at right inputs,
505          *        sub X, C is normalized to add X, -C
506          */
507         have_const_offsets = 1;
508         while (is_Add(adr1)) {
509                 ir_node *add_right = get_Add_right(adr1);
510                 if (is_Const(add_right) && !mode_is_reference(get_irn_mode(add_right))) {
511                         tarval *tv  = get_Const_tarval(add_right);
512                         offset1    += get_tarval_long(tv);
513                         adr1        = get_Add_left(adr1);
514                 } else if (mode_is_reference(get_irn_mode(add_right))) {
515                         adr1 = add_right;
516                         have_const_offsets = 0;
517                 } else {
518                         adr1 = get_Add_left(adr1);
519                         have_const_offsets = 0;
520                 }
521         }
522         while (is_Add(adr2)) {
523                 ir_node *add_right = get_Add_right(adr2);
524                 if (is_Const(add_right) && !mode_is_reference(get_irn_mode(add_right))) {
525                         tarval *tv  = get_Const_tarval(add_right);
526                         offset2    += get_tarval_long(tv);
527                         adr2        = get_Add_left(adr2);
528                 } else if (mode_is_reference(get_irn_mode(add_right))) {
529                         adr2 = add_right;
530                         have_const_offsets = 0;
531                 } else {
532                         adr2 = get_Add_left(adr2);
533                         have_const_offsets = 0;
534                 }
535         }
536
537         mode_size = get_mode_size_bytes(mode1);
538         if (get_mode_size_bytes(mode2) > mode_size) {
539                 mode_size = get_mode_size_bytes(mode2);
540         }
541
542         /* same base address -> compare offsets if possible.
543          * FIXME: type long is not sufficient for this task ...
544          */
545         if (adr1 == adr2 && have_const_offsets) {
546                 if ((unsigned long)labs(offset2 - offset1) >= mode_size)
547                         return ir_no_alias;
548                 else
549                         return ir_sure_alias;
550         }
551
552         /*
553          * Bitfields can be constructed as Sels from its base address.
554          * As they have different entities, the disambiguator would find that they are
555          * alias free. While this is true for it's values, it is false for the addresses
556          * (strictly speaking, the Sel's are NOT the addresses of the bitfields).
557          * So, skip those bitfield selecting Sel's.
558          */
559         adr1 = skip_Bitfield_Sels(adr1);
560         adr2 = skip_Bitfield_Sels(adr2);
561
562         /* skip Sels */
563         base1 = adr1;
564         base2 = adr2;
565         ent1  = NULL;
566         ent2  = NULL;
567         if (is_Sel(adr1)) {
568                 base1 = find_base_adr(adr1, &ent1);
569         }
570         if (is_Sel(adr2)) {
571                 base2 = find_base_adr(adr2, &ent2);
572         }
573
574         /* same base address -> compare Sel entities */
575         if (base1 == base2 && ent1 != NULL && ent2 != NULL) {
576                 if (ent1 != ent2)
577                         return ir_no_alias;
578                 else if (have_const_offsets)
579                         return different_sel_offsets(adr1, adr2);
580         }
581
582         class1 = classify_pointer(irg, base1, ent1);
583         class2 = classify_pointer(irg, base2, ent2);
584
585         if (class1 == ir_sc_pointer) {
586                 if (class2 & ir_sc_modifier_nottaken) {
587                         /* a pointer and an object whose objects was never taken */
588                         return ir_no_alias;
589                 }
590         } else if (class2 == ir_sc_pointer) {
591                 if (class1 & ir_sc_modifier_nottaken) {
592                         /* a pointer and an object whose objects was never taken */
593                         return ir_no_alias;
594                 }
595         } else if (class1 != class2) {
596                 /* two objects from different memory spaces */
597                 return ir_no_alias;
598         } else {
599                 /* both classes are equal */
600                 if (class1 == ir_sc_globalvar) {
601                         ir_entity *entity1 = get_SymConst_entity(base1);
602                         ir_entity *entity2 = get_SymConst_entity(base2);
603                         if (entity1 != entity2)
604                                 return ir_no_alias;
605
606                         /* for some reason CSE didn't happen yet for the 2 SymConsts... */
607                         return ir_may_alias;
608                 }
609         }
610
611         /* Type based alias analysis */
612         if (options & aa_opt_type_based) {
613                 ir_alias_relation rel;
614
615                 if (options & aa_opt_byte_type_may_alias) {
616                         if (get_mode_size_bits(mode1) == 8 || get_mode_size_bits(mode2) == 8) {
617                                 /* One of the modes address a byte. Assume a ir_may_alias and leave
618                                    the type based check. */
619                                 goto leave_type_based_alias;
620                         }
621                 }
622                 /* cheap check: If the mode sizes did not match, the types MUST be different */
623                 if (get_mode_size_bits(mode1) != get_mode_size_bits(mode2))
624                         return ir_no_alias;
625
626                 /* cheap test: if only one is a reference mode, no alias */
627                 if (mode_is_reference(mode1) != mode_is_reference(mode2))
628                         return ir_no_alias;
629
630                 /* cheap test: if arithmetic is different, no alias */
631                 if (get_mode_arithmetic(mode1) != get_mode_arithmetic(mode2))
632                         return ir_no_alias;
633
634                 /* try rule R5 */
635                 rel = different_types(orig_adr1, orig_adr2);
636                 if (rel != ir_may_alias)
637                         return rel;
638 leave_type_based_alias:;
639         }
640
641         /* do we have a language specific memory disambiguator? */
642         if (language_disambuigator) {
643                 ir_alias_relation rel = (*language_disambuigator)(irg, orig_adr1, mode1, orig_adr2, mode2);
644                 if (rel != ir_may_alias)
645                         return rel;
646         }
647
648         /* access points-to information here */
649         return ir_may_alias;
650 }  /* _get_alias_relation */
651
652 /*
653  * Determine the alias relation between two addresses.
654  */
655 ir_alias_relation get_alias_relation(
656         ir_graph *irg,
657         ir_node *adr1, ir_mode *mode1,
658         ir_node *adr2, ir_mode *mode2)
659 {
660         ir_alias_relation rel = _get_alias_relation(irg, adr1, mode1, adr2, mode2);
661         DB((dbg, LEVEL_1, "alias(%+F, %+F) = %s\n", adr1, adr2, get_ir_alias_relation_name(rel)));
662         return rel;
663 }  /* get_alias_relation */
664
665 /* Set a source language specific memory disambiguator function. */
666 void set_language_memory_disambiguator(DISAMBIGUATOR_FUNC func) {
667         language_disambuigator = func;
668 }  /* set_language_memory_disambiguator */
669
670 /** The result cache for the memory disambiguator. */
671 static set *result_cache = NULL;
672
673 /** An entry in the relation cache. */
674 typedef struct mem_disambig_entry {
675         ir_node           *adr1;    /**< The first address. */
676         ir_node           *adr2;    /**< The second address. */
677         ir_alias_relation result;   /**< The alias relation result. */
678 } mem_disambig_entry;
679
680 #define HASH_ENTRY(adr1, adr2)  (HASH_PTR(adr1) ^ HASH_PTR(adr2))
681
682 /**
683  * Compare two relation cache entries.
684  */
685 static int cmp_mem_disambig_entry(const void *elt, const void *key, size_t size) {
686         const mem_disambig_entry *p1 = elt;
687         const mem_disambig_entry *p2 = key;
688         (void) size;
689
690         return p1->adr1 == p2->adr1 && p1->adr2 == p2->adr2;
691 }  /* cmp_mem_disambig_entry */
692
693 /**
694  * Initialize the relation cache.
695  */
696 void mem_disambig_init(void) {
697         result_cache = new_set(cmp_mem_disambig_entry, 8);
698 }  /* mem_disambig_init */
699
700 /*
701  * Determine the alias relation between two addresses.
702  */
703 ir_alias_relation get_alias_relation_ex(
704         ir_graph *irg,
705         ir_node *adr1, ir_mode *mode1,
706         ir_node *adr2, ir_mode *mode2)
707 {
708         mem_disambig_entry key, *entry;
709
710         ir_fprintf(stderr, "%+F <-> %+F\n", adr1, adr2);
711
712         if (! get_opt_alias_analysis())
713                 return ir_may_alias;
714
715         if (get_irn_opcode(adr1) > get_irn_opcode(adr2)) {
716                 ir_node *t = adr1;
717                 adr1 = adr2;
718                 adr2 = t;
719         }
720
721         key.adr1 = adr1;
722         key.adr2 = adr2;
723         entry = set_find(result_cache, &key, sizeof(key), HASH_ENTRY(adr1, adr2));
724         if (entry)
725                 return entry->result;
726
727         key.result = get_alias_relation(irg, adr1, mode1, adr2, mode2);
728
729         set_insert(result_cache, &key, sizeof(key), HASH_ENTRY(adr1, adr2));
730         return key.result;
731 }  /* get_alias_relation_ex */
732
733 /* Free the relation cache. */
734 void mem_disambig_term(void) {
735         if (result_cache) {
736                 del_set(result_cache);
737                 result_cache = NULL;
738         }
739 }  /* mem_disambig_term */
740
741 /**
742  * Check the mode of a Load/Store with the mode of the entity
743  * that is accessed.
744  * If the mode of the entity and the Load/Store mode do not match, we
745  * have the bad reinterpret case:
746  *
747  * int i;
748  * char b = *(char *)&i;
749  *
750  * We do NOT count this as one value and return address_taken
751  * in that case.
752  * However, we support an often used case. If the mode is two-complement
753  * we allow casts between signed/unsigned.
754  *
755  * @param mode     the mode of the Load/Store
756  * @param ent_mode the mode of the accessed entity
757  *
758  * @return non-zero if the Load/Store is a hidden cast, zero else
759  */
760 static int is_hidden_cast(ir_mode *mode, ir_mode *ent_mode) {
761         if (ent_mode == NULL)
762                 return false;
763
764         if (ent_mode != mode) {
765                 if (ent_mode == NULL ||
766                         get_mode_size_bits(ent_mode) != get_mode_size_bits(mode) ||
767                         get_mode_sort(ent_mode) != get_mode_sort(mode) ||
768                         get_mode_arithmetic(ent_mode) != irma_twos_complement ||
769                         get_mode_arithmetic(mode) != irma_twos_complement)
770                         return true;
771         }
772         return false;
773 }  /* is_hidden_cast */
774
775 /**
776  * Determine the usage state of a node (or its successor Sels).
777  *
778  * @param irn  the node
779  */
780 static ir_entity_usage determine_entity_usage(const ir_node *irn, ir_entity *entity) {
781         int       i;
782         ir_mode   *emode, *mode;
783         ir_node   *value;
784         ir_type   *tp;
785         ir_entity_usage res = 0;
786
787         for (i = get_irn_n_outs(irn) - 1; i >= 0; --i) {
788                 ir_node *succ = get_irn_out(irn, i);
789
790                 switch (get_irn_opcode(succ)) {
791                 case iro_Load:
792                         assert(irn == get_Load_ptr(succ));
793                         res |= ir_usage_read;
794
795                         /* check if this load is not a hidden conversion */
796                         mode  = get_Load_mode(succ);
797                         emode = get_type_mode(get_entity_type(entity));
798                         if (is_hidden_cast(mode, emode))
799                                 res |= ir_usage_reinterpret_cast;
800                         break;
801
802                 case iro_Store:
803                         /* check that the node is not the Store's value */
804                         if (irn == get_Store_value(succ)) {
805                                 res |= ir_usage_unknown;
806                         }
807                         if (irn == get_Store_ptr(succ)) {
808                                 res |= ir_usage_write;
809
810                                 /* check if this Store is not a hidden conversion */
811                                 value = get_Store_value(succ);
812                                 mode  = get_irn_mode(value);
813                                 emode = get_type_mode(get_entity_type(entity));
814                                 if (is_hidden_cast(mode, emode))
815                                         res |= ir_usage_reinterpret_cast;
816                         }
817                         assert(irn != get_Store_mem(succ));
818                         break;
819
820                 case iro_CopyB:
821                         /* CopyB are like Loads/Stores */
822                         tp  = get_entity_type(entity);
823                         if (tp != get_CopyB_type(succ)) {
824                                 /* bad, different types, might be a hidden conversion */
825                                 res |= ir_usage_reinterpret_cast;
826                         }
827                         if (irn == get_CopyB_dst(succ)) {
828                                 res |= ir_usage_write;
829                         } else {
830                                 assert(irn == get_CopyB_src(succ));
831                                 res |= ir_usage_read;
832                         }
833                         break;
834
835                 case iro_Add:
836                 case iro_Sub:
837                 case iro_Sel: {
838                         /* Check the successor of irn. */
839                         res |= determine_entity_usage(succ, entity);
840                         break;
841                 }
842
843                 case iro_Call:
844                         if (irn == get_Call_ptr(succ)) {
845                                 /* TODO: we could check for reinterpret casts here...
846                                  * But I doubt anyone is interested in that bit for
847                                  * function entities and I'm too lazy to write the code now.
848                                  */
849                                 res |= ir_usage_read;
850                         } else {
851                                 assert(irn != get_Call_mem(succ));
852                                 res |= ir_usage_unknown;
853                         }
854                         break;
855
856                 /* skip identities */
857                 case iro_Id:
858                         res |= determine_entity_usage(succ, entity);
859                         break;
860
861                 /* skip tuples */
862                 case iro_Tuple: {
863                         int input_nr;
864                         for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0;
865                                         --input_nr) {
866                                 ir_node *pred = get_Tuple_pred(succ, input_nr);
867                                 if (pred == irn) {
868                                         int k;
869                                         /* we found one input */
870                                         for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
871                                                 ir_node *proj = get_irn_out(succ, k);
872
873                                                 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
874                                                         res |= determine_entity_usage(proj, entity);
875                                                         break;
876                                                 }
877                                         }
878                                 }
879                         }
880                         break;
881                 }
882
883                 default:
884                         /* another op, we don't know anything (we could do more advanced
885                          * things like a dataflow analysis here) */
886                         res |= ir_usage_unknown;
887                         break;
888                 }
889         }
890
891         return res;
892 }
893
894 /**
895  * Update the usage flags of all frame entities.
896  */
897 static void analyse_irg_entity_usage(ir_graph *irg) {
898         ir_type *ft = get_irg_frame_type(irg);
899         ir_node *irg_frame;
900         int i;
901
902         /* set initial state to not_taken, as this is the "smallest" state */
903         for (i = get_class_n_members(ft) - 1; i >= 0; --i) {
904                 ir_entity       *ent   = get_class_member(ft, i);
905                 ir_entity_usage  flags =
906                         get_entity_stickyness(ent) == stickyness_sticky ? ir_usage_unknown : 0;
907
908                 set_entity_usage(ent, flags);
909         }
910
911         assure_irg_outs(irg);
912
913         irg_frame = get_irg_frame(irg);
914
915         for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
916                 ir_node        *succ = get_irn_out(irg_frame, i);
917                 ir_entity      *entity;
918                 ir_entity_usage flags;
919
920             if (!is_Sel(succ))
921                         continue;
922
923                 entity = get_Sel_entity(succ);
924                 flags  = get_entity_usage(entity);
925                 flags |= determine_entity_usage(succ, entity);
926                 set_entity_usage(entity, flags);
927         }
928
929         /* now computed */
930         irg->entity_usage_state = ir_entity_usage_computed;
931 }
932
933 ir_entity_usage_computed_state get_irg_entity_usage_state(const ir_graph *irg) {
934         return irg->entity_usage_state;
935 }
936
937 void set_irg_entity_usage_state(ir_graph *irg, ir_entity_usage_computed_state state) {
938         irg->entity_usage_state = state;
939 }
940
941 void assure_irg_entity_usage_computed(ir_graph *irg) {
942         if (irg->entity_usage_state != ir_entity_usage_not_computed)
943                 return;
944
945         analyse_irg_entity_usage(irg);
946 }
947
948
949 /**
950  * Initialize the entity_usage flag for a global type like type.
951  */
952 static void init_entity_usage(ir_type * tp) {
953         int i;
954
955         /* We have to be conservative: All external visible entities are unknown */
956         for (i = get_compound_n_members(tp) - 1; i >= 0; --i) {
957                 ir_entity       *ent  = get_compound_member(tp, i);
958                 ir_entity_usage flags = ir_usage_none;
959                 ir_visibility   vis   = get_entity_visibility(ent);
960
961                 if (vis == visibility_external_visible   ||
962                     vis == visibility_external_allocated ||
963                     get_entity_stickyness(ent) == stickyness_sticky) {
964                         flags |= ir_usage_unknown;
965                 }
966                 set_entity_usage(ent, flags);
967         }
968 }
969
970 /**
971  * Mark all entities used in the initializer as unknown usage.
972  *
973  * @param initializer  the initializer to check
974  */
975 static void check_initializer_nodes(ir_initializer_t *initializer)
976 {
977         unsigned i;
978         ir_node  *n;
979
980         switch (initializer->kind) {
981         case IR_INITIALIZER_CONST:
982                 /* let's check if it's an address */
983                 n = initializer->consti.value;
984                 if (is_Global(n)) {
985                         ir_entity *ent = get_Global_entity(n);
986                         set_entity_usage(ent, ir_usage_unknown);
987                 }
988                 return;
989         case IR_INITIALIZER_TARVAL:
990         case IR_INITIALIZER_NULL:
991                 return;
992         case IR_INITIALIZER_COMPOUND:
993                 for (i = 0; i < initializer->compound.n_initializers; ++i) {
994                         ir_initializer_t *sub_initializer
995                                 = initializer->compound.initializers[i];
996                         check_initializer_nodes(sub_initializer);
997                 }
998                 return;
999         }
1000         panic("invalid initializer found");
1001 }  /* check_initializer_nodes */
1002
1003 /**
1004  * Mark all entities used in the initializer for the given entity as unknown
1005  * usage.
1006  *
1007  * @param ent  the entity
1008  */
1009 static void check_initializer(ir_entity *ent) {
1010         ir_node *n;
1011         int i;
1012
1013         /* do not check uninitialized values */
1014         if (get_entity_variability(ent) == variability_uninitialized)
1015                 return;
1016
1017         /* Beware: Methods are always initialized with "themself". This does not
1018            count as a taken address. */
1019         if (is_Method_type(get_entity_type(ent)))
1020                 return;
1021
1022         if (ent->has_initializer) {
1023                 check_initializer_nodes(ent->attr.initializer);
1024         } else if (is_atomic_entity(ent)) {
1025                 /* let's check if it's an address */
1026                 n = get_atomic_ent_value(ent);
1027                 if (is_Global(n)) {
1028                         ir_entity *ent = get_Global_entity(n);
1029                         set_entity_usage(ent, ir_usage_unknown);
1030                 }
1031         } else {
1032                 for (i = get_compound_ent_n_values(ent) - 1; i >= 0; --i) {
1033                         n = get_compound_ent_value(ent, i);
1034
1035                         /* let's check if it's an address */
1036                         if (is_Global(n)) {
1037                                 ir_entity *ent = get_Global_entity(n);
1038                                 set_entity_usage(ent, ir_usage_unknown);
1039                         }
1040                 }
1041         }
1042 }  /* check_initializer */
1043
1044
1045 /**
1046  * Mark all entities used in initializers as unknown usage.
1047  *
1048  * @param tp  a compound type
1049  */
1050 static void check_initializers(ir_type *tp) {
1051         int i;
1052
1053         for (i = get_compound_n_members(tp) - 1; i >= 0; --i) {
1054                 ir_entity *ent = get_compound_member(tp, i);
1055
1056                 check_initializer(ent);
1057         }
1058 }  /* check_initializers */
1059
1060 #ifdef DEBUG_libfirm
1061 /**
1062  * Print the entity usage flags of all entities of a given type for debugging.
1063  *
1064  * @param tp  a compound type
1065  */
1066 static void print_entity_usage_flags(ir_type *tp) {
1067         int i;
1068         for (i = get_compound_n_members(tp) - 1; i >= 0; --i) {
1069                 ir_entity *ent = get_compound_member(tp, i);
1070                 ir_entity_usage flags = get_entity_usage(ent);
1071
1072                 if (flags == 0)
1073                         continue;
1074                 ir_printf("%+F:", ent);
1075                 if (flags & ir_usage_address_taken)
1076                         printf(" address_taken");
1077                 if (flags & ir_usage_read)
1078                         printf(" read");
1079                 if (flags & ir_usage_write)
1080                         printf(" write");
1081                 if (flags & ir_usage_reinterpret_cast)
1082                         printf(" reinterp_cast");
1083                 printf("\n");
1084         }
1085 }
1086 #endif /* DEBUG_libfirm */
1087
1088 /**
1089  * Post-walker: check for global entity address
1090  */
1091 static void check_global_address(ir_node *irn, void *env) {
1092         ir_node *tls = env;
1093         ir_entity *ent;
1094         ir_entity_usage flags;
1095
1096         if (is_Global(irn)) {
1097                 /* A global. */
1098                 ent = get_Global_entity(irn);
1099         } else if (is_Sel(irn) && get_Sel_ptr(irn) == tls) {
1100                 /* A TLS variable. */
1101                 ent = get_Sel_entity(irn);
1102         } else
1103                 return;
1104
1105         flags = get_entity_usage(ent);
1106         flags |= determine_entity_usage(irn, ent);
1107         set_entity_usage(ent, flags);
1108 }  /* check_global_address */
1109
1110 /**
1111  * Update the entity usage flags of all global entities.
1112  */
1113 static void analyse_irp_globals_entity_usage(void) {
1114         int i;
1115         ir_segment_t s;
1116
1117         for (s = IR_SEGMENT_FIRST; s < IR_SEGMENT_COUNT; ++s) {
1118                 ir_type *type = get_segment_type(s);
1119                 init_entity_usage(type);
1120         }
1121
1122         for (s = IR_SEGMENT_FIRST; s < IR_SEGMENT_COUNT; ++s) {
1123                 ir_type *type = get_segment_type(s);
1124                 check_initializers(type);
1125         }
1126
1127         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
1128                 ir_graph *irg = get_irp_irg(i);
1129
1130                 assure_irg_outs(irg);
1131                 irg_walk_graph(irg, NULL, check_global_address, get_irg_tls(irg));
1132         }
1133
1134 #ifdef DEBUG_libfirm
1135         if (firm_dbg_get_mask(dbg) & LEVEL_1) {
1136                 ir_segment_t s;
1137                 for (s = IR_SEGMENT_FIRST; s < IR_SEGMENT_COUNT; ++s) {
1138                         print_entity_usage_flags(get_segment_type(s));
1139                 }
1140         }
1141 #endif /* DEBUG_libfirm */
1142
1143         /* now computed */
1144         irp->globals_entity_usage_state = ir_entity_usage_computed;
1145 }
1146
1147 /* Returns the current address taken state of the globals. */
1148 ir_entity_usage_computed_state get_irp_globals_entity_usage_state(void) {
1149         return irp->globals_entity_usage_state;
1150 }
1151
1152 /* Sets the current address taken state of the graph. */
1153 void set_irp_globals_entity_usage_state(ir_entity_usage_computed_state state) {
1154         irp->globals_entity_usage_state = state;
1155 }
1156
1157 /* Assure that the address taken flag is computed for the globals. */
1158 void assure_irp_globals_entity_usage_computed(void) {
1159         if (irp->globals_entity_usage_state != ir_entity_usage_not_computed)
1160                 return;
1161
1162         analyse_irp_globals_entity_usage();
1163 }
1164
1165 void firm_init_memory_disambiguator(void) {
1166         FIRM_DBG_REGISTER(dbg, "firm.ana.irmemory");
1167         FIRM_DBG_REGISTER(dbgcall, "firm.opt.cc");
1168 }
1169
1170
1171 /** Maps method types to cloned method types. */
1172 static pmap *mtp_map;
1173
1174 /**
1175  * Clone a method type if not already cloned.
1176  *
1177  * @param tp  the type to clone
1178  */
1179 static ir_type *clone_type_and_cache(ir_type *tp) {
1180         static ident *prefix = NULL;
1181         ir_type *res;
1182         pmap_entry *e = pmap_find(mtp_map, tp);
1183
1184         if (e)
1185                 return e->value;
1186
1187         if (prefix == NULL)
1188                 prefix = new_id_from_chars("C", 1);
1189
1190         res = clone_type_method(tp, prefix);
1191         pmap_insert(mtp_map, tp, res);
1192         DB((dbgcall, LEVEL_2, "cloned type %+F into %+F\n", tp, res));
1193
1194         return res;
1195 }  /* clone_type_and_cache */
1196
1197 /**
1198  * Walker: clone all call types of Calls to methods having the
1199  * mtp_property_private property set.
1200  */
1201 static void update_calls_to_private(ir_node *call, void *env) {
1202         (void) env;
1203         if (is_Call(call)) {
1204                 ir_node *ptr = get_Call_ptr(call);
1205
1206                 if (is_SymConst(ptr)) {
1207                         ir_entity *ent = get_SymConst_entity(ptr);
1208                         ir_type *ctp = get_Call_type(call);
1209
1210                         if (get_entity_additional_properties(ent) & mtp_property_private) {
1211                                 if ((get_method_additional_properties(ctp) & mtp_property_private) == 0) {
1212                                         ctp = clone_type_and_cache(ctp);
1213                                         set_method_additional_property(ctp, mtp_property_private);
1214                                         set_Call_type(call, ctp);
1215                                         DB((dbgcall, LEVEL_1, "changed call to private method %+F\n", ent));
1216                                 }
1217                         }
1218                 }
1219         }
1220 }  /* update_calls_to_private */
1221
1222 /* Mark all private methods, i.e. those of which all call sites are known. */
1223 void mark_private_methods(void) {
1224         int i;
1225         int changed = 0;
1226
1227         assure_irp_globals_entity_usage_computed();
1228
1229         mtp_map = pmap_create();
1230
1231         /* first step: change the calling conventions of the local non-escaped entities */
1232         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
1233                 ir_graph        *irg   = get_irp_irg(i);
1234                 ir_entity       *ent   = get_irg_entity(irg);
1235                 ir_entity_usage  flags = get_entity_usage(ent);
1236
1237                 /* If an entity is sticky, it might be called from external
1238                    places (like inline assembler), so do NOT mark it as private. */
1239                 if (get_entity_visibility(ent) == visibility_local &&
1240                     !(flags & ir_usage_address_taken) &&
1241                     get_entity_stickyness(ent) != stickyness_sticky) {
1242                         ir_type *mtp = get_entity_type(ent);
1243
1244                         set_entity_additional_property(ent, mtp_property_private);
1245                         DB((dbgcall, LEVEL_1, "found private method %+F\n", ent));
1246                         if ((get_method_additional_properties(mtp) & mtp_property_private) == 0) {
1247                                 /* need a new type */
1248                                 mtp = clone_type_and_cache(mtp);
1249                                 set_entity_type(ent, mtp);
1250                                 set_method_additional_property(mtp, mtp_property_private);
1251                                 changed = 1;
1252                         }
1253                 }
1254         }
1255
1256         if (changed)
1257                 all_irg_walk(NULL, update_calls_to_private, NULL);
1258
1259         pmap_destroy(mtp_map);
1260 }  /* mark_private_methods */