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
35 #include "iroptimize.h"
36 #include "scalar_replace.h"
43 #include "irgraph_t.h"
52 DEBUG_ONLY(static firm_dbg_module_t *dbg);
55 * the environment for collecting data
57 typedef struct _collect_t {
58 ir_node *proj_X; /**< initial exec proj */
59 ir_node *block; /**< old first block */
60 int blk_idx; /**< cfgpred index of the initial exec in block */
61 ir_node *proj_m; /**< memory from start proj's */
62 ir_node *proj_data; /**< linked list of all parameter access proj's */
66 * walker for collecting data, fills a collect_t environment
68 static void collect_data(ir_node *node, void *env) {
69 collect_t *data = env;
73 switch (get_irn_opcode(node)) {
75 pred = get_Proj_pred(node);
77 op = get_irn_op(pred);
79 ir_node *start = get_Proj_pred(pred);
81 if (is_Start(start)) {
82 if (get_Proj_proj(pred) == pn_Start_T_args) {
83 /* found Proj(ProjT(Start)) */
84 set_irn_link(node, data->proj_data);
85 data->proj_data = node;
88 } else if (op == op_Start) {
89 if (get_Proj_proj(node) == pn_Start_X_initial_exec) {
90 /* found ProjX(Start) */
96 int i, n_pred = get_Block_n_cfgpreds(node);
99 * the first block has the initial exec as cfg predecessor
101 if (node != get_irg_start_block(current_ir_graph)) {
102 for (i = 0; i < n_pred; ++i) {
103 if (get_Block_cfgpred(node, i) == data->proj_X) {
117 typedef enum tail_rec_variants {
118 TR_DIRECT, /**< direct return value, i.e. return func(). */
119 TR_ADD, /**< additive return value, i.e. return x +/- func() */
120 TR_MUL, /**< multiplicative return value, i.e. return x * func() or return -func() */
121 TR_BAD, /**< any other transformation */
122 TR_UNKNOWN /**< during construction */
125 typedef struct tr_env {
126 int n_tail_calls; /**< number of tail calls found */
127 int n_ress; /**< number of return values */
128 tail_rec_variants *variants; /**< return value variants */
129 ir_node *rets; /**< list of returns that can be transformed */
134 * do the graph reconstruction for tail-recursion elimination
136 * @param irg the graph that will reconstructed
137 * @param rets linked list of all rets
138 * @param n_tail_calls number of tail-recursion calls
140 static void do_opt_tail_rec(ir_graph *irg, tr_env *env) {
141 ir_node *end_block = get_irg_end_block(irg);
142 ir_node *block, *jmp, *call, *calls;
145 ir_node ***call_params;
147 int i, j, n_params, n_locs;
149 int rem = get_optimize();
150 ir_entity *ent = get_irg_entity(irg);
151 ir_type *method_tp = get_entity_type(ent);
152 ir_graph *old = current_ir_graph;
154 current_ir_graph = irg;
156 assert(env->n_tail_calls > 0);
158 /* we add new nodes, so the outs are inconsistent */
159 set_irg_outs_inconsistent(irg);
161 /* we add new blocks and change the control flow */
162 set_irg_doms_inconsistent(irg);
163 set_irg_extblk_inconsistent(irg);
165 /* we add a new loop */
166 set_irg_loopinfo_inconsistent(irg);
168 /* calls are removed */
169 set_trouts_inconsistent();
171 /* we must build some new nodes WITHOUT CSE */
174 /* collect needed data */
178 data.proj_m = get_irg_initial_mem(irg);
179 data.proj_data = NULL;
180 irg_walk_graph(irg, NULL, collect_data, &data);
182 /* check number of arguments */
183 call = get_irn_link(end_block);
184 n_params = get_Call_n_params(call);
186 assert(data.proj_X && "Could not find initial exec from Start");
187 assert(data.block && "Could not find first block");
188 assert(data.proj_m && "Could not find initial memory");
189 assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
191 /* allocate in's for phi and block construction */
192 NEW_ARR_A(ir_node *, in, env->n_tail_calls + 1);
196 /* turn Return's into Jmp's */
197 for (i = 1, p = env->rets; p; p = n) {
198 ir_node *block = get_nodes_block(p);
201 in[i++] = new_r_Jmp(irg, block);
203 // exchange(p, new_r_Bad(irg));
205 /* we might generate an endless loop, so add
206 * the block to the keep-alive list */
207 add_End_keepalive(get_irg_end(irg), block);
210 /* create a new block at start */
211 block = new_r_Block(irg, env->n_tail_calls + 1, in);
212 jmp = new_r_Jmp(irg, block);
214 /* the old first block is now the second one */
215 set_Block_cfgpred(data.block, data.blk_idx, jmp);
217 /* allocate phi's, position 0 contains the memory phi */
218 NEW_ARR_A(ir_node *, phis, n_params + 1);
220 /* build the memory phi */
222 in[i] = new_r_Proj(irg, get_irg_start_block(irg), get_irg_start(irg), mode_M, pn_Start_M);
223 set_irg_initial_mem(irg, in[i]);
226 for (calls = call; calls; calls = get_irn_link(calls)) {
227 in[i] = get_Call_mem(calls);
230 assert(i == env->n_tail_calls + 1);
232 phis[0] = new_r_Phi(irg, block, env->n_tail_calls + 1, in, mode_M);
234 /* build the data Phi's */
240 NEW_ARR_A(ir_node **, call_params, env->n_tail_calls);
242 /* collect all parameters */
243 for (i = 0, calls = call; calls; calls = get_irn_link(calls)) {
244 call_params[i] = get_Call_param_arr(calls);
248 /* build new Proj's and Phi's */
249 args = get_irg_args(irg);
250 args_bl = get_nodes_block(args);
251 for (i = 0; i < n_params; ++i) {
252 ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
254 in[0] = new_r_Proj(irg, args_bl, args, mode, i);
255 for (j = 0; j < env->n_tail_calls; ++j)
256 in[j + 1] = call_params[j][i];
258 phis[i + 1] = new_r_Phi(irg, block, env->n_tail_calls + 1, in, mode);
263 * ok, we are here, so we have build and collected all needed Phi's
264 * now exchange all Projs into links to Phi
266 exchange(data.proj_m, phis[0]);
267 for (p = data.proj_data; p; p = n) {
268 long proj = get_Proj_proj(p);
270 assert(0 <= proj && proj < n_params);
272 exchange(p, phis[proj + 1]);
275 /* tail recursion was done, all info is invalid */
276 set_irg_doms_inconsistent(irg);
277 set_irg_outs_inconsistent(irg);
278 set_irg_extblk_inconsistent(irg);
279 set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
280 set_trouts_inconsistent();
281 set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
285 /* check if we need new values */
287 for (i = 0; i < env->n_ress; ++i) {
288 if (env->variants[i] != TR_DIRECT)
293 ir_node *bad, *start_block;
297 NEW_ARR_A(ir_node *, in, n_locs);
298 NEW_ARR_A(ir_mode *, modes, n_locs);
299 ssa_cons_start(irg, n_locs);
301 start_block = get_irg_start_block(irg);
302 set_cur_block(start_block);
304 for (i = 0; i < env->n_ress; ++i) {
305 ir_type *tp = get_method_res_type(method_tp, i);
306 ir_mode *mode = get_type_mode(tp);
309 if (env->variants[i] == TR_ADD) {
310 set_value(i, new_Const(mode, get_mode_null(mode)));
311 } else if (env->variants[i] == TR_MUL) {
312 set_value(i, new_Const(mode, get_mode_one(mode)));
315 mature_immBlock(start_block);
317 /* no: we can kill all returns */
318 bad = get_irg_bad(irg);
320 for (p = env->rets; p; p = n) {
321 ir_node *block = get_nodes_block(p);
322 ir_node *call, *mem, *jmp, *tuple;
324 set_cur_block(block);
327 call = skip_Proj(get_Return_mem(p));
328 assert(is_Call(call));
330 mem = get_Call_mem(call);
332 /* create a new jump, free of CSE */
337 for (i = 0; i < env->n_ress; ++i) {
338 if (env->variants[i] != TR_DIRECT) {
339 in[i] = get_value(i, modes[i]);
344 /* create a new tuple for the return values */
345 tuple = new_Tuple(env->n_ress, in);
347 turn_into_tuple(call, pn_Call_max);
348 set_Tuple_pred(call, pn_Call_M, mem);
349 set_Tuple_pred(call, pn_Call_X_regular, jmp);
350 set_Tuple_pred(call, pn_Call_X_except, bad);
351 set_Tuple_pred(call, pn_Call_T_result, tuple);
352 set_Tuple_pred(call, pn_Call_M_except, mem);
353 set_Tuple_pred(call, pn_Call_P_value_res_base, bad);
355 for (i = 0; i < env->n_ress; ++i) {
356 ir_node *res = get_Return_res(p, i);
357 if (env->variants[i] != TR_DIRECT) {
365 /* finally fix all other returns */
366 end_block = get_irg_end_block(irg);
367 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
368 ir_node *ret = get_Block_cfgpred(end_block, i);
370 /* search all Returns of a block */
371 if (! is_Return(ret))
374 set_cur_block(get_nodes_block(ret));
375 for (j = 0; j < env->n_ress; ++j) {
376 ir_node *pred = get_Return_res(ret, j);
379 switch (env->variants[j]) {
384 n = get_value(j, modes[j]);
385 n = new_Add(n, pred, modes[j]);
386 set_Return_res(ret, j, n);
390 n = get_value(j, modes[j]);
391 n = new_Mul(n, pred, modes[j]);
392 set_Return_res(ret, j, n);
396 assert(!"unexpected tail recursion variant");
400 ssa_cons_finish(irg);
402 ir_node *bad = get_irg_bad(irg);
404 /* no: we can kill all returns */
405 for (p = env->rets; p; p = n) {
410 current_ir_graph = old;
414 * Check the lifetime of locals in the given graph.
415 * Tail recursion can only be done, if we can prove that
416 * the lifetime of locals end with the recursive call.
417 * We do this by checking that no address of a local variable is
418 * stored or transmitted as an argument to a call.
420 * @return non-zero if it's ok to do tail recursion
422 static int check_lifetime_of_locals(ir_graph *irg) {
423 ir_node *irg_frame, *irg_val_param_base;
426 irg_frame = get_irg_frame(irg);
427 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
428 ir_node *succ = get_irn_out(irg_frame, i);
430 if (is_Sel(succ) && is_address_taken(succ))
434 /* Check if we have compound arguments.
435 For now, we cannot handle them, */
436 irg_val_param_base = get_irg_value_param_base(irg);
437 if (get_irn_n_outs(irg_val_param_base) > 0)
444 * Examine irn and detect the recursion variant.
446 static tail_rec_variants find_variant(ir_node *irn, ir_node *call) {
448 tail_rec_variants va, vb, res;
450 if (skip_Proj(skip_Proj(irn)) == call) {
454 switch (get_irn_opcode(irn)) {
457 a = get_Add_left(irn);
458 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
459 /* we are outside, ignore */
462 va = find_variant(a, call);
466 b = get_Add_right(irn);
467 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
468 /* we are outside, ignore */
471 vb = find_variant(b, call);
478 else if (va == TR_UNKNOWN)
480 else if (vb == TR_UNKNOWN)
483 /* they are different but none is TR_UNKNOWN -> incompatible */
486 if (res == TR_DIRECT || res == TR_ADD)
492 /* try additive, but return value must be left */
493 a = get_Sub_left(irn);
494 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
495 /* we are outside, ignore */
498 va = find_variant(a, call);
502 b = get_Sub_right(irn);
503 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
504 /* we are outside, ignore */
507 vb = find_variant(b, call);
508 if (vb != TR_UNKNOWN)
512 if (res == TR_DIRECT || res == TR_ADD)
518 /* try multiplicative */
519 a = get_Mul_left(irn);
520 if (get_irn_MacroBlock(a) != get_irn_MacroBlock(call)) {
521 /* we are outside, ignore */
524 va = find_variant(a, call);
528 b = get_Mul_right(irn);
529 if (get_irn_MacroBlock(b) != get_irn_MacroBlock(call)) {
530 /* we are outside, ignore */
533 vb = find_variant(b, call);
540 else if (va == TR_UNKNOWN)
542 else if (vb == TR_UNKNOWN)
545 /* they are different but none is TR_UNKNOWN -> incompatible */
548 if (res == TR_DIRECT || res == TR_MUL)
554 /* try multiplicative */
555 a = get_Minus_op(irn);
556 res = find_variant(a, call);
557 if (res == TR_DIRECT)
559 if (res == TR_MUL || res == TR_UNKNOWN)
571 * convert simple tail-calls into loops
573 int opt_tail_rec_irg(ir_graph *irg) {
576 int i, n_ress, n_tail_calls = 0;
577 ir_node *rets = NULL;
578 ir_type *mtd_type, *call_type;
581 assure_irg_outs(irg);
583 if (! check_lifetime_of_locals(irg))
587 ent = get_irg_entity(irg);
588 mtd_type = get_entity_type(ent);
589 n_ress = get_method_n_ress(mtd_type);
595 NEW_ARR_A(tail_rec_variants, env.variants, n_ress);
597 for (i = 0; i < n_ress; ++i)
598 env.variants[i] = TR_DIRECT;
602 * This tail recursion optimization works best
603 * if the Returns are normalized.
605 normalize_n_returns(irg);
607 end_block = get_irg_end_block(irg);
608 set_irn_link(end_block, NULL);
610 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
611 ir_node *ret = get_Block_cfgpred(end_block, i);
612 ir_node *call, *call_ptr;
616 /* search all Returns of a block */
617 if (! is_Return(ret))
620 /* check, if it's a Return self() */
621 call = skip_Proj(get_Return_mem(ret));
625 /* the call must be in the same block as the return */
626 if (get_nodes_block(call) != get_nodes_block(ret))
629 /* check if it's a recursive call */
630 call_ptr = get_Call_ptr(call);
632 if (! is_Global(call_ptr))
635 ent = get_Global_entity(call_ptr);
636 if (!ent || get_entity_irg(ent) != irg)
640 * Check, that the types match. At least in C
643 mtd_type = get_entity_type(ent);
644 call_type = get_Call_type(call);
646 if (mtd_type != call_type) {
648 * Hmm, the types did not match, bad.
649 * This can happen in C when no prototype is given
650 * or K&R style is used.
653 printf("Warning: Tail recursion fails because of different method and call types:\n");
655 dump_type(call_type);
660 /* ok, mem is routed to a recursive call, check return args */
661 ress = get_Return_res_arr(ret);
662 for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
663 tail_rec_variants var = find_variant(ress[j], call);
666 /* cannot be transformed */
669 if (var == TR_DIRECT)
670 var = env.variants[j];
671 else if (env.variants[j] == TR_DIRECT)
672 env.variants[j] = var;
673 if (env.variants[j] != var) {
681 /* here, we have found a call */
682 set_irn_link(call, get_irn_link(end_block));
683 set_irn_link(end_block, call);
686 /* link all returns, we will need this */
687 set_irn_link(ret, rets);
691 /* now, end_block->link contains the list of all tail calls */
692 if (n_tail_calls <= 0)
695 DB((dbg, LEVEL_2, " Performing tail recursion for graph %s and %d Calls\n",
696 get_entity_ld_name(get_irg_entity(irg)), n_tail_calls));
698 hook_tail_rec(irg, n_tail_calls);
700 env.n_tail_calls = n_tail_calls;
702 do_opt_tail_rec(irg, &env);
708 * optimize tail recursion away
710 void opt_tail_recursion(void) {
712 int n_opt_applications = 0;
715 FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
717 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
718 irg = get_irp_irg(i);
720 current_ir_graph = irg;
722 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
723 if (opt_tail_rec_irg(irg))
724 ++n_opt_applications;
726 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
729 DB((dbg, LEVEL_1, "Performed tail recursion for %d of %d graphs\n",
730 n_opt_applications, get_irp_n_irgs()));