1 //===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file transforms calls of the current function (self recursion) followed 11 // by a return instruction with a branch to the entry of the function, creating 12 // a loop. This pass also implements the following extensions to the basic 13 // algorithm: 14 // 15 // 1. Trivial instructions between the call and return do not prevent the 16 // transformation from taking place, though currently the analysis cannot 17 // support moving any really useful instructions (only dead ones). 18 // 2. This pass transforms functions that are prevented from being tail 19 // recursive by an associative and commutative expression to use an 20 // accumulator variable, thus compiling the typical naive factorial or 21 // 'fib' implementation into efficient code. 22 // 3. TRE is performed if the function returns void, if the return 23 // returns the result returned by the call, or if the function returns a 24 // run-time constant on all exits from the function. It is possible, though 25 // unlikely, that the return returns something else (like constant 0), and 26 // can still be TRE'd. It can be TRE'd if ALL OTHER return instructions in 27 // the function return the exact same value. 28 // 4. If it can prove that callees do not access their caller stack frame, 29 // they are marked as eligible for tail call elimination (by the code 30 // generator). 31 // 32 // There are several improvements that could be made: 33 // 34 // 1. If the function has any alloca instructions, these instructions will be 35 // moved out of the entry block of the function, causing them to be 36 // evaluated each time through the tail recursion. Safely keeping allocas 37 // in the entry block requires analysis to proves that the tail-called 38 // function does not read or write the stack object. 39 // 2. Tail recursion is only performed if the call immediately precedes the 40 // return instruction. It's possible that there could be a jump between 41 // the call and the return. 42 // 3. There can be intervening operations between the call and the return that 43 // prevent the TRE from occurring. For example, there could be GEP's and 44 // stores to memory that will not be read or written by the call. This 45 // requires some substantial analysis (such as with DSA) to prove safe to 46 // move ahead of the call, but doing so could allow many more TREs to be 47 // performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark. 48 // 4. The algorithm we use to detect if callees access their caller stack 49 // frames is very primitive. 50 // 51 //===----------------------------------------------------------------------===// 52 53 #include "llvm/Transforms/Scalar.h" 54 #include "llvm/ADT/STLExtras.h" 55 #include "llvm/ADT/SmallPtrSet.h" 56 #include "llvm/ADT/Statistic.h" 57 #include "llvm/Analysis/CaptureTracking.h" 58 #include "llvm/Analysis/InlineCost.h" 59 #include "llvm/Analysis/InstructionSimplify.h" 60 #include "llvm/Analysis/Loads.h" 61 #include "llvm/Analysis/TargetTransformInfo.h" 62 #include "llvm/IR/CFG.h" 63 #include "llvm/IR/CallSite.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DerivedTypes.h" 66 #include "llvm/IR/Function.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Module.h" 70 #include "llvm/IR/ValueHandle.h" 71 #include "llvm/Pass.h" 72 #include "llvm/Support/Debug.h" 73 #include "llvm/Support/raw_ostream.h" 74 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 75 #include "llvm/Transforms/Utils/Local.h" 76 using namespace llvm; 77 78 #define DEBUG_TYPE "tailcallelim" 79 80 STATISTIC(NumEliminated, "Number of tail calls removed"); 81 STATISTIC(NumRetDuped, "Number of return duplicated"); 82 STATISTIC(NumAccumAdded, "Number of accumulators introduced"); 83 84 namespace { 85 struct TailCallElim : public FunctionPass { 86 const TargetTransformInfo *TTI; 87 88 static char ID; // Pass identification, replacement for typeid 89 TailCallElim() : FunctionPass(ID) { 90 initializeTailCallElimPass(*PassRegistry::getPassRegistry()); 91 } 92 93 void getAnalysisUsage(AnalysisUsage &AU) const override; 94 95 bool runOnFunction(Function &F) override; 96 97 private: 98 CallInst *FindTRECandidate(Instruction *I, 99 bool CannotTailCallElimCallsMarkedTail); 100 bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret, 101 BasicBlock *&OldEntry, 102 bool &TailCallsAreMarkedTail, 103 SmallVectorImpl<PHINode *> &ArgumentPHIs, 104 bool CannotTailCallElimCallsMarkedTail); 105 bool FoldReturnAndProcessPred(BasicBlock *BB, 106 ReturnInst *Ret, BasicBlock *&OldEntry, 107 bool &TailCallsAreMarkedTail, 108 SmallVectorImpl<PHINode *> &ArgumentPHIs, 109 bool CannotTailCallElimCallsMarkedTail); 110 bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry, 111 bool &TailCallsAreMarkedTail, 112 SmallVectorImpl<PHINode *> &ArgumentPHIs, 113 bool CannotTailCallElimCallsMarkedTail); 114 bool CanMoveAboveCall(Instruction *I, CallInst *CI); 115 Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI); 116 }; 117 } 118 119 char TailCallElim::ID = 0; 120 INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim", 121 "Tail Call Elimination", false, false) 122 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 123 INITIALIZE_PASS_END(TailCallElim, "tailcallelim", 124 "Tail Call Elimination", false, false) 125 126 // Public interface to the TailCallElimination pass 127 FunctionPass *llvm::createTailCallEliminationPass() { 128 return new TailCallElim(); 129 } 130 131 void TailCallElim::getAnalysisUsage(AnalysisUsage &AU) const { 132 AU.addRequired<TargetTransformInfo>(); 133 } 134 135 /// CanTRE - Scan the specified basic block for alloca instructions. 136 /// If it contains any that are variable-sized or not in the entry block, 137 /// returns false. 138 static bool CanTRE(AllocaInst *AI) { 139 // Because of PR962, we don't TRE allocas outside the entry block. 140 141 // If this alloca is in the body of the function, or if it is a variable 142 // sized allocation, we cannot tail call eliminate calls marked 'tail' 143 // with this mechanism. 144 BasicBlock *BB = AI->getParent(); 145 return BB == &BB->getParent()->getEntryBlock() && 146 isa<ConstantInt>(AI->getArraySize()); 147 } 148 149 namespace { 150 struct AllocaCaptureTracker : public CaptureTracker { 151 AllocaCaptureTracker() : Captured(false) {} 152 153 void tooManyUses() override { Captured = true; } 154 155 bool shouldExplore(const Use *U) override { 156 Value *V = U->getUser(); 157 if (isa<CallInst>(V) || isa<InvokeInst>(V)) 158 UsesAlloca.insert(V); 159 return true; 160 } 161 162 bool captured(const Use *U) override { 163 if (isa<ReturnInst>(U->getUser())) 164 return false; 165 Captured = true; 166 return true; 167 } 168 169 bool Captured; 170 SmallPtrSet<const Value *, 16> UsesAlloca; 171 }; 172 } // end anonymous namespace 173 174 bool TailCallElim::runOnFunction(Function &F) { 175 if (skipOptnoneFunction(F)) 176 return false; 177 178 // If this function is a varargs function, we won't be able to PHI the args 179 // right, so don't even try to convert it... 180 if (F.getFunctionType()->isVarArg()) return false; 181 182 TTI = &getAnalysis<TargetTransformInfo>(); 183 BasicBlock *OldEntry = nullptr; 184 bool TailCallsAreMarkedTail = false; 185 SmallVector<PHINode*, 8> ArgumentPHIs; 186 bool MadeChange = false; 187 188 // CanTRETailMarkedCall - If false, we cannot perform TRE on tail calls 189 // marked with the 'tail' attribute, because doing so would cause the stack 190 // size to increase (real TRE would deallocate variable sized allocas, TRE 191 // doesn't). 192 bool CanTRETailMarkedCall = true; 193 194 // Find calls that can be marked tail. 195 AllocaCaptureTracker ACT; 196 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB) { 197 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 198 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { 199 CanTRETailMarkedCall &= CanTRE(AI); 200 PointerMayBeCaptured(AI, &ACT); 201 // If any allocas are captured, exit. 202 if (ACT.Captured) 203 return false; 204 } 205 } 206 } 207 208 // If any byval or inalloca args are captured, exit. They are also allocated 209 // in our stack frame. 210 for (Argument &Arg : F.args()) { 211 if (Arg.hasByValOrInAllocaAttr()) 212 PointerMayBeCaptured(&Arg, &ACT); 213 if (ACT.Captured) 214 return false; 215 } 216 217 // Second pass, change any tail recursive calls to loops. 218 // 219 // FIXME: The code generator produces really bad code when an 'escaping 220 // alloca' is changed from being a static alloca to being a dynamic alloca. 221 // Until this is resolved, disable this transformation if that would ever 222 // happen. This bug is PR962. 223 if (ACT.UsesAlloca.empty()) { 224 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 225 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) { 226 bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail, 227 ArgumentPHIs, !CanTRETailMarkedCall); 228 if (!Change && BB->getFirstNonPHIOrDbg() == Ret) 229 Change = FoldReturnAndProcessPred(BB, Ret, OldEntry, 230 TailCallsAreMarkedTail, ArgumentPHIs, 231 !CanTRETailMarkedCall); 232 MadeChange |= Change; 233 } 234 } 235 } 236 237 // If we eliminated any tail recursions, it's possible that we inserted some 238 // silly PHI nodes which just merge an initial value (the incoming operand) 239 // with themselves. Check to see if we did and clean up our mess if so. This 240 // occurs when a function passes an argument straight through to its tail 241 // call. 242 if (!ArgumentPHIs.empty()) { 243 for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) { 244 PHINode *PN = ArgumentPHIs[i]; 245 246 // If the PHI Node is a dynamic constant, replace it with the value it is. 247 if (Value *PNV = SimplifyInstruction(PN)) { 248 PN->replaceAllUsesWith(PNV); 249 PN->eraseFromParent(); 250 } 251 } 252 } 253 254 // At this point, we know that the function does not have any captured 255 // allocas. If additionally the function does not call setjmp, mark all calls 256 // in the function that do not access stack memory with the tail keyword. This 257 // implies ensuring that there does not exist any path from a call that takes 258 // in an alloca but does not capture it and the call which we wish to mark 259 // with "tail". 260 if (!F.callsFunctionThatReturnsTwice()) { 261 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 262 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 263 if (CallInst *CI = dyn_cast<CallInst>(I)) { 264 if (!ACT.UsesAlloca.count(CI)) { 265 CI->setTailCall(); 266 MadeChange = true; 267 } 268 } 269 } 270 } 271 } 272 273 return MadeChange; 274 } 275 276 277 /// CanMoveAboveCall - Return true if it is safe to move the specified 278 /// instruction from after the call to before the call, assuming that all 279 /// instructions between the call and this instruction are movable. 280 /// 281 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) { 282 // FIXME: We can move load/store/call/free instructions above the call if the 283 // call does not mod/ref the memory location being processed. 284 if (I->mayHaveSideEffects()) // This also handles volatile loads. 285 return false; 286 287 if (LoadInst *L = dyn_cast<LoadInst>(I)) { 288 // Loads may always be moved above calls without side effects. 289 if (CI->mayHaveSideEffects()) { 290 // Non-volatile loads may be moved above a call with side effects if it 291 // does not write to memory and the load provably won't trap. 292 // FIXME: Writes to memory only matter if they may alias the pointer 293 // being loaded from. 294 if (CI->mayWriteToMemory() || 295 !isSafeToLoadUnconditionally(L->getPointerOperand(), L, 296 L->getAlignment())) 297 return false; 298 } 299 } 300 301 // Otherwise, if this is a side-effect free instruction, check to make sure 302 // that it does not use the return value of the call. If it doesn't use the 303 // return value of the call, it must only use things that are defined before 304 // the call, or movable instructions between the call and the instruction 305 // itself. 306 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 307 if (I->getOperand(i) == CI) 308 return false; 309 return true; 310 } 311 312 // isDynamicConstant - Return true if the specified value is the same when the 313 // return would exit as it was when the initial iteration of the recursive 314 // function was executed. 315 // 316 // We currently handle static constants and arguments that are not modified as 317 // part of the recursion. 318 // 319 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) { 320 if (isa<Constant>(V)) return true; // Static constants are always dyn consts 321 322 // Check to see if this is an immutable argument, if so, the value 323 // will be available to initialize the accumulator. 324 if (Argument *Arg = dyn_cast<Argument>(V)) { 325 // Figure out which argument number this is... 326 unsigned ArgNo = 0; 327 Function *F = CI->getParent()->getParent(); 328 for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI) 329 ++ArgNo; 330 331 // If we are passing this argument into call as the corresponding 332 // argument operand, then the argument is dynamically constant. 333 // Otherwise, we cannot transform this function safely. 334 if (CI->getArgOperand(ArgNo) == Arg) 335 return true; 336 } 337 338 // Switch cases are always constant integers. If the value is being switched 339 // on and the return is only reachable from one of its cases, it's 340 // effectively constant. 341 if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor()) 342 if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator())) 343 if (SI->getCondition() == V) 344 return SI->getDefaultDest() != RI->getParent(); 345 346 // Not a constant or immutable argument, we can't safely transform. 347 return false; 348 } 349 350 // getCommonReturnValue - Check to see if the function containing the specified 351 // tail call consistently returns the same runtime-constant value at all exit 352 // points except for IgnoreRI. If so, return the returned value. 353 // 354 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) { 355 Function *F = CI->getParent()->getParent(); 356 Value *ReturnedValue = nullptr; 357 358 for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) { 359 ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()); 360 if (RI == nullptr || RI == IgnoreRI) continue; 361 362 // We can only perform this transformation if the value returned is 363 // evaluatable at the start of the initial invocation of the function, 364 // instead of at the end of the evaluation. 365 // 366 Value *RetOp = RI->getOperand(0); 367 if (!isDynamicConstant(RetOp, CI, RI)) 368 return nullptr; 369 370 if (ReturnedValue && RetOp != ReturnedValue) 371 return nullptr; // Cannot transform if differing values are returned. 372 ReturnedValue = RetOp; 373 } 374 return ReturnedValue; 375 } 376 377 /// CanTransformAccumulatorRecursion - If the specified instruction can be 378 /// transformed using accumulator recursion elimination, return the constant 379 /// which is the start of the accumulator value. Otherwise return null. 380 /// 381 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I, 382 CallInst *CI) { 383 if (!I->isAssociative() || !I->isCommutative()) return nullptr; 384 assert(I->getNumOperands() == 2 && 385 "Associative/commutative operations should have 2 args!"); 386 387 // Exactly one operand should be the result of the call instruction. 388 if ((I->getOperand(0) == CI && I->getOperand(1) == CI) || 389 (I->getOperand(0) != CI && I->getOperand(1) != CI)) 390 return nullptr; 391 392 // The only user of this instruction we allow is a single return instruction. 393 if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back())) 394 return nullptr; 395 396 // Ok, now we have to check all of the other return instructions in this 397 // function. If they return non-constants or differing values, then we cannot 398 // transform the function safely. 399 return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI); 400 } 401 402 static Instruction *FirstNonDbg(BasicBlock::iterator I) { 403 while (isa<DbgInfoIntrinsic>(I)) 404 ++I; 405 return &*I; 406 } 407 408 CallInst* 409 TailCallElim::FindTRECandidate(Instruction *TI, 410 bool CannotTailCallElimCallsMarkedTail) { 411 BasicBlock *BB = TI->getParent(); 412 Function *F = BB->getParent(); 413 414 if (&BB->front() == TI) // Make sure there is something before the terminator. 415 return nullptr; 416 417 // Scan backwards from the return, checking to see if there is a tail call in 418 // this block. If so, set CI to it. 419 CallInst *CI = nullptr; 420 BasicBlock::iterator BBI = TI; 421 while (true) { 422 CI = dyn_cast<CallInst>(BBI); 423 if (CI && CI->getCalledFunction() == F) 424 break; 425 426 if (BBI == BB->begin()) 427 return nullptr; // Didn't find a potential tail call. 428 --BBI; 429 } 430 431 // If this call is marked as a tail call, and if there are dynamic allocas in 432 // the function, we cannot perform this optimization. 433 if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail) 434 return nullptr; 435 436 // As a special case, detect code like this: 437 // double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call 438 // and disable this xform in this case, because the code generator will 439 // lower the call to fabs into inline code. 440 if (BB == &F->getEntryBlock() && 441 FirstNonDbg(BB->front()) == CI && 442 FirstNonDbg(std::next(BB->begin())) == TI && 443 CI->getCalledFunction() && 444 !TTI->isLoweredToCall(CI->getCalledFunction())) { 445 // A single-block function with just a call and a return. Check that 446 // the arguments match. 447 CallSite::arg_iterator I = CallSite(CI).arg_begin(), 448 E = CallSite(CI).arg_end(); 449 Function::arg_iterator FI = F->arg_begin(), 450 FE = F->arg_end(); 451 for (; I != E && FI != FE; ++I, ++FI) 452 if (*I != &*FI) break; 453 if (I == E && FI == FE) 454 return nullptr; 455 } 456 457 return CI; 458 } 459 460 bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret, 461 BasicBlock *&OldEntry, 462 bool &TailCallsAreMarkedTail, 463 SmallVectorImpl<PHINode *> &ArgumentPHIs, 464 bool CannotTailCallElimCallsMarkedTail) { 465 // If we are introducing accumulator recursion to eliminate operations after 466 // the call instruction that are both associative and commutative, the initial 467 // value for the accumulator is placed in this variable. If this value is set 468 // then we actually perform accumulator recursion elimination instead of 469 // simple tail recursion elimination. If the operation is an LLVM instruction 470 // (eg: "add") then it is recorded in AccumulatorRecursionInstr. If not, then 471 // we are handling the case when the return instruction returns a constant C 472 // which is different to the constant returned by other return instructions 473 // (which is recorded in AccumulatorRecursionEliminationInitVal). This is a 474 // special case of accumulator recursion, the operation being "return C". 475 Value *AccumulatorRecursionEliminationInitVal = nullptr; 476 Instruction *AccumulatorRecursionInstr = nullptr; 477 478 // Ok, we found a potential tail call. We can currently only transform the 479 // tail call if all of the instructions between the call and the return are 480 // movable to above the call itself, leaving the call next to the return. 481 // Check that this is the case now. 482 BasicBlock::iterator BBI = CI; 483 for (++BBI; &*BBI != Ret; ++BBI) { 484 if (CanMoveAboveCall(BBI, CI)) continue; 485 486 // If we can't move the instruction above the call, it might be because it 487 // is an associative and commutative operation that could be transformed 488 // using accumulator recursion elimination. Check to see if this is the 489 // case, and if so, remember the initial accumulator value for later. 490 if ((AccumulatorRecursionEliminationInitVal = 491 CanTransformAccumulatorRecursion(BBI, CI))) { 492 // Yes, this is accumulator recursion. Remember which instruction 493 // accumulates. 494 AccumulatorRecursionInstr = BBI; 495 } else { 496 return false; // Otherwise, we cannot eliminate the tail recursion! 497 } 498 } 499 500 // We can only transform call/return pairs that either ignore the return value 501 // of the call and return void, ignore the value of the call and return a 502 // constant, return the value returned by the tail call, or that are being 503 // accumulator recursion variable eliminated. 504 if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI && 505 !isa<UndefValue>(Ret->getReturnValue()) && 506 AccumulatorRecursionEliminationInitVal == nullptr && 507 !getCommonReturnValue(nullptr, CI)) { 508 // One case remains that we are able to handle: the current return 509 // instruction returns a constant, and all other return instructions 510 // return a different constant. 511 if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret)) 512 return false; // Current return instruction does not return a constant. 513 // Check that all other return instructions return a common constant. If 514 // so, record it in AccumulatorRecursionEliminationInitVal. 515 AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI); 516 if (!AccumulatorRecursionEliminationInitVal) 517 return false; 518 } 519 520 BasicBlock *BB = Ret->getParent(); 521 Function *F = BB->getParent(); 522 523 // OK! We can transform this tail call. If this is the first one found, 524 // create the new entry block, allowing us to branch back to the old entry. 525 if (!OldEntry) { 526 OldEntry = &F->getEntryBlock(); 527 BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry); 528 NewEntry->takeName(OldEntry); 529 OldEntry->setName("tailrecurse"); 530 BranchInst::Create(OldEntry, NewEntry); 531 532 // If this tail call is marked 'tail' and if there are any allocas in the 533 // entry block, move them up to the new entry block. 534 TailCallsAreMarkedTail = CI->isTailCall(); 535 if (TailCallsAreMarkedTail) 536 // Move all fixed sized allocas from OldEntry to NewEntry. 537 for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(), 538 NEBI = NewEntry->begin(); OEBI != E; ) 539 if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++)) 540 if (isa<ConstantInt>(AI->getArraySize())) 541 AI->moveBefore(NEBI); 542 543 // Now that we have created a new block, which jumps to the entry 544 // block, insert a PHI node for each argument of the function. 545 // For now, we initialize each PHI to only have the real arguments 546 // which are passed in. 547 Instruction *InsertPos = OldEntry->begin(); 548 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 549 I != E; ++I) { 550 PHINode *PN = PHINode::Create(I->getType(), 2, 551 I->getName() + ".tr", InsertPos); 552 I->replaceAllUsesWith(PN); // Everyone use the PHI node now! 553 PN->addIncoming(I, NewEntry); 554 ArgumentPHIs.push_back(PN); 555 } 556 } 557 558 // If this function has self recursive calls in the tail position where some 559 // are marked tail and some are not, only transform one flavor or another. We 560 // have to choose whether we move allocas in the entry block to the new entry 561 // block or not, so we can't make a good choice for both. NOTE: We could do 562 // slightly better here in the case that the function has no entry block 563 // allocas. 564 if (TailCallsAreMarkedTail && !CI->isTailCall()) 565 return false; 566 567 // Ok, now that we know we have a pseudo-entry block WITH all of the 568 // required PHI nodes, add entries into the PHI node for the actual 569 // parameters passed into the tail-recursive call. 570 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) 571 ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB); 572 573 // If we are introducing an accumulator variable to eliminate the recursion, 574 // do so now. Note that we _know_ that no subsequent tail recursion 575 // eliminations will happen on this function because of the way the 576 // accumulator recursion predicate is set up. 577 // 578 if (AccumulatorRecursionEliminationInitVal) { 579 Instruction *AccRecInstr = AccumulatorRecursionInstr; 580 // Start by inserting a new PHI node for the accumulator. 581 pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry); 582 PHINode *AccPN = 583 PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(), 584 std::distance(PB, PE) + 1, 585 "accumulator.tr", OldEntry->begin()); 586 587 // Loop over all of the predecessors of the tail recursion block. For the 588 // real entry into the function we seed the PHI with the initial value, 589 // computed earlier. For any other existing branches to this block (due to 590 // other tail recursions eliminated) the accumulator is not modified. 591 // Because we haven't added the branch in the current block to OldEntry yet, 592 // it will not show up as a predecessor. 593 for (pred_iterator PI = PB; PI != PE; ++PI) { 594 BasicBlock *P = *PI; 595 if (P == &F->getEntryBlock()) 596 AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P); 597 else 598 AccPN->addIncoming(AccPN, P); 599 } 600 601 if (AccRecInstr) { 602 // Add an incoming argument for the current block, which is computed by 603 // our associative and commutative accumulator instruction. 604 AccPN->addIncoming(AccRecInstr, BB); 605 606 // Next, rewrite the accumulator recursion instruction so that it does not 607 // use the result of the call anymore, instead, use the PHI node we just 608 // inserted. 609 AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN); 610 } else { 611 // Add an incoming argument for the current block, which is just the 612 // constant returned by the current return instruction. 613 AccPN->addIncoming(Ret->getReturnValue(), BB); 614 } 615 616 // Finally, rewrite any return instructions in the program to return the PHI 617 // node instead of the "initval" that they do currently. This loop will 618 // actually rewrite the return value we are destroying, but that's ok. 619 for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) 620 if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator())) 621 RI->setOperand(0, AccPN); 622 ++NumAccumAdded; 623 } 624 625 // Now that all of the PHI nodes are in place, remove the call and 626 // ret instructions, replacing them with an unconditional branch. 627 BranchInst *NewBI = BranchInst::Create(OldEntry, Ret); 628 NewBI->setDebugLoc(CI->getDebugLoc()); 629 630 BB->getInstList().erase(Ret); // Remove return. 631 BB->getInstList().erase(CI); // Remove call. 632 ++NumEliminated; 633 return true; 634 } 635 636 bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB, 637 ReturnInst *Ret, BasicBlock *&OldEntry, 638 bool &TailCallsAreMarkedTail, 639 SmallVectorImpl<PHINode *> &ArgumentPHIs, 640 bool CannotTailCallElimCallsMarkedTail) { 641 bool Change = false; 642 643 // If the return block contains nothing but the return and PHI's, 644 // there might be an opportunity to duplicate the return in its 645 // predecessors and perform TRC there. Look for predecessors that end 646 // in unconditional branch and recursive call(s). 647 SmallVector<BranchInst*, 8> UncondBranchPreds; 648 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 649 BasicBlock *Pred = *PI; 650 TerminatorInst *PTI = Pred->getTerminator(); 651 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) 652 if (BI->isUnconditional()) 653 UncondBranchPreds.push_back(BI); 654 } 655 656 while (!UncondBranchPreds.empty()) { 657 BranchInst *BI = UncondBranchPreds.pop_back_val(); 658 BasicBlock *Pred = BI->getParent(); 659 if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){ 660 DEBUG(dbgs() << "FOLDING: " << *BB 661 << "INTO UNCOND BRANCH PRED: " << *Pred); 662 EliminateRecursiveTailCall(CI, FoldReturnIntoUncondBranch(Ret, BB, Pred), 663 OldEntry, TailCallsAreMarkedTail, ArgumentPHIs, 664 CannotTailCallElimCallsMarkedTail); 665 ++NumRetDuped; 666 Change = true; 667 } 668 } 669 670 return Change; 671 } 672 673 bool 674 TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry, 675 bool &TailCallsAreMarkedTail, 676 SmallVectorImpl<PHINode *> &ArgumentPHIs, 677 bool CannotTailCallElimCallsMarkedTail) { 678 CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail); 679 if (!CI) 680 return false; 681 682 return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail, 683 ArgumentPHIs, 684 CannotTailCallElimCallsMarkedTail); 685 } 686