1 /* Tail call optimization on trees.
2 Copyright (C) 2003-2024 Free Software Foundation, Inc.
4 This file is part of GCC.
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)
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.
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/>. */
22 #include "coretypes.h"
28 #include "tree-pass.h"
31 #include "gimple-pretty-print.h"
32 #include "fold-const.h"
33 #include "stor-layout.h"
34 #include "gimple-iterator.h"
35 #include "gimplify-me.h"
37 #include "tree-into-ssa.h"
44 #include "common/common-target.h"
45 #include "ipa-utils.h"
46 #include "tree-ssa-live.h"
47 #include "diagnostic-core.h"
49 /* The file implements the tail recursion elimination. It is also used to
50 analyze the tail calls in general, passing the results to the rtl level
51 where they are used for sibcall optimization.
53 In addition to the standard tail recursion elimination, we handle the most
54 trivial cases of making the call tail recursive by creating accumulators.
55 For example the following function
60 return n + sum (n - 1);
77 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
78 when we reach the return x statement, we should return a_acc + x * m_acc
79 instead. They are initially initialized to 0 and 1, respectively,
80 so the semantics of the function is obviously preserved. If we are
81 guaranteed that the value of the accumulator never change, we
84 There are three cases how the function may exit. The first one is
85 handled in adjust_return_value, the other two in adjust_accumulator_values
86 (the second case is actually a special case of the third one and we
87 present it separately just for clarity):
89 1) Just return x, where x is not in any of the remaining special shapes.
90 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
92 2) return f (...), where f is the current function, is rewritten in a
93 classical tail-recursion elimination way, into assignment of arguments
94 and jump to the start of the function. Values of the accumulators
97 3) return a + m * f(...), where a and m do not depend on call to f.
98 To preserve the semantics described before we want this to be rewritten
99 in such a way that we finally return
101 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
103 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
104 eliminate the tail call to f. Special cases when the value is just
105 added or just multiplied are obtained by setting a = 0 or m = 1.
107 TODO -- it is possible to do similar tricks for other operations. */
109 /* A structure that describes the tailcall. */
113 /* The iterator pointing to the call statement. */
114 gimple_stmt_iterator call_gsi
;
116 /* True if it is a call to the current function. */
119 /* The return value of the caller is mult * f + add, where f is the return
120 value of the call. */
123 /* Next tailcall in the chain. */
124 struct tailcall
*next
;
127 /* The variables holding the value of multiplicative and additive
129 static tree m_acc
, a_acc
;
131 /* Bitmap with a bit for each function parameter which is set to true if we
132 have to copy the parameter for conversion of tail-recursive calls. */
134 static bitmap tailr_arg_needs_copy
;
136 static void maybe_error_musttail (gcall
*call
, const char *err
);
138 /* Returns false when the function is not suitable for tail call optimization
139 from some reason (e.g. if it takes variable number of arguments). CALL
140 is call to report for. */
143 suitable_for_tail_opt_p (gcall
*call
)
147 maybe_error_musttail (call
, _("caller uses stdargs"));
154 /* Returns false when the function is not suitable for tail call optimization
155 for some reason (e.g. if it takes variable number of arguments).
156 This test must pass in addition to suitable_for_tail_opt_p in order to make
157 tail call discovery happen. CALL is call to report error for. */
160 suitable_for_tail_call_opt_p (gcall
*call
)
164 /* alloca (until we have stack slot life analysis) inhibits
165 sibling call optimizations, but not tail recursion. */
166 if (cfun
->calls_alloca
)
168 maybe_error_musttail (call
, _("caller uses alloca"));
172 /* If we are using sjlj exceptions, we may need to add a call to
173 _Unwind_SjLj_Unregister at exit of the function. Which means
174 that we cannot do any sibcall transformations. */
175 if (targetm_common
.except_unwind_info (&global_options
) == UI_SJLJ
176 && current_function_has_exception_handlers ())
178 maybe_error_musttail (call
, _("caller uses sjlj exceptions"));
182 /* Any function that calls setjmp might have longjmp called from
183 any called function. ??? We really should represent this
184 properly in the CFG so that this needn't be special cased. */
185 if (cfun
->calls_setjmp
)
187 maybe_error_musttail (call
, _("caller uses setjmp"));
191 /* Various targets don't handle tail calls correctly in functions
192 that call __builtin_eh_return. */
193 if (cfun
->calls_eh_return
)
195 maybe_error_musttail (call
, _("caller uses __builtin_eh_return"));
199 /* ??? It is OK if the argument of a function is taken in some cases,
200 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
201 for (param
= DECL_ARGUMENTS (current_function_decl
);
203 param
= DECL_CHAIN (param
))
204 if (TREE_ADDRESSABLE (param
))
206 maybe_error_musttail (call
, _("address of caller arguments taken"));
213 /* Checks whether the expression EXPR in stmt AT is independent of the
214 statement pointed to by GSI (in a sense that we already know EXPR's value
215 at GSI). We use the fact that we are only called from the chain of
216 basic blocks that have only single successor. Returns the expression
217 containing the value of EXPR at GSI. */
220 independent_of_stmt_p (tree expr
, gimple
*at
, gimple_stmt_iterator gsi
,
223 basic_block bb
, call_bb
, at_bb
;
227 if (is_gimple_min_invariant (expr
))
230 if (TREE_CODE (expr
) != SSA_NAME
)
233 if (bitmap_bit_p (to_move
, SSA_NAME_VERSION (expr
)))
236 /* Mark the blocks in the chain leading to the end. */
237 at_bb
= gimple_bb (at
);
238 call_bb
= gimple_bb (gsi_stmt (gsi
));
239 for (bb
= call_bb
; bb
!= at_bb
; bb
= single_succ (bb
))
245 at
= SSA_NAME_DEF_STMT (expr
);
248 /* The default definition or defined before the chain. */
254 for (; !gsi_end_p (gsi
); gsi_next (&gsi
))
255 if (gsi_stmt (gsi
) == at
)
258 if (!gsi_end_p (gsi
))
263 if (gimple_code (at
) != GIMPLE_PHI
)
269 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
274 expr
= PHI_ARG_DEF_FROM_EDGE (at
, e
);
275 if (TREE_CODE (expr
) != SSA_NAME
)
277 /* The value is a constant. */
282 /* Unmark the blocks. */
283 for (bb
= call_bb
; bb
!= at_bb
; bb
= single_succ (bb
))
290 enum par
{ FAIL
, OK
, TRY_MOVE
};
292 /* Simulates the effect of an assignment STMT on the return value of the tail
293 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
294 additive factor for the real return value. */
297 process_assignment (gassign
*stmt
,
298 gimple_stmt_iterator call
, tree
*m
,
299 tree
*a
, tree
*ass_var
, bitmap to_move
)
301 tree op0
, op1
= NULL_TREE
, non_ass_var
= NULL_TREE
;
302 tree dest
= gimple_assign_lhs (stmt
);
303 enum tree_code code
= gimple_assign_rhs_code (stmt
);
304 enum gimple_rhs_class rhs_class
= get_gimple_rhs_class (code
);
305 tree src_var
= gimple_assign_rhs1 (stmt
);
307 /* See if this is a simple copy operation of an SSA name to the function
308 result. In that case we may have a simple tail call. Ignore type
309 conversions that can never produce extra code between the function
310 call and the function return. */
311 if ((rhs_class
== GIMPLE_SINGLE_RHS
|| gimple_assign_cast_p (stmt
))
312 && src_var
== *ass_var
)
314 /* Reject a tailcall if the type conversion might need
316 if (gimple_assign_cast_p (stmt
))
318 if (TYPE_MODE (TREE_TYPE (dest
)) != TYPE_MODE (TREE_TYPE (src_var
)))
321 /* Even if the type modes are the same, if the precision of the
322 type is smaller than mode's precision,
323 reduce_to_bit_field_precision would generate additional code. */
324 if (INTEGRAL_TYPE_P (TREE_TYPE (dest
))
325 && !type_has_mode_precision_p (TREE_TYPE (dest
)))
335 case GIMPLE_BINARY_RHS
:
336 op1
= gimple_assign_rhs2 (stmt
);
340 case GIMPLE_UNARY_RHS
:
341 op0
= gimple_assign_rhs1 (stmt
);
348 /* Accumulator optimizations will reverse the order of operations.
349 We can only do that for floating-point types if we're assuming
350 that addition and multiplication are associative. */
351 if (!flag_associative_math
)
352 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl
))))
355 if (rhs_class
== GIMPLE_UNARY_RHS
358 else if (op0
== *ass_var
359 && (non_ass_var
= independent_of_stmt_p (op1
, stmt
, call
,
364 && (non_ass_var
= independent_of_stmt_p (op0
, stmt
, call
,
377 case POINTER_PLUS_EXPR
:
390 *m
= build_minus_one_cst (TREE_TYPE (op0
));
396 *a
= fold_build1 (NEGATE_EXPR
, TREE_TYPE (non_ass_var
), non_ass_var
);
399 *m
= build_minus_one_cst (TREE_TYPE (non_ass_var
));
400 *a
= fold_build1 (NEGATE_EXPR
, TREE_TYPE (non_ass_var
), non_ass_var
);
411 /* Propagate VAR through phis on edge E. */
414 propagate_through_phis (tree var
, edge e
)
416 basic_block dest
= e
->dest
;
419 for (gsi
= gsi_start_phis (dest
); !gsi_end_p (gsi
); gsi_next (&gsi
))
421 gphi
*phi
= gsi
.phi ();
422 if (PHI_ARG_DEF_FROM_EDGE (phi
, e
) == var
)
423 return PHI_RESULT (phi
);
428 /* Report an error for failing to tail convert must call CALL
429 with error message ERR. Also clear the flag to prevent further
433 maybe_error_musttail (gcall
*call
, const char *err
)
435 if (gimple_call_must_tail_p (call
))
437 error_at (call
->location
, "cannot tail-call: %s", err
);
438 /* Avoid another error. ??? If there are multiple reasons why tail
439 calls fail it might be useful to report them all to avoid
440 whack-a-mole for the user. But currently there is too much
441 redundancy in the reporting, so keep it simple. */
442 gimple_call_set_must_tail (call
, false); /* Avoid another error. */
443 gimple_call_set_tail (call
, false);
447 print_gimple_stmt (dump_file
, call
, 0, TDF_SLIM
);
448 fprintf (dump_file
, "Cannot convert: %s\n", err
);
452 /* Argument for compute_live_vars/live_vars_at_stmt and what compute_live_vars
453 returns. Computed lazily, but just once for the function. */
454 static live_vars_map
*live_vars
;
455 static vec
<bitmap_head
> live_vars_vec
;
457 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
458 added to the start of RET. When ONLY_MUSTTAIL is set only handle musttail.
459 Update OPT_TAILCALLS as output parameter. */
462 find_tail_calls (basic_block bb
, struct tailcall
**ret
, bool only_musttail
,
465 tree ass_var
= NULL_TREE
, ret_var
, func
, param
;
468 gimple_stmt_iterator gsi
, agsi
;
477 if (!single_succ_p (bb
))
479 /* If there is an abnormal edge assume it's the only extra one.
480 Tolerate that case so that we can give better error messages
481 for musttail later. */
482 if (!has_abnormal_or_eh_outgoing_edge_p (bb
))
485 fprintf (dump_file
, "Basic block %d has extra exit edges\n",
489 if (!cfun
->has_musttail
)
493 bool bad_stmt
= false;
494 gimple
*last_stmt
= nullptr;
495 for (gsi
= gsi_last_bb (bb
); !gsi_end_p (gsi
); gsi_prev (&gsi
))
497 stmt
= gsi_stmt (gsi
);
499 /* Ignore labels, returns, nops, clobbers and debug stmts. */
500 if (gimple_code (stmt
) == GIMPLE_LABEL
501 || gimple_code (stmt
) == GIMPLE_RETURN
502 || gimple_code (stmt
) == GIMPLE_NOP
503 || gimple_code (stmt
) == GIMPLE_PREDICT
504 || gimple_clobber_p (stmt
)
505 || is_gimple_debug (stmt
))
510 /* Check for a call. */
511 if (is_gimple_call (stmt
))
513 call
= as_a
<gcall
*> (stmt
);
514 /* Handle only musttail calls when not optimizing. */
515 if (only_musttail
&& !gimple_call_must_tail_p (call
))
519 maybe_error_musttail (call
,
520 _("memory reference or volatile after call"));
523 ass_var
= gimple_call_lhs (call
);
527 /* Allow simple copies between local variables, even if they're
529 if (is_gimple_assign (stmt
)
530 && auto_var_in_fn_p (gimple_assign_lhs (stmt
), cfun
->decl
)
531 && auto_var_in_fn_p (gimple_assign_rhs1 (stmt
), cfun
->decl
))
534 /* If the statement references memory or volatile operands, fail. */
535 if (gimple_references_memory_p (stmt
)
536 || gimple_has_volatile_ops (stmt
))
540 fprintf (dump_file
, "Cannot handle ");
541 print_gimple_stmt (dump_file
, stmt
, 0);
544 if (!cfun
->has_musttail
)
555 /* Recurse to the predecessors. */
556 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
557 find_tail_calls (e
->src
, ret
, only_musttail
, opt_tailcalls
);
562 if (!suitable_for_tail_opt_p (call
))
565 if (!suitable_for_tail_call_opt_p (call
))
566 opt_tailcalls
= false;
568 /* If the LHS of our call is not just a simple register or local
569 variable, we can't transform this into a tail or sibling call.
570 This situation happens, in (e.g.) "*p = foo()" where foo returns a
571 struct. In this case we won't have a temporary here, but we need
572 to carry out the side effect anyway, so tailcall is impossible.
574 ??? In some situations (when the struct is returned in memory via
575 invisible argument) we could deal with this, e.g. by passing 'p'
576 itself as that argument to foo, but it's too early to do this here,
577 and expand_call() will not handle it anyway. If it ever can, then
578 we need to revisit this here, to allow that situation. */
580 && !is_gimple_reg (ass_var
)
581 && !auto_var_in_fn_p (ass_var
, cfun
->decl
))
583 maybe_error_musttail (call
, _("return value in memory"));
587 if (cfun
->calls_setjmp
)
589 maybe_error_musttail (call
, _("caller uses setjmp"));
593 /* If the call might throw an exception that wouldn't propagate out of
594 cfun, we can't transform to a tail or sibling call (82081). */
595 if ((stmt_could_throw_p (cfun
, stmt
)
596 && !stmt_can_throw_external (cfun
, stmt
)) || !single_succ_p (bb
))
598 if (stmt
== last_stmt
)
599 maybe_error_musttail (call
,
600 _("call may throw exception that does not propagate"));
602 maybe_error_musttail (call
,
603 _("code between call and return"));
607 /* If the function returns a value, then at present, the tail call
608 must return the same type of value. There is conceptually a copy
609 between the object returned by the tail call candidate and the
610 object returned by CFUN itself.
612 This means that if we have:
614 lhs = f (&<retval>); // f reads from <retval>
615 // (lhs is usually also <retval>)
617 there is a copy between the temporary object returned by f and lhs,
618 meaning that any use of <retval> in f occurs before the assignment
619 to lhs begins. Thus the <retval> that is live on entry to the call
620 to f is really an independent local variable V that happens to be
621 stored in the RESULT_DECL rather than a local VAR_DECL.
623 Turning this into a tail call would remove the copy and make the
624 lifetimes of the return value and V overlap. The same applies to
625 tail recursion, since if f can read from <retval>, we have to assume
626 that CFUN might already have written to <retval> before the call.
628 The problem doesn't apply when <retval> is passed by value, but that
629 isn't a case we handle anyway. */
630 tree result_decl
= DECL_RESULT (cfun
->decl
);
632 && may_be_aliased (result_decl
)
633 && ref_maybe_used_by_stmt_p (call
, result_decl
, false))
635 maybe_error_musttail (call
, _("return value used after call"));
639 /* We found the call, check whether it is suitable. */
640 tail_recursion
= false;
641 func
= gimple_call_fndecl (call
);
643 && !fndecl_built_in_p (func
)
644 && recursive_call_p (current_function_decl
, func
)
649 for (param
= DECL_ARGUMENTS (current_function_decl
), idx
= 0;
650 param
&& idx
< gimple_call_num_args (call
);
651 param
= DECL_CHAIN (param
), idx
++)
653 arg
= gimple_call_arg (call
, idx
);
656 /* Make sure there are no problems with copying. The parameter
657 have a copyable type and the two arguments must have reasonably
658 equivalent types. The latter requirement could be relaxed if
659 we emitted a suitable type conversion statement. */
660 if (!is_gimple_reg_type (TREE_TYPE (param
))
661 || !useless_type_conversion_p (TREE_TYPE (param
),
665 /* The parameter should be a real operand, so that phi node
666 created for it at the start of the function has the meaning
667 of copying the value. This test implies is_gimple_reg_type
668 from the previous condition, however this one could be
669 relaxed by being more careful with copying the new value
670 of the parameter (emitting appropriate GIMPLE_ASSIGN and
671 updating the virtual operands). */
672 if (!is_gimple_reg (param
))
676 if (idx
== gimple_call_num_args (call
) && !param
)
677 tail_recursion
= true;
680 /* Compute live vars if not computed yet. */
681 if (live_vars
== NULL
)
683 unsigned int cnt
= 0;
684 FOR_EACH_LOCAL_DECL (cfun
, idx
, var
)
686 && auto_var_in_fn_p (var
, cfun
->decl
)
687 && may_be_aliased (var
))
689 if (live_vars
== NULL
)
690 live_vars
= new live_vars_map
;
691 live_vars
->put (DECL_UID (var
), cnt
++);
694 live_vars_vec
= compute_live_vars (cfun
, live_vars
);
697 /* Determine a bitmap of variables which are still in scope after the
699 bitmap local_live_vars
= NULL
;
701 local_live_vars
= live_vars_at_stmt (live_vars_vec
, live_vars
, call
);
703 /* Make sure the tail invocation of this function does not indirectly
704 refer to local variables. (Passing variables directly by value
706 FOR_EACH_LOCAL_DECL (cfun
, idx
, var
)
708 if (TREE_CODE (var
) != PARM_DECL
709 && auto_var_in_fn_p (var
, cfun
->decl
)
710 && may_be_aliased (var
)
711 && (ref_maybe_used_by_stmt_p (call
, var
, false)
712 || call_may_clobber_ref_p (call
, var
, false)))
717 BITMAP_FREE (local_live_vars
);
718 maybe_error_musttail (call
, _("call invocation refers to locals"));
723 unsigned int *v
= live_vars
->get (DECL_UID (var
));
724 if (bitmap_bit_p (local_live_vars
, *v
))
726 BITMAP_FREE (local_live_vars
);
727 maybe_error_musttail (call
, _("call invocation refers to locals"));
735 BITMAP_FREE (local_live_vars
);
737 /* Now check the statements after the call. None of them has virtual
738 operands, so they may only depend on the call through its return
739 value. The return value should also be dependent on each of them,
740 since we are running after dce. */
743 auto_bitmap to_move_defs
;
744 auto_vec
<gimple
*> to_move_stmts
;
750 tree tmp_a
= NULL_TREE
;
751 tree tmp_m
= NULL_TREE
;
754 while (gsi_end_p (agsi
))
756 ass_var
= propagate_through_phis (ass_var
, single_succ_edge (abb
));
757 abb
= single_succ (abb
);
758 agsi
= gsi_start_bb (abb
);
761 stmt
= gsi_stmt (agsi
);
762 if (gimple_code (stmt
) == GIMPLE_RETURN
)
765 if (gimple_code (stmt
) == GIMPLE_LABEL
766 || gimple_code (stmt
) == GIMPLE_NOP
767 || gimple_code (stmt
) == GIMPLE_PREDICT
768 || gimple_clobber_p (stmt
)
769 || is_gimple_debug (stmt
))
772 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
774 maybe_error_musttail (call
, _("unhandled code after call"));
778 /* This is a gimple assign. */
779 par ret
= process_assignment (as_a
<gassign
*> (stmt
), gsi
,
780 &tmp_m
, &tmp_a
, &ass_var
, to_move_defs
);
781 if (ret
== FAIL
|| (ret
== TRY_MOVE
&& !tail_recursion
))
783 maybe_error_musttail (call
, _("return value changed after call"));
786 else if (ret
== TRY_MOVE
)
788 /* Do not deal with checking dominance, the real fix is to
789 do path isolation for the transform phase anyway, removing
790 the need to compute the accumulators with new stmts. */
793 for (unsigned opno
= 1; opno
< gimple_num_ops (stmt
); ++opno
)
795 tree op
= gimple_op (stmt
, opno
);
796 if (independent_of_stmt_p (op
, stmt
, gsi
, to_move_defs
) != op
)
799 bitmap_set_bit (to_move_defs
,
800 SSA_NAME_VERSION (gimple_assign_lhs (stmt
)));
801 to_move_stmts
.safe_push (stmt
);
807 tree type
= TREE_TYPE (tmp_a
);
809 a
= fold_build2 (PLUS_EXPR
, type
, fold_convert (type
, a
), tmp_a
);
815 tree type
= TREE_TYPE (tmp_m
);
817 m
= fold_build2 (MULT_EXPR
, type
, fold_convert (type
, m
), tmp_m
);
822 a
= fold_build2 (MULT_EXPR
, type
, fold_convert (type
, a
), tmp_m
);
826 /* See if this is a tail call we can handle. */
827 ret_var
= gimple_return_retval (as_a
<greturn
*> (stmt
));
829 /* We may proceed if there either is no return value, or the return value
830 is identical to the call's return or if the return decl is an empty type
831 variable and the call's return was not assigned. */
833 && (ret_var
!= ass_var
834 && !(is_empty_type (TREE_TYPE (ret_var
)) && !ass_var
)))
836 maybe_error_musttail (call
, _("call uses return slot"));
840 /* If this is not a tail recursive call, we cannot handle addends or
842 if (!tail_recursion
&& (m
|| a
))
844 maybe_error_musttail (call
, _("operations after non tail recursive call"));
848 /* For pointers only allow additions. */
849 if (m
&& POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl
))))
851 maybe_error_musttail (call
,
852 _("tail recursion with pointers can only use additions"));
856 /* Move queued defs. */
860 FOR_EACH_VEC_ELT (to_move_stmts
, i
, stmt
)
862 gimple_stmt_iterator mgsi
= gsi_for_stmt (stmt
);
863 gsi_move_before (&mgsi
, &gsi
);
865 if (!tailr_arg_needs_copy
)
866 tailr_arg_needs_copy
= BITMAP_ALLOC (NULL
);
867 for (param
= DECL_ARGUMENTS (current_function_decl
), idx
= 0;
869 param
= DECL_CHAIN (param
), idx
++)
871 tree ddef
, arg
= gimple_call_arg (call
, idx
);
872 if (is_gimple_reg (param
)
873 && (ddef
= ssa_default_def (cfun
, param
))
875 bitmap_set_bit (tailr_arg_needs_copy
, idx
);
879 nw
= XNEW (struct tailcall
);
883 nw
->tail_recursion
= tail_recursion
;
892 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
895 add_successor_phi_arg (edge e
, tree var
, tree phi_arg
)
899 for (gsi
= gsi_start_phis (e
->dest
); !gsi_end_p (gsi
); gsi_next (&gsi
))
900 if (PHI_RESULT (gsi
.phi ()) == var
)
903 gcc_assert (!gsi_end_p (gsi
));
904 add_phi_arg (gsi
.phi (), phi_arg
, e
, UNKNOWN_LOCATION
);
907 /* Creates a GIMPLE statement which computes the operation specified by
908 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
909 statement in the position specified by GSI. Returns the
910 tree node of the statement's result. */
913 adjust_return_value_with_ops (enum tree_code code
, const char *label
,
914 tree acc
, tree op1
, gimple_stmt_iterator gsi
)
917 tree ret_type
= TREE_TYPE (DECL_RESULT (current_function_decl
));
918 tree result
= make_temp_ssa_name (ret_type
, NULL
, label
);
921 if (POINTER_TYPE_P (ret_type
))
923 gcc_assert (code
== PLUS_EXPR
&& TREE_TYPE (acc
) == sizetype
);
924 code
= POINTER_PLUS_EXPR
;
926 if (types_compatible_p (TREE_TYPE (acc
), TREE_TYPE (op1
))
927 && code
!= POINTER_PLUS_EXPR
)
928 stmt
= gimple_build_assign (result
, code
, acc
, op1
);
932 if (code
== POINTER_PLUS_EXPR
)
933 tem
= fold_build2 (code
, TREE_TYPE (op1
), op1
, acc
);
935 tem
= fold_build2 (code
, TREE_TYPE (op1
),
936 fold_convert (TREE_TYPE (op1
), acc
), op1
);
937 tree rhs
= fold_convert (ret_type
, tem
);
938 rhs
= force_gimple_operand_gsi (&gsi
, rhs
,
939 false, NULL
, true, GSI_SAME_STMT
);
940 stmt
= gimple_build_assign (result
, rhs
);
943 gsi_insert_before (&gsi
, stmt
, GSI_NEW_STMT
);
947 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
948 the computation specified by CODE and OP1 and insert the statement
949 at the position specified by GSI as a new statement. Returns new SSA name
950 of updated accumulator. */
953 update_accumulator_with_ops (enum tree_code code
, tree acc
, tree op1
,
954 gimple_stmt_iterator gsi
)
957 tree var
= copy_ssa_name (acc
);
958 if (types_compatible_p (TREE_TYPE (acc
), TREE_TYPE (op1
)))
959 stmt
= gimple_build_assign (var
, code
, acc
, op1
);
962 tree rhs
= fold_convert (TREE_TYPE (acc
),
965 fold_convert (TREE_TYPE (op1
), acc
),
967 rhs
= force_gimple_operand_gsi (&gsi
, rhs
,
968 false, NULL
, false, GSI_CONTINUE_LINKING
);
969 stmt
= gimple_build_assign (var
, rhs
);
971 gsi_insert_after (&gsi
, stmt
, GSI_NEW_STMT
);
975 /* Adjust the accumulator values according to A and M after GSI, and update
976 the phi nodes on edge BACK. */
979 adjust_accumulator_values (gimple_stmt_iterator gsi
, tree m
, tree a
, edge back
)
981 tree var
, a_acc_arg
, m_acc_arg
;
984 m
= force_gimple_operand_gsi (&gsi
, m
, true, NULL
, true, GSI_SAME_STMT
);
986 a
= force_gimple_operand_gsi (&gsi
, a
, true, NULL
, true, GSI_SAME_STMT
);
994 if (integer_onep (a
))
997 var
= adjust_return_value_with_ops (MULT_EXPR
, "acc_tmp", m_acc
,
1003 a_acc_arg
= update_accumulator_with_ops (PLUS_EXPR
, a_acc
, var
, gsi
);
1007 m_acc_arg
= update_accumulator_with_ops (MULT_EXPR
, m_acc
, m
, gsi
);
1010 add_successor_phi_arg (back
, a_acc
, a_acc_arg
);
1013 add_successor_phi_arg (back
, m_acc
, m_acc_arg
);
1016 /* Adjust value of the return at the end of BB according to M and A
1020 adjust_return_value (basic_block bb
, tree m
, tree a
)
1023 greturn
*ret_stmt
= as_a
<greturn
*> (gimple_seq_last_stmt (bb_seq (bb
)));
1024 gimple_stmt_iterator gsi
= gsi_last_bb (bb
);
1026 gcc_assert (gimple_code (ret_stmt
) == GIMPLE_RETURN
);
1028 retval
= gimple_return_retval (ret_stmt
);
1029 if (!retval
|| retval
== error_mark_node
)
1033 retval
= adjust_return_value_with_ops (MULT_EXPR
, "mul_tmp", m_acc
, retval
,
1036 retval
= adjust_return_value_with_ops (PLUS_EXPR
, "acc_tmp", a_acc
, retval
,
1038 gimple_return_set_retval (ret_stmt
, retval
);
1039 update_stmt (ret_stmt
);
1042 /* Subtract COUNT and FREQUENCY from the basic block and it's
1045 decrease_profile (basic_block bb
, profile_count count
)
1047 bb
->count
= bb
->count
- count
;
1048 if (!single_succ_p (bb
))
1050 gcc_assert (!EDGE_COUNT (bb
->succs
));
1055 /* Eliminates tail call described by T. TMP_VARS is a list of
1056 temporary variables used to copy the function arguments.
1057 Allocates *NEW_LOOP if not already done and initializes it. */
1060 eliminate_tail_call (struct tailcall
*t
, class loop
*&new_loop
)
1063 gimple
*stmt
, *call
;
1066 basic_block bb
, first
;
1070 gimple_stmt_iterator gsi
;
1073 stmt
= orig_stmt
= gsi_stmt (t
->call_gsi
);
1074 bb
= gsi_bb (t
->call_gsi
);
1076 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1078 fprintf (dump_file
, "Eliminated tail recursion in bb %d : ",
1080 print_gimple_stmt (dump_file
, stmt
, 0, TDF_SLIM
);
1081 fprintf (dump_file
, "\n");
1084 gcc_assert (is_gimple_call (stmt
));
1086 first
= single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
));
1088 /* Remove the code after call_gsi that will become unreachable. The
1089 possibly unreachable code in other blocks is removed later in
1092 gimple_stmt_iterator gsi2
= gsi_last_bb (gimple_bb (gsi_stmt (gsi
)));
1093 while (gsi_stmt (gsi2
) != gsi_stmt (gsi
))
1095 gimple
*t
= gsi_stmt (gsi2
);
1096 /* Do not remove the return statement, so that redirect_edge_and_branch
1097 sees how the block ends. */
1098 if (gimple_code (t
) != GIMPLE_RETURN
)
1100 gimple_stmt_iterator gsi3
= gsi2
;
1102 gsi_remove (&gsi3
, true);
1109 /* Number of executions of function has reduced by the tailcall. */
1110 e
= single_succ_edge (gsi_bb (t
->call_gsi
));
1112 profile_count count
= e
->count ();
1114 /* When profile is inconsistent and the recursion edge is more frequent
1115 than number of executions of functions, scale it down, so we do not end
1116 up with 0 executions of entry block. */
1117 if (count
>= ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
)
1118 count
= ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
.apply_scale (7, 8);
1119 decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun
), count
);
1120 decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun
), count
);
1121 if (e
->dest
!= EXIT_BLOCK_PTR_FOR_FN (cfun
))
1122 decrease_profile (e
->dest
, count
);
1124 /* Replace the call by a jump to the start of function. */
1125 e
= redirect_edge_and_branch (single_succ_edge (gsi_bb (t
->call_gsi
)),
1128 PENDING_STMT (e
) = NULL
;
1130 /* Add the new loop. */
1133 new_loop
= alloc_loop ();
1134 new_loop
->header
= first
;
1135 new_loop
->finite_p
= true;
1138 gcc_assert (new_loop
->header
== first
);
1140 /* Add phi node entries for arguments. The ordering of the phi nodes should
1141 be the same as the ordering of the arguments. */
1142 for (param
= DECL_ARGUMENTS (current_function_decl
),
1143 idx
= 0, gpi
= gsi_start_phis (first
);
1145 param
= DECL_CHAIN (param
), idx
++)
1147 if (!bitmap_bit_p (tailr_arg_needs_copy
, idx
))
1150 arg
= gimple_call_arg (stmt
, idx
);
1152 gcc_assert (param
== SSA_NAME_VAR (PHI_RESULT (phi
)));
1154 add_phi_arg (phi
, arg
, e
, gimple_location (stmt
));
1158 /* Update the values of accumulators. */
1159 adjust_accumulator_values (t
->call_gsi
, t
->mult
, t
->add
, e
);
1161 call
= gsi_stmt (t
->call_gsi
);
1162 rslt
= gimple_call_lhs (call
);
1163 if (rslt
!= NULL_TREE
&& TREE_CODE (rslt
) == SSA_NAME
)
1165 /* Result of the call will no longer be defined. So adjust the
1166 SSA_NAME_DEF_STMT accordingly. */
1167 SSA_NAME_DEF_STMT (rslt
) = gimple_build_nop ();
1170 gsi_remove (&t
->call_gsi
, true);
1171 release_defs (call
);
1174 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
1175 mark the tailcalls for the sibcall optimization. */
1178 optimize_tail_call (struct tailcall
*t
, bool opt_tailcalls
,
1179 class loop
*&new_loop
)
1181 if (t
->tail_recursion
)
1183 eliminate_tail_call (t
, new_loop
);
1189 gcall
*stmt
= as_a
<gcall
*> (gsi_stmt (t
->call_gsi
));
1191 gimple_call_set_tail (stmt
, true);
1192 cfun
->tail_call_marked
= true;
1193 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1195 fprintf (dump_file
, "Found tail call ");
1196 print_gimple_stmt (dump_file
, stmt
, 0, dump_flags
);
1197 fprintf (dump_file
, " in bb %i\n", (gsi_bb (t
->call_gsi
))->index
);
1204 /* Creates a tail-call accumulator of the same type as the return type of the
1205 current function. LABEL is the name used to creating the temporary
1206 variable for the accumulator. The accumulator will be inserted in the
1207 phis of a basic block BB with single predecessor with an initial value
1208 INIT converted to the current function return type. */
1211 create_tailcall_accumulator (const char *label
, basic_block bb
, tree init
)
1213 tree ret_type
= TREE_TYPE (DECL_RESULT (current_function_decl
));
1214 if (POINTER_TYPE_P (ret_type
))
1215 ret_type
= sizetype
;
1217 tree tmp
= make_temp_ssa_name (ret_type
, NULL
, label
);
1220 phi
= create_phi_node (tmp
, bb
);
1221 add_phi_arg (phi
, init
, single_pred_edge (bb
),
1223 return PHI_RESULT (phi
);
1226 /* Optimizes tail calls in the function, turning the tail recursion
1227 into iteration. When ONLY_MUSTCALL is true only optimize mustcall
1231 tree_optimize_tail_calls_1 (bool opt_tailcalls
, bool only_mustcall
)
1234 bool phis_constructed
= false;
1235 struct tailcall
*tailcalls
= NULL
, *act
, *next
;
1236 bool changed
= false;
1237 basic_block first
= single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
));
1241 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
)
1243 /* Only traverse the normal exits, i.e. those that end with return
1245 if (safe_is_a
<greturn
*> (*gsi_last_bb (e
->src
)))
1246 find_tail_calls (e
->src
, &tailcalls
, only_mustcall
, opt_tailcalls
);
1251 destroy_live_vars (live_vars_vec
);
1256 /* Construct the phi nodes and accumulators if necessary. */
1257 a_acc
= m_acc
= NULL_TREE
;
1258 for (act
= tailcalls
; act
; act
= act
->next
)
1260 if (!act
->tail_recursion
)
1263 if (!phis_constructed
)
1265 /* Ensure that there is only one predecessor of the block
1266 or if there are existing degenerate PHI nodes. */
1267 if (!single_pred_p (first
)
1268 || !gimple_seq_empty_p (phi_nodes (first
)))
1270 split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun
)));
1272 /* Copy the args if needed. */
1274 for (param
= DECL_ARGUMENTS (current_function_decl
), idx
= 0;
1276 param
= DECL_CHAIN (param
), idx
++)
1277 if (bitmap_bit_p (tailr_arg_needs_copy
, idx
))
1279 tree name
= ssa_default_def (cfun
, param
);
1280 tree new_name
= make_ssa_name (param
, SSA_NAME_DEF_STMT (name
));
1283 set_ssa_default_def (cfun
, param
, new_name
);
1284 phi
= create_phi_node (name
, first
);
1285 add_phi_arg (phi
, new_name
, single_pred_edge (first
),
1286 EXPR_LOCATION (param
));
1288 phis_constructed
= true;
1290 tree ret_type
= TREE_TYPE (DECL_RESULT (current_function_decl
));
1291 if (POINTER_TYPE_P (ret_type
))
1292 ret_type
= sizetype
;
1294 if (act
->add
&& !a_acc
)
1295 a_acc
= create_tailcall_accumulator ("add_acc", first
,
1296 build_zero_cst (ret_type
));
1298 if (act
->mult
&& !m_acc
)
1299 m_acc
= create_tailcall_accumulator ("mult_acc", first
,
1300 build_one_cst (ret_type
));
1305 /* When the tail call elimination using accumulators is performed,
1306 statements adding the accumulated value are inserted at all exits.
1307 This turns all other tail calls to non-tail ones. */
1308 opt_tailcalls
= false;
1311 class loop
*new_loop
= NULL
;
1312 for (; tailcalls
; tailcalls
= next
)
1314 next
= tailcalls
->next
;
1315 changed
|= optimize_tail_call (tailcalls
, opt_tailcalls
, new_loop
);
1319 add_loop (new_loop
, loops_for_fn (cfun
)->tree_root
);
1323 /* Modify the remaining return statements. */
1324 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
)
1326 if (safe_is_a
<greturn
*> (*gsi_last_bb (e
->src
)))
1327 adjust_return_value (e
->src
, m_acc
, a_acc
);
1332 free_dominance_info (CDI_DOMINATORS
);
1334 /* Add phi nodes for the virtual operands defined in the function to the
1335 header of the loop created by tail recursion elimination. Do so
1336 by triggering the SSA renamer. */
1337 if (phis_constructed
)
1338 mark_virtual_operands_for_renaming (cfun
);
1340 if (tailr_arg_needs_copy
)
1341 BITMAP_FREE (tailr_arg_needs_copy
);
1344 return TODO_cleanup_cfg
| TODO_update_ssa_only_virtuals
;
1349 gate_tail_calls (void)
1351 return flag_optimize_sibling_calls
!= 0 && dbg_cnt (tail_call
);
1355 execute_tail_calls (void)
1357 return tree_optimize_tail_calls_1 (true, false);
1362 const pass_data pass_data_tail_recursion
=
1364 GIMPLE_PASS
, /* type */
1366 OPTGROUP_NONE
, /* optinfo_flags */
1367 TV_NONE
, /* tv_id */
1368 ( PROP_cfg
| PROP_ssa
), /* properties_required */
1369 0, /* properties_provided */
1370 0, /* properties_destroyed */
1371 0, /* todo_flags_start */
1372 0, /* todo_flags_finish */
1375 class pass_tail_recursion
: public gimple_opt_pass
1378 pass_tail_recursion (gcc::context
*ctxt
)
1379 : gimple_opt_pass (pass_data_tail_recursion
, ctxt
)
1382 /* opt_pass methods: */
1383 opt_pass
* clone () final override
1385 return new pass_tail_recursion (m_ctxt
);
1387 bool gate (function
*) final override
{ return gate_tail_calls (); }
1388 unsigned int execute (function
*) final override
1390 return tree_optimize_tail_calls_1 (false, false);
1393 }; // class pass_tail_recursion
1398 make_pass_tail_recursion (gcc::context
*ctxt
)
1400 return new pass_tail_recursion (ctxt
);
1405 const pass_data pass_data_tail_calls
=
1407 GIMPLE_PASS
, /* type */
1409 OPTGROUP_NONE
, /* optinfo_flags */
1410 TV_NONE
, /* tv_id */
1411 ( PROP_cfg
| PROP_ssa
), /* properties_required */
1412 0, /* properties_provided */
1413 0, /* properties_destroyed */
1414 0, /* todo_flags_start */
1415 0, /* todo_flags_finish */
1418 class pass_tail_calls
: public gimple_opt_pass
1421 pass_tail_calls (gcc::context
*ctxt
)
1422 : gimple_opt_pass (pass_data_tail_calls
, ctxt
)
1425 /* opt_pass methods: */
1426 bool gate (function
*) final override
{ return gate_tail_calls (); }
1427 unsigned int execute (function
*) final override
1429 return execute_tail_calls ();
1432 }; // class pass_tail_calls
1437 make_pass_tail_calls (gcc::context
*ctxt
)
1439 return new pass_tail_calls (ctxt
);
1444 const pass_data pass_data_musttail
=
1446 GIMPLE_PASS
, /* type */
1447 "musttail", /* name */
1448 OPTGROUP_NONE
, /* optinfo_flags */
1449 TV_NONE
, /* tv_id */
1450 ( PROP_cfg
| PROP_ssa
), /* properties_required */
1451 0, /* properties_provided */
1452 0, /* properties_destroyed */
1453 0, /* todo_flags_start */
1454 0, /* todo_flags_finish */
1457 class pass_musttail
: public gimple_opt_pass
1460 pass_musttail (gcc::context
*ctxt
)
1461 : gimple_opt_pass (pass_data_musttail
, ctxt
)
1464 /* opt_pass methods: */
1465 /* This pass is only used when the other tail call pass
1466 doesn't run to make [[musttail]] still work. But only
1467 run it when there is actually a musttail in the function. */
1468 bool gate (function
*f
) final override
1470 return !flag_optimize_sibling_calls
&& f
->has_musttail
;
1472 unsigned int execute (function
*) final override
1474 return tree_optimize_tail_calls_1 (true, true);
1477 }; // class pass_musttail
1482 make_pass_musttail (gcc::context
*ctxt
)
1484 return new pass_musttail (ctxt
);