2003-09-20 13:03:31 +08:00
|
|
|
//===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
|
2005-04-22 07:48:37 +08:00
|
|
|
//
|
2003-10-21 03:43:21 +08:00
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
2007-12-30 04:36:04 +08:00
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
2005-04-22 07:48:37 +08:00
|
|
|
//
|
2003-10-21 03:43:21 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2003-09-20 13:03:31 +08:00
|
|
|
//
|
2003-12-08 13:34:54 +08:00
|
|
|
// This file transforms calls of the current function (self recursion) followed
|
|
|
|
// by a return instruction with a branch to the entry of the function, creating
|
|
|
|
// a loop. This pass also implements the following extensions to the basic
|
|
|
|
// algorithm:
|
2003-09-20 13:03:31 +08:00
|
|
|
//
|
2003-12-08 13:34:54 +08:00
|
|
|
// 1. Trivial instructions between the call and return do not prevent the
|
|
|
|
// transformation from taking place, though currently the analysis cannot
|
|
|
|
// support moving any really useful instructions (only dead ones).
|
2003-12-09 07:19:26 +08:00
|
|
|
// 2. This pass transforms functions that are prevented from being tail
|
2010-07-11 04:31:42 +08:00
|
|
|
// recursive by an associative and commutative expression to use an
|
|
|
|
// accumulator variable, thus compiling the typical naive factorial or
|
|
|
|
// 'fib' implementation into efficient code.
|
2003-12-15 07:57:39 +08:00
|
|
|
// 3. TRE is performed if the function returns void, if the return
|
|
|
|
// returns the result returned by the call, or if the function returns a
|
|
|
|
// run-time constant on all exits from the function. It is possible, though
|
|
|
|
// unlikely, that the return returns something else (like constant 0), and
|
|
|
|
// can still be TRE'd. It can be TRE'd if ALL OTHER return instructions in
|
|
|
|
// the function return the exact same value.
|
2009-11-07 15:10:01 +08:00
|
|
|
// 4. If it can prove that callees do not access their caller stack frame,
|
2005-05-10 07:51:13 +08:00
|
|
|
// they are marked as eligible for tail call elimination (by the code
|
|
|
|
// generator).
|
2003-09-20 13:03:31 +08:00
|
|
|
//
|
2003-12-08 13:34:54 +08:00
|
|
|
// There are several improvements that could be made:
|
|
|
|
//
|
|
|
|
// 1. If the function has any alloca instructions, these instructions will be
|
|
|
|
// moved out of the entry block of the function, causing them to be
|
|
|
|
// evaluated each time through the tail recursion. Safely keeping allocas
|
|
|
|
// in the entry block requires analysis to proves that the tail-called
|
|
|
|
// function does not read or write the stack object.
|
2011-04-15 13:18:47 +08:00
|
|
|
// 2. Tail recursion is only performed if the call immediately precedes the
|
2003-12-08 13:34:54 +08:00
|
|
|
// return instruction. It's possible that there could be a jump between
|
|
|
|
// the call and the return.
|
2003-12-15 07:57:39 +08:00
|
|
|
// 3. There can be intervening operations between the call and the return that
|
2003-12-08 13:34:54 +08:00
|
|
|
// prevent the TRE from occurring. For example, there could be GEP's and
|
|
|
|
// stores to memory that will not be read or written by the call. This
|
|
|
|
// requires some substantial analysis (such as with DSA) to prove safe to
|
|
|
|
// move ahead of the call, but doing so could allow many more TREs to be
|
|
|
|
// performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark.
|
2005-05-10 07:51:13 +08:00
|
|
|
// 4. The algorithm we use to detect if callees access their caller stack
|
|
|
|
// frames is very primitive.
|
2003-09-20 13:03:31 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2003-09-20 13:14:13 +08:00
|
|
|
#include "llvm/Transforms/Scalar.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
2013-07-11 12:40:01 +08:00
|
|
|
#include "llvm/ADT/SmallPtrSet.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/ADT/Statistic.h"
|
2015-09-10 18:22:12 +08:00
|
|
|
#include "llvm/Analysis/GlobalsModRef.h"
|
2014-05-06 07:59:03 +08:00
|
|
|
#include "llvm/Analysis/CFG.h"
|
2015-03-24 03:32:43 +08:00
|
|
|
#include "llvm/Analysis/CaptureTracking.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/Analysis/InlineCost.h"
|
|
|
|
#include "llvm/Analysis/InstructionSimplify.h"
|
|
|
|
#include "llvm/Analysis/Loads.h"
|
2013-01-22 19:26:02 +08:00
|
|
|
#include "llvm/Analysis/TargetTransformInfo.h"
|
2014-03-04 19:45:46 +08:00
|
|
|
#include "llvm/IR/CFG.h"
|
2014-03-04 19:01:28 +08:00
|
|
|
#include "llvm/IR/CallSite.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/Constants.h"
|
2014-10-19 16:17:50 +08:00
|
|
|
#include "llvm/IR/DataLayout.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/DerivedTypes.h"
|
2014-05-22 22:19:46 +08:00
|
|
|
#include "llvm/IR/DiagnosticInfo.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/Function.h"
|
|
|
|
#include "llvm/IR/Instructions.h"
|
|
|
|
#include "llvm/IR/IntrinsicInst.h"
|
|
|
|
#include "llvm/IR/Module.h"
|
2014-03-04 19:17:44 +08:00
|
|
|
#include "llvm/IR/ValueHandle.h"
|
2003-09-20 13:03:31 +08:00
|
|
|
#include "llvm/Pass.h"
|
2011-01-29 12:46:23 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
2011-01-30 04:06:16 +08:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
|
|
|
|
#include "llvm/Transforms/Utils/Local.h"
|
2003-11-21 02:25:24 +08:00
|
|
|
using namespace llvm;
|
2003-11-12 06:41:34 +08:00
|
|
|
|
2014-04-22 10:55:47 +08:00
|
|
|
#define DEBUG_TYPE "tailcallelim"
|
|
|
|
|
2006-12-20 05:40:18 +08:00
|
|
|
STATISTIC(NumEliminated, "Number of tail calls removed");
|
2011-01-29 12:53:35 +08:00
|
|
|
STATISTIC(NumRetDuped, "Number of return duplicated");
|
2006-12-20 05:40:18 +08:00
|
|
|
STATISTIC(NumAccumAdded, "Number of accumulators introduced");
|
2003-09-20 13:03:31 +08:00
|
|
|
|
2006-12-20 05:40:18 +08:00
|
|
|
namespace {
|
2009-09-02 14:11:42 +08:00
|
|
|
struct TailCallElim : public FunctionPass {
|
2013-01-22 19:26:02 +08:00
|
|
|
const TargetTransformInfo *TTI;
|
|
|
|
|
2007-05-06 21:37:16 +08:00
|
|
|
static char ID; // Pass identification, replacement for typeid
|
2010-10-20 01:21:58 +08:00
|
|
|
TailCallElim() : FunctionPass(ID) {
|
|
|
|
initializeTailCallElimPass(*PassRegistry::getPassRegistry());
|
|
|
|
}
|
2007-05-02 05:15:47 +08:00
|
|
|
|
2014-03-05 17:10:37 +08:00
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override;
|
2013-01-22 19:26:02 +08:00
|
|
|
|
2014-03-05 17:10:37 +08:00
|
|
|
bool runOnFunction(Function &F) override;
|
2003-12-08 13:34:54 +08:00
|
|
|
|
|
|
|
private:
|
2014-05-06 07:59:03 +08:00
|
|
|
bool runTRE(Function &F);
|
|
|
|
bool markTails(Function &F, bool &AllCallsAreTailCalls);
|
|
|
|
|
2011-01-29 12:46:23 +08:00
|
|
|
CallInst *FindTRECandidate(Instruction *I,
|
|
|
|
bool CannotTailCallElimCallsMarkedTail);
|
|
|
|
bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
|
|
|
|
BasicBlock *&OldEntry,
|
|
|
|
bool &TailCallsAreMarkedTail,
|
2013-07-14 12:42:23 +08:00
|
|
|
SmallVectorImpl<PHINode *> &ArgumentPHIs,
|
2011-01-29 12:46:23 +08:00
|
|
|
bool CannotTailCallElimCallsMarkedTail);
|
|
|
|
bool FoldReturnAndProcessPred(BasicBlock *BB,
|
|
|
|
ReturnInst *Ret, BasicBlock *&OldEntry,
|
|
|
|
bool &TailCallsAreMarkedTail,
|
2013-07-14 12:42:23 +08:00
|
|
|
SmallVectorImpl<PHINode *> &ArgumentPHIs,
|
2011-01-29 12:46:23 +08:00
|
|
|
bool CannotTailCallElimCallsMarkedTail);
|
2003-12-08 13:34:54 +08:00
|
|
|
bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
|
2005-08-07 12:27:41 +08:00
|
|
|
bool &TailCallsAreMarkedTail,
|
2013-07-14 12:42:23 +08:00
|
|
|
SmallVectorImpl<PHINode *> &ArgumentPHIs,
|
2005-08-07 12:27:41 +08:00
|
|
|
bool CannotTailCallElimCallsMarkedTail);
|
2003-12-08 13:34:54 +08:00
|
|
|
bool CanMoveAboveCall(Instruction *I, CallInst *CI);
|
2003-12-09 07:19:26 +08:00
|
|
|
Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
|
2003-09-20 13:03:31 +08:00
|
|
|
};
|
2015-06-23 17:49:53 +08:00
|
|
|
}
|
2003-09-20 13:03:31 +08:00
|
|
|
|
2008-05-13 08:00:25 +08:00
|
|
|
char TailCallElim::ID = 0;
|
2013-01-22 19:26:02 +08:00
|
|
|
INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim",
|
|
|
|
"Tail Call Elimination", false, false)
|
[PM] Change the core design of the TTI analysis to use a polymorphic
type erased interface and a single analysis pass rather than an
extremely complex analysis group.
The end result is that the TTI analysis can contain a type erased
implementation that supports the polymorphic TTI interface. We can build
one from a target-specific implementation or from a dummy one in the IR.
I've also factored all of the code into "mix-in"-able base classes,
including CRTP base classes to facilitate calling back up to the most
specialized form when delegating horizontally across the surface. These
aren't as clean as I would like and I'm planning to work on cleaning
some of this up, but I wanted to start by putting into the right form.
There are a number of reasons for this change, and this particular
design. The first and foremost reason is that an analysis group is
complete overkill, and the chaining delegation strategy was so opaque,
confusing, and high overhead that TTI was suffering greatly for it.
Several of the TTI functions had failed to be implemented in all places
because of the chaining-based delegation making there be no checking of
this. A few other functions were implemented with incorrect delegation.
The message to me was very clear working on this -- the delegation and
analysis group structure was too confusing to be useful here.
The other reason of course is that this is *much* more natural fit for
the new pass manager. This will lay the ground work for a type-erased
per-function info object that can look up the correct subtarget and even
cache it.
Yet another benefit is that this will significantly simplify the
interaction of the pass managers and the TargetMachine. See the future
work below.
The downside of this change is that it is very, very verbose. I'm going
to work to improve that, but it is somewhat an implementation necessity
in C++ to do type erasure. =/ I discussed this design really extensively
with Eric and Hal prior to going down this path, and afterward showed
them the result. No one was really thrilled with it, but there doesn't
seem to be a substantially better alternative. Using a base class and
virtual method dispatch would make the code much shorter, but as
discussed in the update to the programmer's manual and elsewhere,
a polymorphic interface feels like the more principled approach even if
this is perhaps the least compelling example of it. ;]
Ultimately, there is still a lot more to be done here, but this was the
huge chunk that I couldn't really split things out of because this was
the interface change to TTI. I've tried to minimize all the other parts
of this. The follow up work should include at least:
1) Improving the TargetMachine interface by having it directly return
a TTI object. Because we have a non-pass object with value semantics
and an internal type erasure mechanism, we can narrow the interface
of the TargetMachine to *just* do what we need: build and return
a TTI object that we can then insert into the pass pipeline.
2) Make the TTI object be fully specialized for a particular function.
This will include splitting off a minimal form of it which is
sufficient for the inliner and the old pass manager.
3) Add a new pass manager analysis which produces TTI objects from the
target machine for each function. This may actually be done as part
of #2 in order to use the new analysis to implement #2.
4) Work on narrowing the API between TTI and the targets so that it is
easier to understand and less verbose to type erase.
5) Work on narrowing the API between TTI and its clients so that it is
easier to understand and less verbose to forward.
6) Try to improve the CRTP-based delegation. I feel like this code is
just a bit messy and exacerbating the complexity of implementing
the TTI in each target.
Many thanks to Eric and Hal for their help here. I ended up blocked on
this somewhat more abruptly than I expected, and so I appreciate getting
it sorted out very quickly.
Differential Revision: http://reviews.llvm.org/D7293
llvm-svn: 227669
2015-01-31 11:43:40 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
|
2013-01-22 19:26:02 +08:00
|
|
|
INITIALIZE_PASS_END(TailCallElim, "tailcallelim",
|
|
|
|
"Tail Call Elimination", false, false)
|
2008-05-13 08:00:25 +08:00
|
|
|
|
2003-11-12 06:41:34 +08:00
|
|
|
// Public interface to the TailCallElimination pass
|
2003-11-21 02:25:24 +08:00
|
|
|
FunctionPass *llvm::createTailCallEliminationPass() {
|
|
|
|
return new TailCallElim();
|
|
|
|
}
|
2003-09-20 13:14:13 +08:00
|
|
|
|
2013-01-22 19:26:02 +08:00
|
|
|
void TailCallElim::getAnalysisUsage(AnalysisUsage &AU) const {
|
[PM] Change the core design of the TTI analysis to use a polymorphic
type erased interface and a single analysis pass rather than an
extremely complex analysis group.
The end result is that the TTI analysis can contain a type erased
implementation that supports the polymorphic TTI interface. We can build
one from a target-specific implementation or from a dummy one in the IR.
I've also factored all of the code into "mix-in"-able base classes,
including CRTP base classes to facilitate calling back up to the most
specialized form when delegating horizontally across the surface. These
aren't as clean as I would like and I'm planning to work on cleaning
some of this up, but I wanted to start by putting into the right form.
There are a number of reasons for this change, and this particular
design. The first and foremost reason is that an analysis group is
complete overkill, and the chaining delegation strategy was so opaque,
confusing, and high overhead that TTI was suffering greatly for it.
Several of the TTI functions had failed to be implemented in all places
because of the chaining-based delegation making there be no checking of
this. A few other functions were implemented with incorrect delegation.
The message to me was very clear working on this -- the delegation and
analysis group structure was too confusing to be useful here.
The other reason of course is that this is *much* more natural fit for
the new pass manager. This will lay the ground work for a type-erased
per-function info object that can look up the correct subtarget and even
cache it.
Yet another benefit is that this will significantly simplify the
interaction of the pass managers and the TargetMachine. See the future
work below.
The downside of this change is that it is very, very verbose. I'm going
to work to improve that, but it is somewhat an implementation necessity
in C++ to do type erasure. =/ I discussed this design really extensively
with Eric and Hal prior to going down this path, and afterward showed
them the result. No one was really thrilled with it, but there doesn't
seem to be a substantially better alternative. Using a base class and
virtual method dispatch would make the code much shorter, but as
discussed in the update to the programmer's manual and elsewhere,
a polymorphic interface feels like the more principled approach even if
this is perhaps the least compelling example of it. ;]
Ultimately, there is still a lot more to be done here, but this was the
huge chunk that I couldn't really split things out of because this was
the interface change to TTI. I've tried to minimize all the other parts
of this. The follow up work should include at least:
1) Improving the TargetMachine interface by having it directly return
a TTI object. Because we have a non-pass object with value semantics
and an internal type erasure mechanism, we can narrow the interface
of the TargetMachine to *just* do what we need: build and return
a TTI object that we can then insert into the pass pipeline.
2) Make the TTI object be fully specialized for a particular function.
This will include splitting off a minimal form of it which is
sufficient for the inliner and the old pass manager.
3) Add a new pass manager analysis which produces TTI objects from the
target machine for each function. This may actually be done as part
of #2 in order to use the new analysis to implement #2.
4) Work on narrowing the API between TTI and the targets so that it is
easier to understand and less verbose to type erase.
5) Work on narrowing the API between TTI and its clients so that it is
easier to understand and less verbose to forward.
6) Try to improve the CRTP-based delegation. I feel like this code is
just a bit messy and exacerbating the complexity of implementing
the TTI in each target.
Many thanks to Eric and Hal for their help here. I ended up blocked on
this somewhat more abruptly than I expected, and so I appreciate getting
it sorted out very quickly.
Differential Revision: http://reviews.llvm.org/D7293
llvm-svn: 227669
2015-01-31 11:43:40 +08:00
|
|
|
AU.addRequired<TargetTransformInfoWrapperPass>();
|
2015-09-10 18:22:12 +08:00
|
|
|
AU.addPreserved<GlobalsAAWrapperPass>();
|
2013-01-22 19:26:02 +08:00
|
|
|
}
|
|
|
|
|
2014-05-08 09:08:43 +08:00
|
|
|
/// \brief Scan the specified function for alloca instructions.
|
|
|
|
/// If it contains any dynamic allocas, returns false.
|
|
|
|
static bool CanTRE(Function &F) {
|
|
|
|
// Because of PR962, we don't TRE dynamic allocas.
|
|
|
|
for (auto &BB : F) {
|
|
|
|
for (auto &I : BB) {
|
|
|
|
if (AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
|
|
|
|
if (!AI->isStaticAlloca())
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
2009-11-07 15:42:38 +08:00
|
|
|
}
|
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
bool TailCallElim::runOnFunction(Function &F) {
|
|
|
|
if (skipOptnoneFunction(F))
|
|
|
|
return false;
|
2012-10-23 02:16:14 +08:00
|
|
|
|
2015-06-10 03:07:19 +08:00
|
|
|
if (F.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
|
|
|
|
return false;
|
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
bool AllCallsAreTailCalls = false;
|
|
|
|
bool Modified = markTails(F, AllCallsAreTailCalls);
|
|
|
|
if (AllCallsAreTailCalls)
|
|
|
|
Modified |= runTRE(F);
|
|
|
|
return Modified;
|
|
|
|
}
|
2013-07-11 12:40:01 +08:00
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
namespace {
|
|
|
|
struct AllocaDerivedValueTracker {
|
|
|
|
// Start at a root value and walk its use-def chain to mark calls that use the
|
|
|
|
// value or a derived value in AllocaUsers, and places where it may escape in
|
|
|
|
// EscapePoints.
|
|
|
|
void walk(Value *Root) {
|
|
|
|
SmallVector<Use *, 32> Worklist;
|
|
|
|
SmallPtrSet<Use *, 32> Visited;
|
|
|
|
|
|
|
|
auto AddUsesToWorklist = [&](Value *V) {
|
|
|
|
for (auto &U : V->uses()) {
|
2014-11-19 15:49:26 +08:00
|
|
|
if (!Visited.insert(&U).second)
|
2014-05-06 07:59:03 +08:00
|
|
|
continue;
|
|
|
|
Worklist.push_back(&U);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
AddUsesToWorklist(Root);
|
|
|
|
|
|
|
|
while (!Worklist.empty()) {
|
|
|
|
Use *U = Worklist.pop_back_val();
|
|
|
|
Instruction *I = cast<Instruction>(U->getUser());
|
|
|
|
|
|
|
|
switch (I->getOpcode()) {
|
|
|
|
case Instruction::Call:
|
|
|
|
case Instruction::Invoke: {
|
|
|
|
CallSite CS(I);
|
|
|
|
bool IsNocapture = !CS.isCallee(U) &&
|
|
|
|
CS.doesNotCapture(CS.getArgumentNo(U));
|
|
|
|
callUsesLocalStack(CS, IsNocapture);
|
|
|
|
if (IsNocapture) {
|
|
|
|
// If the alloca-derived argument is passed in as nocapture, then it
|
|
|
|
// can't propagate to the call's return. That would be capturing.
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
case Instruction::Load: {
|
|
|
|
// The result of a load is not alloca-derived (unless an alloca has
|
|
|
|
// otherwise escaped, but this is a local analysis).
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
case Instruction::Store: {
|
2014-05-06 08:46:20 +08:00
|
|
|
if (U->getOperandNo() == 0)
|
2014-05-06 07:59:03 +08:00
|
|
|
EscapePoints.insert(I);
|
|
|
|
continue; // Stores have no users to analyze.
|
|
|
|
}
|
|
|
|
case Instruction::BitCast:
|
|
|
|
case Instruction::GetElementPtr:
|
|
|
|
case Instruction::PHI:
|
|
|
|
case Instruction::Select:
|
|
|
|
case Instruction::AddrSpaceCast:
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
EscapePoints.insert(I);
|
2014-05-06 08:46:20 +08:00
|
|
|
break;
|
2014-05-06 07:59:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
AddUsesToWorklist(I);
|
|
|
|
}
|
2013-07-11 12:40:01 +08:00
|
|
|
}
|
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
void callUsesLocalStack(CallSite CS, bool IsNocapture) {
|
2014-07-23 14:24:49 +08:00
|
|
|
// Add it to the list of alloca users.
|
|
|
|
AllocaUsers.insert(CS.getInstruction());
|
2014-05-06 07:59:03 +08:00
|
|
|
|
2014-07-23 14:24:49 +08:00
|
|
|
// If it's nocapture then it can't capture this alloca.
|
2014-05-06 07:59:03 +08:00
|
|
|
if (IsNocapture)
|
|
|
|
return;
|
|
|
|
|
|
|
|
// If it can write to memory, it can leak the alloca value.
|
|
|
|
if (!CS.onlyReadsMemory())
|
|
|
|
EscapePoints.insert(CS.getInstruction());
|
2013-07-11 12:40:01 +08:00
|
|
|
}
|
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
SmallPtrSet<Instruction *, 32> AllocaUsers;
|
|
|
|
SmallPtrSet<Instruction *, 32> EscapePoints;
|
2013-07-11 12:40:01 +08:00
|
|
|
};
|
2015-06-23 17:49:53 +08:00
|
|
|
}
|
2005-05-10 07:51:13 +08:00
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
bool TailCallElim::markTails(Function &F, bool &AllCallsAreTailCalls) {
|
|
|
|
if (F.callsFunctionThatReturnsTwice())
|
2014-02-06 08:07:05 +08:00
|
|
|
return false;
|
2014-05-06 07:59:03 +08:00
|
|
|
AllCallsAreTailCalls = true;
|
|
|
|
|
2014-11-04 10:02:14 +08:00
|
|
|
// The local stack holds all alloca instructions and all byval arguments.
|
2014-05-06 07:59:03 +08:00
|
|
|
AllocaDerivedValueTracker Tracker;
|
2014-11-04 10:02:14 +08:00
|
|
|
for (Argument &Arg : F.args()) {
|
|
|
|
if (Arg.hasByValAttr())
|
|
|
|
Tracker.walk(&Arg);
|
|
|
|
}
|
2014-05-06 07:59:03 +08:00
|
|
|
for (auto &BB : F) {
|
|
|
|
for (auto &I : BB)
|
|
|
|
if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
|
|
|
|
Tracker.walk(AI);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool Modified = false;
|
|
|
|
|
|
|
|
// Track whether a block is reachable after an alloca has escaped. Blocks that
|
|
|
|
// contain the escaping instruction will be marked as being visited without an
|
|
|
|
// escaped alloca, since that is how the block began.
|
|
|
|
enum VisitType {
|
|
|
|
UNVISITED,
|
|
|
|
UNESCAPED,
|
|
|
|
ESCAPED
|
|
|
|
};
|
|
|
|
DenseMap<BasicBlock *, VisitType> Visited;
|
|
|
|
|
|
|
|
// We propagate the fact that an alloca has escaped from block to successor.
|
|
|
|
// Visit the blocks that are propagating the escapedness first. To do this, we
|
|
|
|
// maintain two worklists.
|
|
|
|
SmallVector<BasicBlock *, 32> WorklistUnescaped, WorklistEscaped;
|
|
|
|
|
|
|
|
// We may enter a block and visit it thinking that no alloca has escaped yet,
|
|
|
|
// then see an escape point and go back around a loop edge and come back to
|
|
|
|
// the same block twice. Because of this, we defer setting tail on calls when
|
|
|
|
// we first encounter them in a block. Every entry in this list does not
|
|
|
|
// statically use an alloca via use-def chain analysis, but may find an alloca
|
|
|
|
// through other means if the block turns out to be reachable after an escape
|
|
|
|
// point.
|
|
|
|
SmallVector<CallInst *, 32> DeferredTails;
|
|
|
|
|
|
|
|
BasicBlock *BB = &F.getEntryBlock();
|
|
|
|
VisitType Escaped = UNESCAPED;
|
|
|
|
do {
|
|
|
|
for (auto &I : *BB) {
|
|
|
|
if (Tracker.EscapePoints.count(&I))
|
|
|
|
Escaped = ESCAPED;
|
|
|
|
|
|
|
|
CallInst *CI = dyn_cast<CallInst>(&I);
|
|
|
|
if (!CI || CI->isTailCall())
|
|
|
|
continue;
|
|
|
|
|
2015-11-07 07:55:38 +08:00
|
|
|
bool IsNoTail = CI->isNoTailCall();
|
|
|
|
|
|
|
|
if (!IsNoTail && CI->doesNotAccessMemory()) {
|
2014-05-06 07:59:03 +08:00
|
|
|
// A call to a readnone function whose arguments are all things computed
|
|
|
|
// outside this function can be marked tail. Even if you stored the
|
|
|
|
// alloca address into a global, a readnone function can't load the
|
|
|
|
// global anyhow.
|
|
|
|
//
|
|
|
|
// Note that this runs whether we know an alloca has escaped or not. If
|
|
|
|
// it has, then we can't trust Tracker.AllocaUsers to be accurate.
|
|
|
|
bool SafeToTail = true;
|
|
|
|
for (auto &Arg : CI->arg_operands()) {
|
|
|
|
if (isa<Constant>(Arg.getUser()))
|
|
|
|
continue;
|
2014-11-04 10:02:14 +08:00
|
|
|
if (Argument *A = dyn_cast<Argument>(Arg.getUser()))
|
|
|
|
if (!A->hasByValAttr())
|
|
|
|
continue;
|
2014-05-06 07:59:03 +08:00
|
|
|
SafeToTail = false;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (SafeToTail) {
|
2014-05-22 22:19:46 +08:00
|
|
|
emitOptimizationRemark(
|
|
|
|
F.getContext(), "tailcallelim", F, CI->getDebugLoc(),
|
2014-05-09 07:04:46 +08:00
|
|
|
"marked this readnone call a tail call candidate");
|
2014-05-06 07:59:03 +08:00
|
|
|
CI->setTailCall();
|
|
|
|
Modified = true;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-07 07:55:38 +08:00
|
|
|
if (!IsNoTail && Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI)) {
|
2014-05-06 07:59:03 +08:00
|
|
|
DeferredTails.push_back(CI);
|
|
|
|
} else {
|
|
|
|
AllCallsAreTailCalls = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-22 01:06:51 +08:00
|
|
|
for (auto *SuccBB : make_range(succ_begin(BB), succ_end(BB))) {
|
2014-05-06 07:59:03 +08:00
|
|
|
auto &State = Visited[SuccBB];
|
|
|
|
if (State < Escaped) {
|
|
|
|
State = Escaped;
|
|
|
|
if (State == ESCAPED)
|
|
|
|
WorklistEscaped.push_back(SuccBB);
|
|
|
|
else
|
|
|
|
WorklistUnescaped.push_back(SuccBB);
|
|
|
|
}
|
|
|
|
}
|
2014-02-06 08:07:05 +08:00
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
if (!WorklistEscaped.empty()) {
|
|
|
|
BB = WorklistEscaped.pop_back_val();
|
|
|
|
Escaped = ESCAPED;
|
|
|
|
} else {
|
|
|
|
BB = nullptr;
|
|
|
|
while (!WorklistUnescaped.empty()) {
|
|
|
|
auto *NextBB = WorklistUnescaped.pop_back_val();
|
|
|
|
if (Visited[NextBB] == UNESCAPED) {
|
|
|
|
BB = NextBB;
|
|
|
|
Escaped = UNESCAPED;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} while (BB);
|
|
|
|
|
|
|
|
for (CallInst *CI : DeferredTails) {
|
|
|
|
if (Visited[CI->getParent()] != ESCAPED) {
|
|
|
|
// If the escape point was part way through the block, calls after the
|
|
|
|
// escape point wouldn't have been put into DeferredTails.
|
2014-05-22 22:19:46 +08:00
|
|
|
emitOptimizationRemark(F.getContext(), "tailcallelim", F,
|
|
|
|
CI->getDebugLoc(),
|
|
|
|
"marked this call a tail call candidate");
|
2014-05-06 07:59:03 +08:00
|
|
|
CI->setTailCall();
|
|
|
|
Modified = true;
|
|
|
|
} else {
|
|
|
|
AllCallsAreTailCalls = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return Modified;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool TailCallElim::runTRE(Function &F) {
|
2003-09-20 13:03:31 +08:00
|
|
|
// If this function is a varargs function, we won't be able to PHI the args
|
|
|
|
// right, so don't even try to convert it...
|
|
|
|
if (F.getFunctionType()->isVarArg()) return false;
|
|
|
|
|
2015-02-01 20:01:35 +08:00
|
|
|
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
|
2014-04-25 13:29:35 +08:00
|
|
|
BasicBlock *OldEntry = nullptr;
|
2005-08-07 12:27:41 +08:00
|
|
|
bool TailCallsAreMarkedTail = false;
|
2009-11-07 15:10:01 +08:00
|
|
|
SmallVector<PHINode*, 8> ArgumentPHIs;
|
2003-09-20 13:03:31 +08:00
|
|
|
bool MadeChange = false;
|
2005-05-10 07:51:13 +08:00
|
|
|
|
2015-02-28 01:27:15 +08:00
|
|
|
// If false, we cannot perform TRE on tail calls marked with the 'tail'
|
|
|
|
// attribute, because doing so would cause the stack size to increase (real
|
|
|
|
// TRE would deallocate variable sized allocas, TRE doesn't).
|
2014-05-08 09:08:43 +08:00
|
|
|
bool CanTRETailMarkedCall = CanTRE(F);
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
// Change any tail recursive calls to loops.
|
2013-07-11 12:40:01 +08:00
|
|
|
//
|
|
|
|
// FIXME: The code generator produces really bad code when an 'escaping
|
|
|
|
// alloca' is changed from being a static alloca to being a dynamic alloca.
|
|
|
|
// Until this is resolved, disable this transformation if that would ever
|
|
|
|
// happen. This bug is PR962.
|
2015-03-01 00:47:27 +08:00
|
|
|
for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; /*in loop*/) {
|
2015-10-14 03:26:58 +08:00
|
|
|
BasicBlock *BB = &*BBI++; // FoldReturnAndProcessPred may delete BB.
|
2014-05-06 07:59:03 +08:00
|
|
|
if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
|
|
|
|
bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
|
|
|
|
ArgumentPHIs, !CanTRETailMarkedCall);
|
2015-03-01 00:47:27 +08:00
|
|
|
if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
|
2014-05-06 07:59:03 +08:00
|
|
|
Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
|
|
|
|
TailCallsAreMarkedTail, ArgumentPHIs,
|
|
|
|
!CanTRETailMarkedCall);
|
|
|
|
MadeChange |= Change;
|
2011-01-29 12:46:23 +08:00
|
|
|
}
|
|
|
|
}
|
2005-08-07 12:27:41 +08:00
|
|
|
|
2003-12-09 07:37:35 +08:00
|
|
|
// If we eliminated any tail recursions, it's possible that we inserted some
|
|
|
|
// silly PHI nodes which just merge an initial value (the incoming operand)
|
|
|
|
// with themselves. Check to see if we did and clean up our mess if so. This
|
|
|
|
// occurs when a function passes an argument straight through to its tail
|
|
|
|
// call.
|
2014-05-06 07:59:03 +08:00
|
|
|
for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
|
|
|
|
PHINode *PN = ArgumentPHIs[i];
|
2003-12-09 07:37:35 +08:00
|
|
|
|
2014-05-06 07:59:03 +08:00
|
|
|
// If the PHI Node is a dynamic constant, replace it with the value it is.
|
2015-03-10 10:37:25 +08:00
|
|
|
if (Value *PNV = SimplifyInstruction(PN, F.getParent()->getDataLayout())) {
|
2014-05-06 07:59:03 +08:00
|
|
|
PN->replaceAllUsesWith(PNV);
|
|
|
|
PN->eraseFromParent();
|
2013-07-11 12:40:01 +08:00
|
|
|
}
|
|
|
|
}
|
2005-05-10 07:51:13 +08:00
|
|
|
|
2003-09-20 13:03:31 +08:00
|
|
|
return MadeChange;
|
|
|
|
}
|
2003-12-08 13:34:54 +08:00
|
|
|
|
2012-10-23 02:16:14 +08:00
|
|
|
|
2015-02-28 01:27:15 +08:00
|
|
|
/// Return true if it is safe to move the specified
|
2003-12-09 07:19:26 +08:00
|
|
|
/// instruction from after the call to before the call, assuming that all
|
|
|
|
/// instructions between the call and this instruction are movable.
|
|
|
|
///
|
2003-12-08 13:34:54 +08:00
|
|
|
bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
|
|
|
|
// FIXME: We can move load/store/call/free instructions above the call if the
|
|
|
|
// call does not mod/ref the memory location being processed.
|
2009-06-19 12:22:16 +08:00
|
|
|
if (I->mayHaveSideEffects()) // This also handles volatile loads.
|
2003-12-08 13:34:54 +08:00
|
|
|
return false;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2009-11-07 15:10:01 +08:00
|
|
|
if (LoadInst *L = dyn_cast<LoadInst>(I)) {
|
2009-06-19 12:22:16 +08:00
|
|
|
// Loads may always be moved above calls without side effects.
|
|
|
|
if (CI->mayHaveSideEffects()) {
|
|
|
|
// Non-volatile loads may be moved above a call with side effects if it
|
|
|
|
// does not write to memory and the load provably won't trap.
|
|
|
|
// FIXME: Writes to memory only matter if they may alias the pointer
|
|
|
|
// being loaded from.
|
|
|
|
if (CI->mayWriteToMemory() ||
|
2010-01-30 12:42:39 +08:00
|
|
|
!isSafeToLoadUnconditionally(L->getPointerOperand(), L,
|
2015-03-10 10:37:25 +08:00
|
|
|
L->getAlignment()))
|
2009-06-19 12:22:16 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2003-12-08 13:34:54 +08:00
|
|
|
|
|
|
|
// Otherwise, if this is a side-effect free instruction, check to make sure
|
|
|
|
// that it does not use the return value of the call. If it doesn't use the
|
|
|
|
// return value of the call, it must only use things that are defined before
|
|
|
|
// the call, or movable instructions between the call and the instruction
|
|
|
|
// itself.
|
|
|
|
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
|
|
|
|
if (I->getOperand(i) == CI)
|
|
|
|
return false;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-02-28 01:27:15 +08:00
|
|
|
/// Return true if the specified value is the same when the return would exit
|
|
|
|
/// as it was when the initial iteration of the recursive function was executed.
|
|
|
|
///
|
|
|
|
/// We currently handle static constants and arguments that are not modified as
|
|
|
|
/// part of the recursion.
|
2009-11-08 05:10:15 +08:00
|
|
|
static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
|
2003-12-15 07:57:39 +08:00
|
|
|
if (isa<Constant>(V)) return true; // Static constants are always dyn consts
|
|
|
|
|
|
|
|
// Check to see if this is an immutable argument, if so, the value
|
|
|
|
// will be available to initialize the accumulator.
|
|
|
|
if (Argument *Arg = dyn_cast<Argument>(V)) {
|
|
|
|
// Figure out which argument number this is...
|
|
|
|
unsigned ArgNo = 0;
|
|
|
|
Function *F = CI->getParent()->getParent();
|
2005-03-15 12:54:21 +08:00
|
|
|
for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
|
2003-12-15 07:57:39 +08:00
|
|
|
++ArgNo;
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2003-12-15 07:57:39 +08:00
|
|
|
// If we are passing this argument into call as the corresponding
|
|
|
|
// argument operand, then the argument is dynamically constant.
|
|
|
|
// Otherwise, we cannot transform this function safely.
|
2010-06-24 08:44:01 +08:00
|
|
|
if (CI->getArgOperand(ArgNo) == Arg)
|
2003-12-15 07:57:39 +08:00
|
|
|
return true;
|
|
|
|
}
|
2009-11-08 05:10:15 +08:00
|
|
|
|
|
|
|
// Switch cases are always constant integers. If the value is being switched
|
|
|
|
// on and the return is only reachable from one of its cases, it's
|
|
|
|
// effectively constant.
|
|
|
|
if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
|
|
|
|
if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
|
|
|
|
if (SI->getCondition() == V)
|
|
|
|
return SI->getDefaultDest() != RI->getParent();
|
|
|
|
|
2003-12-15 07:57:39 +08:00
|
|
|
// Not a constant or immutable argument, we can't safely transform.
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2015-02-28 01:27:15 +08:00
|
|
|
/// Check to see if the function containing the specified tail call consistently
|
|
|
|
/// returns the same runtime-constant value at all exit points except for
|
|
|
|
/// IgnoreRI. If so, return the returned value.
|
2010-06-26 20:53:31 +08:00
|
|
|
static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
|
|
|
|
Function *F = CI->getParent()->getParent();
|
2014-04-25 13:29:35 +08:00
|
|
|
Value *ReturnedValue = nullptr;
|
2003-12-15 07:57:39 +08:00
|
|
|
|
2010-09-01 05:21:25 +08:00
|
|
|
for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
|
|
|
|
ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
|
2014-04-25 13:29:35 +08:00
|
|
|
if (RI == nullptr || RI == IgnoreRI) continue;
|
2010-09-01 05:21:25 +08:00
|
|
|
|
|
|
|
// We can only perform this transformation if the value returned is
|
|
|
|
// evaluatable at the start of the initial invocation of the function,
|
|
|
|
// instead of at the end of the evaluation.
|
|
|
|
//
|
|
|
|
Value *RetOp = RI->getOperand(0);
|
|
|
|
if (!isDynamicConstant(RetOp, CI, RI))
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2010-09-01 05:21:25 +08:00
|
|
|
|
|
|
|
if (ReturnedValue && RetOp != ReturnedValue)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr; // Cannot transform if differing values are returned.
|
2010-09-01 05:21:25 +08:00
|
|
|
ReturnedValue = RetOp;
|
|
|
|
}
|
2003-12-15 07:57:39 +08:00
|
|
|
return ReturnedValue;
|
|
|
|
}
|
2003-12-08 13:34:54 +08:00
|
|
|
|
2015-02-28 01:27:15 +08:00
|
|
|
/// If the specified instruction can be transformed using accumulator recursion
|
|
|
|
/// elimination, return the constant which is the start of the accumulator
|
|
|
|
/// value. Otherwise return null.
|
2003-12-09 07:19:26 +08:00
|
|
|
Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
|
|
|
|
CallInst *CI) {
|
2014-04-25 13:29:35 +08:00
|
|
|
if (!I->isAssociative() || !I->isCommutative()) return nullptr;
|
2003-12-09 07:19:26 +08:00
|
|
|
assert(I->getNumOperands() == 2 &&
|
2010-07-11 04:31:42 +08:00
|
|
|
"Associative/commutative operations should have 2 args!");
|
2003-12-09 07:19:26 +08:00
|
|
|
|
2010-09-01 05:21:25 +08:00
|
|
|
// Exactly one operand should be the result of the call instruction.
|
2008-02-20 19:26:25 +08:00
|
|
|
if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
|
|
|
|
(I->getOperand(0) != CI && I->getOperand(1) != CI))
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2003-12-09 07:19:26 +08:00
|
|
|
|
|
|
|
// The only user of this instruction we allow is a single return instruction.
|
2014-03-09 11:16:01 +08:00
|
|
|
if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2003-12-09 07:19:26 +08:00
|
|
|
|
|
|
|
// Ok, now we have to check all of the other return instructions in this
|
|
|
|
// function. If they return non-constants or differing values, then we cannot
|
|
|
|
// transform the function safely.
|
2014-03-09 11:16:01 +08:00
|
|
|
return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
|
2003-12-09 07:19:26 +08:00
|
|
|
}
|
|
|
|
|
2011-01-29 12:46:23 +08:00
|
|
|
static Instruction *FirstNonDbg(BasicBlock::iterator I) {
|
|
|
|
while (isa<DbgInfoIntrinsic>(I))
|
|
|
|
++I;
|
|
|
|
return &*I;
|
|
|
|
}
|
|
|
|
|
|
|
|
CallInst*
|
|
|
|
TailCallElim::FindTRECandidate(Instruction *TI,
|
|
|
|
bool CannotTailCallElimCallsMarkedTail) {
|
|
|
|
BasicBlock *BB = TI->getParent();
|
2003-12-08 13:34:54 +08:00
|
|
|
Function *F = BB->getParent();
|
|
|
|
|
2011-01-29 12:46:23 +08:00
|
|
|
if (&BB->front() == TI) // Make sure there is something before the terminator.
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2003-12-08 13:34:54 +08:00
|
|
|
// Scan backwards from the return, checking to see if there is a tail call in
|
|
|
|
// this block. If so, set CI to it.
|
2014-04-25 13:29:35 +08:00
|
|
|
CallInst *CI = nullptr;
|
2015-10-14 03:26:58 +08:00
|
|
|
BasicBlock::iterator BBI(TI);
|
2011-01-29 12:46:23 +08:00
|
|
|
while (true) {
|
2003-12-08 13:34:54 +08:00
|
|
|
CI = dyn_cast<CallInst>(BBI);
|
|
|
|
if (CI && CI->getCalledFunction() == F)
|
|
|
|
break;
|
|
|
|
|
|
|
|
if (BBI == BB->begin())
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr; // Didn't find a potential tail call.
|
2003-12-08 13:34:54 +08:00
|
|
|
--BBI;
|
|
|
|
}
|
|
|
|
|
2005-08-07 12:27:41 +08:00
|
|
|
// If this call is marked as a tail call, and if there are dynamic allocas in
|
|
|
|
// the function, we cannot perform this optimization.
|
|
|
|
if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2005-08-07 12:27:41 +08:00
|
|
|
|
2010-04-16 23:57:50 +08:00
|
|
|
// As a special case, detect code like this:
|
|
|
|
// double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
|
|
|
|
// and disable this xform in this case, because the code generator will
|
|
|
|
// lower the call to fabs into inline code.
|
2012-07-24 18:51:42 +08:00
|
|
|
if (BB == &F->getEntryBlock() &&
|
2015-10-14 03:26:58 +08:00
|
|
|
FirstNonDbg(BB->front().getIterator()) == CI &&
|
|
|
|
FirstNonDbg(std::next(BB->begin())) == TI && CI->getCalledFunction() &&
|
2013-01-22 19:26:02 +08:00
|
|
|
!TTI->isLoweredToCall(CI->getCalledFunction())) {
|
2010-04-16 23:57:50 +08:00
|
|
|
// A single-block function with just a call and a return. Check that
|
|
|
|
// the arguments match.
|
|
|
|
CallSite::arg_iterator I = CallSite(CI).arg_begin(),
|
|
|
|
E = CallSite(CI).arg_end();
|
|
|
|
Function::arg_iterator FI = F->arg_begin(),
|
|
|
|
FE = F->arg_end();
|
|
|
|
for (; I != E && FI != FE; ++I, ++FI)
|
|
|
|
if (*I != &*FI) break;
|
|
|
|
if (I == E && FI == FE)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2010-04-16 23:57:50 +08:00
|
|
|
}
|
|
|
|
|
2011-01-29 12:46:23 +08:00
|
|
|
return CI;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
|
|
|
|
BasicBlock *&OldEntry,
|
|
|
|
bool &TailCallsAreMarkedTail,
|
2013-07-14 12:42:23 +08:00
|
|
|
SmallVectorImpl<PHINode *> &ArgumentPHIs,
|
2011-01-29 12:46:23 +08:00
|
|
|
bool CannotTailCallElimCallsMarkedTail) {
|
2010-07-11 04:31:42 +08:00
|
|
|
// If we are introducing accumulator recursion to eliminate operations after
|
|
|
|
// the call instruction that are both associative and commutative, the initial
|
|
|
|
// value for the accumulator is placed in this variable. If this value is set
|
|
|
|
// then we actually perform accumulator recursion elimination instead of
|
2010-07-13 23:41:41 +08:00
|
|
|
// simple tail recursion elimination. If the operation is an LLVM instruction
|
|
|
|
// (eg: "add") then it is recorded in AccumulatorRecursionInstr. If not, then
|
|
|
|
// we are handling the case when the return instruction returns a constant C
|
|
|
|
// which is different to the constant returned by other return instructions
|
|
|
|
// (which is recorded in AccumulatorRecursionEliminationInitVal). This is a
|
|
|
|
// special case of accumulator recursion, the operation being "return C".
|
2014-04-25 13:29:35 +08:00
|
|
|
Value *AccumulatorRecursionEliminationInitVal = nullptr;
|
|
|
|
Instruction *AccumulatorRecursionInstr = nullptr;
|
2003-12-09 07:19:26 +08:00
|
|
|
|
2003-12-08 13:34:54 +08:00
|
|
|
// Ok, we found a potential tail call. We can currently only transform the
|
|
|
|
// tail call if all of the instructions between the call and the return are
|
|
|
|
// movable to above the call itself, leaving the call next to the return.
|
|
|
|
// Check that this is the case now.
|
2015-10-14 03:26:58 +08:00
|
|
|
BasicBlock::iterator BBI(CI);
|
2011-01-29 12:46:23 +08:00
|
|
|
for (++BBI; &*BBI != Ret; ++BBI) {
|
2015-10-14 03:26:58 +08:00
|
|
|
if (CanMoveAboveCall(&*BBI, CI)) continue;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2010-09-01 05:21:25 +08:00
|
|
|
// If we can't move the instruction above the call, it might be because it
|
2011-04-15 13:18:47 +08:00
|
|
|
// is an associative and commutative operation that could be transformed
|
2010-09-01 05:21:25 +08:00
|
|
|
// using accumulator recursion elimination. Check to see if this is the
|
|
|
|
// case, and if so, remember the initial accumulator value for later.
|
|
|
|
if ((AccumulatorRecursionEliminationInitVal =
|
2015-10-14 03:26:58 +08:00
|
|
|
CanTransformAccumulatorRecursion(&*BBI, CI))) {
|
2010-09-01 05:21:25 +08:00
|
|
|
// Yes, this is accumulator recursion. Remember which instruction
|
|
|
|
// accumulates.
|
2015-10-14 03:26:58 +08:00
|
|
|
AccumulatorRecursionInstr = &*BBI;
|
2010-09-01 05:21:25 +08:00
|
|
|
} else {
|
|
|
|
return false; // Otherwise, we cannot eliminate the tail recursion!
|
2003-12-09 07:19:26 +08:00
|
|
|
}
|
2010-09-01 05:21:25 +08:00
|
|
|
}
|
2003-12-08 13:34:54 +08:00
|
|
|
|
|
|
|
// We can only transform call/return pairs that either ignore the return value
|
2003-12-15 07:57:39 +08:00
|
|
|
// of the call and return void, ignore the value of the call and return a
|
|
|
|
// constant, return the value returned by the tail call, or that are being
|
|
|
|
// accumulator recursion variable eliminated.
|
2008-03-12 01:33:32 +08:00
|
|
|
if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
|
2005-11-05 16:21:11 +08:00
|
|
|
!isa<UndefValue>(Ret->getReturnValue()) &&
|
2014-04-25 13:29:35 +08:00
|
|
|
AccumulatorRecursionEliminationInitVal == nullptr &&
|
|
|
|
!getCommonReturnValue(nullptr, CI)) {
|
2010-07-13 23:41:41 +08:00
|
|
|
// One case remains that we are able to handle: the current return
|
|
|
|
// instruction returns a constant, and all other return instructions
|
|
|
|
// return a different constant.
|
|
|
|
if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
|
|
|
|
return false; // Current return instruction does not return a constant.
|
|
|
|
// Check that all other return instructions return a common constant. If
|
|
|
|
// so, record it in AccumulatorRecursionEliminationInitVal.
|
|
|
|
AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
|
|
|
|
if (!AccumulatorRecursionEliminationInitVal)
|
|
|
|
return false;
|
|
|
|
}
|
2003-12-08 13:34:54 +08:00
|
|
|
|
2011-01-29 12:46:23 +08:00
|
|
|
BasicBlock *BB = Ret->getParent();
|
|
|
|
Function *F = BB->getParent();
|
|
|
|
|
2014-05-22 22:19:46 +08:00
|
|
|
emitOptimizationRemark(F->getContext(), "tailcallelim", *F, CI->getDebugLoc(),
|
|
|
|
"transforming tail recursion to loop");
|
2014-05-06 07:59:03 +08:00
|
|
|
|
2003-12-08 13:34:54 +08:00
|
|
|
// OK! We can transform this tail call. If this is the first one found,
|
|
|
|
// create the new entry block, allowing us to branch back to the old entry.
|
2014-04-25 13:29:35 +08:00
|
|
|
if (!OldEntry) {
|
2003-12-08 13:34:54 +08:00
|
|
|
OldEntry = &F->getEntryBlock();
|
2009-08-14 05:58:54 +08:00
|
|
|
BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
|
2007-02-11 09:23:03 +08:00
|
|
|
NewEntry->takeName(OldEntry);
|
|
|
|
OldEntry->setName("tailrecurse");
|
2008-04-07 04:25:17 +08:00
|
|
|
BranchInst::Create(OldEntry, NewEntry);
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2005-08-07 12:27:41 +08:00
|
|
|
// If this tail call is marked 'tail' and if there are any allocas in the
|
|
|
|
// entry block, move them up to the new entry block.
|
|
|
|
TailCallsAreMarkedTail = CI->isTailCall();
|
|
|
|
if (TailCallsAreMarkedTail)
|
|
|
|
// Move all fixed sized allocas from OldEntry to NewEntry.
|
|
|
|
for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
|
|
|
|
NEBI = NewEntry->begin(); OEBI != E; )
|
|
|
|
if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
|
|
|
|
if (isa<ConstantInt>(AI->getArraySize()))
|
2015-10-14 03:26:58 +08:00
|
|
|
AI->moveBefore(&*NEBI);
|
2005-08-07 12:27:41 +08:00
|
|
|
|
2003-12-08 13:34:54 +08:00
|
|
|
// Now that we have created a new block, which jumps to the entry
|
|
|
|
// block, insert a PHI node for each argument of the function.
|
|
|
|
// For now, we initialize each PHI to only have the real arguments
|
|
|
|
// which are passed in.
|
2015-10-14 03:26:58 +08:00
|
|
|
Instruction *InsertPos = &OldEntry->front();
|
2005-05-10 07:51:13 +08:00
|
|
|
for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
|
|
|
|
I != E; ++I) {
|
2011-03-30 19:28:46 +08:00
|
|
|
PHINode *PN = PHINode::Create(I->getType(), 2,
|
2008-05-15 18:04:30 +08:00
|
|
|
I->getName() + ".tr", InsertPos);
|
2003-12-08 13:34:54 +08:00
|
|
|
I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
|
2015-10-14 03:26:58 +08:00
|
|
|
PN->addIncoming(&*I, NewEntry);
|
2003-12-08 13:34:54 +08:00
|
|
|
ArgumentPHIs.push_back(PN);
|
|
|
|
}
|
|
|
|
}
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2005-08-07 12:27:41 +08:00
|
|
|
// If this function has self recursive calls in the tail position where some
|
|
|
|
// are marked tail and some are not, only transform one flavor or another. We
|
|
|
|
// have to choose whether we move allocas in the entry block to the new entry
|
|
|
|
// block or not, so we can't make a good choice for both. NOTE: We could do
|
|
|
|
// slightly better here in the case that the function has no entry block
|
|
|
|
// allocas.
|
|
|
|
if (TailCallsAreMarkedTail && !CI->isTailCall())
|
|
|
|
return false;
|
|
|
|
|
2003-12-08 13:34:54 +08:00
|
|
|
// Ok, now that we know we have a pseudo-entry block WITH all of the
|
|
|
|
// required PHI nodes, add entries into the PHI node for the actual
|
|
|
|
// parameters passed into the tail-recursive call.
|
2010-06-24 08:48:48 +08:00
|
|
|
for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
|
2010-06-24 08:44:01 +08:00
|
|
|
ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2003-12-09 07:19:26 +08:00
|
|
|
// If we are introducing an accumulator variable to eliminate the recursion,
|
|
|
|
// do so now. Note that we _know_ that no subsequent tail recursion
|
|
|
|
// eliminations will happen on this function because of the way the
|
|
|
|
// accumulator recursion predicate is set up.
|
|
|
|
//
|
|
|
|
if (AccumulatorRecursionEliminationInitVal) {
|
|
|
|
Instruction *AccRecInstr = AccumulatorRecursionInstr;
|
|
|
|
// Start by inserting a new PHI node for the accumulator.
|
2011-03-30 19:19:20 +08:00
|
|
|
pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
|
2015-10-14 03:26:58 +08:00
|
|
|
PHINode *AccPN = PHINode::Create(
|
|
|
|
AccumulatorRecursionEliminationInitVal->getType(),
|
|
|
|
std::distance(PB, PE) + 1, "accumulator.tr", &OldEntry->front());
|
2003-12-09 07:19:26 +08:00
|
|
|
|
|
|
|
// Loop over all of the predecessors of the tail recursion block. For the
|
|
|
|
// real entry into the function we seed the PHI with the initial value,
|
|
|
|
// computed earlier. For any other existing branches to this block (due to
|
|
|
|
// other tail recursions eliminated) the accumulator is not modified.
|
|
|
|
// Because we haven't added the branch in the current block to OldEntry yet,
|
|
|
|
// it will not show up as a predecessor.
|
2011-03-30 19:19:20 +08:00
|
|
|
for (pred_iterator PI = PB; PI != PE; ++PI) {
|
2010-07-12 18:36:48 +08:00
|
|
|
BasicBlock *P = *PI;
|
|
|
|
if (P == &F->getEntryBlock())
|
|
|
|
AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
|
2003-12-09 07:19:26 +08:00
|
|
|
else
|
2010-07-12 18:36:48 +08:00
|
|
|
AccPN->addIncoming(AccPN, P);
|
2003-12-09 07:19:26 +08:00
|
|
|
}
|
|
|
|
|
2010-07-13 23:41:41 +08:00
|
|
|
if (AccRecInstr) {
|
|
|
|
// Add an incoming argument for the current block, which is computed by
|
|
|
|
// our associative and commutative accumulator instruction.
|
|
|
|
AccPN->addIncoming(AccRecInstr, BB);
|
|
|
|
|
|
|
|
// Next, rewrite the accumulator recursion instruction so that it does not
|
|
|
|
// use the result of the call anymore, instead, use the PHI node we just
|
|
|
|
// inserted.
|
|
|
|
AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
|
|
|
|
} else {
|
|
|
|
// Add an incoming argument for the current block, which is just the
|
|
|
|
// constant returned by the current return instruction.
|
|
|
|
AccPN->addIncoming(Ret->getReturnValue(), BB);
|
|
|
|
}
|
2003-12-09 07:19:26 +08:00
|
|
|
|
|
|
|
// Finally, rewrite any return instructions in the program to return the PHI
|
|
|
|
// node instead of the "initval" that they do currently. This loop will
|
|
|
|
// actually rewrite the return value we are destroying, but that's ok.
|
|
|
|
for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
|
|
|
|
if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
|
|
|
|
RI->setOperand(0, AccPN);
|
|
|
|
++NumAccumAdded;
|
|
|
|
}
|
|
|
|
|
2003-12-08 13:34:54 +08:00
|
|
|
// Now that all of the PHI nodes are in place, remove the call and
|
|
|
|
// ret instructions, replacing them with an unconditional branch.
|
2011-04-29 02:43:39 +08:00
|
|
|
BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
|
|
|
|
NewBI->setDebugLoc(CI->getDebugLoc());
|
|
|
|
|
2003-12-08 13:34:54 +08:00
|
|
|
BB->getInstList().erase(Ret); // Remove return.
|
|
|
|
BB->getInstList().erase(CI); // Remove call.
|
2003-12-09 07:19:26 +08:00
|
|
|
++NumEliminated;
|
2003-12-08 13:34:54 +08:00
|
|
|
return true;
|
|
|
|
}
|
2011-01-29 12:46:23 +08:00
|
|
|
|
|
|
|
bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
|
|
|
|
ReturnInst *Ret, BasicBlock *&OldEntry,
|
|
|
|
bool &TailCallsAreMarkedTail,
|
2013-07-14 12:42:23 +08:00
|
|
|
SmallVectorImpl<PHINode *> &ArgumentPHIs,
|
2011-01-29 12:46:23 +08:00
|
|
|
bool CannotTailCallElimCallsMarkedTail) {
|
|
|
|
bool Change = false;
|
|
|
|
|
|
|
|
// If the return block contains nothing but the return and PHI's,
|
|
|
|
// there might be an opportunity to duplicate the return in its
|
|
|
|
// predecessors and perform TRC there. Look for predecessors that end
|
|
|
|
// in unconditional branch and recursive call(s).
|
|
|
|
SmallVector<BranchInst*, 8> UncondBranchPreds;
|
2014-07-22 01:06:51 +08:00
|
|
|
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
|
|
|
|
BasicBlock *Pred = *PI;
|
2011-01-29 12:46:23 +08:00
|
|
|
TerminatorInst *PTI = Pred->getTerminator();
|
|
|
|
if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
|
|
|
|
if (BI->isUnconditional())
|
|
|
|
UncondBranchPreds.push_back(BI);
|
|
|
|
}
|
|
|
|
|
|
|
|
while (!UncondBranchPreds.empty()) {
|
|
|
|
BranchInst *BI = UncondBranchPreds.pop_back_val();
|
|
|
|
BasicBlock *Pred = BI->getParent();
|
|
|
|
if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
|
|
|
|
DEBUG(dbgs() << "FOLDING: " << *BB
|
|
|
|
<< "INTO UNCOND BRANCH PRED: " << *Pred);
|
2014-11-19 21:32:51 +08:00
|
|
|
ReturnInst *RI = FoldReturnIntoUncondBranch(Ret, BB, Pred);
|
|
|
|
|
|
|
|
// Cleanup: if all predecessors of BB have been eliminated by
|
2015-03-01 00:47:27 +08:00
|
|
|
// FoldReturnIntoUncondBranch, delete it. It is important to empty it,
|
|
|
|
// because the ret instruction in there is still using a value which
|
|
|
|
// EliminateRecursiveTailCall will attempt to remove.
|
2014-11-19 21:32:51 +08:00
|
|
|
if (!BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
|
2015-03-01 00:47:27 +08:00
|
|
|
BB->eraseFromParent();
|
2014-11-19 21:32:51 +08:00
|
|
|
|
|
|
|
EliminateRecursiveTailCall(CI, RI, OldEntry, TailCallsAreMarkedTail,
|
|
|
|
ArgumentPHIs,
|
2011-01-29 12:46:23 +08:00
|
|
|
CannotTailCallElimCallsMarkedTail);
|
2011-01-29 12:53:35 +08:00
|
|
|
++NumRetDuped;
|
2011-01-29 12:46:23 +08:00
|
|
|
Change = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return Change;
|
|
|
|
}
|
|
|
|
|
2013-07-14 12:42:23 +08:00
|
|
|
bool
|
|
|
|
TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
|
|
|
|
bool &TailCallsAreMarkedTail,
|
|
|
|
SmallVectorImpl<PHINode *> &ArgumentPHIs,
|
|
|
|
bool CannotTailCallElimCallsMarkedTail) {
|
2011-01-29 12:46:23 +08:00
|
|
|
CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
|
|
|
|
if (!CI)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
|
|
|
|
ArgumentPHIs,
|
|
|
|
CannotTailCallElimCallsMarkedTail);
|
|
|
|
}
|