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