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