2 * Copyright (C) 1995-2008 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief Tail-recursion call optimization.
24 * @author Michael Beck
33 #include "iroptimize.h"
34 #include "scalar_replace.h"
41 #include "irgraph_t.h"
50 DEBUG_ONLY(static firm_dbg_module_t *dbg);
53 * the environment for collecting data
55 typedef struct _collect_t {
56 ir_node *proj_X; /**< initial exec proj */
57 ir_node *block; /**< old first block */
58 int blk_idx; /**< cfgpred index of the initial exec in block */
59 ir_node *proj_m; /**< memory from start proj's */
60 ir_node *proj_data; /**< linked list of all parameter access proj's */
64 * walker for collecting data, fills a collect_t environment
66 static void collect_data(ir_node *node, void *env) {
67 collect_t *data = env;
71 switch (get_irn_opcode(node)) {
73 pred = get_Proj_pred(node);
75 op = get_irn_op(pred);
77 ir_node *start = get_Proj_pred(pred);
79 if (is_Start(start)) {
80 if (get_Proj_proj(pred) == pn_Start_T_args) {
81 /* found Proj(ProjT(Start)) */
82 set_irn_link(node, data->proj_data);
83 data->proj_data = node;
86 } else if (op == op_Start) {
87 if (get_Proj_proj(node) == pn_Start_X_initial_exec) {
88 /* found ProjX(Start) */
94 int i, n_pred = get_Block_n_cfgpreds(node);
97 * the first block has the initial exec as cfg predecessor
99 if (node != get_irg_start_block(current_ir_graph)) {
100 for (i = 0; i < n_pred; ++i) {
101 if (get_Block_cfgpred(node, i) == data->proj_X) {
115 typedef enum tail_rec_variants {
116 TR_DIRECT, /**< direct return value, i.e. return func(). */
117 TR_ADD, /**< additive return value, i.e. return x +/- func() */
118 TR_MUL, /**< multiplicative return value, i.e. return x * func() or return -func() */
119 TR_BAD, /**< any other transformation */
120 TR_UNKNOWN /**< during construction */
123 typedef struct tr_env {
124 int n_tail_calls; /**< number of tail calls found */
125 int n_ress; /**< number of return values */
126 tail_rec_variants *variants; /**< return value variants */
127 ir_node *rets; /**< list of returns that can be transformed */
132 * do the graph reconstruction for tail-recursion elimination
134 * @param irg the graph that will reconstructed
135 * @param rets linked list of all rets
136 * @param n_tail_calls number of tail-recursion calls
138 static void do_opt_tail_rec(ir_graph *irg, tr_env *env) {
139 ir_node *end_block = get_irg_end_block(irg);
140 ir_node *block, *jmp, *call, *calls;
143 ir_node ***call_params;
145 int i, j, n_params, n_locs;
147 int rem = get_optimize();
148 ir_entity *ent = get_irg_entity(irg);
149 ir_type *method_tp = get_entity_type(ent);
150 ir_graph *old = current_ir_graph;
152 current_ir_graph = irg;
154 assert(env->n_tail_calls > 0);
156 /* we add new nodes, so the outs are inconsistent */
157 set_irg_outs_inconsistent(irg);
159 /* we add new blocks and change the control flow */
160 set_irg_doms_inconsistent(irg);
161 set_irg_extblk_inconsistent(irg);
163 /* we add a new loop */
164 set_irg_loopinfo_inconsistent(irg);
166 /* calls are removed */
167 set_trouts_inconsistent();
169 /* we must build some new nodes WITHOUT CSE */
172 /* collect needed data */
176 data.proj_m = get_irg_initial_mem(irg);
177 data.proj_data = NULL;
178 irg_walk_graph(irg, NULL, collect_data, &data);
180 /* check number of arguments */
181 call = get_irn_link(end_block);
182 n_params = get_Call_n_params(call);
184 assert(data.proj_X && "Could not find initial exec from Start");
185 assert(data.block && "Could not find first block");
186 assert(data.proj_m && "Could not find initial memory");
187 assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
189 /* allocate in's for phi and block construction */
190 NEW_ARR_A(ir_node *, in, env->n_tail_calls + 1);
194 /* turn Return's into Jmp's */
195 for (i = 1, p = env->rets; p; p = n) {
196 ir_node *block = get_nodes_block(p);
199 in[i++] = new_r_Jmp(block);
201 // exchange(p, new_r_Bad(irg));
203 /* we might generate an endless loop, so add
204 * the block to the keep-alive list */
205 add_End_keepalive(get_irg_end(irg), block);
208 /* create a new block at start */
209 block = new_r_Block(irg, env->n_tail_calls + 1, in);
210 jmp = new_r_Jmp(block);
212 /* the old first block is now the second one */
213 set_Block_cfgpred(data.block, data.blk_idx, jmp);
215 /* allocate phi's, position 0 contains the memory phi */
216 NEW_ARR_A(ir_node *, phis, n_params + 1);
218 /* build the memory phi */
220 in[i] = new_r_Proj(get_irg_start_block(irg), get_irg_start(irg), mode_M, pn_Start_M);
221 set_irg_initial_mem(irg, in[i]);
224 for (calls = call; calls; calls = get_irn_link(calls)) {
225 in[i] = get_Call_mem(calls);
228 assert(i == env->n_tail_calls + 1);
230 phis[0] = new_r_Phi(block, env->n_tail_calls + 1, in, mode_M);
232 /* build the data Phi's */
238 NEW_ARR_A(ir_node **, call_params, env->n_tail_calls);
240 /* collect all parameters */
241 for (i = 0, calls = call; calls; calls = get_irn_link(calls)) {
242 call_params[i] = get_Call_param_arr(calls);
246 /* build new Proj's and Phi's */
247 args = get_irg_args(irg);
248 args_bl = get_nodes_block(args);
249 for (i = 0; i < n_params; ++i) {
250 ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
252 in[0] = new_r_Proj(args_bl, args, mode, i);
253 for (j = 0; j < env->n_tail_calls; ++j)
254 in[j + 1] = call_params[j][i];
256 phis[i + 1] = new_r_Phi(block, env->n_tail_calls + 1, in, mode);
261 * ok, we are here, so we have build and collected all needed Phi's
262 * now exchange all Projs into links to Phi
264 exchange(data.proj_m, phis[0]);
265 for (p = data.proj_data; p; p = n) {
266 long proj = get_Proj_proj(p);
268 assert(0 <= proj && proj < n_params);
270 exchange(p, phis[proj + 1]);
273 /* tail recursion was done, all info is invalid */
274 set_irg_doms_inconsistent(irg);
275 set_irg_outs_inconsistent(irg);
276 set_irg_extblk_inconsistent(irg);
277 set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
278 set_trouts_inconsistent();
279 set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
283 /* check if we need new values */
285 for (i = 0; i < env->n_ress; ++i) {
286 if (env->variants[i] != TR_DIRECT)
291 ir_node *bad, *start_block;
295 NEW_ARR_A(ir_node *, in, n_locs);
296 NEW_ARR_A(ir_mode *, modes, n_locs);
297 ssa_cons_start(irg, n_locs);
299 start_block = get_irg_start_block(irg);
300 set_cur_block(start_block);
302 for (i = 0; i < env->n_ress; ++i) {
303 ir_type *tp = get_method_res_type(method_tp, i);
304 ir_mode *mode = get_type_mode(tp);
307 if (env->variants[i] == TR_ADD) {
308 set_value(i, new_Const(get_mode_null(mode)));
309 } else if (env->variants[i] == TR_MUL) {
310 set_value(i, new_Const(get_mode_one(mode)));
313 mature_immBlock(start_block);
315 /* no: we can kill all returns */
316 bad = get_irg_bad(irg);
318 for (p = env->rets; p; p = n) {
319 ir_node *block = get_nodes_block(p);
320 ir_node *call, *mem, *jmp, *tuple;
322 set_cur_block(block);
325 call = skip_Proj(get_Return_mem(p));
326 assert(is_Call(call));
328 mem = get_Call_mem(call);
330 /* create a new jump, free of CSE */
335 for (i = 0; i < env->n_ress; ++i) {
336 if (env->variants[i] != TR_DIRECT) {
337 in[i] = get_value(i, modes[i]);
342 /* create a new tuple for the return values */
343 tuple = new_Tuple(env->n_ress, in);
345 turn_into_tuple(call, pn_Call_max);
346 set_Tuple_pred(call, pn_Call_M, mem);
347 set_Tuple_pred(call, pn_Call_X_regular, jmp);
348 set_Tuple_pred(call, pn_Call_X_except, bad);
349 set_Tuple_pred(call, pn_Call_T_result, tuple);
350 set_Tuple_pred(call, pn_Call_M_except, mem);
351 set_Tuple_pred(call, pn_Call_P_value_res_base, bad);
353 for (i = 0; i < env->n_ress; ++i) {
354 ir_node *res = get_Return_res(p, i);
355 if (env->variants[i] != TR_DIRECT) {
363 /* finally fix all other returns */
364 end_block = get_irg_end_block(irg);
365 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
366 ir_node *ret = get_Block_cfgpred(end_block, i);
368 /* search all Returns of a block */
369 if (! is_Return(ret))
372 set_cur_block(get_nodes_block(ret));
373 for (j = 0; j < env->n_ress; ++j) {
374 ir_node *pred = get_Return_res(ret, j);
377 switch (env->variants[j]) {
382 n = get_value(j, modes[j]);
383 n = new_Add(n, pred, modes[j]);
384 set_Return_res(ret, j, n);
388 n = get_value(j, modes[j]);
389 n = new_Mul(n, pred, modes[j]);
390 set_Return_res(ret, j, n);
394 assert(!"unexpected tail recursion variant");
398 ssa_cons_finish(irg);
400 ir_node *bad = get_irg_bad(irg);
402 /* no: we can kill all returns */
403 for (p = env->rets; p; p = n) {
408 current_ir_graph = old;
412 * Check the lifetime of locals in the given graph.
413 * Tail recursion can only be done, if we can prove that
414 * the lifetime of locals end with the recursive call.
415 * We do this by checking that no address of a local variable is
416 * stored or transmitted as an argument to a call.
418 * @return non-zero if it's ok to do tail recursion
420 static int check_lifetime_of_locals(ir_graph *irg) {
423 ir_type *frame_tp = get_irg_frame_type(irg);
425 irg_frame = get_irg_frame(irg);
426 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
427 ir_node *succ = get_irn_out(irg_frame, i);
430 /* Check if we have compound arguments.
431 For now, we cannot handle them, */
432 if (get_entity_owner(get_Sel_entity(succ)) != frame_tp)
435 if (is_address_taken(succ))
443 * Examine irn and detect the recursion variant.
445 static tail_rec_variants find_variant(ir_node *irn, ir_node *call) {
447 tail_rec_variants va, vb, res;
449 if (skip_Proj(skip_Proj(irn)) == call) {
453 switch (get_irn_opcode(irn)) {
456 a = get_Add_left(irn);
457 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
458 /* we are outside, ignore */
461 va = find_variant(a, call);
465 b = get_Add_right(irn);
466 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
467 /* we are outside, ignore */
470 vb = find_variant(b, call);
477 else if (va == TR_UNKNOWN)
479 else if (vb == TR_UNKNOWN)
482 /* they are different but none is TR_UNKNOWN -> incompatible */
485 if (res == TR_DIRECT || res == TR_ADD)
491 /* try additive, but return value must be left */
492 a = get_Sub_left(irn);
493 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
494 /* we are outside, ignore */
497 va = find_variant(a, call);
501 b = get_Sub_right(irn);
502 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
503 /* we are outside, ignore */
506 vb = find_variant(b, call);
507 if (vb != TR_UNKNOWN)
511 if (res == TR_DIRECT || res == TR_ADD)
517 /* try multiplicative */
518 a = get_Mul_left(irn);
519 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
520 /* we are outside, ignore */
523 va = find_variant(a, call);
527 b = get_Mul_right(irn);
528 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
529 /* we are outside, ignore */
532 vb = find_variant(b, call);
539 else if (va == TR_UNKNOWN)
541 else if (vb == TR_UNKNOWN)
544 /* they are different but none is TR_UNKNOWN -> incompatible */
547 if (res == TR_DIRECT || res == TR_MUL)
553 /* try multiplicative */
554 a = get_Minus_op(irn);
555 res = find_variant(a, call);
556 if (res == TR_DIRECT)
558 if (res == TR_MUL || res == TR_UNKNOWN)
570 * convert simple tail-calls into loops
572 int opt_tail_rec_irg(ir_graph *irg) {
575 int i, n_ress, n_tail_calls = 0;
576 ir_node *rets = NULL;
577 ir_type *mtd_type, *call_type;
580 assure_irg_outs(irg);
582 if (! check_lifetime_of_locals(irg))
586 ent = get_irg_entity(irg);
587 mtd_type = get_entity_type(ent);
588 n_ress = get_method_n_ress(mtd_type);
594 NEW_ARR_A(tail_rec_variants, env.variants, n_ress);
596 for (i = 0; i < n_ress; ++i)
597 env.variants[i] = TR_DIRECT;
601 * This tail recursion optimization works best
602 * if the Returns are normalized.
604 normalize_n_returns(irg);
606 end_block = get_irg_end_block(irg);
607 set_irn_link(end_block, NULL);
609 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
610 ir_node *ret = get_Block_cfgpred(end_block, i);
611 ir_node *call, *call_ptr;
615 /* search all Returns of a block */
616 if (! is_Return(ret))
619 /* check, if it's a Return self() */
620 call = skip_Proj(get_Return_mem(ret));
624 /* the call must be in the same block as the return */
625 if (get_nodes_block(call) != get_nodes_block(ret))
628 /* check if it's a recursive call */
629 call_ptr = get_Call_ptr(call);
631 if (! is_Global(call_ptr))
634 ent = get_Global_entity(call_ptr);
635 if (!ent || get_entity_irg(ent) != irg)
639 * Check, that the types match. At least in C
642 mtd_type = get_entity_type(ent);
643 call_type = get_Call_type(call);
645 if (mtd_type != call_type) {
647 * Hmm, the types did not match, bad.
648 * This can happen in C when no prototype is given
649 * or K&R style is used.
652 printf("Warning: Tail recursion fails because of different method and call types:\n");
654 dump_type(call_type);
659 /* ok, mem is routed to a recursive call, check return args */
660 ress = get_Return_res_arr(ret);
661 for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
662 tail_rec_variants var = find_variant(ress[j], call);
665 /* cannot be transformed */
668 if (var == TR_DIRECT)
669 var = env.variants[j];
670 else if (env.variants[j] == TR_DIRECT)
671 env.variants[j] = var;
672 if (env.variants[j] != var) {
680 /* here, we have found a call */
681 set_irn_link(call, get_irn_link(end_block));
682 set_irn_link(end_block, call);
685 /* link all returns, we will need this */
686 set_irn_link(ret, rets);
690 /* now, end_block->link contains the list of all tail calls */
691 if (n_tail_calls <= 0)
694 DB((dbg, LEVEL_2, " Performing tail recursion for graph %s and %d Calls\n",
695 get_entity_ld_name(get_irg_entity(irg)), n_tail_calls));
697 hook_tail_rec(irg, n_tail_calls);
699 env.n_tail_calls = n_tail_calls;
701 do_opt_tail_rec(irg, &env);
706 ir_graph_pass_t *opt_tail_rec_irg_pass(const char *name, int verify, int dump)
708 return def_graph_pass_ret(name ? name : "tailrec", verify, dump, opt_tail_rec_irg);
712 * optimize tail recursion away
714 void opt_tail_recursion(void) {
716 int n_opt_applications = 0;
719 FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
721 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
722 irg = get_irp_irg(i);
724 current_ir_graph = irg;
726 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
727 if (opt_tail_rec_irg(irg))
728 ++n_opt_applications;
730 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
733 DB((dbg, LEVEL_1, "Performed tail recursion for %d of %d graphs\n",
734 n_opt_applications, get_irp_n_irgs()));
737 ir_prog_pass_t *opt_tail_recursion_pass(const char *name, int verify, int dump)
739 return def_prog_pass(name ? name : "tailrec", verify, dump, opt_tail_recursion);