b593ed143842c9909400ef42c9ee6808a28bbccb
[libfirm] / ir / ir / iredges.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   Always available outs.
23  * @author  Sebastian Hack, Michael Beck, Andreas Schoesser
24  * @date    14.1.2005
25  * @version $Id$
26  * @summary
27  *   This are out-edges (also called def-use edges) that are dynamically
28  *   updated as the graph changes.
29  */
30 #include "config.h"
31
32 #include "irnode_t.h"
33 #include "iropt_t.h"
34 #include "iredgekinds.h"
35 #include "iredges_t.h"
36 #include "irgwalk.h"
37 #include "irdump_t.h"
38 #include "irprintf.h"
39 #include "debug.h"
40 #include "set.h"
41 #include "bitset.h"
42
43 #include "iredgeset.h"
44 #include "hashptr.h"
45
46 #define DO_REHASH
47 #define SCALAR_RETURN
48 #define HashSet                   ir_edgeset_t
49 #define HashSetIterator           ir_edgeset_iterator_t
50 #define ValueType                 ir_edge_t*
51 #define NullValue                 NULL
52 #define DeletedValue              ((ir_edge_t*)-1)
53 #define Hash(this,key)            (HASH_PTR(key->src) ^ (key->pos * 40013))
54 #define KeysEqual(this,key1,key2) ((key1->src) == (key2->src) && (key1->pos == key2->pos))
55 #define SetRangeEmpty(ptr,size)   memset(ptr, 0, (size) * sizeof((ptr)[0]))
56
57 #define hashset_init            ir_edgeset_init
58 #define hashset_init_size       ir_edgeset_init_size
59 #define hashset_destroy         ir_edgeset_destroy
60 #define hashset_insert          ir_edgeset_insert
61 #define hashset_remove          ir_edgeset_remove
62 #define hashset_find            ir_edgeset_find
63 #define hashset_size            ir_edgeset_size
64 #define hashset_iterator_init   ir_edgeset_iterator_init
65 #define hashset_iterator_next   ir_edgeset_iterator_next
66 #define hashset_remove_iterator ir_edgeset_remove_iterator
67
68 #include "hashset.c"
69
70 /**
71  * A function that allows for setting an edge.
72  * This abstraction is necessary since different edge kind have
73  * different methods of setting edges.
74  */
75 typedef void (set_edge_func_t)(ir_node *src, int pos, ir_node *tgt);
76
77 typedef int (get_edge_src_arity_func_t)(const ir_node *src);
78
79 typedef ir_node *(get_edge_src_n_func_t)(const ir_node *src, int pos);
80
81 /**
82  * Additional data for an edge kind.
83  */
84 typedef struct {
85         const char                *name;       /**< name of this edge kind */
86         set_edge_func_t           *set_edge;   /**< the set_edge function */
87         int                       first_idx;   /**< index of the first possible edge */
88         get_edge_src_arity_func_t *get_arity;  /**< the get_arity function */
89         get_edge_src_n_func_t     *get_n;      /**< the get_n function */
90 } ir_edge_kind_info_t;
91
92 /**
93  * Get the predecessor block.
94  */
95 static ir_node *get_block_n(const ir_node *irn, int pos) {
96         if (is_Block(irn))
97                 return get_Block_cfgpred_block(irn, pos);
98         /* might be a Bad */
99         return NULL;
100 }
101
102 static const ir_edge_kind_info_t edge_kind_info[EDGE_KIND_LAST] = {
103         { "normal"     , set_irn_n,   -1, get_irn_arity,  get_irn_n   },
104         { "block succs", NULL,         0, get_irn_arity,  get_block_n },
105         { "dependency",  set_irn_dep,  0, get_irn_deps,   get_irn_dep }
106 };
107
108 #define foreach_tgt(irn, i, n, kind) for(i = edge_kind_info[kind].first_idx, n = edge_kind_info[kind].get_arity(irn); i < n; ++i)
109 #define get_n(irn, pos, kind)        (edge_kind_info[kind].get_n(irn, pos))
110 #define get_kind_str(kind)           (edge_kind_info[kind].name)
111
112 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
113
114 /**
115  * This flag is set to 1, if the edges get initialized for an irg.
116  * Then register additional data is forbidden.
117  */
118 static int edges_used = 0;
119
120 /**
121  * Summed size of all users private data
122  */
123
124 static int edges_private_size = 0;
125 #define EDGE_SIZE (sizeof(ir_edge_t) + edges_private_size)
126
127 /**
128  * If set to 1, the list heads are checked every time an edge is changed.
129  */
130 static int edges_dbg = 0;
131
132 #ifdef DEBUG_libfirm
133 /* a static variable holding the last number assigned to a new edge */
134 static long last_edge_num = -1;
135 #endif
136
137 static inline long edge_get_id(const ir_edge_t *e) {
138 #ifdef DEBUG_libfirm
139         return e->edge_nr;
140 #else /* DEBUG_libfirm */
141         return (long)e;
142 #endif /* DEBUG_libfirm */
143 }
144
145 /**
146  * Announce to reserve extra space for each edge to be allocated.
147  *
148  * @param n: Size of the space to reserve
149  *
150  * @return Offset at which the private data will begin
151  *
152  * Several users can reserve extra space for private usage.
153  * Each user has to remember his given offset and the size of his private data.
154  * To be called before FIRM is initialized.
155  */
156 int edges_register_private_data(size_t n) {
157         int res = edges_private_size;
158
159         assert(!edges_used && "you cannot register private edge data, if edges have been initialized");
160
161         edges_private_size += n;
162         return res;
163 }
164
165 /**
166  * Reset the user's private data at offset 'offset'
167  * The user has to remember his offset and the size of his data!
168  * Caution: Using wrong values here can destroy other users private data!
169  */
170 void edges_reset_private_data(ir_graph *irg, int offset, size_t size) {
171         irg_edge_info_t       *info = _get_irg_edge_info(irg, EDGE_KIND_NORMAL);
172         ir_edge_t             *edge;
173         ir_edgeset_iterator_t  iter;
174
175         foreach_ir_edgeset(&info->edges, edge, iter) {
176                 memset(edge + sizeof(*edge) + offset, 0, size);
177         }
178 }
179
180 #define TIMES37(x) (((x) << 5) + ((x) << 2) + (x))
181
182 #define get_irn_out_list_head(irn) (&get_irn_out_info(irn)->outs)
183
184 #define edge_hash(edge) (TIMES37((edge)->pos) + HASH_PTR((edge)->src))
185
186 /**
187  * Initialize the out information for a graph.
188  * @note Dead node elimination can call this on an already initialized graph.
189  */
190 void edges_init_graph_kind(ir_graph *irg, ir_edge_kind_t kind) {
191         if (edges_activated_kind(irg, kind)) {
192                 irg_edge_info_t *info = _get_irg_edge_info(irg, kind);
193                 size_t amount = irg->estimated_node_count * 2;
194
195                 edges_used = 1;
196                 if(info->allocated) {
197                         amount = ir_edgeset_size(&info->edges);
198                         ir_edgeset_destroy(&info->edges);
199                         obstack_free(&info->edges_obst, NULL);
200                 }
201                 obstack_init(&info->edges_obst);
202                 ir_edgeset_init_size(&info->edges, amount);
203                 info->allocated = 1;
204         }
205 }
206
207 /**
208  * Get the edge object of an outgoing edge at a node.
209  * @param   irg The graph, the node is in.
210  * @param   src The node at which the edge originates.
211  * @param   pos The position of the edge.
212  * @return      The corresponding edge object or NULL,
213  *              if no such edge exists.
214  */
215 const ir_edge_t *get_irn_edge_kind(ir_graph *irg, const ir_node *src, int pos, ir_edge_kind_t kind)
216 {
217         if (edges_activated_kind(irg, kind)) {
218                 irg_edge_info_t *info = _get_irg_edge_info(irg, kind);
219                 ir_edge_t       key;
220
221                 key.src = (ir_node *)src;
222                 key.pos = pos;
223
224                 return ir_edgeset_find(&info->edges, &key);
225         }
226
227         return NULL;
228 }
229
230 /**
231  * Get the edge object of an outgoing edge at a node.
232  * Looks for an edge for all kinds.
233  */
234 const ir_edge_t *get_irn_edge(ir_graph *irg, const ir_node *src, int pos) {
235         const ir_edge_t *edge;
236         if((edge = get_irn_edge_kind(irg, src, pos, EDGE_KIND_NORMAL)) == NULL)
237                 edge = get_irn_edge_kind(irg, src, pos, EDGE_KIND_BLOCK);
238         return(edge);
239 }
240
241 /**
242  * Change the out count
243  *
244  * @param tgt  the edge target
245  * @param kind the kind of the edge
246  */
247 static inline void edge_change_cnt(ir_node *tgt, ir_edge_kind_t kind, int ofs) {
248         irn_edge_info_t *info = _get_irn_edge_info(tgt, kind);
249         info->out_count += ofs;
250
251 #if 0
252         assert(info->out_count >= 0);
253         if (info->out_count == 0 && kind == EDGE_KIND_NORMAL) {
254                 /* tgt lost it's last user */
255                 int i;
256
257                 for (i = get_irn_arity(tgt) - 1; i >= -1; --i) {
258                         ir_node *prev = get_irn_n(tgt, i);
259
260                         edges_notify_edge(tgt, i, NULL, prev, current_ir_graph);
261                 }
262                 for (i = get_irn_deps(tgt) - 1; i >= 0; --i) {
263                         ir_node *prev = get_irn_dep(tgt, i);
264
265                         edges_notify_edge_kind(tgt, i, NULL, prev, EDGE_KIND_DEP, current_ir_graph);
266
267                 }
268         }
269 #endif
270 }
271
272 /**
273  * Verify the edge list of a node, ie. ensure it's a loop:
274  * head -> e_1 -> ... -> e_n -> head
275  */
276 static inline void vrfy_list_head(ir_node *irn, ir_edge_kind_t kind) {
277         int                    err       = 0;
278         int                    num       = 0;
279         pset                   *lh_set   = pset_new_ptr(16);
280         const struct list_head *head     = _get_irn_outs_head(irn, kind);
281         const struct list_head *pos;
282
283         list_for_each(pos, head) {
284                 if (pset_find_ptr(lh_set, pos)) {
285                         const ir_edge_t *edge = list_entry(pos, ir_edge_t, list);
286
287                         ir_fprintf(stderr, "EDGE Verifier: edge list broken (self loop not to head) for %+F:\n", irn);
288                         fprintf(stderr, "- at list entry %d\n", num);
289                         if (edge->invalid)
290                                 fprintf(stderr, "- edge(%ld) is invalid\n", edge_get_id(edge));
291                         if (edge->src)
292                                 ir_fprintf(stderr, "- edge(%ld) %+F(%d)\n", edge_get_id(edge), edge->src, edge->pos);
293                         err = 1;
294                         break;
295                 }
296                 num++;
297                 pset_insert_ptr(lh_set, pos);
298         }
299
300         del_pset(lh_set);
301
302         assert(err == 0);
303 }
304
305 /* The edge from (src, pos) -> old_tgt is redirected to tgt */
306 void edges_notify_edge_kind(ir_node *src, int pos, ir_node *tgt,
307                             ir_node *old_tgt, ir_edge_kind_t kind,
308                             ir_graph *irg)
309 {
310         const char      *msg = "";
311         irg_edge_info_t *info;
312         ir_edgeset_t    *edges;
313         ir_edge_t        templ;
314         ir_edge_t       *edge;
315
316         assert(edges_activated_kind(irg, kind));
317
318         /*
319          * Only do something, if the old and new target differ.
320          */
321         if (tgt == old_tgt)
322                 return;
323
324         info  = _get_irg_edge_info(irg, kind);
325         edges = &info->edges;
326
327         /* Initialize the edge template to search in the set. */
328         templ.src = src;
329         templ.pos = pos;
330
331         /*
332          * If the target is NULL, the edge shall be deleted.
333          */
334         if (tgt == NULL) {
335                 /* search the edge in the set. */
336                 edge = ir_edgeset_find(edges, &templ);
337
338                 /* mark the edge invalid if it was found */
339                 if (edge) {
340                         msg = "deleting";
341                         list_del(&edge->list);
342                         ir_edgeset_remove(edges, edge);
343                         edge->invalid = 1;
344                         edge->pos = -2;
345                         edge->src = NULL;
346 #ifdef DEBUG_libfirm
347                         edge->edge_nr = -1;
348 #endif /* DEBUG_libfirm */
349                         edge_change_cnt(old_tgt, kind, -1);
350                 }
351
352                 /* If the edge was not found issue a warning on the debug stream */
353                 else {
354                         msg = "edge to delete not found!\n";
355                 }
356         } /* if */
357
358         /*
359          * The target is not NULL and the old target differs
360          * from the new target, the edge shall be moved (if the
361          * old target was != NULL) or added (if the old target was
362          * NULL).
363          */
364         else {
365                 struct list_head *head = _get_irn_outs_head(tgt, kind);
366
367                 assert(head->next && head->prev &&
368                                 "target list head must have been initialized");
369
370                 /* If the old target is not null, the edge is moved. */
371                 if (old_tgt) {
372                         edge = ir_edgeset_find(edges, &templ);
373                         assert(edge && "edge to redirect not found!");
374                         assert(! edge->invalid && "Invalid edge encountered");
375
376                         msg = "redirecting";
377
378                         list_move(&edge->list, head);
379                         edge_change_cnt(old_tgt, kind, -1);
380                 }
381
382                 /* The old target was null, thus, the edge is newly created. */
383                 else {
384                         ir_edge_t *new_edge;
385                         ir_edge_t *edge
386                                 = obstack_alloc(&info->edges_obst, EDGE_SIZE);
387                         memset(edge, 0, EDGE_SIZE);
388                         edge->src = src;
389                         edge->pos = pos;
390                         edge->kind = kind;
391                         DEBUG_ONLY(edge->src_nr = get_irn_node_nr(src));
392
393                         new_edge = ir_edgeset_insert(edges, edge);
394                         if(new_edge != edge) {
395                                 obstack_free(&info->edges_obst, edge);
396                         }
397
398                         assert(! edge->invalid && "Freshly inserted edge is invalid?!?");
399                         assert(edge->list.next == NULL && edge->list.prev == NULL &&
400                                 "New edge must not have list head initialized");
401
402                         msg = "adding";
403                         list_add(&edge->list, head);
404 #ifdef DEBUG_libfirm
405                         edge->edge_nr = ++last_edge_num;
406 #endif /* DEBUG_libfirm */
407                 }
408
409                 edge_change_cnt(tgt, kind, +1);
410         } /* else */
411
412 #ifndef DEBUG_libfirm
413         /* verify list heads */
414         if (edges_dbg) {
415                 if (tgt)
416                         vrfy_list_head(tgt, kind);
417                 if (old_tgt)
418                         vrfy_list_head(old_tgt, kind);
419         }
420 #endif
421
422         DBG((dbg, LEVEL_5, "announce out edge: %+F %d-> %+F(%+F): %s\n", src, pos, tgt, old_tgt, msg));
423 }
424
425 void edges_notify_edge(ir_node *src, int pos, ir_node *tgt, ir_node *old_tgt, ir_graph *irg)
426 {
427         if (edges_activated_kind(irg, EDGE_KIND_NORMAL)) {
428                 edges_notify_edge_kind(src, pos, tgt, old_tgt, EDGE_KIND_NORMAL, irg);
429         }
430
431         if (edges_activated_kind(irg, EDGE_KIND_BLOCK) && is_Block(src)) {
432                 if (pos == -1) {
433                         /* a MacroBlock edge: ignore it here */
434                 } else {
435                         ir_node *bl_old = old_tgt ? get_nodes_block(skip_Proj(old_tgt)) : NULL;
436                         ir_node *bl_tgt = NULL;
437
438                         if (tgt)
439                                 bl_tgt = is_Bad(tgt) ? tgt : get_nodes_block(skip_Proj(tgt));
440
441                         edges_notify_edge_kind(src, pos, bl_tgt, bl_old, EDGE_KIND_BLOCK, irg);
442                 }
443         }
444 }
445
446 /**
447  * Delete all in edges of a given kind from the node old.
448  *
449  * @param old   the node
450  * @param kind  the kind of edges to remove
451  * @param irg   the irg of the old node
452  */
453 static void edges_node_deleted_kind(ir_node *old, ir_edge_kind_t kind, ir_graph *irg)
454 {
455         int i, n;
456
457         if (!edges_activated_kind(irg, kind))
458                 return;
459
460         DBG((dbg, LEVEL_5, "node deleted (kind: %s): %+F\n", get_kind_str(kind), old));
461
462         foreach_tgt(old, i, n, kind) {
463                 ir_node *old_tgt = get_n(old, i, kind);
464                 edges_notify_edge_kind(old, i, NULL, old_tgt, kind, irg);
465         }
466 }
467
468 struct build_walker {
469         ir_graph       *irg;
470         ir_edge_kind_t kind;
471         bitset_t       *reachable;
472         unsigned       problem_found;
473 };
474
475 /**
476  * Post-Walker: notify all edges
477  */
478 static void build_edges_walker(ir_node *irn, void *data) {
479         struct build_walker   *w = data;
480         int                   i, n;
481         ir_edge_kind_t        kind = w->kind;
482         ir_graph              *irg = w->irg;
483         get_edge_src_n_func_t *get_n;
484
485         get_n = edge_kind_info[kind].get_n;
486         foreach_tgt(irn, i, n, kind) {
487                 ir_node *pred = get_n(irn, i, kind);
488                 edges_notify_edge_kind(irn, i, pred, NULL, kind, irg);
489         }
490 }
491
492 /**
493  * Pre-Walker: initializes the list-heads and set the out-count
494  * of all nodes to 0.
495  */
496 static void init_lh_walker(ir_node *irn, void *data) {
497         struct build_walker *w   = data;
498         ir_edge_kind_t      kind = w->kind;
499         list_head           *head = _get_irn_outs_head(irn, kind);
500         INIT_LIST_HEAD(head);
501         _get_irn_edge_info(irn, kind)->out_count = 0;
502 }
503
504 /**
505  * Pre-Walker: initializes the list-heads and set the out-count
506  * of all nodes to 0.
507  *
508  * Additionally touches DEP nodes, as they might be DEAD.
509  * THIS IS UGLY, but I don't find a better way until we
510  *
511  * a) ensure that dead nodes are not used as input
512  * b) it might be sufficient to add those stupid NO_REG nodes
513  * to the anchor
514  */
515 static void init_lh_walker_dep(ir_node *irn, void *data) {
516         struct build_walker *w   = data;
517         ir_edge_kind_t      kind = w->kind;
518         list_head           *head = _get_irn_outs_head(irn, kind);
519         int                 i;
520
521         INIT_LIST_HEAD(head);
522         _get_irn_edge_info(irn, kind)->out_count = 0;
523
524         for (i = get_irn_deps(irn) - 1; i >= 0; --i) {
525                 ir_node *dep = get_irn_dep(irn, i);
526
527                 head = _get_irn_outs_head(dep, kind);
528
529                 INIT_LIST_HEAD(head);
530                 _get_irn_edge_info(dep, kind)->out_count = 0;
531         }
532 }
533
534 typedef struct visitor_info_t {
535         irg_walk_func *visit;
536         void *data;
537 } visitor_info_t;
538
539 /**
540  * Visitor: initializes the list-heads and set the out-count
541  * of all nodes to 0 of nodes that are not seen so far.
542  */
543 static void visitor(ir_node *irn, void *data) {
544         visitor_info_t *info = data;
545
546         if (!irn_visited(irn)) {
547                 mark_irn_visited(irn);
548                 info->visit(irn, info->data);
549         }
550 }
551
552 /*
553  * Build the initial edge set.
554  * Beware, this is not a simple task because it suffers from two
555  * difficulties:
556  * - the anchor set allows access to Nodes that may not be reachable from
557  *   the End node
558  * - the identities add nodes to the "root set" that are not yet reachable
559  *   from End. However, after some transformations, the CSE may revival these
560  *   nodes
561  *
562  * These problems can be fixed using different strategies:
563  * - Add an age flag to every node. Whenever the edge of a node is older
564  *   then the current edge, invalidate the edges of this node.
565  *   While this would help for revivaled nodes, it increases memory and runtime.
566  * - Delete the identities set.
567  *   Solves the revival problem, but may increase the memory consumption, as
568  *   nodes cannot be revivaled at all.
569  * - Manually iterate over the identities root set. This did not consume more memory
570  *   but increase the computation time because the |identities| >= |V|
571  *
572  * Currently, we use the last option.
573  */
574 void edges_activate_kind(ir_graph *irg, ir_edge_kind_t kind)
575 {
576         struct build_walker w;
577         irg_edge_info_t     *info = _get_irg_edge_info(irg, kind);
578         visitor_info_t      visit;
579
580         w.irg  = irg;
581         w.kind = kind;
582
583         visit.data = &w;
584
585         info->activated = 1;
586         edges_init_graph_kind(irg, kind);
587         if (kind == EDGE_KIND_DEP) {
588                 irg_walk_anchors(irg, init_lh_walker_dep, NULL, &w);
589                 /* Argh: Dep nodes might be dead, so we MUST visit identities first */
590                 visit.visit = init_lh_walker_dep;
591                 visit_all_identities(irg, visitor, &visit);
592                 irg_walk_anchors(irg, NULL, build_edges_walker, &w);
593         } else {
594                 irg_walk_anchors(irg, init_lh_walker, build_edges_walker, &w);
595                 visit.visit = init_lh_walker;
596                 visit_all_identities(irg, visitor, &visit);
597         }
598 }
599
600 void edges_deactivate_kind(ir_graph *irg, ir_edge_kind_t kind)
601 {
602         irg_edge_info_t *info = _get_irg_edge_info(irg, kind);
603
604         info->activated = 0;
605         if (info->allocated) {
606                 obstack_free(&info->edges_obst, NULL);
607                 ir_edgeset_destroy(&info->edges);
608                 info->allocated = 0;
609         }
610 }
611
612 int (edges_activated_kind)(const ir_graph *irg, ir_edge_kind_t kind)
613 {
614         return _edges_activated_kind(irg, kind);
615 }
616
617
618 /**
619  * Reroute all use-edges from a node to another.
620  * @param from The node whose use-edges shall be withdrawn.
621  * @param to   The node to which all the use-edges of @p from shall be
622  *             sent to.
623  * @param irg  The graph.
624  */
625 void edges_reroute_kind(ir_node *from, ir_node *to, ir_edge_kind_t kind, ir_graph *irg)
626 {
627         set_edge_func_t *set_edge = edge_kind_info[kind].set_edge;
628
629         if(set_edge && edges_activated_kind(irg, kind)) {
630                 struct list_head *head = _get_irn_outs_head(from, kind);
631
632                 DBG((dbg, LEVEL_5, "reroute from %+F to %+F\n", from, to));
633
634                 while (head != head->next) {
635                         ir_edge_t *edge = list_entry(head->next, ir_edge_t, list);
636                         assert(edge->pos >= -1);
637                         set_edge(edge->src, edge->pos, to);
638                 }
639         }
640 }
641
642 static void verify_set_presence(ir_node *irn, void *data)
643 {
644         struct build_walker *w     = data;
645         ir_edgeset_t        *edges = &_get_irg_edge_info(w->irg, w->kind)->edges;
646         int i, n;
647
648         foreach_tgt(irn, i, n, w->kind) {
649                 ir_edge_t templ, *e;
650
651                 templ.src = irn;
652                 templ.pos = i;
653
654                 e = ir_edgeset_find(edges, &templ);
655                 if(e != NULL) {
656                         e->present = 1;
657                 } else {
658                         w->problem_found = 1;
659 #if 0
660                         ir_fprintf(stderr, "Edge Verifier: edge %+F,%d -> %+F (kind: \"%s\") is missing\n",
661                                 irn, i, get_n(irn, i, w->kind), get_kind_str(w->kind));
662 #endif
663                 }
664         }
665 }
666
667 static void verify_list_presence(ir_node *irn, void *data)
668 {
669         struct build_walker *w = data;
670         const ir_edge_t     *e;
671
672         bitset_set(w->reachable, get_irn_idx(irn));
673
674         /* check list heads */
675         vrfy_list_head(irn, w->kind);
676
677         foreach_out_edge_kind(irn, e, w->kind) {
678                 ir_node *tgt;
679
680                 if (w->kind == EDGE_KIND_NORMAL && get_irn_arity(e->src) <= e->pos) {
681                         w->problem_found = 1;
682 #if 0
683                         ir_fprintf(stderr, "Edge Verifier: edge(%ld) %+F -> %+F recorded at src position %d, but src has arity %d\n",
684                                 edge_get_id(e), e->src, irn, e->pos, get_irn_arity(e->src));
685 #endif
686                         continue;
687                 }
688
689                 tgt = get_n(e->src, e->pos, w->kind);
690
691                 if (irn != tgt) {
692                         w->problem_found = 1;
693 #if 0
694                         ir_fprintf(stderr, "Edge Verifier: edge(%ld) %+F,%d (kind \"%s\") is no out edge of %+F but of %+F\n",
695                                 edge_get_id(e), e->src, e->pos, get_kind_str(w->kind), irn, tgt);
696 #endif
697                 }
698         }
699 }
700
701 int edges_verify_kind(ir_graph *irg, ir_edge_kind_t kind)
702 {
703         struct build_walker w;
704         ir_edgeset_t        *edges = &_get_irg_edge_info(irg, kind)->edges;
705         ir_edge_t           *e;
706         ir_edgeset_iterator_t  iter;
707
708         w.irg           = irg;
709         w.kind          = kind;
710         w.reachable     = bitset_alloca(get_irg_last_idx(irg));
711         w.problem_found = 0;
712
713         /* Clear the present bit in all edges available. */
714         foreach_ir_edgeset(edges, e, iter) {
715                 e->present = 0;
716         }
717
718         irg_walk_graph(irg, verify_set_presence, verify_list_presence, &w);
719
720         /*
721          * Dump all edges which are not invalid and not present.
722          * These edges are superfluous and their presence in the
723          * edge set is wrong.
724          */
725         foreach_ir_edgeset(edges, e, iter) {
726                 if (! e->invalid && ! e->present && bitset_is_set(w.reachable, get_irn_idx(e->src))) {
727                         w.problem_found = 1;
728                         ir_fprintf(stderr, "Edge Verifier: edge(%ld) %+F,%d is superfluous\n", edge_get_id(e), e->src, e->pos);
729                 }
730         }
731
732         return w.problem_found;
733 }
734
735 #define IGNORE_NODE(irn) (is_Bad((irn)) || is_Block((irn)))
736
737 /**
738  * Clear link field of all nodes.
739  */
740 static void clear_links(ir_node *irn, void *env) {
741         struct build_walker *w  = env;
742         bitset_t            *bs;
743
744         if (IGNORE_NODE(irn)) {
745                 set_irn_link(irn, NULL);
746                 return;
747         }
748
749         bs = bitset_malloc(get_irg_last_idx(w->irg));
750         set_irn_link(irn, bs);
751 }
752
753 /**
754  * Increases count (stored in link field) for all operands of a node.
755  */
756 static void count_user(ir_node *irn, void *env) {
757         int i;
758         int first;
759         (void) env;
760
761         first = -1;
762         for (i = get_irn_arity(irn) - 1; i >= first; --i) {
763                 ir_node  *op = get_irn_n(irn, i);
764                 bitset_t *bs = get_irn_link(op);
765
766                 if (bs)
767                         bitset_set(bs, get_irn_idx(irn));
768         }
769 }
770
771 /**
772  * Verifies if collected count, number of edges in list and stored edge count are in sync.
773  */
774 static void verify_edge_counter(ir_node *irn, void *env) {
775         struct build_walker    *w = env;
776         bitset_t               *bs;
777         int                    list_cnt;
778         int                    ref_cnt;
779         int                    edge_cnt;
780         unsigned long          idx;
781         const struct list_head *head;
782         const struct list_head *pos;
783
784         if (IGNORE_NODE(irn))
785                 return;
786
787         bs       = get_irn_link(irn);
788         list_cnt = 0;
789         ref_cnt  = 0;
790         edge_cnt = _get_irn_edge_info(irn, EDGE_KIND_NORMAL)->out_count;
791         head     = _get_irn_outs_head(irn, EDGE_KIND_NORMAL);
792
793         /* We can iterate safely here, list heads have already been verified. */
794         list_for_each(pos, head) {
795                 ++list_cnt;
796         }
797
798         /* check all nodes that reference us and count edges that point number
799          * of ins that actually point to us */
800         ref_cnt = 0;
801         bitset_foreach(bs, idx) {
802                 int i, arity;
803                 ir_node *src = get_idx_irn(w->irg, idx);
804
805                 arity = get_irn_arity(src);
806                 for (i = 0; i < arity; ++i) {
807                         ir_node *in = get_irn_n(src, i);
808                         if (in == irn)
809                                 ++ref_cnt;
810                 }
811         }
812
813         if (edge_cnt != list_cnt) {
814                 w->problem_found = 1;
815                 ir_fprintf(stderr, "Edge Verifier: edge count is %d, but %d edge(s) are recorded in list at %+F\n",
816                         edge_cnt, list_cnt, irn);
817         }
818
819         if (ref_cnt != list_cnt) {
820                 w->problem_found = 1;
821                 ir_fprintf(stderr, "Edge Verifier: %+F reachable by %d node(s), but the list contains %d edge(s)\n",
822                         irn, ref_cnt, list_cnt);
823
824                 /* Matze: buggy if a node has multiple ins pointing at irn */
825 #if 0
826                 list_for_each(pos, head) {
827                         ir_edge_t *edge = list_entry(pos, ir_edge_t, list);
828                         bitset_flip(bs, get_irn_idx(edge->src));
829                 }
830
831                 if (ref_cnt < list_cnt)
832                         fprintf(stderr,"               following nodes are recorded in list, but not as user:\n");
833                 else
834                         fprintf(stderr,"               following nodes are user, but not recorded in list:\n");
835
836                 fprintf(stderr,"              ");
837                 bitset_foreach(bs, idx) {
838                         ir_node *src = get_idx_irn(w->irg, idx);
839                         ir_fprintf(stderr, " %+F", src);
840                 }
841                 fprintf(stderr, "\n");
842 #endif
843         }
844
845         bitset_free(bs);
846 }
847
848 /**
849  * Verifies the out edges of an irg.
850  */
851 int edges_verify(ir_graph *irg) {
852         struct build_walker w;
853         int    problem_found = 0;
854
855         /* verify normal edges only */
856         problem_found  = edges_verify_kind(irg, EDGE_KIND_NORMAL);
857
858         w.irg           = irg;
859         w.kind          = EDGE_KIND_NORMAL;
860         w.problem_found = 0;
861
862         /* verify counter */
863         irg_walk_anchors(irg, clear_links, count_user, &w);
864         irg_walk_anchors(irg, NULL, verify_edge_counter, &w);
865
866         return problem_found ? 1 : w.problem_found;
867 }
868
869 void init_edges(void) {
870         FIRM_DBG_REGISTER(dbg, DBG_EDGES);
871         /* firm_dbg_set_mask(dbg, -1); */
872 }
873
874 void edges_init_dbg(int do_dbg) {
875         edges_dbg = do_dbg;
876 }
877
878 void edges_activate(ir_graph *irg) {
879         edges_activate_kind(irg, EDGE_KIND_NORMAL);
880         edges_activate_kind(irg, EDGE_KIND_BLOCK);
881         if (get_irg_phase_state(irg) == phase_backend)
882                 edges_activate_kind(irg, EDGE_KIND_DEP);
883 }
884
885 void edges_deactivate(ir_graph *irg) {
886         if (get_irg_phase_state(irg) == phase_backend)
887                 edges_deactivate_kind(irg, EDGE_KIND_DEP);
888         edges_deactivate_kind(irg, EDGE_KIND_BLOCK);
889         edges_deactivate_kind(irg, EDGE_KIND_NORMAL);
890 }
891
892 int edges_assure(ir_graph *irg) {
893         int activated = edges_activated(irg);
894
895         if (!activated)
896                 edges_activate(irg);
897
898         return activated;
899 }
900
901 int edges_assure_kind(ir_graph *irg, ir_edge_kind_t kind) {
902         int activated = edges_activated_kind(irg, kind);
903
904         if (!activated)
905                 edges_activate_kind(irg, kind);
906
907         return activated;
908 }
909
910 void edges_node_deleted(ir_node *irn, ir_graph *irg) {
911         edges_node_deleted_kind(irn, EDGE_KIND_NORMAL, irg);
912         edges_node_deleted_kind(irn, EDGE_KIND_BLOCK, irg);
913 }
914
915
916 const ir_edge_t *(get_irn_out_edge_first_kind)(const ir_node *irn, ir_edge_kind_t kind) {
917         return _get_irn_out_edge_first_kind(irn, kind);
918 }
919
920 const ir_edge_t *(get_irn_out_edge_next)(const ir_node *irn, const ir_edge_t *last) {
921         return _get_irn_out_edge_next(irn, last);
922 }
923
924 ir_node *(get_edge_src_irn)(const ir_edge_t *edge) {
925         return _get_edge_src_irn(edge);
926 }
927
928 int (get_edge_src_pos)(const ir_edge_t *edge) {
929         return _get_edge_src_pos(edge);
930 }
931
932 int (get_irn_n_edges_kind)(const ir_node *irn, ir_edge_kind_t kind) {
933         return _get_irn_n_edges_kind(irn, kind);
934 }
935
936 void dump_all_out_edges(ir_node *irn) {
937         int i;
938         for (i = 0; i < EDGE_KIND_LAST; ++i) {
939                 const ir_edge_t *edge;
940
941                 printf("kind \"%s\"\n", get_kind_str(i));
942                 foreach_out_edge_kind(irn, edge, i) {
943                         ir_printf("\t%+F(%d)\n", edge->src, edge->pos);
944                 }
945         }
946 }
947
948 static void irg_block_edges_walk2(ir_node *bl,
949                                 irg_walk_func *pre, irg_walk_func *post,
950                                 void *env) {
951         const ir_edge_t *edge, *next;
952
953         if (!Block_block_visited(bl)) {
954                 mark_Block_block_visited(bl);
955
956                 if (pre)
957                         pre(bl, env);
958
959                 foreach_out_edge_kind_safe(bl, edge, next, EDGE_KIND_BLOCK) {
960                         /* find the corresponding successor block. */
961                         ir_node *pred = get_edge_src_irn(edge);
962                         irg_block_edges_walk2(pred, pre, post, env);
963                 }
964
965                 if (post)
966                         post(bl, env);
967         }
968 }
969
970 void irg_block_edges_walk(ir_node *node,
971                           irg_walk_func *pre, irg_walk_func *post,
972                           void *env) {
973
974         assert(edges_activated(current_ir_graph));
975         assert(is_Block(node));
976
977         ir_reserve_resources(current_ir_graph, IR_RESOURCE_BLOCK_VISITED);
978
979         inc_irg_block_visited(current_ir_graph);
980         irg_block_edges_walk2(node, pre, post, env);
981
982         ir_free_resources(current_ir_graph, IR_RESOURCE_BLOCK_VISITED);
983 }