remove #ifdef HAVE_CONFIG_Hs
[libfirm] / ir / opt / tailrec.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   Tail-recursion call optimization.
23  * @date    08.06.2004
24  * @author  Michael Beck
25  * @version $Id$
26  */
27 #include "config.h"
28
29 #include <string.h>
30 #include <assert.h>
31
32 #include "debug.h"
33 #include "iroptimize.h"
34 #include "scalar_replace.h"
35 #include "array_t.h"
36 #include "irprog_t.h"
37 #include "irgwalk.h"
38 #include "irgmod.h"
39 #include "irop.h"
40 #include "irnode_t.h"
41 #include "irgraph_t.h"
42 #include "ircons.h"
43 #include "irflag.h"
44 #include "trouts.h"
45 #include "irouts.h"
46 #include "irhooks.h"
47 #include "ircons_t.h"
48
49 DEBUG_ONLY(static firm_dbg_module_t *dbg);
50
51 /**
52  * the environment for collecting data
53  */
54 typedef struct _collect_t {
55         ir_node *proj_X;      /**< initial exec proj */
56         ir_node *block;       /**< old first block */
57         int     blk_idx;      /**< cfgpred index of the initial exec in block */
58         ir_node *proj_m;      /**< memory from start proj's */
59         ir_node *proj_data;   /**< linked list of all parameter access proj's */
60 } collect_t;
61
62 /**
63  * walker for collecting data, fills a collect_t environment
64  */
65 static void collect_data(ir_node *node, void *env) {
66         collect_t *data = env;
67         ir_node *pred;
68         ir_op *op;
69
70         switch (get_irn_opcode(node)) {
71         case iro_Proj:
72                 pred = get_Proj_pred(node);
73
74                 op = get_irn_op(pred);
75                 if (op == op_Proj) {
76                         ir_node *start = get_Proj_pred(pred);
77
78                         if (is_Start(start)) {
79                                 if (get_Proj_proj(pred) == pn_Start_T_args) {
80                                         /* found Proj(ProjT(Start)) */
81                                         set_irn_link(node, data->proj_data);
82                                         data->proj_data = node;
83                                 }
84                         }
85                 } else if (op == op_Start) {
86                         if (get_Proj_proj(node) == pn_Start_X_initial_exec) {
87                                 /* found ProjX(Start) */
88                                 data->proj_X = node;
89                         }
90                 }
91                 break;
92         case iro_Block: {
93                 int i, n_pred = get_Block_n_cfgpreds(node);
94
95                 /*
96                  * the first block has the initial exec as cfg predecessor
97                  */
98                 if (node != get_irg_start_block(current_ir_graph)) {
99                         for (i = 0; i < n_pred; ++i) {
100                                 if (get_Block_cfgpred(node, i) == data->proj_X) {
101                                         data->block   = node;
102                                         data->blk_idx = i;
103                                         break;
104                                 }
105                         }
106                 }
107                 break;
108         }
109         default:
110                 break;
111         }
112 }
113
114 typedef enum tail_rec_variants {
115         TR_DIRECT,  /**< direct return value, i.e. return func(). */
116         TR_ADD,     /**< additive return value, i.e. return x +/- func() */
117         TR_MUL,     /**< multiplicative return value, i.e. return x * func() or return -func() */
118         TR_BAD,     /**< any other transformation */
119         TR_UNKNOWN  /**< during construction */
120 } tail_rec_variants;
121
122 typedef struct tr_env {
123         int               n_tail_calls;  /**< number of tail calls found */
124         int               n_ress;        /**< number of return values */
125         tail_rec_variants *variants;     /**< return value variants */
126         ir_node           *rets;         /**< list of returns that can be transformed */
127 } tr_env;
128
129
130 /**
131  * do the graph reconstruction for tail-recursion elimination
132  *
133  * @param irg           the graph that will reconstructed
134  * @param rets          linked list of all rets
135  * @param n_tail_calls  number of tail-recursion calls
136  */
137 static void do_opt_tail_rec(ir_graph *irg, tr_env *env) {
138         ir_node *end_block = get_irg_end_block(irg);
139         ir_node *block, *jmp, *call, *calls;
140         ir_node **in;
141         ir_node **phis;
142         ir_node ***call_params;
143         ir_node *p, *n;
144         int i, j, n_params, n_locs;
145         collect_t data;
146         int rem            = get_optimize();
147         ir_entity *ent     = get_irg_entity(irg);
148         ir_type *method_tp = get_entity_type(ent);
149         ir_graph *old      = current_ir_graph;
150
151         current_ir_graph = irg;
152
153         assert(env->n_tail_calls > 0);
154
155         /* we add new nodes, so the outs are inconsistent */
156         set_irg_outs_inconsistent(irg);
157
158         /* we add new blocks and change the control flow */
159         set_irg_doms_inconsistent(irg);
160         set_irg_extblk_inconsistent(irg);
161
162         /* we add a new loop */
163         set_irg_loopinfo_inconsistent(irg);
164
165         /* calls are removed */
166         set_trouts_inconsistent();
167
168         /* we must build some new nodes WITHOUT CSE */
169         set_optimize(0);
170
171         /* collect needed data */
172         data.proj_X    = NULL;
173         data.block     = NULL;
174         data.blk_idx   = -1;
175         data.proj_m    = get_irg_initial_mem(irg);
176         data.proj_data = NULL;
177         irg_walk_graph(irg, NULL, collect_data, &data);
178
179         /* check number of arguments */
180         call = get_irn_link(end_block);
181         n_params = get_Call_n_params(call);
182
183         assert(data.proj_X && "Could not find initial exec from Start");
184         assert(data.block  && "Could not find first block");
185         assert(data.proj_m && "Could not find initial memory");
186         assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
187
188         /* allocate in's for phi and block construction */
189         NEW_ARR_A(ir_node *, in, env->n_tail_calls + 1);
190
191         in[0] = data.proj_X;
192
193         /* turn Return's into Jmp's */
194         for (i = 1, p = env->rets; p; p = n) {
195                 ir_node *block = get_nodes_block(p);
196
197                 n = get_irn_link(p);
198                 in[i++] = new_r_Jmp(irg, block);
199
200                 // exchange(p, new_r_Bad(irg));
201
202                 /* we might generate an endless loop, so add
203                  * the block to the keep-alive list */
204                 add_End_keepalive(get_irg_end(irg), block);
205         }
206
207         /* create a new block at start */
208         block = new_r_Block(irg, env->n_tail_calls + 1, in);
209         jmp   = new_r_Jmp(irg, block);
210
211         /* the old first block is now the second one */
212         set_Block_cfgpred(data.block, data.blk_idx, jmp);
213
214         /* allocate phi's, position 0 contains the memory phi */
215         NEW_ARR_A(ir_node *, phis, n_params + 1);
216
217         /* build the memory phi */
218         i = 0;
219         in[i] = new_r_Proj(irg, get_irg_start_block(irg), get_irg_start(irg), mode_M, pn_Start_M);
220         set_irg_initial_mem(irg, in[i]);
221         ++i;
222
223         for (calls = call; calls; calls = get_irn_link(calls)) {
224                 in[i] = get_Call_mem(calls);
225                 ++i;
226         }
227         assert(i == env->n_tail_calls + 1);
228
229         phis[0] = new_r_Phi(irg, block, env->n_tail_calls + 1, in, mode_M);
230
231         /* build the data Phi's */
232         if (n_params > 0) {
233                 ir_node *calls;
234                 ir_node *args;
235                 ir_node *args_bl;
236
237                 NEW_ARR_A(ir_node **, call_params, env->n_tail_calls);
238
239                 /* collect all parameters */
240                 for (i = 0, calls = call; calls; calls = get_irn_link(calls)) {
241                         call_params[i] = get_Call_param_arr(calls);
242                         ++i;
243                 }
244
245                 /* build new Proj's and Phi's */
246                 args    = get_irg_args(irg);
247                 args_bl = get_nodes_block(args);
248                 for (i = 0; i < n_params; ++i) {
249                         ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
250
251                         in[0] = new_r_Proj(irg, args_bl, args, mode, i);
252                         for (j = 0; j < env->n_tail_calls; ++j)
253                                 in[j + 1] = call_params[j][i];
254
255                         phis[i + 1] = new_r_Phi(irg, block, env->n_tail_calls + 1, in, mode);
256                 }
257         }
258
259         /*
260          * ok, we are here, so we have build and collected all needed Phi's
261          * now exchange all Projs into links to Phi
262          */
263         exchange(data.proj_m, phis[0]);
264         for (p = data.proj_data; p; p = n) {
265                 long proj = get_Proj_proj(p);
266
267                 assert(0 <= proj && proj < n_params);
268                 n = get_irn_link(p);
269                 exchange(p, phis[proj + 1]);
270         }
271
272         /* tail recursion was done, all info is invalid */
273         set_irg_doms_inconsistent(irg);
274         set_irg_outs_inconsistent(irg);
275         set_irg_extblk_inconsistent(irg);
276         set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
277         set_trouts_inconsistent();
278         set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
279
280         set_optimize(rem);
281
282         /* check if we need new values */
283         n_locs = 0;
284         for (i = 0; i < env->n_ress; ++i) {
285                 if (env->variants[i] != TR_DIRECT)
286                         ++n_locs;
287         }
288
289         if (n_locs > 0) {
290                 ir_node *bad, *start_block;
291                 ir_node **in;
292                 ir_mode **modes;
293
294                 NEW_ARR_A(ir_node *, in, n_locs);
295                 NEW_ARR_A(ir_mode *, modes, n_locs);
296                 ssa_cons_start(irg, n_locs);
297
298                 start_block = get_irg_start_block(irg);
299                 set_cur_block(start_block);
300
301                 for (i = 0; i < env->n_ress; ++i) {
302                         ir_type *tp = get_method_res_type(method_tp, i);
303                         ir_mode *mode = get_type_mode(tp);
304
305                         modes[i] = mode;
306                         if (env->variants[i] == TR_ADD) {
307                                 set_value(i, new_Const(mode, get_mode_null(mode)));
308                         } else if (env->variants[i] == TR_MUL) {
309                                 set_value(i, new_Const(mode, get_mode_one(mode)));
310                         }
311                 }
312                 mature_immBlock(start_block);
313
314                 /* no: we can kill all returns */
315                 bad = get_irg_bad(irg);
316
317                 for (p = env->rets; p; p = n) {
318                         ir_node *block = get_nodes_block(p);
319                         ir_node *call, *mem, *jmp, *tuple;
320
321                         set_cur_block(block);
322                         n = get_irn_link(p);
323
324                         call = skip_Proj(get_Return_mem(p));
325                         assert(is_Call(call));
326
327                         mem = get_Call_mem(call);
328
329                         /* create a new jump, free of CSE */
330                         set_optimize(0);
331                         jmp = new_Jmp();
332                         set_optimize(rem);
333
334                         for (i = 0; i < env->n_ress; ++i) {
335                                 if (env->variants[i] != TR_DIRECT) {
336                                         in[i] = get_value(i, modes[i]);
337                                 } else {
338                                         in[i] = bad;
339                                 }
340                         }
341                         /* create a new tuple for the return values */
342                         tuple = new_Tuple(env->n_ress, in);
343
344                         turn_into_tuple(call, pn_Call_max);
345                         set_Tuple_pred(call, pn_Call_M,                mem);
346                         set_Tuple_pred(call, pn_Call_X_regular,        jmp);
347                         set_Tuple_pred(call, pn_Call_X_except,         bad);
348                         set_Tuple_pred(call, pn_Call_T_result,         tuple);
349                         set_Tuple_pred(call, pn_Call_M_except,         mem);
350                         set_Tuple_pred(call, pn_Call_P_value_res_base, bad);
351
352                         for (i = 0; i < env->n_ress; ++i) {
353                                 ir_node *res = get_Return_res(p, i);
354                                 if (env->variants[i] != TR_DIRECT) {
355                                         set_value(i, res);
356                                 }
357                         }
358
359                         exchange(p, bad);
360                 }
361
362                 /* finally fix all other returns */
363                 end_block = get_irg_end_block(irg);
364                 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
365                         ir_node *ret = get_Block_cfgpred(end_block, i);
366
367                         /* search all Returns of a block */
368                         if (! is_Return(ret))
369                                 continue;
370
371                         set_cur_block(get_nodes_block(ret));
372                         for (j = 0; j < env->n_ress; ++j) {
373                                 ir_node *pred = get_Return_res(ret, j);
374                                 ir_node *n;
375
376                                 switch (env->variants[j]) {
377                                 case TR_DIRECT:
378                                         continue;
379
380                                 case TR_ADD:
381                                         n = get_value(j, modes[j]);
382                                         n = new_Add(n, pred, modes[j]);
383                                         set_Return_res(ret, j, n);
384                                         break;
385
386                                 case TR_MUL:
387                                         n = get_value(j, modes[j]);
388                                         n = new_Mul(n, pred, modes[j]);
389                                         set_Return_res(ret, j, n);
390                                         break;
391
392                                 default:
393                                         assert(!"unexpected tail recursion variant");
394                                 }
395                         }
396                 }
397                 ssa_cons_finish(irg);
398         } else {
399                 ir_node *bad = get_irg_bad(irg);
400
401                 /* no: we can kill all returns */
402                 for (p = env->rets; p; p = n) {
403                         n = get_irn_link(p);
404                         exchange(p, bad);
405                 }
406         }
407         current_ir_graph = old;
408 }
409
410 /**
411  * Check the lifetime of locals in the given graph.
412  * Tail recursion can only be done, if we can prove that
413  * the lifetime of locals end with the recursive call.
414  * We do this by checking that no address of a local variable is
415  * stored or transmitted as an argument to a call.
416  *
417  * @return non-zero if it's ok to do tail recursion
418  */
419 static int check_lifetime_of_locals(ir_graph *irg) {
420         ir_node *irg_frame, *irg_val_param_base;
421         int i;
422
423         irg_frame = get_irg_frame(irg);
424         for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
425                 ir_node *succ = get_irn_out(irg_frame, i);
426
427                 if (is_Sel(succ) && is_address_taken(succ))
428                         return 0;
429         }
430
431         /* Check if we have compound arguments.
432            For now, we cannot handle them, */
433         irg_val_param_base = get_irg_value_param_base(irg);
434         if (get_irn_n_outs(irg_val_param_base) > 0)
435                 return 0;
436
437         return 1;
438 }
439
440 /**
441  * Examine irn and detect the recursion variant.
442  */
443 static tail_rec_variants find_variant(ir_node *irn, ir_node *call) {
444         ir_node           *a, *b;
445         tail_rec_variants va, vb, res;
446
447         if (skip_Proj(skip_Proj(irn)) == call) {
448                 /* found it */
449                 return TR_DIRECT;
450         }
451         switch (get_irn_opcode(irn)) {
452         case iro_Add:
453                 /* try additive */
454                 a = get_Add_left(irn);
455                 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
456                         /* we are outside, ignore */
457                         va = TR_UNKNOWN;
458                 } else {
459                         va = find_variant(a, call);
460                         if (va == TR_BAD)
461                                 return TR_BAD;
462                 }
463                 b = get_Add_right(irn);
464                 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
465                         /* we are outside, ignore */
466                         vb = TR_UNKNOWN;
467                 } else {
468                         vb = find_variant(b, call);
469                         if (vb == TR_BAD)
470                                 return TR_BAD;
471                 }
472                 if (va == vb) {
473                         res = va;
474                 }
475                 else if (va == TR_UNKNOWN)
476                         res = vb;
477                 else if (vb == TR_UNKNOWN)
478                         res = va;
479                 else {
480                         /* they are different but none is TR_UNKNOWN -> incompatible */
481                         return TR_BAD;
482                 }
483                 if (res == TR_DIRECT || res == TR_ADD)
484                         return TR_ADD;
485                 /* not compatible */
486                 return TR_BAD;
487
488         case iro_Sub:
489                 /* try additive, but return value must be left */
490                 a = get_Sub_left(irn);
491                 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
492                         /* we are outside, ignore */
493                         va = TR_UNKNOWN;
494                 } else {
495                         va = find_variant(a, call);
496                         if (va == TR_BAD)
497                                 return TR_BAD;
498                 }
499                 b = get_Sub_right(irn);
500                 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
501                         /* we are outside, ignore */
502                         vb = TR_UNKNOWN;
503                 } else {
504                         vb = find_variant(b, call);
505                         if (vb != TR_UNKNOWN)
506                                 return TR_BAD;
507                 }
508                 res = va;
509                 if (res == TR_DIRECT || res == TR_ADD)
510                         return res;
511                 /* not compatible */
512                 return TR_BAD;
513
514         case iro_Mul:
515                 /* try multiplicative */
516                 a = get_Mul_left(irn);
517                 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
518                         /* we are outside, ignore */
519                         va = TR_UNKNOWN;
520                 } else {
521                         va = find_variant(a, call);
522                         if (va == TR_BAD)
523                                 return TR_BAD;
524                 }
525                 b = get_Mul_right(irn);
526                 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
527                         /* we are outside, ignore */
528                         vb = TR_UNKNOWN;
529                 } else {
530                         vb = find_variant(b, call);
531                         if (vb == TR_BAD)
532                                 return TR_BAD;
533                 }
534                 if (va == vb) {
535                         res = va;
536                 }
537                 else if (va == TR_UNKNOWN)
538                         res = vb;
539                 else if (vb == TR_UNKNOWN)
540                         res = va;
541                 else {
542                         /* they are different but none is TR_UNKNOWN -> incompatible */
543                         return TR_BAD;
544                 }
545                 if (res == TR_DIRECT || res == TR_MUL)
546                         return TR_MUL;
547                 /* not compatible */
548                 return TR_BAD;
549
550         case iro_Minus:
551                 /* try multiplicative */
552                 a = get_Minus_op(irn);
553                 res =  find_variant(a, call);
554                 if (res == TR_DIRECT)
555                         return TR_MUL;
556                 if (res == TR_MUL || res == TR_UNKNOWN)
557                         return res;
558                 /* not compatible */
559                 return TR_BAD;
560
561         default:
562                 return TR_UNKNOWN;
563         }
564 }
565
566
567 /*
568  * convert simple tail-calls into loops
569  */
570 int opt_tail_rec_irg(ir_graph *irg) {
571         tr_env            env;
572         ir_node           *end_block;
573         int               i, n_ress, n_tail_calls = 0;
574         ir_node           *rets = NULL;
575         ir_type           *mtd_type, *call_type;
576         ir_entity         *ent;
577
578         assure_irg_outs(irg);
579
580         if (! check_lifetime_of_locals(irg))
581                 return 0;
582
583
584         ent      = get_irg_entity(irg);
585         mtd_type = get_entity_type(ent);
586     n_ress   = get_method_n_ress(mtd_type);
587
588         env.variants = NULL;
589         env.n_ress   = n_ress;
590
591         if (n_ress > 0) {
592                 NEW_ARR_A(tail_rec_variants, env.variants, n_ress);
593
594                 for (i = 0; i < n_ress; ++i)
595                         env.variants[i] = TR_DIRECT;
596         }
597
598         /*
599          * This tail recursion optimization works best
600          * if the Returns are normalized.
601          */
602         normalize_n_returns(irg);
603
604         end_block = get_irg_end_block(irg);
605         set_irn_link(end_block, NULL);
606
607         for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
608                 ir_node *ret = get_Block_cfgpred(end_block, i);
609                 ir_node *call, *call_ptr;
610                 int j;
611                 ir_node **ress;
612
613                 /* search all Returns of a block */
614                 if (! is_Return(ret))
615                         continue;
616
617                 /* check, if it's a Return self() */
618                 call = skip_Proj(get_Return_mem(ret));
619                 if (! is_Call(call))
620                         continue;
621
622                 /* the call must be in the same block as the return */
623                 if (get_nodes_block(call) != get_nodes_block(ret))
624                         continue;
625
626                 /* check if it's a recursive call */
627                 call_ptr = get_Call_ptr(call);
628
629                 if (! is_Global(call_ptr))
630                         continue;
631
632                 ent = get_Global_entity(call_ptr);
633                 if (!ent || get_entity_irg(ent) != irg)
634                         continue;
635
636                 /*
637                  * Check, that the types match. At least in C
638                  * this might fail.
639                  */
640                 mtd_type  = get_entity_type(ent);
641                 call_type = get_Call_type(call);
642
643                 if (mtd_type != call_type) {
644                         /*
645                          * Hmm, the types did not match, bad.
646                          * This can happen in C when no prototype is given
647                          * or K&R style is used.
648                          */
649 #if 0
650                         printf("Warning: Tail recursion fails because of different method and call types:\n");
651                         dump_type(mtd_type);
652                         dump_type(call_type);
653 #endif
654                         continue;
655                 }
656
657                 /* ok, mem is routed to a recursive call, check return args */
658                 ress = get_Return_res_arr(ret);
659                 for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
660                         tail_rec_variants var = find_variant(ress[j], call);
661
662                         if (var >= TR_BAD) {
663                                 /* cannot be transformed */
664                                 break;
665                         }
666                         if (var == TR_DIRECT)
667                                 var = env.variants[j];
668                         else if (env.variants[j] == TR_DIRECT)
669                                 env.variants[j] = var;
670                         if (env.variants[j] != var) {
671                                 /* not compatible */
672                                 break;
673                         }
674                 }
675                 if (j >= 0)
676                         continue;
677
678                 /* here, we have found a call */
679                 set_irn_link(call, get_irn_link(end_block));
680                 set_irn_link(end_block, call);
681                 ++n_tail_calls;
682
683                 /* link all returns, we will need this */
684                 set_irn_link(ret, rets);
685                 rets = ret;
686         }
687
688         /* now, end_block->link contains the list of all tail calls */
689         if (n_tail_calls <= 0)
690                 return 0;
691
692         DB((dbg, LEVEL_2, "  Performing tail recursion for graph %s and %d Calls\n",
693             get_entity_ld_name(get_irg_entity(irg)), n_tail_calls));
694
695         hook_tail_rec(irg, n_tail_calls);
696
697         env.n_tail_calls = n_tail_calls;
698         env.rets         = rets;
699         do_opt_tail_rec(irg, &env);
700
701         return n_tail_calls;
702 }
703
704 /*
705  * optimize tail recursion away
706  */
707 void opt_tail_recursion(void) {
708         int i;
709         int n_opt_applications = 0;
710         ir_graph *irg;
711
712         FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
713
714         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
715                 irg = get_irp_irg(i);
716
717                 current_ir_graph = irg;
718
719                 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
720                 if (opt_tail_rec_irg(irg))
721                         ++n_opt_applications;
722
723                 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
724         }
725
726         DB((dbg, LEVEL_1, "Performed tail recursion for %d of %d graphs\n",
727             n_opt_applications, get_irp_n_irgs()));
728 }