fix for my last commit
[libfirm] / ir / opt / loop.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  * @author   Christian Helmer
23  * @brief    loop inversion and loop unrolling, loop peeling
24  *
25  * @version  $Id$
26  */
27 #include "config.h"
28
29 #include "irnode.h"
30 #include "debug.h"
31
32 #include "ircons.h"
33 #include "irgopt.h"
34 #include "irgmod.h"
35 #include "irgwalk.h"
36 #include "irouts.h"
37 #include "iredges.h"
38 #include "irtools.h"
39 #include "array_t.h"    /* automatic array */
40 #include "beutil.h"             /* get_block */
41 #include "irloop_t.h"   /* set_irn_loop*/
42 #include "irpass.h"
43
44 DEBUG_ONLY(static firm_dbg_module_t *dbg);
45
46 /**
47  * Convenience macro for iterating over every phi node of the given block.
48  * Requires phi list per block.
49  */
50 #define for_each_phi(block, phi) \
51         for ( (phi) = get_Block_phis( (block) ); (phi) ; (phi) = get_Phi_next( (phi) ) )
52
53 /* current loop */
54 static ir_loop *cur_loop;
55
56 /* abortable walker function */
57 typedef unsigned irg_walk_func_abortable(ir_node *, void *);
58
59 /* condition for walking a node during a copy_walk */
60 typedef unsigned walker_condition(ir_node *);
61
62 /* node and position of a predecessor */
63 typedef struct out_edges {
64         ir_node *node;
65         int pred_irn_n;
66 } out_edge;
67
68 /* access complex values through the nodes links */
69 typedef struct node_info {
70         unsigned invariant:1;
71         ir_node *copy;
72         ir_node *link;                                  /* temporary links for ssa creation */
73         ir_node **ins;                                  /* ins for phi nodes, during rewiring of blocks */
74         unsigned done;
75         struct node_info *freelistnext; /* linked list to free all node_infos */
76 } node_info;
77
78 static node_info *link_node_state_list;         /* head of the linked list to free all node_infos */
79
80 static out_edge *cur_loop_outs;                         /* A walker may start visiting the current loop with these nodes. */
81 static out_edge *cur_head_outs;                         /* A walker may start visiting the cur head with these nodes. */
82
83 static ir_node *loop_cf_head = NULL;                            /* Loop head node */
84 static unsigned loop_cf_head_valid = 1;                         /* A loop may have one head, otherwise we do not touch it. */
85
86 ir_node **loops;
87
88 /* Inverted head */
89 static ir_node *loop_inv_head = NULL;
90 /* Peeled head */
91 static ir_node *loop_peeled_head = NULL;
92
93 /* Loop analysis informations */
94 typedef struct loop_info_t {
95         unsigned blocks;                        /* number of blocks in the loop */
96         unsigned calls;                         /* number of calls */
97         unsigned loads;                         /* number of load nodes */
98         unsigned outs;                          /* outs without keepalives */
99 #if 0
100         unsigned invariant_loads;
101         unsigned stores;                        /* number of store nodes */
102         unsigned opnodes_n;                     /* nodes that probably result in an instruction */
103         unsigned do_invariant_opt;
104 #endif
105 } loop_info_t;
106
107 /* Information about the current loop */
108 static loop_info_t loop_info;
109
110 /* A walker may start visiting a condition chain with these nodes. */
111 static out_edge *cond_chain_entries;
112
113 /* Number of unrolling */
114 int unroll_times;
115
116 static unsigned head_inversion_node_count;
117 static unsigned inversion_head_node_limit;
118 static unsigned head_inversion_block_count;
119
120 static unsigned enable_peeling;
121 static unsigned enable_inversion;
122 static unsigned enable_unrolling;
123
124 /**
125  *
126  * ============= AUXILIARY FUNCTIONS =====================================
127  */
128
129
130 /**
131  * Creates object on the heap, and adds it to a linked list to free it later.
132  */
133 static node_info *new_node_info(void)
134 {
135         node_info *l = XMALLOCZ(node_info);
136         l->freelistnext = link_node_state_list;
137         link_node_state_list = l;
138         l->copy = NULL;
139         l->invariant = 0;
140         return l;
141 }
142
143 static node_info *get_node_info(ir_node *n)
144 {
145         return ((node_info *)get_irn_link(n));
146 }
147
148 /* Allocates a node_info struct for the given node. For use with a walker. */
149 static void alloc_node_info(ir_node *node, void *env)
150 {
151         node_info *state;
152         (void) env;
153         state = new_node_info();
154         set_irn_link(node, (void *)state);
155 }
156
157 static void free_node_info(void)
158 {
159         int a = 0;
160         node_info *n;
161         n = link_node_state_list;
162         while (n) {
163                 node_info *next = n->freelistnext;
164                 ++a;
165                 xfree(n);
166                 n = next;
167         }
168         link_node_state_list = NULL;
169 }
170
171 /**
172  * Use the linked list to reset the reused values of all node_infos
173  * Reset in particular the copy attribute as copy_walk uses it to determine a present copy
174  */
175 static void reset_node_infos(void)
176 {
177         node_info *next;
178         next = link_node_state_list;
179         while (next->freelistnext) {
180                 node_info *cur = next;
181                 next = cur->freelistnext;
182                 cur->copy = NULL;
183                 cur->ins = NULL;
184                 cur->link = NULL;
185         }
186 }
187
188 /* Returns the nodes node_info link. */
189 static ir_node *get_link(ir_node *n)
190 {
191         return ((node_info *)get_irn_link(n))->link;
192 }
193
194 /* Sets the nodes node_info link. */
195 static void set_link(ir_node *n, ir_node *link)
196 {
197         ((node_info *)get_irn_link(n))->link = link;
198 }
199
200 /* Returns a nodes copy. */
201 static ir_node *get_copy(ir_node *n)
202 {
203         return ((node_info *)get_irn_link(n))->copy;
204 }
205
206 /* Sets a nodes copy. */
207 static void set_copy(ir_node *n, ir_node *copy)
208 {
209         ((node_info *)get_irn_link(n) )->copy = copy;
210 }
211
212 /**
213  * Convenience macro for iterating over every copy in a linked list
214  * of copies.
215  */
216 #define for_each_copy(node) \
217         for ( ; (node) ; (node) = get_copy(node))
218
219 /**
220  * Convenience macro for iterating over every copy in 2 linked lists
221  * of copies in parallel.
222  */
223 #define for_each_copy2(high1, low1, high2, low2) \
224         for ( ; (low1) && (low2); (high1) = (low1), (low1) = get_copy(low1), \
225                                                         (high2) = (low2), (low2) = get_copy(low2))
226
227 /*
228  * Returns 0 if the node or block is not in cur_loop.
229  */
230 static unsigned is_in_loop(ir_node *node)
231 {
232         return (get_irn_loop(get_block(node)) == cur_loop);
233 }
234
235 /* Returns if the given be is an alien edge. This is the case when the pred is not in the loop. */
236 static unsigned is_alien_edge(ir_node *n, int i)
237 {
238         return(!is_in_loop(get_irn_n(n, i)));
239 }
240
241 /* used for block walker */
242 static void reset_block_mark(ir_node *node, void * env)
243 {
244         (void) env;
245
246         if (is_Block(node))
247                 set_Block_mark(node, 0);
248 }
249
250 static unsigned is_nodesblock_marked(ir_node* node)
251 {
252         return (get_Block_mark(get_block(node)));
253 }
254
255 /* Returns the number of blocks in a loop. */
256 int get_loop_n_blocks(ir_loop *loop)
257 {
258         int elements, e;
259         int blocks = 0;
260         elements = get_loop_n_elements(loop);
261
262         for (e=0; e<elements; e++) {
263                 loop_element elem = get_loop_element(loop, e);
264                 if (is_ir_node(elem.kind) && is_Block(elem.node))
265                         ++blocks;
266         }
267         return blocks;
268 }
269
270 /**
271  * Add newpred at position pos to node and also add the corresponding value to the phis.
272  * Requires block phi list.
273  */
274 static int duplicate_preds(ir_node* block, unsigned pos, ir_node* newpred)
275 {
276         ir_node **ins;
277         /*int *is_be;*/
278         ir_node *phi;
279         int block_arity;
280         int i;
281
282         assert(is_Block(block) && "duplicate_preds may be called for blocks only");
283
284         DB((dbg, LEVEL_5, "duplicate_preds(node %N, pos %d, newpred %N)\n", block, pos, newpred));
285
286         block_arity = get_irn_arity(block);
287
288         NEW_ARR_A(ir_node*, ins, block_arity + 1);
289
290         for (i = 0; i < block_arity; ++i) {
291                 ins[i] = get_irn_n(block, i);
292         }
293         ins[block_arity] = newpred;
294
295         set_irn_in(block, block_arity + 1, ins);
296
297         /* LDBG 1 */
298 #if 1
299         for_each_phi(block, phi) {
300                 int phi_arity = get_irn_arity(phi);
301                 DB((dbg, LEVEL_5, "duplicate_preds: fixing phi %N\n", phi));
302
303                 NEW_ARR_A(ir_node *, ins, block_arity + 1);
304                 for (i = 0; i < phi_arity; ++i) {
305                         DB((dbg, LEVEL_5, "pos %N\n", get_irn_n(phi, i)));
306                         ins[i] = get_irn_n(phi, i);
307                 }
308                 ins[block_arity] = get_copy(get_irn_n(phi, pos));
309                 set_irn_in(phi, block_arity + 1, ins);
310         }
311 #endif
312         return block_arity;
313 }
314
315 /**
316  * Finds loop head and loop_info.
317  */
318 static void get_loop_info(ir_node *node, void *env)
319 {
320         unsigned node_in_loop, pred_in_loop;
321         int i, arity;
322         (void) env;
323
324         arity = get_irn_arity(node);
325         for (i = 0; i < arity; i++) {
326                 ir_node *pred = get_irn_n(node, i);
327
328                 pred_in_loop = is_in_loop(pred);
329                 node_in_loop = is_in_loop(node);
330
331                 /* collect some loop information */
332                 if (node_in_loop) {
333                         if (is_Call(node))
334                                 ++loop_info.calls;
335                 }
336
337                 /* Find the loops head/the blocks with cfpred outside of the loop */
338                 if (is_Block(node) && node_in_loop && !pred_in_loop && loop_cf_head_valid) {
339                         ir_node *cfgpred = get_Block_cfgpred(node, i);
340
341                         if (!is_in_loop(cfgpred)) {
342                                 DB((dbg, LEVEL_5, "potential head %+F because inloop and pred %+F not inloop\n", node, pred));
343                                 /* another head? We do not touch this. */
344                                 if (loop_cf_head && loop_cf_head != node) {
345                                         loop_cf_head_valid = 0;
346                                 } else {
347                                         loop_cf_head = node;
348                                 }
349                         }
350                 }
351         }
352 }
353
354 /* Adds all nodes pointing into the loop to loop_entries and also finds the loops head */
355 static void get_loop_outs(ir_node *node, void *env)
356 {
357         unsigned node_in_loop, pred_in_loop;
358         int i, arity;
359         (void) env;
360
361         arity = get_irn_arity(node);
362         for (i = 0; i < arity; ++i) {
363                 ir_node *pred = get_irn_n(node, i);
364
365                 pred_in_loop = is_in_loop(pred);
366                 node_in_loop = is_in_loop(node);
367
368                 if (pred_in_loop && !node_in_loop) {
369                         out_edge entry;
370                         entry.node = node;
371                         entry.pred_irn_n = i;
372                         ARR_APP1(out_edge, cur_loop_outs, entry);
373                 }
374         }
375 }
376
377 static ir_node *ssa_second_def;
378 static ir_node *ssa_second_def_block;
379
380 /**
381  * Walks the graph bottom up, searching for definitions and creates phis.
382  */
383 static ir_node *search_def_and_create_phis(ir_node *block, ir_mode *mode)
384 {
385         int i;
386         int n_cfgpreds;
387         ir_graph *irg;
388         ir_node *phi;
389         ir_node **in;
390
391         DB((dbg, LEVEL_5, "ssa search_def_and_create_phis: block %N\n", block));
392
393         /* Prevents creation of phi that would be bad anyway.
394          * Dead and bad blocks. */
395         if (get_irn_arity(block) < 1 || is_Bad(block))
396                 return new_Bad();
397
398         if (block == ssa_second_def_block) {
399                 DB((dbg, LEVEL_5, "ssa found second definition: use second def %N\n", ssa_second_def));
400                 return ssa_second_def;
401         }
402
403         /* already processed this block? */
404         if (irn_visited(block)) {
405                 ir_node *value = get_link(block);
406                 DB((dbg, LEVEL_5, "ssa already visited: use linked %N\n", value));
407                 return value;
408         }
409
410         irg = get_irn_irg(block);
411         assert(block != get_irg_start_block(irg));
412
413         /* a Block with only 1 predecessor needs no Phi */
414         n_cfgpreds = get_Block_n_cfgpreds(block);
415         if (n_cfgpreds == 1) {
416                 ir_node *pred_block = get_Block_cfgpred_block(block, 0);
417                 ir_node *value;
418
419                 DB((dbg, LEVEL_5, "ssa 1 pred: walk pred %N\n", pred_block));
420
421                 value = search_def_and_create_phis(pred_block, mode);
422                 set_link(block, value);
423                 mark_irn_visited(block);
424
425                 return value;
426         }
427
428         /* create a new Phi */
429         NEW_ARR_A(ir_node*, in, n_cfgpreds);
430         for (i = 0; i < n_cfgpreds; ++i)
431                 in[i] = new_Unknown(mode);
432
433         phi = new_r_Phi(block, n_cfgpreds, in, mode);
434
435         /* Important: always keep block phi list up to date. */
436         add_Block_phi(block, phi);
437         /* EVERY node is assumed to have a node_info linked. */
438         alloc_node_info(phi, NULL);
439
440         DB((dbg, LEVEL_5, "ssa phi creation: link new phi %N to block %N\n", phi, block));
441
442         set_link(block, phi);
443         mark_irn_visited(block);
444
445         /* set Phi predecessors */
446         for (i = 0; i < n_cfgpreds; ++i) {
447                 ir_node *pred_val;
448                 ir_node *pred_block = get_Block_cfgpred_block(block, i);
449                 assert(pred_block != NULL);
450                 pred_val = search_def_and_create_phis(pred_block, mode);
451                 assert(pred_val != NULL);
452
453                 DB((dbg, LEVEL_5, "ssa phi pred:phi %N, pred %N\n", phi, pred_val));
454                 set_irn_n(phi, i, pred_val);
455         }
456         return phi;
457 }
458
459 /**
460  * Given a set of values this function constructs SSA-form for the users of the
461  * first value (the users are determined through the out-edges of the value).
462  * Works without using the dominance tree.
463  */
464 static void construct_ssa(ir_node *orig_block, ir_node *orig_val,
465                           ir_node *second_block, ir_node *second_val)
466 {
467         ir_graph *irg;
468         ir_mode *mode;
469         const ir_edge_t *edge;
470         const ir_edge_t *next;
471
472         assert(orig_block && orig_val && second_block && second_val &&
473                         "no parameter of construct_ssa may be NULL");
474
475         /* no need to do anything */
476         if (orig_val == second_val)
477                 return;
478
479         irg = get_irn_irg(orig_val);
480
481         ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
482         inc_irg_visited(irg);
483
484         mode = get_irn_mode(orig_val);
485         set_link(orig_block, orig_val);
486         mark_irn_visited(orig_block);
487
488         ssa_second_def_block = second_block;
489         ssa_second_def       = second_val;
490
491         /* Only fix the users of the first, i.e. the original node */
492         foreach_out_edge_safe(orig_val, edge, next) {
493                 ir_node *user = get_edge_src_irn(edge);
494                 int j = get_edge_src_pos(edge);
495                 ir_node *user_block = get_nodes_block(user);
496                 ir_node *newval;
497
498                 /* ignore keeps */
499                 if (is_End(user))
500                         continue;
501
502                 DB((dbg, LEVEL_5, "original user %N\n", user));
503
504                 if (is_Phi(user)) {
505                         ir_node *pred_block = get_Block_cfgpred_block(user_block, j);
506                         newval = search_def_and_create_phis(pred_block, mode);
507                 } else {
508                         newval = search_def_and_create_phis(user_block, mode);
509                 }
510
511                 /* If we get a bad node the user keeps the original in. No second definition needed. */
512                 if (newval != user && !is_Bad(newval))
513                         set_irn_n(user, j, newval);
514         }
515
516         ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
517 }
518
519 /*
520  * Construct SSA for def and all of its copies.
521  */
522 static void construct_ssa_n(ir_node *def, ir_node *user)
523 {
524         ir_graph *irg;
525         ir_mode *mode;
526         ir_node *iter = def;
527         const ir_edge_t *edge;
528         const ir_edge_t *next;
529         irg = get_irn_irg(def);
530
531         ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
532         inc_irg_visited(irg);
533
534         mode = get_irn_mode(def);
535
536         for_each_copy(iter) {
537                 set_link(get_nodes_block(iter), iter);
538                 mark_irn_visited(get_nodes_block(iter));
539
540                 DB((dbg, LEVEL_5, "ssa_n:  Link def %N to block %N\n",
541                                                                         iter, get_nodes_block(iter)));
542         }
543
544         /* Need to search the outs, because we need the in-pos on the user node. */
545         foreach_out_edge_safe(def, edge, next) {
546                 ir_node *edge_user = get_edge_src_irn(edge);
547                 int edge_src = get_edge_src_pos(edge);
548                 ir_node *user_block = get_nodes_block(user);
549                 ir_node *newval;
550
551                 if (edge_user != user)
552                         continue;
553
554                 if (is_Phi(user)) {
555                         ir_node *pred_block = get_Block_cfgpred_block(user_block, edge_src);
556                         newval = search_def_and_create_phis(pred_block, mode);
557                 } else {
558                         newval = search_def_and_create_phis(user_block, mode);
559                 }
560
561                 if (newval != user && !is_Bad(newval))
562                         set_irn_n(user, edge_src, newval);
563         }
564
565         ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
566 }
567
568 /**
569  * Construct SSA for all definitions in arr.
570  */
571 void construct_ssa_foreach(ir_node **arr, int arr_n)
572 {
573         int i;
574         for (i = 0; i < arr_n ; ++i) {
575                 ir_node *cppred, *block, *cpblock, *pred;
576
577                 pred = arr[i];
578                 cppred = get_copy(pred);
579                 block = get_nodes_block(pred);
580                 cpblock = get_nodes_block(cppred);
581                 construct_ssa(block, pred, cpblock, cppred);
582         }
583 }
584
585 /* get the number of backedges without alien bes */
586 static int get_backedge_n(ir_node *loophead, unsigned with_alien)
587 {
588         int i;
589         int be_n = 0;
590         int arity = get_irn_arity(loophead);
591         for (i = 0; i < arity; ++i) {
592                 ir_node *pred = get_irn_n(loophead, i);
593                 if (is_backedge(loophead, i) && (with_alien || is_in_loop(pred)))
594                         ++be_n;
595         }
596         return be_n;
597 }
598
599 /**
600  * Rewires the heads after peeling.
601  */
602 static void peel_fix_heads(void)
603 {
604         ir_node **loopheadnins, **peelheadnins;
605         ir_node *loophead = loop_cf_head;
606         ir_node *peelhead = get_copy(loophead);
607
608         int headarity = get_irn_arity(loophead);
609         ir_node *phi;
610         int i;
611
612         int lheadin_c = 0;
613         int pheadin_c = 0;
614
615         int backedges_n = get_backedge_n(loophead, 0);
616
617         int lhead_arity = 2 * backedges_n;
618         int phead_arity = headarity - backedges_n;
619
620         /* new in arrays */
621         NEW_ARR_A(ir_node *, loopheadnins, lhead_arity );
622         NEW_ARR_A(ir_node *, peelheadnins, phead_arity );
623
624         for_each_phi(loophead, phi) {
625                 NEW_ARR_A(ir_node *, get_node_info(phi)->ins, lhead_arity);
626         }
627         for_each_phi(peelhead, phi) {
628                 NEW_ARR_A(ir_node *, get_node_info(phi)->ins, phead_arity);
629         }
630
631         for (i = 0; i < headarity; i++)
632         {
633                 ir_node *orgjmp = get_irn_n(loophead, i);
634                 ir_node *copyjmp = get_copy(orgjmp);
635
636                 /**
637                  * Rewire the head blocks ins and their phi ins.
638                  * Requires phi list per block.
639                  */
640                 if (is_backedge(loophead, i) && !is_alien_edge(loophead, i)) {
641                         loopheadnins[lheadin_c] = orgjmp;
642                         for_each_phi(loophead, phi) {
643                                 get_node_info( phi )->ins[lheadin_c] =  get_irn_n( phi, i) ;
644                         }
645                         ++lheadin_c;
646
647                         /* former bes of the peeled code origin now from the loophead */
648                         loopheadnins[lheadin_c] = copyjmp;
649
650                         /* get_irn_n( get_copy_of(phi), i ) <!=> get_copy_of( get_irn_n( phi, i) )
651                          * Order is crucial! Predecessors outside of the loop are non existent.
652                          * The copy (cloned with its ins!) has pred i,
653                          * but phis pred i might not have a copy of itself.
654                          */
655                         for_each_phi(loophead, phi) {
656                                 get_node_info( phi )->ins[lheadin_c] =  get_irn_n( get_copy(phi), i) ;
657                         }
658                         ++lheadin_c;
659                 } else {
660                         peelheadnins[pheadin_c] = orgjmp;
661                         for_each_phi(peelhead, phi) {
662                                 get_node_info( phi )->ins[pheadin_c] = get_irn_n(phi, i);
663                         }
664                         ++pheadin_c;
665                 }
666         }/* for */
667
668         assert(pheadin_c == ARR_LEN(peelheadnins) &&
669                         lheadin_c == ARR_LEN(loopheadnins) &&
670                         "the constructed head arities do not match the predefined arities");
671
672         /* assign the ins to the nodes */
673         set_irn_in(loophead, ARR_LEN(loopheadnins), loopheadnins);
674         set_irn_in(peelhead, ARR_LEN(peelheadnins), peelheadnins);
675
676         for_each_phi(loophead, phi) {
677                 ir_node **ins = get_node_info( phi )->ins;
678                 set_irn_in(phi, lhead_arity, ins);
679         }
680
681         for_each_phi(peelhead, phi) {
682                 ir_node **ins = get_node_info( phi )->ins;
683                 set_irn_in(phi, phead_arity, ins);
684         }
685 }
686
687 /**
688  * Create a raw copy (ins are still the old ones) of the given node.
689  * We rely on copies to be NOT visited.
690  */
691 static ir_node *rawcopy_node(ir_node *node)
692 {
693         int i, arity;
694         ir_node *cp;
695         node_info *cpstate;
696
697         cp = exact_copy(node);
698
699         arity = get_irn_arity(node);
700
701         for (i = 0; i < arity; ++i) {
702                 if (is_backedge(node, i))
703                         set_backedge(cp, i);
704         }
705
706         set_copy(node, cp);
707         cpstate = new_node_info();
708         set_irn_link(cp, cpstate);
709
710
711         if (is_Block(cp)) {
712                 /* TODO
713                  * exact_copy already sets Macroblock.
714                  * Why should we do this anyway? */
715                 set_Block_MacroBlock(cp, cp);
716         }
717
718         return cp;
719 }
720
721 /**
722  * This walker copies all walked nodes.
723  * If the walk_condition is true for a node, it is walked.
724  * All nodes node_info->copy attributes have to be NULL prior to every walk.
725  */
726 static void copy_walk(ir_node *node, walker_condition *walk_condition, ir_loop *set_loop)
727 {
728         int i;
729         int arity;
730         ir_node *cp;
731         ir_node **cpin;
732         ir_graph *irg = current_ir_graph;
733         node_info *node_info = get_node_info(node);
734
735         /**
736          * break condition and cycle resolver, creating temporary node copies
737          */
738         if (get_irn_visited(node) >= get_irg_visited(irg)) {
739                 /* Here we rely on nodestate's copy being initialized with NULL */
740                 DB((dbg, LEVEL_5, "copy_walk: We have already visited %N\n", node));
741                 if (node_info->copy == NULL) {
742                         cp = rawcopy_node(node);
743                         DB((dbg, LEVEL_5, "The TEMP copy of %N is created %N\n", node, cp));
744                 }
745                 return;
746         }
747
748         /* Walk */
749         mark_irn_visited(node);
750
751         if (!is_Block(node)) {
752                 ir_node *pred = get_nodes_block(node);
753                 if (walk_condition(pred))
754                         DB((dbg, LEVEL_5, "walk block %N\n", pred));
755                         copy_walk(pred, walk_condition, set_loop);
756         }
757
758         arity = get_irn_arity(node);
759
760         NEW_ARR_A(ir_node *, cpin, arity);
761
762         for (i = 0; i < arity; ++i) {
763                 ir_node *pred = get_irn_n(node, i);
764
765                 if (walk_condition(pred)) {
766                         DB((dbg, LEVEL_5, "walk node %N\n", pred));
767                         copy_walk(pred, walk_condition, set_loop);
768                         cpin[i] = get_copy(pred);
769                         DB((dbg, LEVEL_5, "copy of %N gets new in %N which is copy of %N\n",
770                                 node, get_copy(pred), pred));
771                 } else {
772                         cpin[i] = pred;
773                 }
774         }
775
776         /* copy node / finalize temp node */
777         if (node_info->copy == NULL) {
778                 /* No temporary copy existent */
779                 cp = rawcopy_node(node);
780                 DB((dbg, LEVEL_5, "The FINAL copy of %N is CREATED %N\n", node, cp));
781         } else {
782                 /* temporary copy is existent but without correct ins */
783                 cp = get_copy(node);
784                 DB((dbg, LEVEL_5, "The FINAL copy of %N is EXISTENT %N\n", node, cp));
785         }
786
787         if (!is_Block(node)) {
788                 ir_node *cpblock = get_copy(get_nodes_block(node));
789
790                 set_nodes_block(cp, cpblock );
791                 if (is_Phi(cp))
792                         add_Block_phi(cpblock, cp);
793         }
794
795         set_irn_loop(cp, set_loop);
796         set_irn_in(cp, ARR_LEN(cpin), cpin);
797 }
798
799 /**
800  * Loop peeling, and fix the cf for the loop entry nodes, which have now more preds
801  */
802 static void peel(out_edge *loop_outs)
803 {
804         int i;
805         ir_node **entry_buffer;
806         int entry_c = 0;
807
808         ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
809
810         NEW_ARR_A(ir_node *, entry_buffer, ARR_LEN(loop_outs));
811
812         /* duplicate loop walk */
813         inc_irg_visited(current_ir_graph);
814
815         for (i = 0; i < ARR_LEN(loop_outs); i++) {
816                 out_edge entry = loop_outs[i];
817                 ir_node *node = entry.node;
818                 ir_node *pred = get_irn_n(entry.node, entry.pred_irn_n);
819
820                 if (is_Block(node)) {
821                         copy_walk(pred, is_in_loop, NULL);
822                         duplicate_preds(node, entry.pred_irn_n, get_copy(pred) );
823                 } else {
824                         copy_walk(pred, is_in_loop, NULL);
825                         /* leave out keepalives */
826                         if (!is_End(node)) {
827                                 /* Node is user of a value defined inside the loop.
828                                  * We'll need a phi since we duplicated the loop. */
829                                 /* Cannot construct_ssa here, because it needs another walker. */
830                                 entry_buffer[entry_c] = pred;
831                                 ++entry_c;
832                         }
833                 }
834         }
835
836         ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
837
838         /* Rewires the 2 heads */
839         peel_fix_heads();
840
841         /* Generate phis for values from peeled code and original loop */
842         construct_ssa_foreach(entry_buffer, entry_c);
843         /*for (i = 0; i < entry_c; i++)
844         {
845                 ir_node *cppred, *block, *cpblock, *pred;
846
847                 pred = entry_buffer[i];
848                 cppred = get_copy(pred);
849                 block = get_nodes_block(pred);
850                 cpblock = get_nodes_block(cppred);
851                 construct_ssa(block, pred, cpblock, cppred);
852         }*/
853 }
854
855 /**
856  * Populates head_entries with (node, pred_pos) tuple
857  * whereas the node's pred at pred_pos is in the head but not the node itself.
858  * Head and condition chain blocks must be marked.
859  */
860 static void get_head_outs(ir_node *node, void *env)
861 {
862         int i;
863         int arity = get_irn_arity(node);
864         (void) env;
865
866         DB((dbg, LEVEL_5, "get head entries %N \n", node));
867
868         for (i = 0; i < arity; ++i) {
869                 /* node is not in the head, but the predecessor is.
870                  * (head or loop chain nodes are marked) */
871
872                 DB((dbg, LEVEL_5, "... "));
873                 DB((dbg, LEVEL_5, "node %N  marked %d (0)  pred %d marked %d (1) \n",
874                     node->node_nr, is_nodesblock_marked(node),i, is_nodesblock_marked(get_irn_n(node, i))));
875
876                 if (!is_nodesblock_marked(node) && is_nodesblock_marked(get_irn_n(node, i))) {
877                         out_edge entry;
878                         entry.node = node;
879                         entry.pred_irn_n = i;
880                         DB((dbg, LEVEL_5,
881                                 "Found head chain entry %N @%d because !inloop %N and inloop %N\n",
882                                 node, i, node, get_irn_n(node, i)));
883                         ARR_APP1(out_edge, cur_head_outs, entry);
884                 }
885         }
886 }
887
888 /**
889  * Find condition chains, and add them to be inverted, until the node count exceeds the limit.
890  * A block belongs to the chain if a condition branches out of the loop.
891  * Returns 1 if the given block belongs to the condition chain.
892  */
893 static unsigned find_condition_chains(ir_node *block)
894 {
895         const ir_edge_t *edge;
896         unsigned mark = 0;
897         int nodes_n = 0;
898
899         DB((dbg, LEVEL_5, "condition_chains for block %N\n", block));
900
901         /* Collect all outs, including keeps.
902          * (TODO firm function for number of out edges?) */
903         foreach_out_edge_kind(block, edge, EDGE_KIND_NORMAL) {
904                 ++nodes_n;
905         }
906
907         /* We do not want to collect more nodes from condition chains, than the limit allows us to.
908          * Also, leave at least one block as body. */
909         if (head_inversion_node_count + nodes_n > inversion_head_node_limit
910                     || head_inversion_block_count + 1 == loop_info.blocks) {
911                 set_Block_mark(block, 0);
912
913                 return 0;
914         }
915
916         /* First: check our successors, and add all succs that are outside of the loop to the list */
917         foreach_block_succ(block, edge) {
918                 ir_node *src = get_edge_src_irn( edge );
919                 int pos = get_edge_src_pos( edge );
920
921                 if (!is_in_loop(src)) {
922                         out_edge entry;
923
924                         mark = 1;
925                         entry.node = src;
926                         entry.pred_irn_n = pos;
927                         ARR_APP1(out_edge, cond_chain_entries, entry);
928                         mark_irn_visited(src);
929                 }
930         }
931
932         if (mark == 0) {
933                 /* this block is not part of the chain,
934                  * because the chain would become too long or we have no successor outside of the loop */
935
936                 set_Block_mark(block, 0);
937                 return 0;
938         } else {
939                 set_Block_mark(block, 1);
940                 ++head_inversion_block_count;
941                 DB((dbg, LEVEL_5, "block %N is part of condition chain\n", block));
942                 head_inversion_node_count += nodes_n;
943         }
944
945         /* Second: walk all successors, and add them to the list if they are not part of the chain */
946         foreach_block_succ(block, edge) {
947                 unsigned inchain;
948                 ir_node *src = get_edge_src_irn( edge );
949                 int pos = get_edge_src_pos( edge );
950
951                 /* already done cases */
952                 if (!is_in_loop( src ) || (get_irn_visited(src) >= get_irg_visited(current_ir_graph))) {
953                         continue;
954                 }
955
956                 mark_irn_visited(src);
957                 DB((dbg, LEVEL_5, "condition chain walk %N\n", src));
958                 inchain = find_condition_chains(src);
959
960                 /* if successor is not part of chain we need to collect its outs */
961                 if (!inchain) {
962                         out_edge entry;
963                         entry.node = src;
964                         entry.pred_irn_n = pos;
965                         ARR_APP1(out_edge, cond_chain_entries, entry);
966                 }
967         }
968         return mark;
969 }
970
971 /**
972  * Rewire the loop head and inverted head for loop inversion.
973  */
974 static void inversion_fix_heads(void)
975 {
976         ir_node **loopheadnins, **invheadnins;
977         ir_node *loophead = loop_cf_head;
978         ir_node *invhead =      get_copy(loophead);
979
980         int headarity =         get_irn_arity(loophead);
981         ir_node *phi;
982         int i;
983
984         int lheadin_c = 0;
985         int iheadin_c = 0;
986
987         int backedges_n = get_backedge_n(loophead, 0);
988         int lhead_arity = backedges_n;
989         int ihead_arity = headarity - backedges_n;
990
991         assert(lhead_arity != 0 && "Loophead has arity 0. Probably wrong backedge informations.");
992         assert(ihead_arity != 0 && "Inversionhead has arity 0. Probably wrong backedge informations.");
993
994         /* new in arrays for all phis in the head blocks */
995         NEW_ARR_A(ir_node *, loopheadnins, lhead_arity);
996         NEW_ARR_A(ir_node *, invheadnins, ihead_arity);
997
998         for_each_phi(loophead, phi) {
999                 NEW_ARR_A(ir_node *, get_node_info(phi)->ins, lhead_arity);
1000         }
1001         for_each_phi(invhead, phi) {
1002                 NEW_ARR_A(ir_node *, get_node_info(phi)->ins, ihead_arity);
1003         }
1004
1005         for (i = 0; i < headarity; i++) {
1006                 ir_node *pred = get_irn_n(loophead, i);
1007
1008                 /**
1009                  * Rewire the head blocks ins and their phi ins.
1010                  * Requires phi list per block.
1011                  */
1012                 if (is_backedge(loophead, i) && !is_alien_edge(loophead, i)) {
1013                         /* just copy these edges */
1014                         loopheadnins[lheadin_c] = pred;
1015                         for_each_phi(loophead, phi) {
1016                                 get_node_info(phi)->ins[lheadin_c] = get_irn_n(phi, i);
1017                         }
1018                         ++lheadin_c;
1019                 } else {
1020                         invheadnins[iheadin_c] = pred;
1021                         for_each_phi(invhead, phi) {
1022                                 get_node_info(phi)->ins[iheadin_c] = get_irn_n(phi, i) ;
1023                         }
1024                         ++iheadin_c;
1025                 }
1026         }
1027
1028         /* assign the ins to the head blocks */
1029         set_irn_in(loophead, ARR_LEN(loopheadnins), loopheadnins);
1030         set_irn_in(invhead, ARR_LEN(invheadnins), invheadnins);
1031
1032         /* assign the ins for the phis */
1033         for_each_phi(loophead, phi) {
1034                 ir_node **ins = get_node_info(phi)->ins;
1035                 set_irn_in(phi, lhead_arity, ins);
1036         }
1037
1038         for_each_phi(invhead, phi) {
1039                 ir_node **ins = get_node_info(phi)->ins;
1040                 set_irn_in(phi, ihead_arity, ins);
1041         }
1042 }
1043
1044 static void inversion_walk(out_edge *head_entries)
1045 {
1046         int i;
1047         ir_node *phi;
1048         int entry_c = 0;
1049         ir_node **entry_buffer;
1050         ir_node **head_phi_assign;
1051
1052         NEW_ARR_A(ir_node *, entry_buffer, ARR_LEN(head_entries));
1053
1054         head_phi_assign = NEW_ARR_F(ir_node *, 0);
1055
1056         /* Find assignments in the condition chain,
1057          * to construct_ssa for them after the loop inversion. */
1058         for_each_phi(loop_cf_head , phi) {
1059                 int arity = get_irn_arity(phi);
1060                 for (i = 0; i < arity; ++i) {
1061                         ir_node *def = get_irn_n(phi, i);
1062                         if (is_nodesblock_marked(def)) {
1063                                 ARR_APP1(ir_node *, head_phi_assign, def);
1064                         }
1065                 }
1066         }
1067
1068         ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1069
1070         /**
1071          * duplicate condition chain
1072          **/
1073         inc_irg_visited(current_ir_graph);
1074
1075         for (i = 0; i < ARR_LEN(head_entries); ++i) {
1076                 out_edge entry = head_entries[i];
1077                 ir_node *node = entry.node;
1078                 ir_node *pred = get_irn_n(entry.node, entry.pred_irn_n);
1079
1080                 if (is_Block(node)) {
1081                         DB((dbg, LEVEL_5, "\nInit walk block %N\n", pred));
1082
1083                         copy_walk(pred, is_nodesblock_marked, cur_loop);
1084                         duplicate_preds(node, entry.pred_irn_n, get_copy(pred) );
1085                 } else {
1086                         DB((dbg, LEVEL_5, "\nInit walk node  %N\n", pred));
1087
1088                         copy_walk(pred, is_nodesblock_marked, cur_loop);
1089
1090                         /* ignore keepalives */
1091                         if (!is_End(node)) {
1092                                 /* Node is user of a value assigned inside the loop.
1093                                  * We will need a phi since we duplicated the head. */
1094                                 entry_buffer[entry_c] = pred;
1095                                 ++entry_c;
1096                         }
1097                 }
1098         }
1099
1100         ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1101
1102         inversion_fix_heads();
1103
1104         /* Generate phis for users of values assigned in the condition chain
1105          * and read in the loops body */
1106         construct_ssa_foreach(entry_buffer, entry_c);
1107
1108         /* Generate phis for values that are assigned in the condition chain
1109          * but not read in the loops body. */
1110         construct_ssa_foreach(head_phi_assign, ARR_LEN(head_phi_assign));
1111
1112         loop_cf_head = get_copy(loop_cf_head);
1113 }
1114
1115 /* Loop peeling */
1116 void loop_peeling(void)
1117 {
1118         cur_loop_outs = NEW_ARR_F(out_edge, 0);
1119         irg_walk_graph( current_ir_graph, get_loop_outs, NULL, NULL );
1120
1121         peel(cur_loop_outs);
1122
1123         /* clean up */
1124         reset_node_infos();
1125
1126         set_irg_doms_inconsistent(current_ir_graph);
1127         set_irg_loopinfo_inconsistent(current_ir_graph);
1128         set_irg_outs_inconsistent(current_ir_graph);
1129
1130         DEL_ARR_F(cur_loop_outs);
1131 }
1132
1133 /* Loop inversion */
1134 void loop_inversion(void)
1135 {
1136         unsigned do_inversion = 1;
1137
1138         inversion_head_node_limit = INT_MAX;
1139
1140         /* Search for condition chains. */
1141         ir_reserve_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1142
1143         irg_walk_graph(current_ir_graph, reset_block_mark, NULL, NULL);
1144
1145         loop_info.blocks = get_loop_n_blocks(cur_loop);
1146         cond_chain_entries = NEW_ARR_F(out_edge, 0);
1147
1148         head_inversion_node_count = 0;
1149         head_inversion_block_count = 0;
1150
1151         set_Block_mark(loop_cf_head, 1);
1152         mark_irn_visited(loop_cf_head);
1153         inc_irg_visited(current_ir_graph);
1154
1155         find_condition_chains(loop_cf_head);
1156
1157         DB((dbg, LEVEL_3, "Loop contains %d blocks.\n", loop_info.blocks));
1158         if (loop_info.blocks < 2) {
1159                 do_inversion = 0;
1160                 DB((dbg, LEVEL_3, "Loop contains %d (less than 2) blocks => No Inversion done.\n", loop_info.blocks));
1161         }
1162
1163         /* We also catch endless loops here,
1164          * because they do not have a condition chain. */
1165         if (head_inversion_block_count < 1) {
1166                 do_inversion = 0;
1167                 DB((dbg, LEVEL_3, "Loop contains %d (less than 1) invertible blocks => No Inversion done.\n", head_inversion_block_count));
1168         }
1169
1170         if (do_inversion) {
1171                 cur_head_outs = NEW_ARR_F(out_edge, 0);
1172
1173                 /* Get all edges pointing into the head or condition chain (outs). */
1174                 irg_walk_graph(current_ir_graph, get_head_outs, NULL, NULL);
1175                 inversion_walk(cur_head_outs);
1176
1177                 DEL_ARR_F(cur_head_outs);
1178
1179                 set_irg_doms_inconsistent(current_ir_graph);
1180                 set_irg_loopinfo_inconsistent(current_ir_graph);
1181                 set_irg_outs_inconsistent(current_ir_graph);
1182         }
1183
1184         /* free */
1185         DEL_ARR_F(cond_chain_entries);
1186         ir_free_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1187 }
1188
1189 /**
1190  * Returns last element of linked list of copies by
1191  * walking the linked list.
1192  */
1193 ir_node *get_last_copy(ir_node *node)
1194 {
1195         ir_node *copy, *cur;
1196         cur = node;
1197         while ((copy = get_copy(cur))) {
1198                 cur = copy;
1199         }
1200         return cur;
1201 }
1202
1203 /**
1204  * Rewire floating copies of the current loop.
1205  */
1206 void unrolling_fix_cf(void)
1207 {
1208         ir_node *loophead = loop_cf_head;
1209         int headarity =         get_irn_arity(loophead);
1210         ir_node *phi, *headnode;
1211         /*ir_node *high, *low;*/
1212         int i;
1213
1214         int uhead_in_n = 0;
1215         int backedges_n = get_backedge_n(loophead, 0);
1216         int unroll_arity = backedges_n;
1217
1218         /* Create ins for all heads and their phis */
1219         headnode = get_copy(loophead);
1220         for_each_copy(headnode) {
1221                 NEW_ARR_A(ir_node *, get_node_info(headnode)->ins, unroll_arity);
1222                 for_each_phi(headnode, phi) {
1223                         NEW_ARR_A(ir_node *, get_node_info(phi)->ins, unroll_arity);
1224                 }
1225         }
1226
1227         /* Append the copies to the existing loop. */
1228         for (i = 0; i < headarity; i++) {
1229                 ir_node *upper_head = loophead;
1230                 ir_node *lower_head = get_copy(loophead);
1231
1232                 ir_node *upper_pred = get_irn_n(loophead, i);
1233                 ir_node *lower_pred = get_copy(get_irn_n(loophead, i));
1234
1235                 ir_node *last_pred;
1236
1237                 /**
1238                  * Build unrolled loop top down
1239                  */
1240                 if (is_backedge(loophead, i) && !is_alien_edge(loophead, i)) {
1241                         for_each_copy2(upper_head, lower_head, upper_pred, lower_pred) {
1242                                 get_node_info(lower_head)->ins[uhead_in_n] = upper_pred;
1243
1244                                 for_each_phi(upper_head, phi) {
1245                                         ir_node *phi_copy = get_copy(phi);
1246                                         get_node_info(phi_copy)->ins[uhead_in_n] = get_irn_n(phi, i);
1247                                 }
1248                         }
1249
1250                         last_pred = upper_pred;
1251                         ++uhead_in_n;
1252
1253                         /* Fix the topmost loop heads backedges. */
1254                         set_irn_n(loophead, i, last_pred);
1255                         for_each_phi(loophead, phi) {
1256                                 ir_node *last_phi = get_last_copy(phi);
1257                                 ir_node *pred = get_irn_n(last_phi, i);
1258                                 set_irn_n(phi, i, pred);
1259                         }
1260                 }
1261         }
1262
1263         headnode = get_copy(loophead);
1264         for_each_copy(headnode) {
1265                 set_irn_in(headnode, unroll_arity, get_node_info(headnode)->ins);
1266                 for_each_phi(headnode, phi) {
1267                         set_irn_in(phi, unroll_arity, get_node_info(phi)->ins);
1268                 }
1269         }
1270 }
1271
1272 #if 0
1273 static ir_node *add_phi(ir_node *node, int phi_pos)
1274 {
1275         ir_mode *mode;
1276         ir_node *phi;
1277         ir_node **in;
1278         mode = get_irn_mode(get_irn_n(node, phi_pos));
1279         ir_node *block = get_nodes_block(node);
1280         int n_cfgpreds = get_irn_arity(block);
1281         ir_node *pred = get_irn_n(node, phi_pos);
1282         int i;
1283
1284         /* create a new Phi */
1285         NEW_ARR_A(ir_node*, in, n_cfgpreds);
1286         for (i = 0; i < n_cfgpreds; ++i)
1287                 in[i] = new_Unknown(mode);  /*pred;*/
1288
1289         phi = new_r_Phi(block, n_cfgpreds, in, mode);
1290
1291         assert(phi && "phi null");
1292         assert(is_Bad(phi) && "phi bad");
1293
1294         /* Important: always keep block phi list up to date. */
1295         add_Block_phi(block, phi);
1296         /* EVERY node is assumed to have a node_info linked. */
1297         alloc_node_info(phi, NULL);
1298
1299         set_irn_n(node, phi_pos, phi);
1300         return phi;
1301 }
1302 #endif
1303
1304
1305 /**
1306  * Loop unrolling
1307  * Could be improved with variable range informations.
1308  */
1309 void loop_unrolling(void)
1310 {
1311         int i, j;
1312
1313         unroll_times = 7;
1314
1315         cur_loop_outs = NEW_ARR_F(out_edge, 0);
1316         irg_walk_graph( current_ir_graph, get_loop_outs, NULL, NULL );
1317
1318         ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1319
1320         /* duplicate whole loop content */
1321         inc_irg_visited(current_ir_graph);
1322
1323         for (i = 0; i < ARR_LEN(cur_loop_outs); ++i) {
1324                 out_edge entry = cur_loop_outs[i];
1325                 ir_node *node = entry.node;
1326                 ir_node *pred = get_irn_n(entry.node, entry.pred_irn_n);
1327                 if (!is_Block(node)) {
1328                         for (j = 0; j < unroll_times - 1; ++j) {
1329                                 copy_walk(pred, is_in_loop, cur_loop);
1330                                 pred = get_copy(pred);
1331                         }
1332                 }
1333         }
1334
1335         for (i = 0; i < ARR_LEN(cur_loop_outs); ++i) {
1336                 out_edge entry = cur_loop_outs[i];
1337                 ir_node *node = entry.node;
1338                 ir_node *pred = get_irn_n(entry.node, entry.pred_irn_n);
1339
1340                 if (is_Block(node)) {
1341                         for (j = 0; j < unroll_times - 1; ++j) {
1342                                 copy_walk(pred, is_in_loop, cur_loop);
1343                                 duplicate_preds(node, entry.pred_irn_n, get_copy(pred));
1344
1345                                 pred = get_copy(pred);
1346                         }
1347                 }
1348         }
1349
1350         ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1351
1352         /*dump_ir_graph(current_ir_graph, "-raw");*/
1353
1354         /* LDBG 2 */
1355 #if 1
1356         /* Line up the floating copies. */
1357         unrolling_fix_cf();
1358
1359         /* Generate phis for all loop outs */
1360         for (i = 0; i < ARR_LEN(cur_loop_outs); ++i) {
1361                 out_edge entry = cur_loop_outs[i];
1362                 ir_node *node = entry.node;
1363                 ir_node *pred = get_irn_n(entry.node, entry.pred_irn_n);
1364
1365                 if (!is_Block(node) && !is_End(node)) {
1366                         DB((dbg, LEVEL_5, "  construct_ssa_n def %N  node %N  pos %d\n",
1367                                         pred, node, entry.pred_irn_n));
1368                         construct_ssa_n(pred, node);
1369                 }
1370         }
1371 #endif
1372
1373         DEL_ARR_F(cur_loop_outs);
1374
1375         set_irg_doms_inconsistent(current_ir_graph);
1376         set_irg_loopinfo_inconsistent(current_ir_graph);
1377         set_irg_outs_inconsistent(current_ir_graph);
1378 }
1379
1380 /* Initialization and */
1381 static void init_analyze(ir_loop *loop)
1382 {
1383         /* Init new for every loop */
1384         cur_loop = loop;
1385
1386         loop_cf_head = NULL;
1387         loop_cf_head_valid = 1;
1388         loop_inv_head = NULL;
1389         loop_peeled_head = NULL;
1390
1391         loop_info.outs = 0;
1392         loop_info.calls = 0;
1393         loop_info.loads = 0;
1394         loop_info.blocks = 0;
1395
1396         DB((dbg, LEVEL_2, "  >>>> current loop includes node %N <<<\n", get_loop_node(loop, 0)));
1397
1398         irg_walk_graph(current_ir_graph, get_loop_info, NULL, NULL);
1399
1400         /* RETURN if there is no valid head */
1401         if (!loop_cf_head || !loop_cf_head_valid) {
1402                 DB((dbg, LEVEL_2,   "No valid loop head. Nothing done.\n"));
1403                 return;
1404         }
1405
1406         if (enable_peeling)
1407                 loop_peeling();
1408
1409         if (enable_inversion)
1410                 loop_inversion();
1411         if (enable_unrolling)
1412                 loop_unrolling();
1413
1414 #if 0
1415         /* RETURN if there is a call in the loop */
1416         if (loop_info.calls)
1417                 return;
1418 #endif
1419
1420         DB((dbg, LEVEL_2, "      <<<< end of loop with node %N >>>>\n", get_loop_node(loop, 0)));
1421 }
1422
1423 /* Find most inner loops and send them to analyze_loop */
1424 static void find_most_inner_loop(ir_loop *loop)
1425 {
1426         /* descend into sons */
1427         int sons = get_loop_n_sons(loop);
1428
1429         if (sons == 0) {
1430                 loop_element elem;
1431                 int el_n, i;
1432
1433                 el_n = get_loop_n_elements(loop);
1434
1435                 for (i=0; i < el_n; ++i) {
1436                         elem = get_loop_element(loop, i);
1437                         /* We can only rely on the blocks,
1438                          * as the loop attribute of the nodes seems not to be set. */
1439                         if (is_ir_node(elem.kind) && is_Block(elem.node)) {
1440                                 ARR_APP1(ir_node *, loops, elem.node);
1441                                 DB((dbg, LEVEL_5, "Found most inner loop (contains block %+F)\n", elem.node));
1442                                 break;
1443                         }
1444                 }
1445         } else {
1446                 int s;
1447                 for (s=0; s<sons; s++) {
1448                         find_most_inner_loop(get_loop_son(loop, s));
1449                 }
1450         }
1451 }
1452
1453 /**
1454  * Assure preconditions are met and go through all loops.
1455  */
1456 void loop_optimization(ir_graph *irg)
1457 {
1458         ir_loop *loop;
1459         int     i, sons, nr;
1460
1461         /* Init */
1462         link_node_state_list = NULL;
1463         set_current_ir_graph(irg);
1464
1465         /* preconditions */
1466         edges_assure(irg);
1467         assure_irg_outs(irg);
1468
1469         /* NOTE: sets only the loop attribute of blocks, not nodes */
1470         /* NOTE: Kills links */
1471         assure_cf_loop(irg);
1472
1473         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK|IR_RESOURCE_PHI_LIST);
1474         collect_phiprojs(irg);
1475         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1476
1477         /* allocate node_info for additional information on nodes */
1478         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1479         irg_walk_graph(current_ir_graph, alloc_node_info, NULL, NULL);
1480
1481         loop = get_irg_loop(irg);
1482         sons = get_loop_n_sons(loop);
1483
1484         loops = NEW_ARR_F(ir_node *, 0);
1485
1486         for (nr = 0; nr < sons; ++nr) {
1487                 find_most_inner_loop(get_loop_son(loop, nr));
1488         }
1489
1490 /* TODO Keep backedges during optimization to avoid
1491  * this ugly allocation and deallocation.
1492  * (set_irn_in seems to destroy them)
1493  */
1494 #if 0
1495         for (i = 0; i < ARR_LEN(loops); ++i) {
1496                 ir_loop *loop;
1497
1498                 loop = get_irn_loop(loops[i]);
1499                 init_analyze(loop);
1500         }
1501 #else
1502         /* This part is useful for testing
1503          * or has to be used if the backedge information is destroyed.
1504          * Which is the case at the moment, because the backedge information gets lost
1505          * before inversion_fix_heads/unrolling_fix_cf, which results in bads.
1506          * NOTE!: Testsuite runs successfully nevertheless...
1507          */
1508
1509         /**
1510          * assure_cf_loop() creates a completely new loop tree.
1511          * Thus we cannot optimize a loop, assure_cf_loop() and continue with the next loop,
1512          * as the next loop must be searched because it is not distinguishable from the
1513          * already done loops.
1514          * The links of the loops are also not available anymore (to store a "loop done" flag).
1515          * Therefore we save a block per loop.
1516          * NOTE: We rely on the loop optimizations not to remove any block from the loop.
1517          * Later, we fetch the blocks loop attribute, as it is updated by assure_cf_loop.
1518          */
1519         for (i = 0; i < ARR_LEN(loops); ++i) {
1520                 ir_loop *loop;
1521
1522                 free_node_info();
1523                 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1524
1525                 edges_assure(current_ir_graph);
1526                 assure_irg_outs(current_ir_graph);
1527
1528                 /* NOTE: sets only the loop attribute of blocks */
1529                 /* NOTE: Kills links */
1530                 assure_cf_loop(current_ir_graph);
1531
1532                 irg_walk_graph(current_ir_graph, alloc_node_info, NULL, NULL);
1533                 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1534
1535                 /* Get loop from block */
1536                 loop = get_irn_loop(loops[i]);
1537                 init_analyze(loop);
1538         }
1539 #endif
1540
1541         /* Free */
1542         DEL_ARR_F(loops);
1543
1544         free_node_info();
1545         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1546         ir_free_resources(irg, IR_RESOURCE_PHI_LIST);
1547 }
1548
1549 void do_loop_unrolling(ir_graph *irg)
1550 {
1551         enable_unrolling = 1;
1552         enable_peeling = 0;
1553         enable_inversion = 0;
1554
1555         DB((dbg, LEVEL_2, " >>> unrolling (Startnode %N) <<<\n",
1556                 get_irg_start(irg)));
1557
1558         loop_optimization(irg);
1559
1560         DB((dbg, LEVEL_2, " >>> unrolling done (Startnode %N) <<<\n",
1561                 get_irg_start(irg)));
1562 }
1563
1564 void do_loop_inversion(ir_graph *irg)
1565 {
1566         enable_unrolling = 0;
1567         enable_peeling = 0;
1568         enable_inversion = 1;
1569
1570         DB((dbg, LEVEL_2, " >>> inversion (Startnode %N) <<<\n",
1571                 get_irg_start(irg)));
1572
1573         loop_optimization(irg);
1574
1575         DB((dbg, LEVEL_2, " >>> inversion done (Startnode %N) <<<\n",
1576                 get_irg_start(irg)));
1577 }
1578
1579 void do_loop_peeling(ir_graph *irg)
1580 {
1581         enable_unrolling = 0;
1582         enable_peeling = 1;
1583         enable_inversion = 0;
1584
1585         DB((dbg, LEVEL_2, " >>> peeling (Startnode %N) <<<\n",
1586                 get_irg_start(irg)));
1587
1588         loop_optimization(irg);
1589
1590         DB((dbg, LEVEL_2, " >>> peeling done (Startnode %N) <<<\n",
1591                 get_irg_start(irg)));
1592
1593 }
1594
1595 ir_graph_pass_t *loop_inversion_pass(const char *name)
1596 {
1597         return def_graph_pass(name ? name : "loop_inversion", do_loop_inversion);
1598 }
1599
1600 ir_graph_pass_t *loop_unroll_pass(const char *name)
1601 {
1602         return def_graph_pass(name ? name : "loop_unroll", do_loop_unrolling);
1603 }
1604
1605 ir_graph_pass_t *loop_peeling_pass(const char *name)
1606 {
1607         return def_graph_pass(name ? name : "loop_peeling", do_loop_peeling);
1608 }
1609
1610 void firm_init_loop_opt(void)
1611 {
1612         FIRM_DBG_REGISTER(dbg, "firm.opt.loop");
1613 }