b40244cd754c1ab5078184b290a5893277bcc229
[libfirm] / ir / ana / cgana.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/ana/cgana.c
4  * Purpose:     Intraprozedural analyses to estimate the call graph.
5  * Author:      Hubert Schmid
6  * Modified by:
7  * Created:     09.06.2002
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 1999-2003 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12
13 /** @file cgana.c
14  *
15  * Interprocedural analysis to estimate the calling relation.
16  *
17  * This analysis computes all entities representing methods that
18  * can be called at a Call node.  Further it computes a set of
19  * methods that are 'free', i.e., their adress is handled by
20  * the program directly, or they are visible external.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 # include "config.h"
25 #endif
26
27 #ifdef HAVE_STRING_H
28 # include <string.h>
29 #endif
30
31 #include "cgana.h"
32 #include "rta.h"
33
34 #include "xmalloc.h"
35 #include "irnode_t.h"
36 #include "irmode_t.h"
37 #include "irprog_t.h"
38 #include "irgwalk.h"
39 #include "ircons.h"
40 #include "irgmod.h"
41 #include "iropt.h"
42
43 #include "irflag_t.h"
44 #include "dbginfo_t.h"
45 #include "iropt_dbg.h"
46
47 #include "eset.h"
48 #include "pmap.h"
49 #include "array.h"
50
51 #include "irdump.h"
52
53 #include "irhooks.h"
54
55
56
57 /* Eindeutige Adresse zur Markierung von besuchten Knoten und zur
58  * Darstellung der unbekannten Methode. */
59 static void *MARK = &MARK;
60
61 static eset *entities = NULL;
62
63 /*--------------------------------------------------------------------------*/
64 /* The analysis                                                             */
65 /*--------------------------------------------------------------------------*/
66
67
68 /*--------------------------------------------------------------------------*/
69 /* Initialize datastructures, remove unwanted constructs, optimize          */
70 /* call target computations.                                                */
71 /*--------------------------------------------------------------------------*/
72
73 /** Returns the entity that contains the implementation of the inherited
74  *  entity if available, else returns the entity passed. */
75 static entity *get_inherited_methods_implementation(entity *inh_meth) {
76   assert(get_atomic_ent_value(inh_meth) && "constant entity without value");
77   assert((get_irn_op(get_atomic_ent_value(inh_meth)) == op_SymConst) &&
78          (get_SymConst_kind(get_atomic_ent_value(inh_meth)) == symconst_addr_ent) &&
79          "Complex constant values not supported -- address of method should be straight constant!");
80
81   return get_SymConst_entity(get_atomic_ent_value(inh_meth));
82 }
83
84 /** Collect the entity representing the implementation of this
85  *  entity (not the same if inherited) and all entities for overwriting
86  *  implementations in "set".
87  *  If the implementation of the method is not included in the
88  *  compilation unit "open" is set to true.
89  *  A recursive descend in the overwritten relation.
90  *  Cycle-free, therefore must terminate.
91  *
92  * @param method
93  * @param set      A set of entities.
94  * @param size     Number of entities in set.
95  * @param open
96  */
97 static void collect_impls(entity *method, eset *set, int *size, bool *open) {
98   int i;
99   entity *impl;
100
101   /* Add the implementation to the set if it contains an irg, else
102      remember that there are more methods called. */
103   impl = method;
104   if (get_entity_peculiarity(method) == peculiarity_inherited)
105     impl = get_inherited_methods_implementation(method);
106
107   if (get_entity_peculiarity(method) != peculiarity_description) {
108     eset_insert(set, impl);
109     ++(*size);
110   }
111
112   /*- recursive descent -*/
113   for (i = get_entity_n_overwrittenby(method) - 1; i >= 0; --i)
114     collect_impls(get_entity_overwrittenby(method, i), set, size, open);
115 }
116
117 /** Alle Methoden bestimmen, die die übergebene Methode überschreiben
118  *  (und implementieren). In der zurückgegebenen Reihung kommt jede
119  *  Methode nur einmal vor. Der Wert 'NULL' steht für unbekannte
120  *  (externe) Methoden. Die zurückgegebene Reihung muß vom Aufrufer
121  *  wieder freigegeben werden (siehe "DEL_ARR_F"). Gibt es überhaupt
122  *  keine Methoden, die "method" überschreiben, so gibt die Methode
123  *  "NULL" zurück.
124  *
125  *  @param method
126  */
127 static entity ** get_impl_methods(entity * method) {
128   eset * set = eset_create();
129   int size = 0;
130   entity ** arr;
131   bool open = false;
132
133   /* Collect all method entities that can be called here */
134   collect_impls(method, set, &size, &open);
135
136   /* Vorgaenger einfuegen. */
137   if (size == 0 && !open) {
138     /* keine implementierte überschriebene Methode */
139     arr = NULL;
140   } else if (open) {
141     entity * ent;
142     arr = NEW_ARR_F(entity *, size + 1);
143     arr[0] = NULL;  /* Represents open method */
144     for (ent = eset_first(set); size > 0; ent = eset_next(set), --size)
145       arr[size] = ent;
146   } else {
147     entity * ent;
148     arr = NEW_ARR_F(entity *, size);
149     for (size -= 1, ent = eset_first(set); size >= 0; ent = eset_next(set), --size)
150       arr[size] = ent;
151   }
152   eset_destroy(set);
153   return arr;
154 }
155
156 /** Analyze address computations.
157  *
158  *  Compute for all Sel nodes the set of methods that can be selected.
159  *  For each entity we store the set of subentities in the link field.
160  *
161  *  Further do some optimizations:
162  *  - Call standard optimizations for Sel nodes: this removes polymorphic
163  *    calls.
164  *  - If the node is a SymConst(name) replace it by SymConst(ent) if possible.
165  *    For this we precomputed a map name->entity.  Nowadays, we no more support
166  *    this and assert.
167  *  - If the node is a Sel:
168  *    If we found only a single method that can be called, replace the Sel
169  *    by a SymConst.  This is more powerful than the analysis in opt_polymorphy,
170  *    as here we walk the type graph.  In opt_polymorphy we only apply a local
171  *    pattern.
172  *
173  *  @param node The node to analyze
174  *  @param env  A map that maps names of entities to the entities.
175  */
176 static void sel_methods_walker(ir_node * node, void *env) {
177   pmap *ldname_map = env;
178   entity **arr;
179
180   /* Call standard optimizations */
181   if (get_irn_op(node) == op_Sel) {
182     ir_node *new_node = optimize_in_place(node);
183     if (node != new_node)
184       exchange(node, new_node);
185   }
186
187   /* replace SymConst(name)-operations by SymConst(ent) */
188   if (get_irn_op(node) == op_SymConst) {
189     if (get_SymConst_kind(node) == symconst_addr_name) {
190       pmap_entry * entry = pmap_find(ldname_map, (void *) get_SymConst_name(node));
191       if (entry != NULL) { /* Method is declared in the compiled code */
192         assert(0 && "There should not be a SymConst[addr_name] addressing a method with an implementation"
193                     "in this compilation unit.  Use a SymConst[addr_ent].");
194       }
195     }
196   }
197   else if (get_irn_op(node) == op_Sel &&
198            is_Method_type(get_entity_type(get_Sel_entity(node)))) {
199     entity * ent = get_SymConst_entity(get_atomic_ent_value(get_Sel_entity(node)));
200     assert(get_entity_peculiarity(ent) != peculiarity_inherited);
201
202     if (!eset_contains(entities, ent)) {
203       /* Entity not yet handled. Find all (internal or external)
204        * implemented methods that overwrites this entity.
205        * This set is stored in the entity link. */
206       set_entity_link(ent, get_impl_methods(ent));
207       eset_insert(entities, ent);
208     }
209
210     /* -- As an add on we get an optimization that removes polymorphic calls.
211        This optimization is more powerful than that in transform_node_Sel().  -- */
212     arr = get_entity_link(ent);
213     if (arr == NULL) {
214       /*
215        * The Sel node never returns a pointer to a usable method.
216        * We could not call it, but it may be description:
217        * We call a method in a dead part of the program.
218        */
219       assert (get_entity_peculiarity(ent) == peculiarity_description);
220     }
221     else if (get_opt_optimize() && get_opt_dyn_meth_dispatch() &&
222         (ARR_LEN(arr) == 1 && arr[0] != NULL)) {
223       ir_node *new_node;
224
225       /*
226        * The Sel node returns only one possible method.
227        * So we could replace the Sel node by a SymConst.
228        * This method must exists.
229        */
230       set_irg_current_block(current_ir_graph, get_nodes_block(node));
231       assert(get_entity_peculiarity(get_SymConst_entity(get_atomic_ent_value(arr[0]))) ==
232              peculiarity_existent);
233       new_node = copy_const_value(get_irn_dbg_info(node), get_atomic_ent_value(arr[0]));
234       DBG_OPT_POLY(node, new_node);
235       exchange(node, new_node);
236     }
237   }
238 }
239
240 /** Initialize auxiliary data structures.
241  *
242  *  Computes a set of entities that overwrite an entity and contain
243  *  an implementation. The set is stored in the entity's link field.
244  *
245  *  Further replaces Sel nodes where this set contains exactly one
246  *  method by SymConst nodes.
247  *  Finally asserts if there is a SymConst(name) if there could be a
248  *  SymConst(ent). */
249 static void sel_methods_init(void) {
250   int i;
251   pmap * ldname_map = pmap_create();   /* Map entity names to entities: to replace
252                                           SymConst(name) by SymConst(ent). */
253   assert(entities == NULL);
254   entities = eset_create();
255   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
256     entity * ent = get_irg_entity(get_irp_irg(i));
257     /* only external visible methods are allowed to call by a SymConst_ptr_name */
258     if (get_entity_visibility(ent) != visibility_local) {
259       pmap_insert(ldname_map, (void *) get_entity_ld_ident(ent), ent);
260     }
261   }
262
263   all_irg_walk(sel_methods_walker, NULL, ldname_map);
264   pmap_destroy(ldname_map);
265 }
266
267 /*--------------------------------------------------------------------------*/
268 /* Find free methods.
269  *
270  * We expect that each entity has an array with all implementations in its
271  * link field.                                                              */
272 /*--------------------------------------------------------------------------*/
273
274 /**
275  * Returns an array of all methods that could be called at a Sel node.
276  * This array contains every entry only once.
277  *
278  * @param sel  the Sel node
279  */
280 static entity ** get_Sel_arr(ir_node * sel) {
281   static entity ** NULL_ARRAY = NULL;
282   entity * ent;
283   entity ** arr;
284
285   assert(sel && get_irn_op(sel) == op_Sel);
286   ent = get_Sel_entity(sel);
287   ent = get_inherited_methods_implementation(ent);
288
289   assert(is_Method_type(get_entity_type(ent))); /* what else? */
290   arr = get_entity_link(ent);
291   if (arr) {
292     return arr;
293   } else {
294     /* "NULL" zeigt an, dass keine Implementierung existiert. Dies
295      * kann für polymorphe (abstrakte) Methoden passieren. */
296     if (!NULL_ARRAY) {
297       NULL_ARRAY = NEW_ARR_F(entity *, 0);
298     }
299     return NULL_ARRAY;
300   }
301 }
302
303 /**
304  * Returns the number of possible called methods at a Sel node.
305  *
306  * @param sel  the Sel node
307  */
308 static int get_Sel_n_methods(ir_node * sel) {
309   return ARR_LEN(get_Sel_arr(sel));
310 }
311
312 /**
313  * Returns the ith possible called method entity at a Sel node.
314  */
315 static entity * get_Sel_method(ir_node * sel, int pos) {
316   entity ** arr = get_Sel_arr(sel);
317   assert(pos >= 0 && pos < ARR_LEN(arr));
318   return arr[pos];
319 }
320
321 static void free_mark(ir_node * node, eset * set);
322
323 static void free_mark_proj(ir_node * node, long n, eset * set) {
324   assert(get_irn_mode(node) == mode_T);
325   if (get_irn_link(node) == MARK) {
326     /* already visited */
327     return;
328   }
329   set_irn_link(node, MARK);
330   switch (get_irn_opcode(node)) {
331   case iro_Proj: {
332     /* proj_proj: in einem "sinnvollen" Graphen kommt jetzt ein
333      * op_Tuple oder ein Knoten, der in "free_ana_walker" behandelt
334      * wird. */
335     ir_node * pred = get_Proj_pred(node);
336     if (get_irn_link(pred) != MARK && get_irn_op(pred) == op_Tuple) {
337       free_mark_proj(get_Tuple_pred(pred, get_Proj_proj(node)), n, set);
338     } else {
339       /* nothing: da in "free_ana_walker" behandelt. */
340     }
341     break;
342   }
343
344   case iro_Tuple:
345     free_mark(get_Tuple_pred(node, n), set);
346     break;
347
348   case iro_Id:
349     free_mark_proj(get_Id_pred(node), n, set);
350     break;
351
352   case iro_Start:
353   case iro_Alloc:
354   case iro_Load:
355     /* nothing: Die Operationen werden in free_ana_walker() selbst
356      * behandelt. */
357     break;
358
359   default:
360     assert(0 && "unexpected opcode or opcode not implemented");
361     break;
362   }
363   set_irn_link(node, NULL);
364 }
365
366 /**
367  * Called for predecessors nodes of "interesting" ones.
368  * Interesting ones include all nodes that can somehow make
369  * a method visible.
370  *
371  * If a method (or a set of methods in case of polymorph calls) gets visible,
372  * add it to the set of 'free' methods
373  *
374  * @param node  the current visited node
375  * @param set   the set of all free methods
376  */
377 static void free_mark(ir_node *node, eset * set) {
378   int i;
379
380   if (get_irn_link(node) == MARK)
381     return; /* already visited */
382
383   set_irn_link(node, MARK);
384
385   switch (get_irn_opcode(node)) {
386   case iro_Sel: {
387     entity * ent = get_Sel_entity(node);
388     if (is_Method_type(get_entity_type(ent))) {
389       for (i = get_Sel_n_methods(node) - 1; i >= 0; --i) {
390         eset_insert(set, get_Sel_method(node, i));
391       }
392     }
393     break;
394   }
395   case iro_SymConst:
396     if (get_SymConst_kind(node) == symconst_addr_ent) {
397       entity * ent = get_SymConst_entity(node);
398       if (is_Method_type(get_entity_type(ent))) {
399         eset_insert(set, ent);
400       }
401     } else {
402       assert(get_SymConst_kind(node) == symconst_addr_name);
403       /* nothing: SymConst points to extern method */
404     }
405     break;
406
407   case iro_Phi:
408     for (i = get_Phi_n_preds(node) - 1; i >= 0; --i) {
409       free_mark(get_Phi_pred(node, i), set);
410     }
411     break;
412   case iro_Id:
413     free_mark(get_Id_pred(node), set);
414     break;
415   case iro_Proj:
416     free_mark_proj(get_Proj_pred(node), get_Proj_proj(node), set);
417     break;
418   default:
419     /* nothing: Wird unten behandelt! */
420     break;
421   }
422   set_irn_link(node, NULL);
423 }
424
425 /**
426  * post-walker. Find method addresses.
427  */
428 static void free_ana_walker(ir_node *node, void *env) {
429   eset *set = env;
430   int i;
431
432   if (get_irn_link(node) == MARK) {
433     /* already visited */
434     return;
435   }
436   switch (get_irn_opcode(node)) {
437   /* special nodes */
438   case iro_Sel:
439   case iro_SymConst:
440   case iro_Const:
441   case iro_Phi:
442   case iro_Id:
443   case iro_Proj:
444   case iro_Tuple:
445     /* nothing */
446     break;
447   /* Sonderbehandlung, da der Funktionszeigereingang natürlich kein
448    * Verräter ist. */
449   case iro_Call:
450     set_irn_link(node, MARK);
451     for (i = get_Call_n_params(node) - 1; i >= 0; --i) {
452       ir_node *pred = get_Call_param(node, i);
453       if (mode_is_reference(get_irn_mode(pred))) {
454         free_mark(pred, set);
455       }
456     }
457     break;
458   /* other nodes: Alle anderen Knoten nehmen wir als Verräter an, bis
459    * jemand das Gegenteil implementiert. */
460   default:
461     set_irn_link(node, MARK);
462     for (i = get_irn_arity(node) - 1; i >= 0; --i) {
463       ir_node * pred = get_irn_n(node, i);
464       if (mode_is_reference(get_irn_mode(pred))) {
465         free_mark(pred, set);
466       }
467     }
468     break;
469   }
470   set_irn_link(node, NULL);
471 }
472
473 /**
474  * Add all method addresses in global initializers to the set.
475  *
476  * @note
477  * We do NOT check the type here, just it it's an entity address.
478  * The reason for this is code like:
479  *
480  * void *p = function;
481  *
482  * which is sometimes used to anchor functions.
483  */
484 static void add_method_address(entity *ent, eset *set)
485 {
486   ir_node *n;
487   type *tp;
488   int i;
489
490   /* do not check uninitialized values */
491   if (get_entity_variability(ent) == variability_uninitialized)
492     return;
493
494   if (is_atomic_entity(ent)) {
495     tp = get_entity_type(ent);
496
497     /* ignore methods: these of course reference it's address */
498     if (is_Method_type(tp))
499
500     /* let's check if it's the address of a function */
501     n = get_atomic_ent_value(ent);
502     if (get_irn_op(n) == op_SymConst) {
503       if (get_SymConst_kind(n) == symconst_addr_ent) {
504         ent = get_SymConst_entity(n);
505
506         if (is_Method_type(get_entity_type(ent)))
507           eset_insert(set, ent);
508       }
509     }
510   }
511   else {
512     for (i = get_compound_ent_n_values(ent) - 1; i >= 0; --i) {
513       n = get_compound_ent_value(ent, i);
514
515       /* let's check if it's the address of a function */
516       if (get_irn_op(n) == op_SymConst) {
517         if (get_SymConst_kind(n) == symconst_addr_ent) {
518           entity *ent = get_SymConst_entity(n);
519
520           if (is_Method_type(get_entity_type(ent)))
521             eset_insert(set, ent);
522         }
523       }
524     }
525   }
526 }
527
528 /**
529  * returns a list of 'free' methods, i.e., the methods that can be called
530  * from external or via function pointers.
531  *
532  * Die Datenstrukturen für sel-Methoden (sel_methods) muß vor dem
533  * Aufruf von "get_free_methods" aufgebaut sein. Die (internen)
534  * SymConst(name)-Operationen müssen in passende SymConst(ent)-Operationen
535  * umgewandelt worden sein, d.h. SymConst-Operationen verweisen immer
536  * auf eine echt externe Methode.
537  */
538 static entity ** get_free_methods(void)
539 {
540   eset *free_set = eset_create();
541   int i;
542   entity **arr = NEW_ARR_F(entity *, 0);
543   entity *ent;
544   ir_graph *irg;
545   type *glob;
546
547   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
548     irg = get_irp_irg(i);
549     ent = get_irg_entity(irg);
550     /* insert "external visible" methods. */
551     if (get_entity_visibility(ent) != visibility_local) {
552       eset_insert(free_set, ent);
553     }
554     /* Finde alle Methoden die in dieser Methode extern sichtbar werden,
555        z.B. da die Adresse einer Methode abgespeichert wird. */
556     irg_walk_graph(irg, NULL, free_ana_walker, free_set);
557   }
558
559   /* insert sticky methods, too */
560   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
561     ent = get_irg_entity(get_irp_irg(i));
562     /* insert "sticky" methods. */
563     if (get_entity_stickyness (ent) == stickyness_sticky) {
564       eset_insert(free_set, ent);
565     }
566   }
567
568   /* insert all methods the initializes global variables */
569   glob = get_glob_type();
570   for (i = get_class_n_members(glob) - 1; i >= 0; --i) {
571     ent = get_class_member(glob, i);
572
573     add_method_address(ent, free_set);
574   }
575
576   /* the main program is even then "free", if it's not external visible. */
577   irg = get_irp_main_irg();
578   if (irg)
579     eset_insert(free_set, get_irg_entity(irg));
580
581   /* Finally, transform the set into an array. */
582   for (ent = eset_first(free_set); ent; ent = eset_next(free_set)) {
583     ARR_APP1(entity *, arr, ent);
584   }
585   eset_destroy(free_set);
586
587   return arr;
588 }
589
590 /*--------------------------------------------------------------------------*/
591 /* Callee analysis.                                                         */
592 /*--------------------------------------------------------------------------*/
593
594 static void callee_ana_node(ir_node * node, eset * methods);
595
596 static void callee_ana_proj(ir_node * node, long n, eset * methods) {
597   assert(get_irn_mode(node) == mode_T);
598   if (get_irn_link(node) == MARK) {
599     /* already visited */
600     return;
601   }
602   set_irn_link(node, MARK);
603
604   switch (get_irn_opcode(node)) {
605   case iro_Proj: {
606     /* proj_proj: in einem "sinnvollen" Graphen kommt jetzt ein
607      * op_Tuple oder ein Knoten, der eine "freie Methode"
608      * zurückgibt. */
609     ir_node * pred = get_Proj_pred(node);
610     if (get_irn_link(pred) != MARK) {
611       if (get_irn_op(pred) == op_Tuple) {
612         callee_ana_proj(get_Tuple_pred(pred, get_Proj_proj(node)), n, methods);
613       } else {
614         eset_insert(methods, MARK); /* free method -> unknown */
615       }
616     }
617     break;
618   }
619
620   case iro_Tuple:
621     callee_ana_node(get_Tuple_pred(node, n), methods);
622     break;
623
624   case iro_Id:
625     callee_ana_proj(get_Id_pred(node), n, methods);
626     break;
627
628   default:
629     eset_insert(methods, MARK); /* free method -> unknown */
630     break;
631   }
632
633   set_irn_link(node, NULL);
634 }
635
636
637 static void callee_ana_node(ir_node * node, eset * methods) {
638   int i;
639
640   assert(mode_is_reference(get_irn_mode(node)) || is_Bad(node));
641   /* rekursion verhindern */
642   if (get_irn_link(node) == MARK) {
643     /* already visited */
644     return;
645   }
646   set_irn_link(node, MARK);
647
648   switch (get_irn_opcode(node)) {
649   case iro_SymConst:
650     if (get_SymConst_kind(node) == symconst_addr_ent) {
651       entity * ent = get_SymConst_entity(node);
652       assert(ent && is_Method_type(get_entity_type(ent)));
653       eset_insert(methods, ent);
654     } else {
655       assert(get_SymConst_kind(node) == symconst_addr_name);
656       /* externe Methode (wegen fix_symconst!) */
657       eset_insert(methods, MARK); /* free method -> unknown */
658     }
659     break;
660   case iro_Sel:
661     /* polymorphe Methode */
662     for (i = get_Sel_n_methods(node) - 1; i >= 0; --i) {
663       entity * ent = get_Sel_method(node, i);
664       if (ent) {
665         eset_insert(methods, ent);
666       } else {
667         eset_insert(methods, MARK);
668       }
669     }
670     break;
671
672   case iro_Bad:
673     /* nothing */
674     break;
675
676   case iro_Phi: /* Vereinigung */
677     for (i = get_Phi_n_preds(node) - 1; i >= 0; --i) {
678       callee_ana_node(get_Phi_pred(node, i), methods);
679     }
680     break;
681
682   case iro_Mux:
683     callee_ana_node(get_Mux_false(node), methods);
684     callee_ana_node(get_Mux_true(node), methods);
685     break;
686
687   case iro_Id:
688     callee_ana_node(get_Id_pred(node), methods);
689     break;
690
691   case iro_Proj:
692     callee_ana_proj(get_Proj_pred(node), get_Proj_proj(node), methods);
693     break;
694
695   case iro_Add:
696   case iro_Sub:
697   case iro_Conv:
698     /* extern */
699     eset_insert(methods, MARK); /* free method -> unknown */
700     break;
701
702   default:
703     assert(0 && "invalid opcode or opcode not implemented");
704     break;
705   }
706
707   set_irn_link(node, NULL);
708 }
709
710 /* */
711 static void callee_walker(ir_node * call, void * env) {
712   if (get_irn_op(call) == op_Call) {
713     eset * methods = eset_create();
714     entity * ent;
715     entity ** arr = NEW_ARR_F(entity *, 0);
716     assert(get_irn_op(get_Call_ptr(call)) != op_Id);
717     callee_ana_node(get_Call_ptr(call), methods);
718     if (eset_contains(methods, MARK)) { /* unknown method */
719       ARR_APP1(entity *, arr, unknown_entity);
720     }
721     for (ent = eset_first(methods); ent; ent = eset_next(methods)) {
722       if (ent != MARK) {
723         ARR_APP1(entity *, arr, ent);
724       }
725     }
726 #if 0  /* This generates Bad nodes when we don't want it.
727           Call it with a check for valid cgana information in local_optimize. */
728     if (ARR_LEN(arr) == 0 && get_opt_optimize() && get_opt_dyn_meth_dispatch()) {
729       /* Kann vorkommen, wenn der Vorgänger beispielsweise eine
730        * Sel-Operation war, die keine Methoden zurückgeben
731        * konnte. Wir ersetzen die Call-Operation ebenfalls durch
732        * eine Bad-Operation. Die Verlinkung muss wiederhergestellt
733        * werden! */
734       ir_node *mem = get_Call_mem(call);
735       turn_into_tuple (call, 5 /* pn_Call_max */);
736       set_Tuple_pred(call, pn_Call_M_regular       , mem);
737       set_Tuple_pred(call, pn_Call_T_result        , new_Bad());
738       set_Tuple_pred(call, pn_Call_P_value_res_base, new_Bad());
739       set_Tuple_pred(call, pn_Call_X_except        , new_Bad());  /* new_Jmp() ?? new_Raise() ?? */
740       set_Tuple_pred(call, pn_Call_M_except        , new_Bad());
741
742     } else
743 #endif
744     {
745       set_Call_callee_arr(call, ARR_LEN(arr), arr);
746     }
747     DEL_ARR_F(arr);
748     eset_destroy(methods);
749   }
750 }
751
752
753 static void remove_Tuples(ir_node * proj, void * env) {
754   ir_node *new;
755   if (get_irn_opcode(proj) != iro_Proj) return;
756
757   new = skip_Tuple(proj);
758   if (new != proj) exchange(proj, new);
759 }
760
761
762 /* Bestimmt für jede Call-Operation die Menge der aufrufbaren Methode
763  * und speichert das Ergebnis in der Call-Operation. (siehe
764  * "set_Call_callee"). "sel_methods" wird für den Aufbau benötigt und
765  * muss bereits aufgebaut sein. */
766 static void callee_ana(void) {
767   int i;
768   /* Alle Graphen analysieren. */
769   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
770     irg_walk_graph(get_irp_irg(i), callee_walker, remove_Tuples, NULL);
771     set_irg_callee_info_state(get_irp_irg(i), irg_callee_info_consistent);
772   }
773   set_irp_callee_info_state(irg_callee_info_consistent);
774 }
775
776 /*--------------------------------------------------------------------------*/
777 /* Cleanup after analyses.                                                  */
778 /*--------------------------------------------------------------------------*/
779
780 /** Frees intermediate data structures. */
781 static void sel_methods_dispose(void) {
782   entity * ent;
783   assert(entities);
784   for (ent = eset_first(entities); ent; ent = eset_next(entities)) {
785     entity ** arr = get_entity_link(ent);
786     if (arr) {
787       DEL_ARR_F(arr);
788     }
789     set_entity_link(ent, NULL);
790   }
791   eset_destroy(entities);
792   entities = NULL;
793 }
794
795 /*--------------------------------------------------------------------------*/
796 /* Freeing the callee arrays.                                               */
797 /*--------------------------------------------------------------------------*/
798
799 static void destruct_walker(ir_node * node, void * env) {
800   if (get_irn_op(node) == op_Call) {
801     remove_Call_callee_arr(node);
802   }
803 }
804
805 /*--------------------------------------------------------------------------*/
806 /* Main drivers.                                                            */
807 /*--------------------------------------------------------------------------*/
808
809 void cgana(int *length, entity ***free_methods) {
810   entity ** free_meths, **p;
811
812   /* Optimize Sel/SymConst nodes and compute all methods that implement an entity. */
813   sel_methods_init();
814   free_meths = get_free_methods();
815   callee_ana();
816   sel_methods_dispose();
817
818   /* Convert the flexible array to an array that can be handled
819      by standard C. */
820   p = xmalloc(sizeof(*p) * ARR_LEN(free_meths));
821   memcpy(p, free_meths, ARR_LEN(free_meths) * sizeof(*p));
822
823   *length       = ARR_LEN(free_meths);
824   *free_methods = p;
825
826   DEL_ARR_F(free_meths);
827 }
828
829 void free_callee_info(ir_graph *irg) {
830   irg_walk_graph(irg, destruct_walker, NULL, NULL);
831   set_irg_callee_info_state(irg, irg_callee_info_none);
832 }
833
834 void free_irp_callee_info(void) {
835   int i;
836   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
837     free_callee_info(get_irp_irg(i));
838   }
839 }
840
841 /* Optimize the address expressions passed to call nodes.
842  *
843  * This optimization performs the following transformations for
844  * all ir graphs:
845  * - All SymConst operations that refer to intern methods are replaced
846  *   by Const operations referring to the corresponding entity.
847  * - Sel nodes, that select entities that are not overwritten are
848  *   replaced by Const nodes referring to the selected entity.
849  * - Sel nodes, for which no method exists at all are replaced by Bad
850  *   nodes.
851  * - Sel nodes with a pointer input that is an Alloc node are replaced
852  *   by Const nodes referring to the entity that implements the method in
853  *   the type given by the Alloc node.
854  */
855 void opt_call_addrs(void) {
856   sel_methods_init();
857   sel_methods_dispose();
858 }