LLVM API Documentation
00001 //===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file transforms calls of the current function (self recursion) followed 00011 // by a return instruction with a branch to the entry of the function, creating 00012 // a loop. This pass also implements the following extensions to the basic 00013 // algorithm: 00014 // 00015 // 1. Trivial instructions between the call and return do not prevent the 00016 // transformation from taking place, though currently the analysis cannot 00017 // support moving any really useful instructions (only dead ones). 00018 // 2. This pass transforms functions that are prevented from being tail 00019 // recursive by an associative expression to use an accumulator variable, 00020 // thus compiling the typical naive factorial or 'fib' implementation into 00021 // efficient code. 00022 // 3. TRE is performed if the function returns void, if the return 00023 // returns the result returned by the call, or if the function returns a 00024 // run-time constant on all exits from the function. It is possible, though 00025 // unlikely, that the return returns something else (like constant 0), and 00026 // can still be TRE'd. It can be TRE'd if ALL OTHER return instructions in 00027 // the function return the exact same value. 00028 // 00029 // There are several improvements that could be made: 00030 // 00031 // 1. If the function has any alloca instructions, these instructions will be 00032 // moved out of the entry block of the function, causing them to be 00033 // evaluated each time through the tail recursion. Safely keeping allocas 00034 // in the entry block requires analysis to proves that the tail-called 00035 // function does not read or write the stack object. 00036 // 2. Tail recursion is only performed if the call immediately preceeds the 00037 // return instruction. It's possible that there could be a jump between 00038 // the call and the return. 00039 // 3. There can be intervening operations between the call and the return that 00040 // prevent the TRE from occurring. For example, there could be GEP's and 00041 // stores to memory that will not be read or written by the call. This 00042 // requires some substantial analysis (such as with DSA) to prove safe to 00043 // move ahead of the call, but doing so could allow many more TREs to be 00044 // performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark. 00045 // 00046 //===----------------------------------------------------------------------===// 00047 00048 #include "llvm/Transforms/Scalar.h" 00049 #include "llvm/DerivedTypes.h" 00050 #include "llvm/Function.h" 00051 #include "llvm/Instructions.h" 00052 #include "llvm/Pass.h" 00053 #include "llvm/Support/CFG.h" 00054 #include "llvm/ADT/Statistic.h" 00055 using namespace llvm; 00056 00057 namespace { 00058 Statistic<> NumEliminated("tailcallelim", "Number of tail calls removed"); 00059 Statistic<> NumAccumAdded("tailcallelim","Number of accumulators introduced"); 00060 00061 struct TailCallElim : public FunctionPass { 00062 virtual bool runOnFunction(Function &F); 00063 00064 private: 00065 bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry, 00066 std::vector<PHINode*> &ArgumentPHIs); 00067 bool CanMoveAboveCall(Instruction *I, CallInst *CI); 00068 Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI); 00069 }; 00070 RegisterOpt<TailCallElim> X("tailcallelim", "Tail Call Elimination"); 00071 } 00072 00073 // Public interface to the TailCallElimination pass 00074 FunctionPass *llvm::createTailCallEliminationPass() { 00075 return new TailCallElim(); 00076 } 00077 00078 00079 bool TailCallElim::runOnFunction(Function &F) { 00080 // If this function is a varargs function, we won't be able to PHI the args 00081 // right, so don't even try to convert it... 00082 if (F.getFunctionType()->isVarArg()) return false; 00083 00084 BasicBlock *OldEntry = 0; 00085 std::vector<PHINode*> ArgumentPHIs; 00086 bool MadeChange = false; 00087 00088 // Loop over the function, looking for any returning blocks... 00089 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 00090 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) 00091 MadeChange |= ProcessReturningBlock(Ret, OldEntry, ArgumentPHIs); 00092 00093 // If we eliminated any tail recursions, it's possible that we inserted some 00094 // silly PHI nodes which just merge an initial value (the incoming operand) 00095 // with themselves. Check to see if we did and clean up our mess if so. This 00096 // occurs when a function passes an argument straight through to its tail 00097 // call. 00098 if (!ArgumentPHIs.empty()) { 00099 unsigned NumIncoming = ArgumentPHIs[0]->getNumIncomingValues(); 00100 for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) { 00101 PHINode *PN = ArgumentPHIs[i]; 00102 Value *V = 0; 00103 for (unsigned op = 0, e = NumIncoming; op != e; ++op) { 00104 Value *Op = PN->getIncomingValue(op); 00105 if (Op != PN) { 00106 if (V == 0) { 00107 V = Op; // First value seen? 00108 } else if (V != Op) { 00109 V = 0; 00110 break; 00111 } 00112 } 00113 } 00114 00115 // If the PHI Node is a dynamic constant, replace it with the value it is. 00116 if (V) { 00117 PN->replaceAllUsesWith(V); 00118 PN->getParent()->getInstList().erase(PN); 00119 } 00120 } 00121 } 00122 00123 return MadeChange; 00124 } 00125 00126 00127 /// CanMoveAboveCall - Return true if it is safe to move the specified 00128 /// instruction from after the call to before the call, assuming that all 00129 /// instructions between the call and this instruction are movable. 00130 /// 00131 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) { 00132 // FIXME: We can move load/store/call/free instructions above the call if the 00133 // call does not mod/ref the memory location being processed. 00134 if (I->mayWriteToMemory() || isa<LoadInst>(I)) 00135 return false; 00136 00137 // Otherwise, if this is a side-effect free instruction, check to make sure 00138 // that it does not use the return value of the call. If it doesn't use the 00139 // return value of the call, it must only use things that are defined before 00140 // the call, or movable instructions between the call and the instruction 00141 // itself. 00142 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 00143 if (I->getOperand(i) == CI) 00144 return false; 00145 return true; 00146 } 00147 00148 // isDynamicConstant - Return true if the specified value is the same when the 00149 // return would exit as it was when the initial iteration of the recursive 00150 // function was executed. 00151 // 00152 // We currently handle static constants and arguments that are not modified as 00153 // part of the recursion. 00154 // 00155 static bool isDynamicConstant(Value *V, CallInst *CI) { 00156 if (isa<Constant>(V)) return true; // Static constants are always dyn consts 00157 00158 // Check to see if this is an immutable argument, if so, the value 00159 // will be available to initialize the accumulator. 00160 if (Argument *Arg = dyn_cast<Argument>(V)) { 00161 // Figure out which argument number this is... 00162 unsigned ArgNo = 0; 00163 Function *F = CI->getParent()->getParent(); 00164 for (Function::aiterator AI = F->abegin(); &*AI != Arg; ++AI) 00165 ++ArgNo; 00166 00167 // If we are passing this argument into call as the corresponding 00168 // argument operand, then the argument is dynamically constant. 00169 // Otherwise, we cannot transform this function safely. 00170 if (CI->getOperand(ArgNo+1) == Arg) 00171 return true; 00172 } 00173 // Not a constant or immutable argument, we can't safely transform. 00174 return false; 00175 } 00176 00177 // getCommonReturnValue - Check to see if the function containing the specified 00178 // return instruction and tail call consistently returns the same 00179 // runtime-constant value at all exit points. If so, return the returned value. 00180 // 00181 static Value *getCommonReturnValue(ReturnInst *TheRI, CallInst *CI) { 00182 Function *F = TheRI->getParent()->getParent(); 00183 Value *ReturnedValue = 0; 00184 00185 for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) 00186 if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator())) 00187 if (RI != TheRI) { 00188 Value *RetOp = RI->getOperand(0); 00189 00190 // We can only perform this transformation if the value returned is 00191 // evaluatable at the start of the initial invocation of the function, 00192 // instead of at the end of the evaluation. 00193 // 00194 if (!isDynamicConstant(RetOp, CI)) 00195 return 0; 00196 00197 if (ReturnedValue && RetOp != ReturnedValue) 00198 return 0; // Cannot transform if differing values are returned. 00199 ReturnedValue = RetOp; 00200 } 00201 return ReturnedValue; 00202 } 00203 00204 /// CanTransformAccumulatorRecursion - If the specified instruction can be 00205 /// transformed using accumulator recursion elimination, return the constant 00206 /// which is the start of the accumulator value. Otherwise return null. 00207 /// 00208 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I, 00209 CallInst *CI) { 00210 if (!I->isAssociative()) return 0; 00211 assert(I->getNumOperands() == 2 && 00212 "Associative operations should have 2 args!"); 00213 00214 // Exactly one operand should be the result of the call instruction... 00215 if (I->getOperand(0) == CI && I->getOperand(1) == CI || 00216 I->getOperand(0) != CI && I->getOperand(1) != CI) 00217 return 0; 00218 00219 // The only user of this instruction we allow is a single return instruction. 00220 if (!I->hasOneUse() || !isa<ReturnInst>(I->use_back())) 00221 return 0; 00222 00223 // Ok, now we have to check all of the other return instructions in this 00224 // function. If they return non-constants or differing values, then we cannot 00225 // transform the function safely. 00226 return getCommonReturnValue(cast<ReturnInst>(I->use_back()), CI); 00227 } 00228 00229 bool TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry, 00230 std::vector<PHINode*> &ArgumentPHIs) { 00231 BasicBlock *BB = Ret->getParent(); 00232 Function *F = BB->getParent(); 00233 00234 if (&BB->front() == Ret) // Make sure there is something before the ret... 00235 return false; 00236 00237 // Scan backwards from the return, checking to see if there is a tail call in 00238 // this block. If so, set CI to it. 00239 CallInst *CI; 00240 BasicBlock::iterator BBI = Ret; 00241 while (1) { 00242 CI = dyn_cast<CallInst>(BBI); 00243 if (CI && CI->getCalledFunction() == F) 00244 break; 00245 00246 if (BBI == BB->begin()) 00247 return false; // Didn't find a potential tail call. 00248 --BBI; 00249 } 00250 00251 // If we are introducing accumulator recursion to eliminate associative 00252 // operations after the call instruction, this variable contains the initial 00253 // value for the accumulator. If this value is set, we actually perform 00254 // accumulator recursion elimination instead of simple tail recursion 00255 // elimination. 00256 Value *AccumulatorRecursionEliminationInitVal = 0; 00257 Instruction *AccumulatorRecursionInstr = 0; 00258 00259 // Ok, we found a potential tail call. We can currently only transform the 00260 // tail call if all of the instructions between the call and the return are 00261 // movable to above the call itself, leaving the call next to the return. 00262 // Check that this is the case now. 00263 for (BBI = CI, ++BBI; &*BBI != Ret; ++BBI) 00264 if (!CanMoveAboveCall(BBI, CI)) { 00265 // If we can't move the instruction above the call, it might be because it 00266 // is an associative operation that could be tranformed using accumulator 00267 // recursion elimination. Check to see if this is the case, and if so, 00268 // remember the initial accumulator value for later. 00269 if ((AccumulatorRecursionEliminationInitVal = 00270 CanTransformAccumulatorRecursion(BBI, CI))) { 00271 // Yes, this is accumulator recursion. Remember which instruction 00272 // accumulates. 00273 AccumulatorRecursionInstr = BBI; 00274 } else { 00275 return false; // Otherwise, we cannot eliminate the tail recursion! 00276 } 00277 } 00278 00279 // We can only transform call/return pairs that either ignore the return value 00280 // of the call and return void, ignore the value of the call and return a 00281 // constant, return the value returned by the tail call, or that are being 00282 // accumulator recursion variable eliminated. 00283 if (Ret->getNumOperands() != 0 && Ret->getReturnValue() != CI && 00284 AccumulatorRecursionEliminationInitVal == 0 && 00285 !getCommonReturnValue(Ret, CI)) 00286 return false; 00287 00288 // OK! We can transform this tail call. If this is the first one found, 00289 // create the new entry block, allowing us to branch back to the old entry. 00290 if (OldEntry == 0) { 00291 OldEntry = &F->getEntryBlock(); 00292 std::string OldName = OldEntry->getName(); OldEntry->setName("tailrecurse"); 00293 BasicBlock *NewEntry = new BasicBlock(OldName, F, OldEntry); 00294 new BranchInst(OldEntry, NewEntry); 00295 00296 // Now that we have created a new block, which jumps to the entry 00297 // block, insert a PHI node for each argument of the function. 00298 // For now, we initialize each PHI to only have the real arguments 00299 // which are passed in. 00300 Instruction *InsertPos = OldEntry->begin(); 00301 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I) { 00302 PHINode *PN = new PHINode(I->getType(), I->getName()+".tr", InsertPos); 00303 I->replaceAllUsesWith(PN); // Everyone use the PHI node now! 00304 PN->addIncoming(I, NewEntry); 00305 ArgumentPHIs.push_back(PN); 00306 } 00307 } 00308 00309 // Ok, now that we know we have a pseudo-entry block WITH all of the 00310 // required PHI nodes, add entries into the PHI node for the actual 00311 // parameters passed into the tail-recursive call. 00312 for (unsigned i = 0, e = CI->getNumOperands()-1; i != e; ++i) 00313 ArgumentPHIs[i]->addIncoming(CI->getOperand(i+1), BB); 00314 00315 // If we are introducing an accumulator variable to eliminate the recursion, 00316 // do so now. Note that we _know_ that no subsequent tail recursion 00317 // eliminations will happen on this function because of the way the 00318 // accumulator recursion predicate is set up. 00319 // 00320 if (AccumulatorRecursionEliminationInitVal) { 00321 Instruction *AccRecInstr = AccumulatorRecursionInstr; 00322 // Start by inserting a new PHI node for the accumulator. 00323 PHINode *AccPN = new PHINode(AccRecInstr->getType(), "accumulator.tr", 00324 OldEntry->begin()); 00325 00326 // Loop over all of the predecessors of the tail recursion block. For the 00327 // real entry into the function we seed the PHI with the initial value, 00328 // computed earlier. For any other existing branches to this block (due to 00329 // other tail recursions eliminated) the accumulator is not modified. 00330 // Because we haven't added the branch in the current block to OldEntry yet, 00331 // it will not show up as a predecessor. 00332 for (pred_iterator PI = pred_begin(OldEntry), PE = pred_end(OldEntry); 00333 PI != PE; ++PI) { 00334 if (*PI == &F->getEntryBlock()) 00335 AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, *PI); 00336 else 00337 AccPN->addIncoming(AccPN, *PI); 00338 } 00339 00340 // Add an incoming argument for the current block, which is computed by our 00341 // associative accumulator instruction. 00342 AccPN->addIncoming(AccRecInstr, BB); 00343 00344 // Next, rewrite the accumulator recursion instruction so that it does not 00345 // use the result of the call anymore, instead, use the PHI node we just 00346 // inserted. 00347 AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN); 00348 00349 // Finally, rewrite any return instructions in the program to return the PHI 00350 // node instead of the "initval" that they do currently. This loop will 00351 // actually rewrite the return value we are destroying, but that's ok. 00352 for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) 00353 if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator())) 00354 RI->setOperand(0, AccPN); 00355 ++NumAccumAdded; 00356 } 00357 00358 // Now that all of the PHI nodes are in place, remove the call and 00359 // ret instructions, replacing them with an unconditional branch. 00360 new BranchInst(OldEntry, Ret); 00361 BB->getInstList().erase(Ret); // Remove return. 00362 BB->getInstList().erase(CI); // Remove call. 00363 ++NumEliminated; 00364 return true; 00365 }