move backend into libfirm
[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;      /**< 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       if (get_Proj_proj(node) == pn_Start_X_initial_exec) {
81         /* found ProjX(Start) */
82         data->proj_X = node;
83       }
84     }
85     break;
86   case iro_Block: {
87     int i, n_pred = get_Block_n_cfgpreds(node);
88
89     /*
90      * the first block has the initial exec as cfg predecessor
91      */
92     if (node != get_irg_start_block(current_ir_graph)) {
93       for (i = 0; i < n_pred; ++i) {
94         if (get_Block_cfgpred(node, i) == data->proj_X) {
95           data->block   = node;
96           data->blk_idx = i;
97           break;
98         }
99       }
100     }
101     break;
102   }
103   default:
104     break;
105   }
106 }
107
108 /**
109  * do the graph reconstruction for tail-recursion elimination
110  *
111  * @param irg           the graph that will reconstructed
112  * @param rets          linked list of all rets
113  * @param n_tail_calls  number of tail-recursion calls
114  */
115 static void do_opt_tail_rec(ir_graph *irg, ir_node *rets, int n_tail_calls)
116 {
117   ir_node *end_block = get_irg_end_block(irg);
118   ir_node *block, *jmp, *call, *calls;
119   ir_node **in;
120   ir_node **phis;
121   ir_node ***call_params;
122   ir_node *p, *n;
123   int i, j, n_params;
124   collect_t data;
125   int rem            = get_optimize();
126   ir_entity *ent     = get_irg_entity(irg);
127   ir_type *method_tp = get_entity_type(ent);
128
129   assert(n_tail_calls);
130
131   /* we add new nodes, so the outs are inconsistent */
132   set_irg_outs_inconsistent(irg);
133
134   /* we add new blocks and change the control flow */
135   set_irg_doms_inconsistent(irg);
136   set_irg_extblk_inconsistent(irg);
137
138   /* we add a new loop */
139   set_irg_loopinfo_inconsistent(irg);
140
141   /* calls are removed */
142   set_trouts_inconsistent();
143
144   /* we must build some new nodes WITHOUT CSE */
145   set_optimize(0);
146
147   /* collect needed data */
148   data.proj_X    = NULL;
149   data.block     = NULL;
150   data.blk_idx   = -1;
151   data.proj_m    = get_irg_initial_mem(irg);
152   data.proj_data = NULL;
153   irg_walk_graph(irg, NULL, collect_data, &data);
154
155   /* check number of arguments */
156   call = get_irn_link(end_block);
157   n_params = get_Call_n_params(call);
158
159   assert(data.proj_X && "Could not find initial exec from Start");
160   assert(data.block  && "Could not find first block");
161   assert(data.proj_m && "Could not find initial memory");
162   assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
163
164   /* allocate in's for phi and block construction */
165   NEW_ARR_A(ir_node *, in, n_tail_calls + 1);
166
167   in[0] = data.proj_X;
168
169   /* turn Return's into Jmp's */
170   for (i = 1, p = rets; p; p = n) {
171     ir_node *block = get_nodes_block(p);
172
173     n = get_irn_link(p);
174     in[i++] = new_r_Jmp(irg, block);
175
176     exchange(p, new_r_Bad(irg));
177
178     /* we might generate an endless loop, so add
179      * the block to the keep-alive list */
180     add_End_keepalive(get_irg_end(irg), block);
181   }
182
183   /* create a new block at start */
184   block = new_r_Block(irg, n_tail_calls + 1, in);
185   jmp   = new_r_Jmp(irg, block);
186
187   /* the old first block is now the second one */
188   set_Block_cfgpred(data.block, data.blk_idx, jmp);
189
190   /* allocate phi's, position 0 contains the memory phi */
191   NEW_ARR_A(ir_node *, phis, n_params + 1);
192
193   /* build the memory phi */
194   i = 0;
195   in[i] = new_r_Proj(irg, get_irg_start_block(irg), get_irg_start(irg), mode_M, pn_Start_M);
196   set_irg_initial_mem(irg, in[i]);
197   ++i;
198
199   for (calls = call; calls; calls = get_irn_link(calls)) {
200     in[i] = get_Call_mem(calls);
201     ++i;
202   }
203   assert(i == n_tail_calls + 1);
204
205   phis[0] = new_r_Phi(irg, block, n_tail_calls + 1, in, mode_M);
206
207   /* build the data Phi's */
208   if (n_params > 0) {
209     ir_node *calls;
210     ir_node *args;
211     ir_node *args_bl;
212
213     NEW_ARR_A(ir_node **, call_params, n_tail_calls);
214
215     /* collect all parameters */
216     for (i = 0, calls = call; calls; calls = get_irn_link(calls)) {
217       call_params[i] = get_Call_param_arr(calls);
218       ++i;
219     }
220
221     /* build new Proj's and Phi's */
222     args    = get_irg_args(irg);
223     args_bl = get_nodes_block(args);
224     for (i = 0; i < n_params; ++i) {
225       ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
226
227       in[0] = new_r_Proj(irg, args_bl, args, mode, i);
228       for (j = 0; j < n_tail_calls; ++j)
229         in[j + 1] = call_params[j][i];
230
231       phis[i + 1] = new_r_Phi(irg, block, n_tail_calls + 1, in, mode);
232     }
233   }
234
235   /*
236    * ok, we are here, so we have build and collected all needed Phi's
237    * now exchange all Projs into links to Phi
238    */
239   for (p = data.proj_m; p; p = n) {
240     n = get_irn_link(p);
241     exchange(p, phis[0]);
242   }
243   for (p = data.proj_data; p; p = n) {
244     long proj = get_Proj_proj(p);
245
246     assert(0 <= proj && proj < n_params);
247     n = get_irn_link(p);
248     exchange(p, phis[proj + 1]);
249   }
250
251   /* tail recursion was done, all info is invalid */
252   set_irg_doms_inconsistent(irg);
253   set_irg_outs_inconsistent(irg);
254   set_irg_extblk_inconsistent(irg);
255   set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
256   set_trouts_inconsistent();
257   set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
258
259   set_optimize(rem);
260 }
261
262 /**
263  * Check the lifetime of locals in the given graph.
264  * Tail recursion can only be done, if we can prove that
265  * the lifetime of locals end with the recursive call.
266  * We do this by checking that no address of a local variable is
267  * stored or transmitted as an argument to a call.
268  *
269  * @return non-zero if it's ok to do tail recursion
270  */
271 static int check_lifetime_of_locals(ir_graph *irg)
272 {
273   ir_node *irg_frame = get_irg_frame(irg);
274   int i;
275
276   if (get_irg_outs_state(irg) != outs_consistent)
277     compute_irg_outs(irg);
278
279   for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
280     ir_node *succ = get_irn_out(irg_frame, i);
281
282     if (is_Sel(succ) && is_address_taken(succ))
283       return 0;
284   }
285   return 1;
286 }
287
288 /*
289  * convert simple tail-calls into loops
290  */
291 int opt_tail_rec_irg(ir_graph *irg)
292 {
293   ir_node *end_block;
294   int i, n_tail_calls = 0;
295   ir_node *rets = NULL;
296   ir_type *mtd_type, *call_type;
297
298   if (! get_opt_tail_recursion() || ! get_opt_optimize())
299     return 0;
300
301   if (! check_lifetime_of_locals(irg))
302     return 0;
303
304   /*
305    * This tail recursion optimization works best
306    * if the Returns are normalized.
307    */
308   normalize_n_returns(irg);
309
310   end_block = get_irg_end_block(irg);
311   set_irn_link(end_block, NULL);
312
313   for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
314     ir_node *ret = get_Block_cfgpred(end_block, i);
315     ir_node *call, *call_ptr;
316     ir_entity *ent;
317     int j;
318     ir_node **ress;
319
320     /* search all Returns of a block */
321     if (! is_Return(ret))
322       continue;
323
324     /* check, if it's a Return self() */
325     call = skip_Proj(get_Return_mem(ret));
326     if (! is_Call(call))
327       continue;
328
329     /* check if it's a recursive call */
330     call_ptr = get_Call_ptr(call);
331
332     if (get_irn_op(call_ptr) != op_SymConst)
333       continue;
334
335     if (get_SymConst_kind(call_ptr) != symconst_addr_ent)
336       continue;
337
338     ent = get_SymConst_entity(call_ptr);
339     if (!ent || get_entity_irg(ent) != irg)
340       continue;
341
342     /* ok, mem is routed to a recursive call, check return args */
343     ress = get_Return_res_arr(ret);
344     for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
345       ir_node *irn = skip_Proj(skip_Proj(ress[j]));
346
347       if (irn != call) {
348         /* not routed to a call */
349         break;
350       }
351     }
352     if (j >= 0)
353       continue;
354
355     /*
356      * Check, that the types match. At least in C
357      * this might fail.
358      */
359     mtd_type  = get_entity_type(ent);
360     call_type = get_Call_type(call);
361
362     if (mtd_type != call_type) {
363       /*
364        * Hmm, the types did not match, bad.
365        * This can happen in C when no prototype is given
366        * or K&R style is used.
367        */
368 #if 0
369       printf("Warning: Tail recursion fails because of different method and call types:\n");
370       dump_type(mtd_type);
371       dump_type(call_type);
372 #endif
373       return 0;
374     }
375
376     /* here, we have found a call */
377     set_irn_link(call, get_irn_link(end_block));
378     set_irn_link(end_block, call);
379     ++n_tail_calls;
380
381     /* link all returns, we will need this */
382     set_irn_link(ret, rets);
383     rets = ret;
384   }
385
386   /* now, end_block->link contains the list of all tail calls */
387   if (! n_tail_calls)
388     return 0;
389
390   if (get_opt_tail_recursion_verbose() && get_firm_verbosity() > 1)
391     printf("  Performing tail recursion for graph %s and %d Calls\n",
392        get_entity_ld_name(get_irg_entity(irg)), n_tail_calls);
393
394   hook_tail_rec(irg, n_tail_calls);
395   do_opt_tail_rec(irg, rets, n_tail_calls);
396
397   return n_tail_calls;
398 }
399
400 /*
401  * optimize tail recursion away
402  */
403 void opt_tail_recursion(void)
404 {
405   int i;
406   int n_opt_applications = 0;
407   ir_graph *irg;
408
409   if (! get_opt_tail_recursion() || ! get_opt_optimize())
410     return;
411
412   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
413     irg = get_irp_irg(i);
414
415     if (opt_tail_rec_irg(irg))
416       ++n_opt_applications;
417   }
418
419   if (get_opt_tail_recursion_verbose())
420     printf("Performed tail recursion for %d of %d graphs\n", n_opt_applications, get_irp_n_irgs());
421 }