LLVM API Documentation
00001 //===- CloneFunction.cpp - Clone a function into another function ---------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the CloneFunctionInto interface, which is used as the 00011 // low-level function cloner. This is used by the CloneFunction and function 00012 // inliner to do the dirty work of copying the body of a function around. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "llvm/Transforms/Utils/Cloning.h" 00017 #include "llvm/ADT/SmallVector.h" 00018 #include "llvm/Analysis/ConstantFolding.h" 00019 #include "llvm/Analysis/InstructionSimplify.h" 00020 #include "llvm/DebugInfo.h" 00021 #include "llvm/IR/Constants.h" 00022 #include "llvm/IR/DerivedTypes.h" 00023 #include "llvm/IR/Function.h" 00024 #include "llvm/IR/GlobalVariable.h" 00025 #include "llvm/IR/Instructions.h" 00026 #include "llvm/IR/IntrinsicInst.h" 00027 #include "llvm/IR/LLVMContext.h" 00028 #include "llvm/IR/Metadata.h" 00029 #include "llvm/Support/CFG.h" 00030 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00031 #include "llvm/Transforms/Utils/Local.h" 00032 #include "llvm/Transforms/Utils/ValueMapper.h" 00033 #include <map> 00034 using namespace llvm; 00035 00036 // CloneBasicBlock - See comments in Cloning.h 00037 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, 00038 ValueToValueMapTy &VMap, 00039 const Twine &NameSuffix, Function *F, 00040 ClonedCodeInfo *CodeInfo) { 00041 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F); 00042 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 00043 00044 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 00045 00046 // Loop over all instructions, and copy them over. 00047 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); 00048 II != IE; ++II) { 00049 Instruction *NewInst = II->clone(); 00050 if (II->hasName()) 00051 NewInst->setName(II->getName()+NameSuffix); 00052 NewBB->getInstList().push_back(NewInst); 00053 VMap[II] = NewInst; // Add instruction map to value. 00054 00055 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 00056 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 00057 if (isa<ConstantInt>(AI->getArraySize())) 00058 hasStaticAllocas = true; 00059 else 00060 hasDynamicAllocas = true; 00061 } 00062 } 00063 00064 if (CodeInfo) { 00065 CodeInfo->ContainsCalls |= hasCalls; 00066 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 00067 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 00068 BB != &BB->getParent()->getEntryBlock(); 00069 } 00070 return NewBB; 00071 } 00072 00073 // Clone OldFunc into NewFunc, transforming the old arguments into references to 00074 // VMap values. 00075 // 00076 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc, 00077 ValueToValueMapTy &VMap, 00078 bool ModuleLevelChanges, 00079 SmallVectorImpl<ReturnInst*> &Returns, 00080 const char *NameSuffix, ClonedCodeInfo *CodeInfo, 00081 ValueMapTypeRemapper *TypeMapper) { 00082 assert(NameSuffix && "NameSuffix cannot be null!"); 00083 00084 #ifndef NDEBUG 00085 for (Function::const_arg_iterator I = OldFunc->arg_begin(), 00086 E = OldFunc->arg_end(); I != E; ++I) 00087 assert(VMap.count(I) && "No mapping from source argument specified!"); 00088 #endif 00089 00090 AttributeSet OldAttrs = OldFunc->getAttributes(); 00091 // Clone any argument attributes that are present in the VMap. 00092 for (Function::const_arg_iterator I = OldFunc->arg_begin(), 00093 E = OldFunc->arg_end(); 00094 I != E; ++I) 00095 if (Argument *Anew = dyn_cast<Argument>(VMap[I])) { 00096 AttributeSet attrs = 00097 OldAttrs.getParamAttributes(I->getArgNo() + 1); 00098 if (attrs.getNumSlots() > 0) 00099 Anew->addAttr(attrs); 00100 } 00101 00102 NewFunc->setAttributes(NewFunc->getAttributes() 00103 .addAttributes(NewFunc->getContext(), 00104 AttributeSet::ReturnIndex, 00105 OldAttrs.getRetAttributes())); 00106 NewFunc->setAttributes(NewFunc->getAttributes() 00107 .addAttributes(NewFunc->getContext(), 00108 AttributeSet::FunctionIndex, 00109 OldAttrs.getFnAttributes())); 00110 00111 // Loop over all of the basic blocks in the function, cloning them as 00112 // appropriate. Note that we save BE this way in order to handle cloning of 00113 // recursive functions into themselves. 00114 // 00115 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end(); 00116 BI != BE; ++BI) { 00117 const BasicBlock &BB = *BI; 00118 00119 // Create a new basic block and copy instructions into it! 00120 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo); 00121 00122 // Add basic block mapping. 00123 VMap[&BB] = CBB; 00124 00125 // It is only legal to clone a function if a block address within that 00126 // function is never referenced outside of the function. Given that, we 00127 // want to map block addresses from the old function to block addresses in 00128 // the clone. (This is different from the generic ValueMapper 00129 // implementation, which generates an invalid blockaddress when 00130 // cloning a function.) 00131 if (BB.hasAddressTaken()) { 00132 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 00133 const_cast<BasicBlock*>(&BB)); 00134 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB); 00135 } 00136 00137 // Note return instructions for the caller. 00138 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator())) 00139 Returns.push_back(RI); 00140 } 00141 00142 // Loop over all of the instructions in the function, fixing up operand 00143 // references as we go. This uses VMap to do all the hard work. 00144 for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]), 00145 BE = NewFunc->end(); BB != BE; ++BB) 00146 // Loop over all instructions, fixing each one as we find it... 00147 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) 00148 RemapInstruction(II, VMap, 00149 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 00150 TypeMapper); 00151 } 00152 00153 /// CloneFunction - Return a copy of the specified function, but without 00154 /// embedding the function into another module. Also, any references specified 00155 /// in the VMap are changed to refer to their mapped value instead of the 00156 /// original one. If any of the arguments to the function are in the VMap, 00157 /// the arguments are deleted from the resultant function. The VMap is 00158 /// updated to include mappings from all of the instructions and basicblocks in 00159 /// the function from their old to new values. 00160 /// 00161 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap, 00162 bool ModuleLevelChanges, 00163 ClonedCodeInfo *CodeInfo) { 00164 std::vector<Type*> ArgTypes; 00165 00166 // The user might be deleting arguments to the function by specifying them in 00167 // the VMap. If so, we need to not add the arguments to the arg ty vector 00168 // 00169 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 00170 I != E; ++I) 00171 if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet? 00172 ArgTypes.push_back(I->getType()); 00173 00174 // Create a new function type... 00175 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(), 00176 ArgTypes, F->getFunctionType()->isVarArg()); 00177 00178 // Create the new function... 00179 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName()); 00180 00181 // Loop over the arguments, copying the names of the mapped arguments over... 00182 Function::arg_iterator DestI = NewF->arg_begin(); 00183 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 00184 I != E; ++I) 00185 if (VMap.count(I) == 0) { // Is this argument preserved? 00186 DestI->setName(I->getName()); // Copy the name over... 00187 VMap[I] = DestI++; // Add mapping to VMap 00188 } 00189 00190 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned. 00191 CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo); 00192 return NewF; 00193 } 00194 00195 00196 00197 namespace { 00198 /// PruningFunctionCloner - This class is a private class used to implement 00199 /// the CloneAndPruneFunctionInto method. 00200 struct PruningFunctionCloner { 00201 Function *NewFunc; 00202 const Function *OldFunc; 00203 ValueToValueMapTy &VMap; 00204 bool ModuleLevelChanges; 00205 const char *NameSuffix; 00206 ClonedCodeInfo *CodeInfo; 00207 const DataLayout *TD; 00208 public: 00209 PruningFunctionCloner(Function *newFunc, const Function *oldFunc, 00210 ValueToValueMapTy &valueMap, 00211 bool moduleLevelChanges, 00212 const char *nameSuffix, 00213 ClonedCodeInfo *codeInfo, 00214 const DataLayout *td) 00215 : NewFunc(newFunc), OldFunc(oldFunc), 00216 VMap(valueMap), ModuleLevelChanges(moduleLevelChanges), 00217 NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) { 00218 } 00219 00220 /// CloneBlock - The specified block is found to be reachable, clone it and 00221 /// anything that it can reach. 00222 void CloneBlock(const BasicBlock *BB, 00223 std::vector<const BasicBlock*> &ToClone); 00224 }; 00225 } 00226 00227 /// CloneBlock - The specified block is found to be reachable, clone it and 00228 /// anything that it can reach. 00229 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB, 00230 std::vector<const BasicBlock*> &ToClone){ 00231 WeakVH &BBEntry = VMap[BB]; 00232 00233 // Have we already cloned this block? 00234 if (BBEntry) return; 00235 00236 // Nope, clone it now. 00237 BasicBlock *NewBB; 00238 BBEntry = NewBB = BasicBlock::Create(BB->getContext()); 00239 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 00240 00241 // It is only legal to clone a function if a block address within that 00242 // function is never referenced outside of the function. Given that, we 00243 // want to map block addresses from the old function to block addresses in 00244 // the clone. (This is different from the generic ValueMapper 00245 // implementation, which generates an invalid blockaddress when 00246 // cloning a function.) 00247 // 00248 // Note that we don't need to fix the mapping for unreachable blocks; 00249 // the default mapping there is safe. 00250 if (BB->hasAddressTaken()) { 00251 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 00252 const_cast<BasicBlock*>(BB)); 00253 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB); 00254 } 00255 00256 00257 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 00258 00259 // Loop over all instructions, and copy them over, DCE'ing as we go. This 00260 // loop doesn't include the terminator. 00261 for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end(); 00262 II != IE; ++II) { 00263 Instruction *NewInst = II->clone(); 00264 00265 // Eagerly remap operands to the newly cloned instruction, except for PHI 00266 // nodes for which we defer processing until we update the CFG. 00267 if (!isa<PHINode>(NewInst)) { 00268 RemapInstruction(NewInst, VMap, 00269 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 00270 00271 // If we can simplify this instruction to some other value, simply add 00272 // a mapping to that value rather than inserting a new instruction into 00273 // the basic block. 00274 if (Value *V = SimplifyInstruction(NewInst, TD)) { 00275 // On the off-chance that this simplifies to an instruction in the old 00276 // function, map it back into the new function. 00277 if (Value *MappedV = VMap.lookup(V)) 00278 V = MappedV; 00279 00280 VMap[II] = V; 00281 delete NewInst; 00282 continue; 00283 } 00284 } 00285 00286 if (II->hasName()) 00287 NewInst->setName(II->getName()+NameSuffix); 00288 VMap[II] = NewInst; // Add instruction map to value. 00289 NewBB->getInstList().push_back(NewInst); 00290 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 00291 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 00292 if (isa<ConstantInt>(AI->getArraySize())) 00293 hasStaticAllocas = true; 00294 else 00295 hasDynamicAllocas = true; 00296 } 00297 } 00298 00299 // Finally, clone over the terminator. 00300 const TerminatorInst *OldTI = BB->getTerminator(); 00301 bool TerminatorDone = false; 00302 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) { 00303 if (BI->isConditional()) { 00304 // If the condition was a known constant in the callee... 00305 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 00306 // Or is a known constant in the caller... 00307 if (Cond == 0) { 00308 Value *V = VMap[BI->getCondition()]; 00309 Cond = dyn_cast_or_null<ConstantInt>(V); 00310 } 00311 00312 // Constant fold to uncond branch! 00313 if (Cond) { 00314 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue()); 00315 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 00316 ToClone.push_back(Dest); 00317 TerminatorDone = true; 00318 } 00319 } 00320 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) { 00321 // If switching on a value known constant in the caller. 00322 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition()); 00323 if (Cond == 0) { // Or known constant after constant prop in the callee... 00324 Value *V = VMap[SI->getCondition()]; 00325 Cond = dyn_cast_or_null<ConstantInt>(V); 00326 } 00327 if (Cond) { // Constant fold to uncond branch! 00328 SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond); 00329 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor()); 00330 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 00331 ToClone.push_back(Dest); 00332 TerminatorDone = true; 00333 } 00334 } 00335 00336 if (!TerminatorDone) { 00337 Instruction *NewInst = OldTI->clone(); 00338 if (OldTI->hasName()) 00339 NewInst->setName(OldTI->getName()+NameSuffix); 00340 NewBB->getInstList().push_back(NewInst); 00341 VMap[OldTI] = NewInst; // Add instruction map to value. 00342 00343 // Recursively clone any reachable successor blocks. 00344 const TerminatorInst *TI = BB->getTerminator(); 00345 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 00346 ToClone.push_back(TI->getSuccessor(i)); 00347 } 00348 00349 if (CodeInfo) { 00350 CodeInfo->ContainsCalls |= hasCalls; 00351 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 00352 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 00353 BB != &BB->getParent()->front(); 00354 } 00355 } 00356 00357 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto, 00358 /// except that it does some simple constant prop and DCE on the fly. The 00359 /// effect of this is to copy significantly less code in cases where (for 00360 /// example) a function call with constant arguments is inlined, and those 00361 /// constant arguments cause a significant amount of code in the callee to be 00362 /// dead. Since this doesn't produce an exact copy of the input, it can't be 00363 /// used for things like CloneFunction or CloneModule. 00364 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, 00365 ValueToValueMapTy &VMap, 00366 bool ModuleLevelChanges, 00367 SmallVectorImpl<ReturnInst*> &Returns, 00368 const char *NameSuffix, 00369 ClonedCodeInfo *CodeInfo, 00370 const DataLayout *TD, 00371 Instruction *TheCall) { 00372 assert(NameSuffix && "NameSuffix cannot be null!"); 00373 00374 #ifndef NDEBUG 00375 for (Function::const_arg_iterator II = OldFunc->arg_begin(), 00376 E = OldFunc->arg_end(); II != E; ++II) 00377 assert(VMap.count(II) && "No mapping from source argument specified!"); 00378 #endif 00379 00380 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges, 00381 NameSuffix, CodeInfo, TD); 00382 00383 // Clone the entry block, and anything recursively reachable from it. 00384 std::vector<const BasicBlock*> CloneWorklist; 00385 CloneWorklist.push_back(&OldFunc->getEntryBlock()); 00386 while (!CloneWorklist.empty()) { 00387 const BasicBlock *BB = CloneWorklist.back(); 00388 CloneWorklist.pop_back(); 00389 PFC.CloneBlock(BB, CloneWorklist); 00390 } 00391 00392 // Loop over all of the basic blocks in the old function. If the block was 00393 // reachable, we have cloned it and the old block is now in the value map: 00394 // insert it into the new function in the right order. If not, ignore it. 00395 // 00396 // Defer PHI resolution until rest of function is resolved. 00397 SmallVector<const PHINode*, 16> PHIToResolve; 00398 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end(); 00399 BI != BE; ++BI) { 00400 Value *V = VMap[BI]; 00401 BasicBlock *NewBB = cast_or_null<BasicBlock>(V); 00402 if (NewBB == 0) continue; // Dead block. 00403 00404 // Add the new block to the new function. 00405 NewFunc->getBasicBlockList().push_back(NewBB); 00406 00407 // Handle PHI nodes specially, as we have to remove references to dead 00408 // blocks. 00409 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) 00410 if (const PHINode *PN = dyn_cast<PHINode>(I)) 00411 PHIToResolve.push_back(PN); 00412 else 00413 break; 00414 00415 // Finally, remap the terminator instructions, as those can't be remapped 00416 // until all BBs are mapped. 00417 RemapInstruction(NewBB->getTerminator(), VMap, 00418 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 00419 } 00420 00421 // Defer PHI resolution until rest of function is resolved, PHI resolution 00422 // requires the CFG to be up-to-date. 00423 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) { 00424 const PHINode *OPN = PHIToResolve[phino]; 00425 unsigned NumPreds = OPN->getNumIncomingValues(); 00426 const BasicBlock *OldBB = OPN->getParent(); 00427 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]); 00428 00429 // Map operands for blocks that are live and remove operands for blocks 00430 // that are dead. 00431 for (; phino != PHIToResolve.size() && 00432 PHIToResolve[phino]->getParent() == OldBB; ++phino) { 00433 OPN = PHIToResolve[phino]; 00434 PHINode *PN = cast<PHINode>(VMap[OPN]); 00435 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) { 00436 Value *V = VMap[PN->getIncomingBlock(pred)]; 00437 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) { 00438 Value *InVal = MapValue(PN->getIncomingValue(pred), 00439 VMap, 00440 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 00441 assert(InVal && "Unknown input value?"); 00442 PN->setIncomingValue(pred, InVal); 00443 PN->setIncomingBlock(pred, MappedBlock); 00444 } else { 00445 PN->removeIncomingValue(pred, false); 00446 --pred, --e; // Revisit the next entry. 00447 } 00448 } 00449 } 00450 00451 // The loop above has removed PHI entries for those blocks that are dead 00452 // and has updated others. However, if a block is live (i.e. copied over) 00453 // but its terminator has been changed to not go to this block, then our 00454 // phi nodes will have invalid entries. Update the PHI nodes in this 00455 // case. 00456 PHINode *PN = cast<PHINode>(NewBB->begin()); 00457 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB)); 00458 if (NumPreds != PN->getNumIncomingValues()) { 00459 assert(NumPreds < PN->getNumIncomingValues()); 00460 // Count how many times each predecessor comes to this block. 00461 std::map<BasicBlock*, unsigned> PredCount; 00462 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); 00463 PI != E; ++PI) 00464 --PredCount[*PI]; 00465 00466 // Figure out how many entries to remove from each PHI. 00467 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 00468 ++PredCount[PN->getIncomingBlock(i)]; 00469 00470 // At this point, the excess predecessor entries are positive in the 00471 // map. Loop over all of the PHIs and remove excess predecessor 00472 // entries. 00473 BasicBlock::iterator I = NewBB->begin(); 00474 for (; (PN = dyn_cast<PHINode>(I)); ++I) { 00475 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(), 00476 E = PredCount.end(); PCI != E; ++PCI) { 00477 BasicBlock *Pred = PCI->first; 00478 for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove) 00479 PN->removeIncomingValue(Pred, false); 00480 } 00481 } 00482 } 00483 00484 // If the loops above have made these phi nodes have 0 or 1 operand, 00485 // replace them with undef or the input value. We must do this for 00486 // correctness, because 0-operand phis are not valid. 00487 PN = cast<PHINode>(NewBB->begin()); 00488 if (PN->getNumIncomingValues() == 0) { 00489 BasicBlock::iterator I = NewBB->begin(); 00490 BasicBlock::const_iterator OldI = OldBB->begin(); 00491 while ((PN = dyn_cast<PHINode>(I++))) { 00492 Value *NV = UndefValue::get(PN->getType()); 00493 PN->replaceAllUsesWith(NV); 00494 assert(VMap[OldI] == PN && "VMap mismatch"); 00495 VMap[OldI] = NV; 00496 PN->eraseFromParent(); 00497 ++OldI; 00498 } 00499 } 00500 } 00501 00502 // Make a second pass over the PHINodes now that all of them have been 00503 // remapped into the new function, simplifying the PHINode and performing any 00504 // recursive simplifications exposed. This will transparently update the 00505 // WeakVH in the VMap. Notably, we rely on that so that if we coalesce 00506 // two PHINodes, the iteration over the old PHIs remains valid, and the 00507 // mapping will just map us to the new node (which may not even be a PHI 00508 // node). 00509 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx) 00510 if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]])) 00511 recursivelySimplifyInstruction(PN, TD); 00512 00513 // Now that the inlined function body has been fully constructed, go through 00514 // and zap unconditional fall-through branches. This happen all the time when 00515 // specializing code: code specialization turns conditional branches into 00516 // uncond branches, and this code folds them. 00517 Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]); 00518 Function::iterator I = Begin; 00519 while (I != NewFunc->end()) { 00520 // Check if this block has become dead during inlining or other 00521 // simplifications. Note that the first block will appear dead, as it has 00522 // not yet been wired up properly. 00523 if (I != Begin && (pred_begin(I) == pred_end(I) || 00524 I->getSinglePredecessor() == I)) { 00525 BasicBlock *DeadBB = I++; 00526 DeleteDeadBlock(DeadBB); 00527 continue; 00528 } 00529 00530 // We need to simplify conditional branches and switches with a constant 00531 // operand. We try to prune these out when cloning, but if the 00532 // simplification required looking through PHI nodes, those are only 00533 // available after forming the full basic block. That may leave some here, 00534 // and we still want to prune the dead code as early as possible. 00535 ConstantFoldTerminator(I); 00536 00537 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator()); 00538 if (!BI || BI->isConditional()) { ++I; continue; } 00539 00540 BasicBlock *Dest = BI->getSuccessor(0); 00541 if (!Dest->getSinglePredecessor()) { 00542 ++I; continue; 00543 } 00544 00545 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify 00546 // above should have zapped all of them.. 00547 assert(!isa<PHINode>(Dest->begin())); 00548 00549 // We know all single-entry PHI nodes in the inlined function have been 00550 // removed, so we just need to splice the blocks. 00551 BI->eraseFromParent(); 00552 00553 // Make all PHI nodes that referred to Dest now refer to I as their source. 00554 Dest->replaceAllUsesWith(I); 00555 00556 // Move all the instructions in the succ to the pred. 00557 I->getInstList().splice(I->end(), Dest->getInstList()); 00558 00559 // Remove the dest block. 00560 Dest->eraseFromParent(); 00561 00562 // Do not increment I, iteratively merge all things this block branches to. 00563 } 00564 00565 // Make a final pass over the basic blocks from theh old function to gather 00566 // any return instructions which survived folding. We have to do this here 00567 // because we can iteratively remove and merge returns above. 00568 for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]), 00569 E = NewFunc->end(); 00570 I != E; ++I) 00571 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) 00572 Returns.push_back(RI); 00573 }