tree-ssa.h: Remove all #include's
[gcc.git] / gcc / tree-tailcall.c
1 /* Tail call optimization on trees.
2 Copyright (C) 2003-2013 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "tm_p.h"
26 #include "basic-block.h"
27 #include "function.h"
28 #include "gimple.h"
29 #include "gimple-ssa.h"
30 #include "tree-cfg.h"
31 #include "tree-phinodes.h"
32 #include "tree-ssanames.h"
33 #include "tree-into-ssa.h"
34 #include "tree-dfa.h"
35 #include "gimple-pretty-print.h"
36 #include "except.h"
37 #include "tree-pass.h"
38 #include "flags.h"
39 #include "langhooks.h"
40 #include "dbgcnt.h"
41 #include "target.h"
42 #include "cfgloop.h"
43 #include "common/common-target.h"
44 #include "ipa-utils.h"
45
46 /* The file implements the tail recursion elimination. It is also used to
47 analyze the tail calls in general, passing the results to the rtl level
48 where they are used for sibcall optimization.
49
50 In addition to the standard tail recursion elimination, we handle the most
51 trivial cases of making the call tail recursive by creating accumulators.
52 For example the following function
53
54 int sum (int n)
55 {
56 if (n > 0)
57 return n + sum (n - 1);
58 else
59 return 0;
60 }
61
62 is transformed into
63
64 int sum (int n)
65 {
66 int acc = 0;
67
68 while (n > 0)
69 acc += n--;
70
71 return acc;
72 }
73
74 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
75 when we reach the return x statement, we should return a_acc + x * m_acc
76 instead. They are initially initialized to 0 and 1, respectively,
77 so the semantics of the function is obviously preserved. If we are
78 guaranteed that the value of the accumulator never change, we
79 omit the accumulator.
80
81 There are three cases how the function may exit. The first one is
82 handled in adjust_return_value, the other two in adjust_accumulator_values
83 (the second case is actually a special case of the third one and we
84 present it separately just for clarity):
85
86 1) Just return x, where x is not in any of the remaining special shapes.
87 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
88
89 2) return f (...), where f is the current function, is rewritten in a
90 classical tail-recursion elimination way, into assignment of arguments
91 and jump to the start of the function. Values of the accumulators
92 are unchanged.
93
94 3) return a + m * f(...), where a and m do not depend on call to f.
95 To preserve the semantics described before we want this to be rewritten
96 in such a way that we finally return
97
98 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
99
100 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
101 eliminate the tail call to f. Special cases when the value is just
102 added or just multiplied are obtained by setting a = 0 or m = 1.
103
104 TODO -- it is possible to do similar tricks for other operations. */
105
106 /* A structure that describes the tailcall. */
107
108 struct tailcall
109 {
110 /* The iterator pointing to the call statement. */
111 gimple_stmt_iterator call_gsi;
112
113 /* True if it is a call to the current function. */
114 bool tail_recursion;
115
116 /* The return value of the caller is mult * f + add, where f is the return
117 value of the call. */
118 tree mult, add;
119
120 /* Next tailcall in the chain. */
121 struct tailcall *next;
122 };
123
124 /* The variables holding the value of multiplicative and additive
125 accumulator. */
126 static tree m_acc, a_acc;
127
128 static bool suitable_for_tail_opt_p (void);
129 static bool optimize_tail_call (struct tailcall *, bool);
130 static void eliminate_tail_call (struct tailcall *);
131 static void find_tail_calls (basic_block, struct tailcall **);
132
133 /* Returns false when the function is not suitable for tail call optimization
134 from some reason (e.g. if it takes variable number of arguments). */
135
136 static bool
137 suitable_for_tail_opt_p (void)
138 {
139 if (cfun->stdarg)
140 return false;
141
142 return true;
143 }
144 /* Returns false when the function is not suitable for tail call optimization
145 from some reason (e.g. if it takes variable number of arguments).
146 This test must pass in addition to suitable_for_tail_opt_p in order to make
147 tail call discovery happen. */
148
149 static bool
150 suitable_for_tail_call_opt_p (void)
151 {
152 tree param;
153
154 /* alloca (until we have stack slot life analysis) inhibits
155 sibling call optimizations, but not tail recursion. */
156 if (cfun->calls_alloca)
157 return false;
158
159 /* If we are using sjlj exceptions, we may need to add a call to
160 _Unwind_SjLj_Unregister at exit of the function. Which means
161 that we cannot do any sibcall transformations. */
162 if (targetm_common.except_unwind_info (&global_options) == UI_SJLJ
163 && current_function_has_exception_handlers ())
164 return false;
165
166 /* Any function that calls setjmp might have longjmp called from
167 any called function. ??? We really should represent this
168 properly in the CFG so that this needn't be special cased. */
169 if (cfun->calls_setjmp)
170 return false;
171
172 /* ??? It is OK if the argument of a function is taken in some cases,
173 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
174 for (param = DECL_ARGUMENTS (current_function_decl);
175 param;
176 param = DECL_CHAIN (param))
177 if (TREE_ADDRESSABLE (param))
178 return false;
179
180 return true;
181 }
182
183 /* Checks whether the expression EXPR in stmt AT is independent of the
184 statement pointed to by GSI (in a sense that we already know EXPR's value
185 at GSI). We use the fact that we are only called from the chain of
186 basic blocks that have only single successor. Returns the expression
187 containing the value of EXPR at GSI. */
188
189 static tree
190 independent_of_stmt_p (tree expr, gimple at, gimple_stmt_iterator gsi)
191 {
192 basic_block bb, call_bb, at_bb;
193 edge e;
194 edge_iterator ei;
195
196 if (is_gimple_min_invariant (expr))
197 return expr;
198
199 if (TREE_CODE (expr) != SSA_NAME)
200 return NULL_TREE;
201
202 /* Mark the blocks in the chain leading to the end. */
203 at_bb = gimple_bb (at);
204 call_bb = gimple_bb (gsi_stmt (gsi));
205 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
206 bb->aux = &bb->aux;
207 bb->aux = &bb->aux;
208
209 while (1)
210 {
211 at = SSA_NAME_DEF_STMT (expr);
212 bb = gimple_bb (at);
213
214 /* The default definition or defined before the chain. */
215 if (!bb || !bb->aux)
216 break;
217
218 if (bb == call_bb)
219 {
220 for (; !gsi_end_p (gsi); gsi_next (&gsi))
221 if (gsi_stmt (gsi) == at)
222 break;
223
224 if (!gsi_end_p (gsi))
225 expr = NULL_TREE;
226 break;
227 }
228
229 if (gimple_code (at) != GIMPLE_PHI)
230 {
231 expr = NULL_TREE;
232 break;
233 }
234
235 FOR_EACH_EDGE (e, ei, bb->preds)
236 if (e->src->aux)
237 break;
238 gcc_assert (e);
239
240 expr = PHI_ARG_DEF_FROM_EDGE (at, e);
241 if (TREE_CODE (expr) != SSA_NAME)
242 {
243 /* The value is a constant. */
244 break;
245 }
246 }
247
248 /* Unmark the blocks. */
249 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
250 bb->aux = NULL;
251 bb->aux = NULL;
252
253 return expr;
254 }
255
256 /* Simulates the effect of an assignment STMT on the return value of the tail
257 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
258 additive factor for the real return value. */
259
260 static bool
261 process_assignment (gimple stmt, gimple_stmt_iterator call, tree *m,
262 tree *a, tree *ass_var)
263 {
264 tree op0, op1 = NULL_TREE, non_ass_var = NULL_TREE;
265 tree dest = gimple_assign_lhs (stmt);
266 enum tree_code code = gimple_assign_rhs_code (stmt);
267 enum gimple_rhs_class rhs_class = get_gimple_rhs_class (code);
268 tree src_var = gimple_assign_rhs1 (stmt);
269
270 /* See if this is a simple copy operation of an SSA name to the function
271 result. In that case we may have a simple tail call. Ignore type
272 conversions that can never produce extra code between the function
273 call and the function return. */
274 if ((rhs_class == GIMPLE_SINGLE_RHS || gimple_assign_cast_p (stmt))
275 && (TREE_CODE (src_var) == SSA_NAME))
276 {
277 /* Reject a tailcall if the type conversion might need
278 additional code. */
279 if (gimple_assign_cast_p (stmt)
280 && TYPE_MODE (TREE_TYPE (dest)) != TYPE_MODE (TREE_TYPE (src_var)))
281 return false;
282
283 if (src_var != *ass_var)
284 return false;
285
286 *ass_var = dest;
287 return true;
288 }
289
290 switch (rhs_class)
291 {
292 case GIMPLE_BINARY_RHS:
293 op1 = gimple_assign_rhs2 (stmt);
294
295 /* Fall through. */
296
297 case GIMPLE_UNARY_RHS:
298 op0 = gimple_assign_rhs1 (stmt);
299 break;
300
301 default:
302 return false;
303 }
304
305 /* Accumulator optimizations will reverse the order of operations.
306 We can only do that for floating-point types if we're assuming
307 that addition and multiplication are associative. */
308 if (!flag_associative_math)
309 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
310 return false;
311
312 if (rhs_class == GIMPLE_UNARY_RHS)
313 ;
314 else if (op0 == *ass_var
315 && (non_ass_var = independent_of_stmt_p (op1, stmt, call)))
316 ;
317 else if (op1 == *ass_var
318 && (non_ass_var = independent_of_stmt_p (op0, stmt, call)))
319 ;
320 else
321 return false;
322
323 switch (code)
324 {
325 case PLUS_EXPR:
326 *a = non_ass_var;
327 *ass_var = dest;
328 return true;
329
330 case POINTER_PLUS_EXPR:
331 if (op0 != *ass_var)
332 return false;
333 *a = non_ass_var;
334 *ass_var = dest;
335 return true;
336
337 case MULT_EXPR:
338 *m = non_ass_var;
339 *ass_var = dest;
340 return true;
341
342 case NEGATE_EXPR:
343 *m = build_minus_one_cst (TREE_TYPE (op0));
344 *ass_var = dest;
345 return true;
346
347 case MINUS_EXPR:
348 if (*ass_var == op0)
349 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
350 else
351 {
352 *m = build_minus_one_cst (TREE_TYPE (non_ass_var));
353 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
354 }
355
356 *ass_var = dest;
357 return true;
358
359 /* TODO -- Handle POINTER_PLUS_EXPR. */
360
361 default:
362 return false;
363 }
364 }
365
366 /* Propagate VAR through phis on edge E. */
367
368 static tree
369 propagate_through_phis (tree var, edge e)
370 {
371 basic_block dest = e->dest;
372 gimple_stmt_iterator gsi;
373
374 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
375 {
376 gimple phi = gsi_stmt (gsi);
377 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var)
378 return PHI_RESULT (phi);
379 }
380 return var;
381 }
382
383 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
384 added to the start of RET. */
385
386 static void
387 find_tail_calls (basic_block bb, struct tailcall **ret)
388 {
389 tree ass_var = NULL_TREE, ret_var, func, param;
390 gimple stmt, call = NULL;
391 gimple_stmt_iterator gsi, agsi;
392 bool tail_recursion;
393 struct tailcall *nw;
394 edge e;
395 tree m, a;
396 basic_block abb;
397 size_t idx;
398 tree var;
399
400 if (!single_succ_p (bb))
401 return;
402
403 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
404 {
405 stmt = gsi_stmt (gsi);
406
407 /* Ignore labels, returns, clobbers and debug stmts. */
408 if (gimple_code (stmt) == GIMPLE_LABEL
409 || gimple_code (stmt) == GIMPLE_RETURN
410 || gimple_clobber_p (stmt)
411 || is_gimple_debug (stmt))
412 continue;
413
414 /* Check for a call. */
415 if (is_gimple_call (stmt))
416 {
417 call = stmt;
418 ass_var = gimple_call_lhs (stmt);
419 break;
420 }
421
422 /* If the statement references memory or volatile operands, fail. */
423 if (gimple_references_memory_p (stmt)
424 || gimple_has_volatile_ops (stmt))
425 return;
426 }
427
428 if (gsi_end_p (gsi))
429 {
430 edge_iterator ei;
431 /* Recurse to the predecessors. */
432 FOR_EACH_EDGE (e, ei, bb->preds)
433 find_tail_calls (e->src, ret);
434
435 return;
436 }
437
438 /* If the LHS of our call is not just a simple register, we can't
439 transform this into a tail or sibling call. This situation happens,
440 in (e.g.) "*p = foo()" where foo returns a struct. In this case
441 we won't have a temporary here, but we need to carry out the side
442 effect anyway, so tailcall is impossible.
443
444 ??? In some situations (when the struct is returned in memory via
445 invisible argument) we could deal with this, e.g. by passing 'p'
446 itself as that argument to foo, but it's too early to do this here,
447 and expand_call() will not handle it anyway. If it ever can, then
448 we need to revisit this here, to allow that situation. */
449 if (ass_var && !is_gimple_reg (ass_var))
450 return;
451
452 /* We found the call, check whether it is suitable. */
453 tail_recursion = false;
454 func = gimple_call_fndecl (call);
455 if (func
456 && !DECL_BUILT_IN (func)
457 && recursive_call_p (current_function_decl, func))
458 {
459 tree arg;
460
461 for (param = DECL_ARGUMENTS (func), idx = 0;
462 param && idx < gimple_call_num_args (call);
463 param = DECL_CHAIN (param), idx ++)
464 {
465 arg = gimple_call_arg (call, idx);
466 if (param != arg)
467 {
468 /* Make sure there are no problems with copying. The parameter
469 have a copyable type and the two arguments must have reasonably
470 equivalent types. The latter requirement could be relaxed if
471 we emitted a suitable type conversion statement. */
472 if (!is_gimple_reg_type (TREE_TYPE (param))
473 || !useless_type_conversion_p (TREE_TYPE (param),
474 TREE_TYPE (arg)))
475 break;
476
477 /* The parameter should be a real operand, so that phi node
478 created for it at the start of the function has the meaning
479 of copying the value. This test implies is_gimple_reg_type
480 from the previous condition, however this one could be
481 relaxed by being more careful with copying the new value
482 of the parameter (emitting appropriate GIMPLE_ASSIGN and
483 updating the virtual operands). */
484 if (!is_gimple_reg (param))
485 break;
486 }
487 }
488 if (idx == gimple_call_num_args (call) && !param)
489 tail_recursion = true;
490 }
491
492 /* Make sure the tail invocation of this function does not refer
493 to local variables. */
494 FOR_EACH_LOCAL_DECL (cfun, idx, var)
495 {
496 if (TREE_CODE (var) != PARM_DECL
497 && auto_var_in_fn_p (var, cfun->decl)
498 && (ref_maybe_used_by_stmt_p (call, var)
499 || call_may_clobber_ref_p (call, var)))
500 return;
501 }
502
503 /* Now check the statements after the call. None of them has virtual
504 operands, so they may only depend on the call through its return
505 value. The return value should also be dependent on each of them,
506 since we are running after dce. */
507 m = NULL_TREE;
508 a = NULL_TREE;
509
510 abb = bb;
511 agsi = gsi;
512 while (1)
513 {
514 tree tmp_a = NULL_TREE;
515 tree tmp_m = NULL_TREE;
516 gsi_next (&agsi);
517
518 while (gsi_end_p (agsi))
519 {
520 ass_var = propagate_through_phis (ass_var, single_succ_edge (abb));
521 abb = single_succ (abb);
522 agsi = gsi_start_bb (abb);
523 }
524
525 stmt = gsi_stmt (agsi);
526
527 if (gimple_code (stmt) == GIMPLE_LABEL)
528 continue;
529
530 if (gimple_code (stmt) == GIMPLE_RETURN)
531 break;
532
533 if (gimple_clobber_p (stmt))
534 continue;
535
536 if (is_gimple_debug (stmt))
537 continue;
538
539 if (gimple_code (stmt) != GIMPLE_ASSIGN)
540 return;
541
542 /* This is a gimple assign. */
543 if (! process_assignment (stmt, gsi, &tmp_m, &tmp_a, &ass_var))
544 return;
545
546 if (tmp_a)
547 {
548 tree type = TREE_TYPE (tmp_a);
549 if (a)
550 a = fold_build2 (PLUS_EXPR, type, fold_convert (type, a), tmp_a);
551 else
552 a = tmp_a;
553 }
554 if (tmp_m)
555 {
556 tree type = TREE_TYPE (tmp_m);
557 if (m)
558 m = fold_build2 (MULT_EXPR, type, fold_convert (type, m), tmp_m);
559 else
560 m = tmp_m;
561
562 if (a)
563 a = fold_build2 (MULT_EXPR, type, fold_convert (type, a), tmp_m);
564 }
565 }
566
567 /* See if this is a tail call we can handle. */
568 ret_var = gimple_return_retval (stmt);
569
570 /* We may proceed if there either is no return value, or the return value
571 is identical to the call's return. */
572 if (ret_var
573 && (ret_var != ass_var))
574 return;
575
576 /* If this is not a tail recursive call, we cannot handle addends or
577 multiplicands. */
578 if (!tail_recursion && (m || a))
579 return;
580
581 /* For pointers only allow additions. */
582 if (m && POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
583 return;
584
585 nw = XNEW (struct tailcall);
586
587 nw->call_gsi = gsi;
588
589 nw->tail_recursion = tail_recursion;
590
591 nw->mult = m;
592 nw->add = a;
593
594 nw->next = *ret;
595 *ret = nw;
596 }
597
598 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
599
600 static void
601 add_successor_phi_arg (edge e, tree var, tree phi_arg)
602 {
603 gimple_stmt_iterator gsi;
604
605 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
606 if (PHI_RESULT (gsi_stmt (gsi)) == var)
607 break;
608
609 gcc_assert (!gsi_end_p (gsi));
610 add_phi_arg (gsi_stmt (gsi), phi_arg, e, UNKNOWN_LOCATION);
611 }
612
613 /* Creates a GIMPLE statement which computes the operation specified by
614 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
615 statement in the position specified by GSI. Returns the
616 tree node of the statement's result. */
617
618 static tree
619 adjust_return_value_with_ops (enum tree_code code, const char *label,
620 tree acc, tree op1, gimple_stmt_iterator gsi)
621 {
622
623 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
624 tree result = make_temp_ssa_name (ret_type, NULL, label);
625 gimple stmt;
626
627 if (POINTER_TYPE_P (ret_type))
628 {
629 gcc_assert (code == PLUS_EXPR && TREE_TYPE (acc) == sizetype);
630 code = POINTER_PLUS_EXPR;
631 }
632 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1))
633 && code != POINTER_PLUS_EXPR)
634 stmt = gimple_build_assign_with_ops (code, result, acc, op1);
635 else
636 {
637 tree tem;
638 if (code == POINTER_PLUS_EXPR)
639 tem = fold_build2 (code, TREE_TYPE (op1), op1, acc);
640 else
641 tem = fold_build2 (code, TREE_TYPE (op1),
642 fold_convert (TREE_TYPE (op1), acc), op1);
643 tree rhs = fold_convert (ret_type, tem);
644 rhs = force_gimple_operand_gsi (&gsi, rhs,
645 false, NULL, true, GSI_SAME_STMT);
646 stmt = gimple_build_assign (result, rhs);
647 }
648
649 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
650 return result;
651 }
652
653 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
654 the computation specified by CODE and OP1 and insert the statement
655 at the position specified by GSI as a new statement. Returns new SSA name
656 of updated accumulator. */
657
658 static tree
659 update_accumulator_with_ops (enum tree_code code, tree acc, tree op1,
660 gimple_stmt_iterator gsi)
661 {
662 gimple stmt;
663 tree var = copy_ssa_name (acc, NULL);
664 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1)))
665 stmt = gimple_build_assign_with_ops (code, var, acc, op1);
666 else
667 {
668 tree rhs = fold_convert (TREE_TYPE (acc),
669 fold_build2 (code,
670 TREE_TYPE (op1),
671 fold_convert (TREE_TYPE (op1), acc),
672 op1));
673 rhs = force_gimple_operand_gsi (&gsi, rhs,
674 false, NULL, false, GSI_CONTINUE_LINKING);
675 stmt = gimple_build_assign (var, rhs);
676 }
677 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
678 return var;
679 }
680
681 /* Adjust the accumulator values according to A and M after GSI, and update
682 the phi nodes on edge BACK. */
683
684 static void
685 adjust_accumulator_values (gimple_stmt_iterator gsi, tree m, tree a, edge back)
686 {
687 tree var, a_acc_arg, m_acc_arg;
688
689 if (m)
690 m = force_gimple_operand_gsi (&gsi, m, true, NULL, true, GSI_SAME_STMT);
691 if (a)
692 a = force_gimple_operand_gsi (&gsi, a, true, NULL, true, GSI_SAME_STMT);
693
694 a_acc_arg = a_acc;
695 m_acc_arg = m_acc;
696 if (a)
697 {
698 if (m_acc)
699 {
700 if (integer_onep (a))
701 var = m_acc;
702 else
703 var = adjust_return_value_with_ops (MULT_EXPR, "acc_tmp", m_acc,
704 a, gsi);
705 }
706 else
707 var = a;
708
709 a_acc_arg = update_accumulator_with_ops (PLUS_EXPR, a_acc, var, gsi);
710 }
711
712 if (m)
713 m_acc_arg = update_accumulator_with_ops (MULT_EXPR, m_acc, m, gsi);
714
715 if (a_acc)
716 add_successor_phi_arg (back, a_acc, a_acc_arg);
717
718 if (m_acc)
719 add_successor_phi_arg (back, m_acc, m_acc_arg);
720 }
721
722 /* Adjust value of the return at the end of BB according to M and A
723 accumulators. */
724
725 static void
726 adjust_return_value (basic_block bb, tree m, tree a)
727 {
728 tree retval;
729 gimple ret_stmt = gimple_seq_last_stmt (bb_seq (bb));
730 gimple_stmt_iterator gsi = gsi_last_bb (bb);
731
732 gcc_assert (gimple_code (ret_stmt) == GIMPLE_RETURN);
733
734 retval = gimple_return_retval (ret_stmt);
735 if (!retval || retval == error_mark_node)
736 return;
737
738 if (m)
739 retval = adjust_return_value_with_ops (MULT_EXPR, "mul_tmp", m_acc, retval,
740 gsi);
741 if (a)
742 retval = adjust_return_value_with_ops (PLUS_EXPR, "acc_tmp", a_acc, retval,
743 gsi);
744 gimple_return_set_retval (ret_stmt, retval);
745 update_stmt (ret_stmt);
746 }
747
748 /* Subtract COUNT and FREQUENCY from the basic block and it's
749 outgoing edge. */
750 static void
751 decrease_profile (basic_block bb, gcov_type count, int frequency)
752 {
753 edge e;
754 bb->count -= count;
755 if (bb->count < 0)
756 bb->count = 0;
757 bb->frequency -= frequency;
758 if (bb->frequency < 0)
759 bb->frequency = 0;
760 if (!single_succ_p (bb))
761 {
762 gcc_assert (!EDGE_COUNT (bb->succs));
763 return;
764 }
765 e = single_succ_edge (bb);
766 e->count -= count;
767 if (e->count < 0)
768 e->count = 0;
769 }
770
771 /* Returns true if argument PARAM of the tail recursive call needs to be copied
772 when the call is eliminated. */
773
774 static bool
775 arg_needs_copy_p (tree param)
776 {
777 tree def;
778
779 if (!is_gimple_reg (param))
780 return false;
781
782 /* Parameters that are only defined but never used need not be copied. */
783 def = ssa_default_def (cfun, param);
784 if (!def)
785 return false;
786
787 return true;
788 }
789
790 /* Eliminates tail call described by T. TMP_VARS is a list of
791 temporary variables used to copy the function arguments. */
792
793 static void
794 eliminate_tail_call (struct tailcall *t)
795 {
796 tree param, rslt;
797 gimple stmt, call;
798 tree arg;
799 size_t idx;
800 basic_block bb, first;
801 edge e;
802 gimple phi;
803 gimple_stmt_iterator gsi;
804 gimple orig_stmt;
805
806 stmt = orig_stmt = gsi_stmt (t->call_gsi);
807 bb = gsi_bb (t->call_gsi);
808
809 if (dump_file && (dump_flags & TDF_DETAILS))
810 {
811 fprintf (dump_file, "Eliminated tail recursion in bb %d : ",
812 bb->index);
813 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
814 fprintf (dump_file, "\n");
815 }
816
817 gcc_assert (is_gimple_call (stmt));
818
819 first = single_succ (ENTRY_BLOCK_PTR);
820
821 /* Remove the code after call_gsi that will become unreachable. The
822 possibly unreachable code in other blocks is removed later in
823 cfg cleanup. */
824 gsi = t->call_gsi;
825 gsi_next (&gsi);
826 while (!gsi_end_p (gsi))
827 {
828 gimple t = gsi_stmt (gsi);
829 /* Do not remove the return statement, so that redirect_edge_and_branch
830 sees how the block ends. */
831 if (gimple_code (t) == GIMPLE_RETURN)
832 break;
833
834 gsi_remove (&gsi, true);
835 release_defs (t);
836 }
837
838 /* Number of executions of function has reduced by the tailcall. */
839 e = single_succ_edge (gsi_bb (t->call_gsi));
840 decrease_profile (EXIT_BLOCK_PTR, e->count, EDGE_FREQUENCY (e));
841 decrease_profile (ENTRY_BLOCK_PTR, e->count, EDGE_FREQUENCY (e));
842 if (e->dest != EXIT_BLOCK_PTR)
843 decrease_profile (e->dest, e->count, EDGE_FREQUENCY (e));
844
845 /* Replace the call by a jump to the start of function. */
846 e = redirect_edge_and_branch (single_succ_edge (gsi_bb (t->call_gsi)),
847 first);
848 gcc_assert (e);
849 PENDING_STMT (e) = NULL;
850
851 /* Add phi node entries for arguments. The ordering of the phi nodes should
852 be the same as the ordering of the arguments. */
853 for (param = DECL_ARGUMENTS (current_function_decl),
854 idx = 0, gsi = gsi_start_phis (first);
855 param;
856 param = DECL_CHAIN (param), idx++)
857 {
858 if (!arg_needs_copy_p (param))
859 continue;
860
861 arg = gimple_call_arg (stmt, idx);
862 phi = gsi_stmt (gsi);
863 gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
864
865 add_phi_arg (phi, arg, e, gimple_location (stmt));
866 gsi_next (&gsi);
867 }
868
869 /* Update the values of accumulators. */
870 adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
871
872 call = gsi_stmt (t->call_gsi);
873 rslt = gimple_call_lhs (call);
874 if (rslt != NULL_TREE)
875 {
876 /* Result of the call will no longer be defined. So adjust the
877 SSA_NAME_DEF_STMT accordingly. */
878 SSA_NAME_DEF_STMT (rslt) = gimple_build_nop ();
879 }
880
881 gsi_remove (&t->call_gsi, true);
882 release_defs (call);
883 }
884
885 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
886 mark the tailcalls for the sibcall optimization. */
887
888 static bool
889 optimize_tail_call (struct tailcall *t, bool opt_tailcalls)
890 {
891 if (t->tail_recursion)
892 {
893 eliminate_tail_call (t);
894 return true;
895 }
896
897 if (opt_tailcalls)
898 {
899 gimple stmt = gsi_stmt (t->call_gsi);
900
901 gimple_call_set_tail (stmt, true);
902 if (dump_file && (dump_flags & TDF_DETAILS))
903 {
904 fprintf (dump_file, "Found tail call ");
905 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
906 fprintf (dump_file, " in bb %i\n", (gsi_bb (t->call_gsi))->index);
907 }
908 }
909
910 return false;
911 }
912
913 /* Creates a tail-call accumulator of the same type as the return type of the
914 current function. LABEL is the name used to creating the temporary
915 variable for the accumulator. The accumulator will be inserted in the
916 phis of a basic block BB with single predecessor with an initial value
917 INIT converted to the current function return type. */
918
919 static tree
920 create_tailcall_accumulator (const char *label, basic_block bb, tree init)
921 {
922 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
923 if (POINTER_TYPE_P (ret_type))
924 ret_type = sizetype;
925
926 tree tmp = make_temp_ssa_name (ret_type, NULL, label);
927 gimple phi;
928
929 phi = create_phi_node (tmp, bb);
930 /* RET_TYPE can be a float when -ffast-maths is enabled. */
931 add_phi_arg (phi, fold_convert (ret_type, init), single_pred_edge (bb),
932 UNKNOWN_LOCATION);
933 return PHI_RESULT (phi);
934 }
935
936 /* Optimizes tail calls in the function, turning the tail recursion
937 into iteration. */
938
939 static unsigned int
940 tree_optimize_tail_calls_1 (bool opt_tailcalls)
941 {
942 edge e;
943 bool phis_constructed = false;
944 struct tailcall *tailcalls = NULL, *act, *next;
945 bool changed = false;
946 basic_block first = single_succ (ENTRY_BLOCK_PTR);
947 tree param;
948 gimple stmt;
949 edge_iterator ei;
950
951 if (!suitable_for_tail_opt_p ())
952 return 0;
953 if (opt_tailcalls)
954 opt_tailcalls = suitable_for_tail_call_opt_p ();
955
956 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
957 {
958 /* Only traverse the normal exits, i.e. those that end with return
959 statement. */
960 stmt = last_stmt (e->src);
961
962 if (stmt
963 && gimple_code (stmt) == GIMPLE_RETURN)
964 find_tail_calls (e->src, &tailcalls);
965 }
966
967 /* Construct the phi nodes and accumulators if necessary. */
968 a_acc = m_acc = NULL_TREE;
969 for (act = tailcalls; act; act = act->next)
970 {
971 if (!act->tail_recursion)
972 continue;
973
974 if (!phis_constructed)
975 {
976 /* Ensure that there is only one predecessor of the block
977 or if there are existing degenerate PHI nodes. */
978 if (!single_pred_p (first)
979 || !gimple_seq_empty_p (phi_nodes (first)))
980 first = split_edge (single_succ_edge (ENTRY_BLOCK_PTR));
981
982 /* Copy the args if needed. */
983 for (param = DECL_ARGUMENTS (current_function_decl);
984 param;
985 param = DECL_CHAIN (param))
986 if (arg_needs_copy_p (param))
987 {
988 tree name = ssa_default_def (cfun, param);
989 tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
990 gimple phi;
991
992 set_ssa_default_def (cfun, param, new_name);
993 phi = create_phi_node (name, first);
994 add_phi_arg (phi, new_name, single_pred_edge (first),
995 EXPR_LOCATION (param));
996 }
997 phis_constructed = true;
998 }
999
1000 if (act->add && !a_acc)
1001 a_acc = create_tailcall_accumulator ("add_acc", first,
1002 integer_zero_node);
1003
1004 if (act->mult && !m_acc)
1005 m_acc = create_tailcall_accumulator ("mult_acc", first,
1006 integer_one_node);
1007 }
1008
1009 if (a_acc || m_acc)
1010 {
1011 /* When the tail call elimination using accumulators is performed,
1012 statements adding the accumulated value are inserted at all exits.
1013 This turns all other tail calls to non-tail ones. */
1014 opt_tailcalls = false;
1015 }
1016
1017 for (; tailcalls; tailcalls = next)
1018 {
1019 next = tailcalls->next;
1020 changed |= optimize_tail_call (tailcalls, opt_tailcalls);
1021 free (tailcalls);
1022 }
1023
1024 if (a_acc || m_acc)
1025 {
1026 /* Modify the remaining return statements. */
1027 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1028 {
1029 stmt = last_stmt (e->src);
1030
1031 if (stmt
1032 && gimple_code (stmt) == GIMPLE_RETURN)
1033 adjust_return_value (e->src, m_acc, a_acc);
1034 }
1035 }
1036
1037 if (changed)
1038 {
1039 /* We may have created new loops. Make them magically appear. */
1040 if (current_loops)
1041 loops_state_set (LOOPS_NEED_FIXUP);
1042 free_dominance_info (CDI_DOMINATORS);
1043 }
1044
1045 /* Add phi nodes for the virtual operands defined in the function to the
1046 header of the loop created by tail recursion elimination. Do so
1047 by triggering the SSA renamer. */
1048 if (phis_constructed)
1049 mark_virtual_operands_for_renaming (cfun);
1050
1051 if (changed)
1052 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
1053 return 0;
1054 }
1055
1056 static unsigned int
1057 execute_tail_recursion (void)
1058 {
1059 return tree_optimize_tail_calls_1 (false);
1060 }
1061
1062 static bool
1063 gate_tail_calls (void)
1064 {
1065 return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
1066 }
1067
1068 static unsigned int
1069 execute_tail_calls (void)
1070 {
1071 return tree_optimize_tail_calls_1 (true);
1072 }
1073
1074 namespace {
1075
1076 const pass_data pass_data_tail_recursion =
1077 {
1078 GIMPLE_PASS, /* type */
1079 "tailr", /* name */
1080 OPTGROUP_NONE, /* optinfo_flags */
1081 true, /* has_gate */
1082 true, /* has_execute */
1083 TV_NONE, /* tv_id */
1084 ( PROP_cfg | PROP_ssa ), /* properties_required */
1085 0, /* properties_provided */
1086 0, /* properties_destroyed */
1087 0, /* todo_flags_start */
1088 TODO_verify_ssa, /* todo_flags_finish */
1089 };
1090
1091 class pass_tail_recursion : public gimple_opt_pass
1092 {
1093 public:
1094 pass_tail_recursion (gcc::context *ctxt)
1095 : gimple_opt_pass (pass_data_tail_recursion, ctxt)
1096 {}
1097
1098 /* opt_pass methods: */
1099 opt_pass * clone () { return new pass_tail_recursion (m_ctxt); }
1100 bool gate () { return gate_tail_calls (); }
1101 unsigned int execute () { return execute_tail_recursion (); }
1102
1103 }; // class pass_tail_recursion
1104
1105 } // anon namespace
1106
1107 gimple_opt_pass *
1108 make_pass_tail_recursion (gcc::context *ctxt)
1109 {
1110 return new pass_tail_recursion (ctxt);
1111 }
1112
1113 namespace {
1114
1115 const pass_data pass_data_tail_calls =
1116 {
1117 GIMPLE_PASS, /* type */
1118 "tailc", /* name */
1119 OPTGROUP_NONE, /* optinfo_flags */
1120 true, /* has_gate */
1121 true, /* has_execute */
1122 TV_NONE, /* tv_id */
1123 ( PROP_cfg | PROP_ssa ), /* properties_required */
1124 0, /* properties_provided */
1125 0, /* properties_destroyed */
1126 0, /* todo_flags_start */
1127 TODO_verify_ssa, /* todo_flags_finish */
1128 };
1129
1130 class pass_tail_calls : public gimple_opt_pass
1131 {
1132 public:
1133 pass_tail_calls (gcc::context *ctxt)
1134 : gimple_opt_pass (pass_data_tail_calls, ctxt)
1135 {}
1136
1137 /* opt_pass methods: */
1138 bool gate () { return gate_tail_calls (); }
1139 unsigned int execute () { return execute_tail_calls (); }
1140
1141 }; // class pass_tail_calls
1142
1143 } // anon namespace
1144
1145 gimple_opt_pass *
1146 make_pass_tail_calls (gcc::context *ctxt)
1147 {
1148 return new pass_tail_calls (ctxt);
1149 }