1 //===- CloneFunction.cpp - Clone a function into another function ---------===// 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 implements the CloneFunctionInto interface, which is used as the 11 // low-level function cloner. This is used by the CloneFunction and function 12 // inliner to do the dirty work of copying the body of a function around. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/IR/CFG.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DebugInfo.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/GlobalVariable.h" 27 #include "llvm/IR/Instructions.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/Metadata.h" 31 #include "llvm/IR/Module.h" 32 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 33 #include "llvm/Transforms/Utils/Cloning.h" 34 #include "llvm/Transforms/Utils/Local.h" 35 #include "llvm/Transforms/Utils/ValueMapper.h" 36 #include <map> 37 using namespace llvm; 38 39 /// See comments in Cloning.h. 40 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, 41 const Twine &NameSuffix, Function *F, 42 ClonedCodeInfo *CodeInfo, 43 DebugInfoFinder *DIFinder) { 44 DenseMap<const MDNode *, MDNode *> Cache; 45 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F); 46 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 47 48 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 49 50 // Loop over all instructions, and copy them over. 51 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); 52 II != IE; ++II) { 53 54 if (DIFinder && F->getParent() && II->getDebugLoc()) 55 DIFinder->processLocation(*F->getParent(), II->getDebugLoc().get()); 56 57 Instruction *NewInst = II->clone(); 58 if (II->hasName()) 59 NewInst->setName(II->getName()+NameSuffix); 60 NewBB->getInstList().push_back(NewInst); 61 VMap[&*II] = NewInst; // Add instruction map to value. 62 63 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 64 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 65 if (isa<ConstantInt>(AI->getArraySize())) 66 hasStaticAllocas = true; 67 else 68 hasDynamicAllocas = true; 69 } 70 } 71 72 if (CodeInfo) { 73 CodeInfo->ContainsCalls |= hasCalls; 74 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 75 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 76 BB != &BB->getParent()->getEntryBlock(); 77 } 78 return NewBB; 79 } 80 81 // Clone OldFunc into NewFunc, transforming the old arguments into references to 82 // VMap values. 83 // 84 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc, 85 ValueToValueMapTy &VMap, 86 bool ModuleLevelChanges, 87 SmallVectorImpl<ReturnInst*> &Returns, 88 const char *NameSuffix, ClonedCodeInfo *CodeInfo, 89 ValueMapTypeRemapper *TypeMapper, 90 ValueMaterializer *Materializer) { 91 assert(NameSuffix && "NameSuffix cannot be null!"); 92 93 #ifndef NDEBUG 94 for (const Argument &I : OldFunc->args()) 95 assert(VMap.count(&I) && "No mapping from source argument specified!"); 96 #endif 97 98 // Copy all attributes other than those stored in the AttributeList. We need 99 // to remap the parameter indices of the AttributeList. 100 AttributeList NewAttrs = NewFunc->getAttributes(); 101 NewFunc->copyAttributesFrom(OldFunc); 102 NewFunc->setAttributes(NewAttrs); 103 104 // Fix up the personality function that got copied over. 105 if (OldFunc->hasPersonalityFn()) 106 NewFunc->setPersonalityFn( 107 MapValue(OldFunc->getPersonalityFn(), VMap, 108 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 109 TypeMapper, Materializer)); 110 111 SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size()); 112 AttributeList OldAttrs = OldFunc->getAttributes(); 113 114 // Clone any argument attributes that are present in the VMap. 115 for (const Argument &OldArg : OldFunc->args()) { 116 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) { 117 NewArgAttrs[NewArg->getArgNo()] = 118 OldAttrs.getParamAttributes(OldArg.getArgNo()); 119 } 120 } 121 122 NewFunc->setAttributes( 123 AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttributes(), 124 OldAttrs.getRetAttributes(), NewArgAttrs)); 125 126 bool MustCloneSP = 127 OldFunc->getParent() && OldFunc->getParent() == NewFunc->getParent(); 128 DISubprogram *SP = OldFunc->getSubprogram(); 129 if (SP) { 130 assert(!MustCloneSP || ModuleLevelChanges); 131 // Add mappings for some DebugInfo nodes that we don't want duplicated 132 // even if they're distinct. 133 auto &MD = VMap.MD(); 134 MD[SP->getUnit()].reset(SP->getUnit()); 135 MD[SP->getType()].reset(SP->getType()); 136 MD[SP->getFile()].reset(SP->getFile()); 137 // If we're not cloning into the same module, no need to clone the 138 // subprogram 139 if (!MustCloneSP) 140 MD[SP].reset(SP); 141 } 142 143 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 144 OldFunc->getAllMetadata(MDs); 145 for (auto MD : MDs) { 146 NewFunc->addMetadata( 147 MD.first, 148 *MapMetadata(MD.second, VMap, 149 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 150 TypeMapper, Materializer)); 151 } 152 153 // When we remap instructions, we want to avoid duplicating inlined 154 // DISubprograms, so record all subprograms we find as we duplicate 155 // instructions and then freeze them in the MD map. 156 DebugInfoFinder DIFinder; 157 158 // Loop over all of the basic blocks in the function, cloning them as 159 // appropriate. Note that we save BE this way in order to handle cloning of 160 // recursive functions into themselves. 161 // 162 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end(); 163 BI != BE; ++BI) { 164 const BasicBlock &BB = *BI; 165 166 // Create a new basic block and copy instructions into it! 167 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo, 168 SP ? &DIFinder : nullptr); 169 170 // Add basic block mapping. 171 VMap[&BB] = CBB; 172 173 // It is only legal to clone a function if a block address within that 174 // function is never referenced outside of the function. Given that, we 175 // want to map block addresses from the old function to block addresses in 176 // the clone. (This is different from the generic ValueMapper 177 // implementation, which generates an invalid blockaddress when 178 // cloning a function.) 179 if (BB.hasAddressTaken()) { 180 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 181 const_cast<BasicBlock*>(&BB)); 182 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB); 183 } 184 185 // Note return instructions for the caller. 186 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator())) 187 Returns.push_back(RI); 188 } 189 190 for (DISubprogram *ISP : DIFinder.subprograms()) { 191 if (ISP != SP) { 192 VMap.MD()[ISP].reset(ISP); 193 } 194 } 195 196 // Loop over all of the instructions in the function, fixing up operand 197 // references as we go. This uses VMap to do all the hard work. 198 for (Function::iterator BB = 199 cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(), 200 BE = NewFunc->end(); 201 BB != BE; ++BB) 202 // Loop over all instructions, fixing each one as we find it... 203 for (Instruction &II : *BB) 204 RemapInstruction(&II, VMap, 205 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 206 TypeMapper, Materializer); 207 } 208 209 /// Return a copy of the specified function and add it to that function's 210 /// module. Also, any references specified in the VMap are changed to refer to 211 /// their mapped value instead of the original one. If any of the arguments to 212 /// the function are in the VMap, the arguments are deleted from the resultant 213 /// function. The VMap is updated to include mappings from all of the 214 /// instructions and basicblocks in the function from their old to new values. 215 /// 216 Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap, 217 ClonedCodeInfo *CodeInfo) { 218 std::vector<Type*> ArgTypes; 219 220 // The user might be deleting arguments to the function by specifying them in 221 // the VMap. If so, we need to not add the arguments to the arg ty vector 222 // 223 for (const Argument &I : F->args()) 224 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet? 225 ArgTypes.push_back(I.getType()); 226 227 // Create a new function type... 228 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(), 229 ArgTypes, F->getFunctionType()->isVarArg()); 230 231 // Create the new function... 232 Function *NewF = 233 Function::Create(FTy, F->getLinkage(), F->getName(), F->getParent()); 234 235 // Loop over the arguments, copying the names of the mapped arguments over... 236 Function::arg_iterator DestI = NewF->arg_begin(); 237 for (const Argument & I : F->args()) 238 if (VMap.count(&I) == 0) { // Is this argument preserved? 239 DestI->setName(I.getName()); // Copy the name over... 240 VMap[&I] = &*DestI++; // Add mapping to VMap 241 } 242 243 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned. 244 CloneFunctionInto(NewF, F, VMap, F->getSubprogram() != nullptr, Returns, "", 245 CodeInfo); 246 247 return NewF; 248 } 249 250 251 252 namespace { 253 /// This is a private class used to implement CloneAndPruneFunctionInto. 254 struct PruningFunctionCloner { 255 Function *NewFunc; 256 const Function *OldFunc; 257 ValueToValueMapTy &VMap; 258 bool ModuleLevelChanges; 259 const char *NameSuffix; 260 ClonedCodeInfo *CodeInfo; 261 262 public: 263 PruningFunctionCloner(Function *newFunc, const Function *oldFunc, 264 ValueToValueMapTy &valueMap, bool moduleLevelChanges, 265 const char *nameSuffix, ClonedCodeInfo *codeInfo) 266 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap), 267 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix), 268 CodeInfo(codeInfo) {} 269 270 /// The specified block is found to be reachable, clone it and 271 /// anything that it can reach. 272 void CloneBlock(const BasicBlock *BB, 273 BasicBlock::const_iterator StartingInst, 274 std::vector<const BasicBlock*> &ToClone); 275 }; 276 } 277 278 /// The specified block is found to be reachable, clone it and 279 /// anything that it can reach. 280 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB, 281 BasicBlock::const_iterator StartingInst, 282 std::vector<const BasicBlock*> &ToClone){ 283 WeakTrackingVH &BBEntry = VMap[BB]; 284 285 // Have we already cloned this block? 286 if (BBEntry) return; 287 288 // Nope, clone it now. 289 BasicBlock *NewBB; 290 BBEntry = NewBB = BasicBlock::Create(BB->getContext()); 291 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 292 293 // It is only legal to clone a function if a block address within that 294 // function is never referenced outside of the function. Given that, we 295 // want to map block addresses from the old function to block addresses in 296 // the clone. (This is different from the generic ValueMapper 297 // implementation, which generates an invalid blockaddress when 298 // cloning a function.) 299 // 300 // Note that we don't need to fix the mapping for unreachable blocks; 301 // the default mapping there is safe. 302 if (BB->hasAddressTaken()) { 303 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 304 const_cast<BasicBlock*>(BB)); 305 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB); 306 } 307 308 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 309 310 // Loop over all instructions, and copy them over, DCE'ing as we go. This 311 // loop doesn't include the terminator. 312 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); 313 II != IE; ++II) { 314 315 Instruction *NewInst = II->clone(); 316 317 // Eagerly remap operands to the newly cloned instruction, except for PHI 318 // nodes for which we defer processing until we update the CFG. 319 if (!isa<PHINode>(NewInst)) { 320 RemapInstruction(NewInst, VMap, 321 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 322 323 // If we can simplify this instruction to some other value, simply add 324 // a mapping to that value rather than inserting a new instruction into 325 // the basic block. 326 if (Value *V = 327 SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) { 328 assert((!isa<Instruction>(V) || 329 cast<Instruction>(V)->getParent() == nullptr || 330 cast<Instruction>(V)->getFunction() != OldFunc || 331 OldFunc == NewFunc) && 332 "Simplified Instruction should not be in the old function."); 333 334 if (!NewInst->mayHaveSideEffects()) { 335 VMap[&*II] = V; 336 NewInst->deleteValue(); 337 continue; 338 } 339 } 340 } 341 342 if (II->hasName()) 343 NewInst->setName(II->getName()+NameSuffix); 344 VMap[&*II] = NewInst; // Add instruction map to value. 345 NewBB->getInstList().push_back(NewInst); 346 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 347 348 if (CodeInfo) 349 if (auto CS = ImmutableCallSite(&*II)) 350 if (CS.hasOperandBundles()) 351 CodeInfo->OperandBundleCallSites.push_back(NewInst); 352 353 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 354 if (isa<ConstantInt>(AI->getArraySize())) 355 hasStaticAllocas = true; 356 else 357 hasDynamicAllocas = true; 358 } 359 } 360 361 // Finally, clone over the terminator. 362 const TerminatorInst *OldTI = BB->getTerminator(); 363 bool TerminatorDone = false; 364 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) { 365 if (BI->isConditional()) { 366 // If the condition was a known constant in the callee... 367 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 368 // Or is a known constant in the caller... 369 if (!Cond) { 370 Value *V = VMap.lookup(BI->getCondition()); 371 Cond = dyn_cast_or_null<ConstantInt>(V); 372 } 373 374 // Constant fold to uncond branch! 375 if (Cond) { 376 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue()); 377 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 378 ToClone.push_back(Dest); 379 TerminatorDone = true; 380 } 381 } 382 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) { 383 // If switching on a value known constant in the caller. 384 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition()); 385 if (!Cond) { // Or known constant after constant prop in the callee... 386 Value *V = VMap.lookup(SI->getCondition()); 387 Cond = dyn_cast_or_null<ConstantInt>(V); 388 } 389 if (Cond) { // Constant fold to uncond branch! 390 SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond); 391 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor()); 392 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 393 ToClone.push_back(Dest); 394 TerminatorDone = true; 395 } 396 } 397 398 if (!TerminatorDone) { 399 Instruction *NewInst = OldTI->clone(); 400 if (OldTI->hasName()) 401 NewInst->setName(OldTI->getName()+NameSuffix); 402 NewBB->getInstList().push_back(NewInst); 403 VMap[OldTI] = NewInst; // Add instruction map to value. 404 405 if (CodeInfo) 406 if (auto CS = ImmutableCallSite(OldTI)) 407 if (CS.hasOperandBundles()) 408 CodeInfo->OperandBundleCallSites.push_back(NewInst); 409 410 // Recursively clone any reachable successor blocks. 411 const TerminatorInst *TI = BB->getTerminator(); 412 for (const BasicBlock *Succ : TI->successors()) 413 ToClone.push_back(Succ); 414 } 415 416 if (CodeInfo) { 417 CodeInfo->ContainsCalls |= hasCalls; 418 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 419 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 420 BB != &BB->getParent()->front(); 421 } 422 } 423 424 /// This works like CloneAndPruneFunctionInto, except that it does not clone the 425 /// entire function. Instead it starts at an instruction provided by the caller 426 /// and copies (and prunes) only the code reachable from that instruction. 427 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, 428 const Instruction *StartingInst, 429 ValueToValueMapTy &VMap, 430 bool ModuleLevelChanges, 431 SmallVectorImpl<ReturnInst *> &Returns, 432 const char *NameSuffix, 433 ClonedCodeInfo *CodeInfo) { 434 assert(NameSuffix && "NameSuffix cannot be null!"); 435 436 ValueMapTypeRemapper *TypeMapper = nullptr; 437 ValueMaterializer *Materializer = nullptr; 438 439 #ifndef NDEBUG 440 // If the cloning starts at the beginning of the function, verify that 441 // the function arguments are mapped. 442 if (!StartingInst) 443 for (const Argument &II : OldFunc->args()) 444 assert(VMap.count(&II) && "No mapping from source argument specified!"); 445 #endif 446 447 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges, 448 NameSuffix, CodeInfo); 449 const BasicBlock *StartingBB; 450 if (StartingInst) 451 StartingBB = StartingInst->getParent(); 452 else { 453 StartingBB = &OldFunc->getEntryBlock(); 454 StartingInst = &StartingBB->front(); 455 } 456 457 // Clone the entry block, and anything recursively reachable from it. 458 std::vector<const BasicBlock*> CloneWorklist; 459 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist); 460 while (!CloneWorklist.empty()) { 461 const BasicBlock *BB = CloneWorklist.back(); 462 CloneWorklist.pop_back(); 463 PFC.CloneBlock(BB, BB->begin(), CloneWorklist); 464 } 465 466 // Loop over all of the basic blocks in the old function. If the block was 467 // reachable, we have cloned it and the old block is now in the value map: 468 // insert it into the new function in the right order. If not, ignore it. 469 // 470 // Defer PHI resolution until rest of function is resolved. 471 SmallVector<const PHINode*, 16> PHIToResolve; 472 for (const BasicBlock &BI : *OldFunc) { 473 Value *V = VMap.lookup(&BI); 474 BasicBlock *NewBB = cast_or_null<BasicBlock>(V); 475 if (!NewBB) continue; // Dead block. 476 477 // Add the new block to the new function. 478 NewFunc->getBasicBlockList().push_back(NewBB); 479 480 // Handle PHI nodes specially, as we have to remove references to dead 481 // blocks. 482 for (BasicBlock::const_iterator I = BI.begin(), E = BI.end(); I != E; ++I) { 483 // PHI nodes may have been remapped to non-PHI nodes by the caller or 484 // during the cloning process. 485 if (const PHINode *PN = dyn_cast<PHINode>(I)) { 486 if (isa<PHINode>(VMap[PN])) 487 PHIToResolve.push_back(PN); 488 else 489 break; 490 } else { 491 break; 492 } 493 } 494 495 // Finally, remap the terminator instructions, as those can't be remapped 496 // until all BBs are mapped. 497 RemapInstruction(NewBB->getTerminator(), VMap, 498 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 499 TypeMapper, Materializer); 500 } 501 502 // Defer PHI resolution until rest of function is resolved, PHI resolution 503 // requires the CFG to be up-to-date. 504 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) { 505 const PHINode *OPN = PHIToResolve[phino]; 506 unsigned NumPreds = OPN->getNumIncomingValues(); 507 const BasicBlock *OldBB = OPN->getParent(); 508 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]); 509 510 // Map operands for blocks that are live and remove operands for blocks 511 // that are dead. 512 for (; phino != PHIToResolve.size() && 513 PHIToResolve[phino]->getParent() == OldBB; ++phino) { 514 OPN = PHIToResolve[phino]; 515 PHINode *PN = cast<PHINode>(VMap[OPN]); 516 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) { 517 Value *V = VMap.lookup(PN->getIncomingBlock(pred)); 518 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) { 519 Value *InVal = MapValue(PN->getIncomingValue(pred), 520 VMap, 521 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 522 assert(InVal && "Unknown input value?"); 523 PN->setIncomingValue(pred, InVal); 524 PN->setIncomingBlock(pred, MappedBlock); 525 } else { 526 PN->removeIncomingValue(pred, false); 527 --pred; // Revisit the next entry. 528 --e; 529 } 530 } 531 } 532 533 // The loop above has removed PHI entries for those blocks that are dead 534 // and has updated others. However, if a block is live (i.e. copied over) 535 // but its terminator has been changed to not go to this block, then our 536 // phi nodes will have invalid entries. Update the PHI nodes in this 537 // case. 538 PHINode *PN = cast<PHINode>(NewBB->begin()); 539 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB)); 540 if (NumPreds != PN->getNumIncomingValues()) { 541 assert(NumPreds < PN->getNumIncomingValues()); 542 // Count how many times each predecessor comes to this block. 543 std::map<BasicBlock*, unsigned> PredCount; 544 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); 545 PI != E; ++PI) 546 --PredCount[*PI]; 547 548 // Figure out how many entries to remove from each PHI. 549 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 550 ++PredCount[PN->getIncomingBlock(i)]; 551 552 // At this point, the excess predecessor entries are positive in the 553 // map. Loop over all of the PHIs and remove excess predecessor 554 // entries. 555 BasicBlock::iterator I = NewBB->begin(); 556 for (; (PN = dyn_cast<PHINode>(I)); ++I) { 557 for (const auto &PCI : PredCount) { 558 BasicBlock *Pred = PCI.first; 559 for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove) 560 PN->removeIncomingValue(Pred, false); 561 } 562 } 563 } 564 565 // If the loops above have made these phi nodes have 0 or 1 operand, 566 // replace them with undef or the input value. We must do this for 567 // correctness, because 0-operand phis are not valid. 568 PN = cast<PHINode>(NewBB->begin()); 569 if (PN->getNumIncomingValues() == 0) { 570 BasicBlock::iterator I = NewBB->begin(); 571 BasicBlock::const_iterator OldI = OldBB->begin(); 572 while ((PN = dyn_cast<PHINode>(I++))) { 573 Value *NV = UndefValue::get(PN->getType()); 574 PN->replaceAllUsesWith(NV); 575 assert(VMap[&*OldI] == PN && "VMap mismatch"); 576 VMap[&*OldI] = NV; 577 PN->eraseFromParent(); 578 ++OldI; 579 } 580 } 581 } 582 583 // Make a second pass over the PHINodes now that all of them have been 584 // remapped into the new function, simplifying the PHINode and performing any 585 // recursive simplifications exposed. This will transparently update the 586 // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce 587 // two PHINodes, the iteration over the old PHIs remains valid, and the 588 // mapping will just map us to the new node (which may not even be a PHI 589 // node). 590 const DataLayout &DL = NewFunc->getParent()->getDataLayout(); 591 SmallSetVector<const Value *, 8> Worklist; 592 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx) 593 if (isa<PHINode>(VMap[PHIToResolve[Idx]])) 594 Worklist.insert(PHIToResolve[Idx]); 595 596 // Note that we must test the size on each iteration, the worklist can grow. 597 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 598 const Value *OrigV = Worklist[Idx]; 599 auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV)); 600 if (!I) 601 continue; 602 603 // Skip over non-intrinsic callsites, we don't want to remove any nodes from 604 // the CGSCC. 605 CallSite CS = CallSite(I); 606 if (CS && CS.getCalledFunction() && !CS.getCalledFunction()->isIntrinsic()) 607 continue; 608 609 // See if this instruction simplifies. 610 Value *SimpleV = SimplifyInstruction(I, DL); 611 if (!SimpleV) 612 continue; 613 614 // Stash away all the uses of the old instruction so we can check them for 615 // recursive simplifications after a RAUW. This is cheaper than checking all 616 // uses of To on the recursive step in most cases. 617 for (const User *U : OrigV->users()) 618 Worklist.insert(cast<Instruction>(U)); 619 620 // Replace the instruction with its simplified value. 621 I->replaceAllUsesWith(SimpleV); 622 623 // If the original instruction had no side effects, remove it. 624 if (isInstructionTriviallyDead(I)) 625 I->eraseFromParent(); 626 else 627 VMap[OrigV] = I; 628 } 629 630 // Now that the inlined function body has been fully constructed, go through 631 // and zap unconditional fall-through branches. This happens all the time when 632 // specializing code: code specialization turns conditional branches into 633 // uncond branches, and this code folds them. 634 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator(); 635 Function::iterator I = Begin; 636 while (I != NewFunc->end()) { 637 // Check if this block has become dead during inlining or other 638 // simplifications. Note that the first block will appear dead, as it has 639 // not yet been wired up properly. 640 if (I != Begin && (pred_begin(&*I) == pred_end(&*I) || 641 I->getSinglePredecessor() == &*I)) { 642 BasicBlock *DeadBB = &*I++; 643 DeleteDeadBlock(DeadBB); 644 continue; 645 } 646 647 // We need to simplify conditional branches and switches with a constant 648 // operand. We try to prune these out when cloning, but if the 649 // simplification required looking through PHI nodes, those are only 650 // available after forming the full basic block. That may leave some here, 651 // and we still want to prune the dead code as early as possible. 652 ConstantFoldTerminator(&*I); 653 654 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator()); 655 if (!BI || BI->isConditional()) { ++I; continue; } 656 657 BasicBlock *Dest = BI->getSuccessor(0); 658 if (!Dest->getSinglePredecessor()) { 659 ++I; continue; 660 } 661 662 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify 663 // above should have zapped all of them.. 664 assert(!isa<PHINode>(Dest->begin())); 665 666 // We know all single-entry PHI nodes in the inlined function have been 667 // removed, so we just need to splice the blocks. 668 BI->eraseFromParent(); 669 670 // Make all PHI nodes that referred to Dest now refer to I as their source. 671 Dest->replaceAllUsesWith(&*I); 672 673 // Move all the instructions in the succ to the pred. 674 I->getInstList().splice(I->end(), Dest->getInstList()); 675 676 // Remove the dest block. 677 Dest->eraseFromParent(); 678 679 // Do not increment I, iteratively merge all things this block branches to. 680 } 681 682 // Make a final pass over the basic blocks from the old function to gather 683 // any return instructions which survived folding. We have to do this here 684 // because we can iteratively remove and merge returns above. 685 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(), 686 E = NewFunc->end(); 687 I != E; ++I) 688 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) 689 Returns.push_back(RI); 690 } 691 692 693 /// This works exactly like CloneFunctionInto, 694 /// except that it does some simple constant prop and DCE on the fly. The 695 /// effect of this is to copy significantly less code in cases where (for 696 /// example) a function call with constant arguments is inlined, and those 697 /// constant arguments cause a significant amount of code in the callee to be 698 /// dead. Since this doesn't produce an exact copy of the input, it can't be 699 /// used for things like CloneFunction or CloneModule. 700 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, 701 ValueToValueMapTy &VMap, 702 bool ModuleLevelChanges, 703 SmallVectorImpl<ReturnInst*> &Returns, 704 const char *NameSuffix, 705 ClonedCodeInfo *CodeInfo, 706 Instruction *TheCall) { 707 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap, 708 ModuleLevelChanges, Returns, NameSuffix, CodeInfo); 709 } 710 711 /// \brief Remaps instructions in \p Blocks using the mapping in \p VMap. 712 void llvm::remapInstructionsInBlocks( 713 const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) { 714 // Rewrite the code to refer to itself. 715 for (auto *BB : Blocks) 716 for (auto &Inst : *BB) 717 RemapInstruction(&Inst, VMap, 718 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 719 } 720 721 /// \brief Clones a loop \p OrigLoop. Returns the loop and the blocks in \p 722 /// Blocks. 723 /// 724 /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block 725 /// \p LoopDomBB. Insert the new blocks before block specified in \p Before. 726 Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, 727 Loop *OrigLoop, ValueToValueMapTy &VMap, 728 const Twine &NameSuffix, LoopInfo *LI, 729 DominatorTree *DT, 730 SmallVectorImpl<BasicBlock *> &Blocks) { 731 assert(OrigLoop->getSubLoops().empty() && 732 "Loop to be cloned cannot have inner loop"); 733 Function *F = OrigLoop->getHeader()->getParent(); 734 Loop *ParentLoop = OrigLoop->getParentLoop(); 735 736 Loop *NewLoop = new Loop(); 737 if (ParentLoop) 738 ParentLoop->addChildLoop(NewLoop); 739 else 740 LI->addTopLevelLoop(NewLoop); 741 742 BasicBlock *OrigPH = OrigLoop->getLoopPreheader(); 743 assert(OrigPH && "No preheader"); 744 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F); 745 // To rename the loop PHIs. 746 VMap[OrigPH] = NewPH; 747 Blocks.push_back(NewPH); 748 749 // Update LoopInfo. 750 if (ParentLoop) 751 ParentLoop->addBasicBlockToLoop(NewPH, *LI); 752 753 // Update DominatorTree. 754 DT->addNewBlock(NewPH, LoopDomBB); 755 756 for (BasicBlock *BB : OrigLoop->getBlocks()) { 757 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F); 758 VMap[BB] = NewBB; 759 760 // Update LoopInfo. 761 NewLoop->addBasicBlockToLoop(NewBB, *LI); 762 763 // Add DominatorTree node. After seeing all blocks, update to correct IDom. 764 DT->addNewBlock(NewBB, NewPH); 765 766 Blocks.push_back(NewBB); 767 } 768 769 for (BasicBlock *BB : OrigLoop->getBlocks()) { 770 // Update DominatorTree. 771 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock(); 772 DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]), 773 cast<BasicBlock>(VMap[IDomBB])); 774 } 775 776 // Move them physically from the end of the block list. 777 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(), 778 NewPH); 779 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(), 780 NewLoop->getHeader()->getIterator(), F->end()); 781 782 return NewLoop; 783 } 784 785 /// \brief Duplicate non-Phi instructions from the beginning of block up to 786 /// StopAt instruction into a split block between BB and its predecessor. 787 BasicBlock * 788 llvm::DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, 789 Instruction *StopAt, 790 ValueToValueMapTy &ValueMapping) { 791 // We are going to have to map operands from the original BB block to the new 792 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to 793 // account for entry from PredBB. 794 BasicBlock::iterator BI = BB->begin(); 795 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 796 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 797 798 BasicBlock *NewBB = SplitEdge(PredBB, BB); 799 NewBB->setName(PredBB->getName() + ".split"); 800 Instruction *NewTerm = NewBB->getTerminator(); 801 802 // Clone the non-phi instructions of BB into NewBB, keeping track of the 803 // mapping and using it to remap operands in the cloned instructions. 804 for (; StopAt != &*BI; ++BI) { 805 Instruction *New = BI->clone(); 806 New->setName(BI->getName()); 807 New->insertBefore(NewTerm); 808 ValueMapping[&*BI] = New; 809 810 // Remap operands to patch up intra-block references. 811 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 812 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 813 auto I = ValueMapping.find(Inst); 814 if (I != ValueMapping.end()) 815 New->setOperand(i, I->second); 816 } 817 } 818 819 return NewBB; 820 } 821