some cleanup
[libfirm] / ir / opt / tailrec.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/tailrec.c
4  * Purpose:     tail-recursion optimization
5  * Author:      Michael Beck
6  * Modified by:
7  * Created:     08.06.2004
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 2002-2004 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12 #ifdef HAVE_CONFIG_H
13 # include "config.h"
14 #endif
15
16 #ifdef HAVE_ALLOCA_H
17 #include <alloca.h>
18 #endif
19 #ifdef HAVE_MALLOC_H
20 #include <malloc.h>
21 #endif
22 #ifdef HAVE_STRING_H
23 #include <string.h>
24 #endif
25
26 #include <assert.h>
27 #include "tailrec.h"
28 #include "array.h"
29 #include "irprog_t.h"
30 #include "irgwalk.h"
31 #include "irgmod.h"
32 #include "irop.h"
33 #include "irnode_t.h"
34 #include "irgraph_t.h"
35 #include "ircons.h"
36 #include "irflag.h"
37 #include "trouts.h"
38 #include "return.h"
39 #include "scalar_replace.h"
40 #include "irouts.h"
41 #include "irhooks.h"
42
43 /**
44  * the environment for collecting data
45  */
46 typedef struct _collect_t {
47   ir_node *proj_X;      /**< initial exec proj */
48   ir_node *block;       /**< old first block */
49   int     blk_idx;      /**< cfgpred index of the initial exec in block */
50   ir_node *proj_m;      /**< linked list of memory from start proj's */
51   ir_node *proj_data;   /**< linked list of all parameter access proj's */
52 } collect_t;
53
54 /**
55  * walker for collecting data, fills a collect_t environment
56  */
57 static void collect_data(ir_node *node, void *env)
58 {
59   collect_t *data = env;
60   ir_node *pred;
61   ir_op *op;
62
63   switch (get_irn_opcode(node)) {
64   case iro_Proj:
65     pred = get_Proj_pred(node);
66
67     op = get_irn_op(pred);
68     if (op == op_Proj) {
69       ir_node *start = get_Proj_pred(pred);
70
71       if (get_irn_op(start) == op_Start) {
72         if (get_Proj_proj(pred) == pn_Start_T_args) {
73                 /* found Proj(ProjT(Start)) */
74                 set_irn_link(node, data->proj_data);
75                 data->proj_data = node;
76         }
77       }
78     }
79     else if (op == op_Start) {
80       switch (get_Proj_proj(node)) {
81         case pn_Start_M:
82           /* found ProjM(Start) */
83               set_irn_link(node, data->proj_m);
84               data->proj_m = node;
85               break;
86             case pn_Start_X_initial_exec:
87               /* found ProjX(Start) */
88               data->proj_X = node;
89               break;
90             default:
91               break;
92       }
93     }
94     break;
95   case iro_Block: {
96     int i, n_pred = get_Block_n_cfgpreds(node);
97
98     /*
99      * the first block has the initial exec as cfg predecessor
100      */
101     if (node != current_ir_graph->start_block) {
102       for (i = 0; i < n_pred; ++i) {
103         if (get_Block_cfgpred(node, i) == data->proj_X) {
104                 data->block   = node;
105                 data->blk_idx = i;
106                 break;
107         }
108       }
109     }
110     break;
111   }
112   default:
113     break;
114   }
115 }
116
117 /**
118  * do the graph reconstruction for tail-recursion elimination
119  *
120  * @param irg           the graph that will reconstructed
121  * @param rets          linked list of all rets
122  * @param n_tail_calls  number of tail-recursion calls
123  */
124 static void do_opt_tail_rec(ir_graph *irg, ir_node *rets, int n_tail_calls)
125 {
126   ir_node *end_block = get_irg_end_block(irg);
127   ir_node *block, *jmp, *call, *calls;
128   ir_node **in;
129   ir_node **phis;
130   ir_node ***call_params;
131   ir_node *p;
132   int i, j, n_params;
133   collect_t data;
134   int rem         = get_optimize();
135   entity *ent     = get_irg_entity(irg);
136   type *method_tp = get_entity_type(ent);
137
138   assert(n_tail_calls);
139
140   /* we add new nodes, so the outs are inconsistant */
141   set_irg_outs_inconsistent(irg);
142
143   /* we add new blocks and change the control flow */
144   set_irg_dom_inconsistent(irg);
145
146   /* we add a new loop */
147   set_irg_loopinfo_inconsistent(irg);
148
149   /* calls are removed */
150   set_trouts_inconsistent();
151
152   /* we must build some new nodes WITHOUT CSE */
153   set_optimize(0);
154
155   /* collect needed data */
156   data.proj_X    = NULL;
157   data.block     = NULL;
158   data.blk_idx   = -1;
159   data.proj_m    = NULL;
160   data.proj_data = NULL;
161   irg_walk_graph(irg, NULL, collect_data, &data);
162
163   /* check number of arguments */
164   call = get_irn_link(end_block);
165   n_params = get_Call_n_params(call);
166
167   assert(data.proj_X && "Could not find initial exec from Start");
168   assert(data.block  && "Could not find first block");
169   assert(data.proj_m && "Could not find ProjM(Start)");
170   assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
171
172   /* allocate in's for phi and block construction */
173   NEW_ARR_A(ir_node *, in, n_tail_calls + 1);
174
175   in[0] = data.proj_X;
176
177   /* turn Return's into Jmp's */
178   for (i = 1, p = rets; p; p = get_irn_link(p)) {
179     ir_node *jmp;
180     ir_node *block = get_nodes_block(p);
181
182     jmp = new_r_Jmp(irg, block);
183
184     exchange(p, new_r_Bad(irg));
185     in[i++] = jmp;
186
187     /* we might generate an endless loop, so add
188      * the block to the keep-alive list */
189     add_End_keepalive(get_irg_end(irg), block);
190   }
191
192   /* create a new block at start */
193   block = new_r_Block(irg, n_tail_calls + 1, in);
194   jmp   = new_r_Jmp(irg, block);
195
196   /* the old first block is now the second one */
197   set_Block_cfgpred(data.block, data.blk_idx, jmp);
198
199   /* allocate phi's, position 0 contains the memory phi */
200   NEW_ARR_A(ir_node *, phis, n_params + 1);
201
202   /* build the memory phi */
203   i = 0;
204   in[i] = new_r_Proj(irg, get_irg_start_block(irg), get_irg_start(irg), mode_M, pn_Start_M);
205   ++i;
206
207   for (calls = call; calls; calls = get_irn_link(calls)) {
208     in[i] = get_Call_mem(calls);
209     ++i;
210   }
211   assert(i == n_tail_calls + 1);
212
213   phis[0] = new_r_Phi(irg, block, n_tail_calls + 1, in, mode_M);
214
215   /* build the data phi's */
216   if (n_params > 0) {
217     ir_node *calls;
218
219     NEW_ARR_A(ir_node **, call_params, n_tail_calls);
220
221     /* collect all parameters */
222     for (i = 0, calls = call; calls; calls = get_irn_link(calls)) {
223       call_params[i] = get_Call_param_arr(calls);
224       ++i;
225     }
226
227     /* build new projs and Phi's */
228     for (i = 0; i < n_params; ++i) {
229       ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
230
231       in[0] = new_r_Proj(irg, block, irg->args, mode, i);
232       for (j = 0; j < n_tail_calls; ++j)
233         in[j + 1] = call_params[j][i];
234
235       phis[i + 1] = new_r_Phi(irg, block, n_tail_calls + 1, in, mode);
236     }
237   }
238
239   /*
240    * ok, we are here, so we have build and collected all needed Phi's
241    * now exchange all Projs into links to Phi
242    */
243   for (p = data.proj_m; p; p = get_irn_link(p)) {
244     exchange(p, phis[0]);
245   }
246   for (p = data.proj_data; p; p = get_irn_link(p)) {
247     long proj = get_Proj_proj(p);
248
249     assert(0 <= proj && proj < n_params);
250     exchange(p, phis[proj + 1]);
251   }
252
253   /* tail recursion was done, all info is invalid */
254   set_irg_dom_inconsistent(irg);
255   set_irg_outs_inconsistent(irg);
256   set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
257   set_trouts_inconsistent();
258   set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
259
260   set_optimize(rem);
261 }
262
263 /**
264  * Check the lifetime of locals in the given graph.
265  * Tail recursion can only be done, if we can prove that
266  * the lifetime of locals end with the recursive call.
267  * We do this by checking that no address of a local variable is
268  * stored or transmitted as an argument to a call.
269  *
270  * @return non-zero if it's ok to do tail recursion
271  */
272 static int check_lifetime_of_locals(ir_graph *irg)
273 {
274   ir_node *irg_frame = get_irg_frame(irg);
275   int i;
276
277   if (get_irg_outs_state(irg) != outs_consistent)
278     compute_irg_outs(irg);
279
280   for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
281     ir_node *succ = get_irn_out(irg_frame, i);
282
283     if (get_irn_op(succ) == op_Sel && is_address_taken(succ))
284       return 0;
285   }
286   return 1;
287 }
288
289 /*
290  * convert simple tail-calls into loops
291  */
292 int opt_tail_rec_irg(ir_graph *irg)
293 {
294   ir_node *end_block;
295   int i, n_tail_calls = 0;
296   ir_node *rets = NULL;
297   type *mtd_type, *call_type;
298
299   if (! get_opt_tail_recursion() || ! get_opt_optimize())
300     return 0;
301
302   if (! check_lifetime_of_locals(irg))
303     return 0;
304
305   /*
306    * This tail recursion optimization works best
307    * if the Returns are normalized.
308    */
309   normalize_n_returns(irg);
310
311   end_block = get_irg_end_block(irg);
312   set_irn_link(end_block, NULL);
313
314   for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
315     ir_node *ret = get_Block_cfgpred(end_block, i);
316     ir_node *call, *call_ptr;
317     entity *ent;
318     int j;
319     ir_node **ress;
320
321     /* search all returns of a block */
322     if (get_irn_op(ret) != op_Return)
323       continue;
324
325     /* check, if it's a Return self() */
326     call = skip_Proj(get_Return_mem(ret));
327     if (get_irn_op(call) != op_Call)
328       continue;
329
330     /* check if it's a recursive call */
331     call_ptr = get_Call_ptr(call);
332
333     if (get_irn_op(call_ptr) != op_SymConst)
334       continue;
335
336     if (get_SymConst_kind(call_ptr) != symconst_addr_ent)
337       continue;
338
339     ent = get_SymConst_entity(call_ptr);
340     if (!ent || get_entity_irg(ent) != irg)
341       continue;
342
343     /* ok, mem is routed to a recursive call, check return args */
344     ress = get_Return_res_arr(ret);
345     for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
346       ir_node *irn = skip_Proj(skip_Proj(ress[j]));
347
348       if (irn != call) {
349               /* not routed to a call */
350               break;
351       }
352     }
353     if (j >= 0)
354       continue;
355
356     /*
357      * Check, that the types match. At least in C
358      * this might fail.
359      */
360     mtd_type  = get_entity_type(ent);
361     call_type = get_Call_type(call);
362
363     if (mtd_type != call_type) {
364       /*
365        * Hmm, the types did not match, bad.
366        * This can happen in C when no prototype is given
367        * or K&R style is used.
368        */
369 #if 0
370       printf("Warning: Tail recursion fails because of different method and call types:\n");
371       dump_type(mtd_type);
372       dump_type(call_type);
373 #endif
374       return 0;
375     }
376
377     /* here, we have found a call */
378     set_irn_link(call, get_irn_link(end_block));
379     set_irn_link(end_block, call);
380     ++n_tail_calls;
381
382     /* link all returns, we will need this */
383     set_irn_link(ret, rets);
384     rets = ret;
385   }
386
387   /* now, end_block->link contains the list of all tail calls */
388   if (! n_tail_calls)
389     return 0;
390
391   if (get_opt_tail_recursion_verbose() && get_firm_verbosity() > 1)
392     printf("  Performing tail recursion for graph %s and %d Calls\n",
393            get_entity_ld_name(get_irg_entity(irg)), n_tail_calls);
394
395   hook_tail_rec(irg, n_tail_calls);
396   do_opt_tail_rec(irg, rets, n_tail_calls);
397
398   return n_tail_calls;
399 }
400
401 /*
402  * optimize tail recursion away
403  */
404 void opt_tail_recursion(void)
405 {
406   int i;
407   int n_opt_applications = 0;
408   ir_graph *irg;
409
410   if (! get_opt_tail_recursion() || ! get_opt_optimize())
411     return;
412
413   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
414     irg = get_irp_irg(i);
415
416     if (opt_tail_rec_irg(irg))
417       ++n_opt_applications;
418   }
419
420   if (get_opt_tail_recursion_verbose())
421     printf("Performed tail recursion for %d of %d graphs\n", n_opt_applications, get_irp_n_irgs());
422 }