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/MDBuilder.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 34 #include "llvm/Transforms/Utils/Cloning.h" 35 #include "llvm/Transforms/Utils/Local.h" 36 #include "llvm/Transforms/Utils/ValueMapper.h" 37 #include <map> 38 using namespace llvm; 39 40 #define DEBUG_TYPE "clone-function" 41 42 /// See comments in Cloning.h. 43 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, 44 const Twine &NameSuffix, Function *F, 45 ClonedCodeInfo *CodeInfo, 46 DebugInfoFinder *DIFinder) { 47 DenseMap<const MDNode *, MDNode *> Cache; 48 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F); 49 if (BB->hasName()) 50 NewBB->setName(BB->getName() + NameSuffix); 51 52 bool hasCalls = false, hasDynamicAllocas = false; 53 Module *TheModule = F ? F->getParent() : nullptr; 54 55 // Loop over all instructions, and copy them over. 56 for (const Instruction &I : *BB) { 57 if (DIFinder && TheModule) 58 DIFinder->processInstruction(*TheModule, I); 59 60 Instruction *NewInst = I.clone(); 61 if (I.hasName()) 62 NewInst->setName(I.getName() + NameSuffix); 63 NewBB->getInstList().push_back(NewInst); 64 VMap[&I] = NewInst; // Add instruction map to value. 65 66 hasCalls |= (isa<CallInst>(I) && !isa<DbgInfoIntrinsic>(I)); 67 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 68 if (!AI->isStaticAlloca()) { 69 hasDynamicAllocas = true; 70 } 71 } 72 } 73 74 if (CodeInfo) { 75 CodeInfo->ContainsCalls |= hasCalls; 76 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 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 // Everything else beyond this point deals with function instructions, 144 // so if we are dealing with a function declaration, we're done. 145 if (OldFunc->isDeclaration()) 146 return; 147 148 // When we remap instructions, we want to avoid duplicating inlined 149 // DISubprograms, so record all subprograms we find as we duplicate 150 // instructions and then freeze them in the MD map. 151 // We also record information about dbg.value and dbg.declare to avoid 152 // duplicating the types. 153 DebugInfoFinder DIFinder; 154 155 // Loop over all of the basic blocks in the function, cloning them as 156 // appropriate. Note that we save BE this way in order to handle cloning of 157 // recursive functions into themselves. 158 for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end(); 159 BI != BE; ++BI) { 160 const BasicBlock &BB = *BI; 161 162 // Create a new basic block and copy instructions into it! 163 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo, 164 ModuleLevelChanges ? &DIFinder : nullptr); 165 166 // Add basic block mapping. 167 VMap[&BB] = CBB; 168 169 // It is only legal to clone a function if a block address within that 170 // function is never referenced outside of the function. Given that, we 171 // want to map block addresses from the old function to block addresses in 172 // the clone. (This is different from the generic ValueMapper 173 // implementation, which generates an invalid blockaddress when 174 // cloning a function.) 175 if (BB.hasAddressTaken()) { 176 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 177 const_cast<BasicBlock*>(&BB)); 178 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB); 179 } 180 181 // Note return instructions for the caller. 182 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator())) 183 Returns.push_back(RI); 184 } 185 186 for (DISubprogram *ISP : DIFinder.subprograms()) 187 if (ISP != SP) 188 VMap.MD()[ISP].reset(ISP); 189 190 for (DICompileUnit *CU : DIFinder.compile_units()) 191 VMap.MD()[CU].reset(CU); 192 193 for (DIType *Type : DIFinder.types()) 194 VMap.MD()[Type].reset(Type); 195 196 // Duplicate the metadata that is attached to the cloned function. 197 // Subprograms/CUs/types that were already mapped to themselves won't be 198 // duplicated. 199 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 200 OldFunc->getAllMetadata(MDs); 201 for (auto MD : MDs) { 202 NewFunc->addMetadata( 203 MD.first, 204 *MapMetadata(MD.second, VMap, 205 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 206 TypeMapper, Materializer)); 207 } 208 209 // Loop over all of the instructions in the function, fixing up operand 210 // references as we go. This uses VMap to do all the hard work. 211 for (Function::iterator BB = 212 cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(), 213 BE = NewFunc->end(); 214 BB != BE; ++BB) 215 // Loop over all instructions, fixing each one as we find it... 216 for (Instruction &II : *BB) 217 RemapInstruction(&II, VMap, 218 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 219 TypeMapper, Materializer); 220 221 // Register all DICompileUnits of the old parent module in the new parent module 222 auto* OldModule = OldFunc->getParent(); 223 auto* NewModule = NewFunc->getParent(); 224 if (OldModule && NewModule && OldModule != NewModule && DIFinder.compile_unit_count()) { 225 auto* NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu"); 226 // Avoid multiple insertions of the same DICompileUnit to NMD. 227 SmallPtrSet<const void*, 8> Visited; 228 for (auto* Operand : NMD->operands()) 229 Visited.insert(Operand); 230 for (auto* Unit : DIFinder.compile_units()) 231 // VMap.MD()[Unit] == Unit 232 if (Visited.insert(Unit).second) 233 NMD->addOperand(Unit); 234 } 235 } 236 237 /// Return a copy of the specified function and add it to that function's 238 /// module. Also, any references specified in the VMap are changed to refer to 239 /// their mapped value instead of the original one. If any of the arguments to 240 /// the function are in the VMap, the arguments are deleted from the resultant 241 /// function. The VMap is updated to include mappings from all of the 242 /// instructions and basicblocks in the function from their old to new values. 243 /// 244 Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap, 245 ClonedCodeInfo *CodeInfo) { 246 std::vector<Type*> ArgTypes; 247 248 // The user might be deleting arguments to the function by specifying them in 249 // the VMap. If so, we need to not add the arguments to the arg ty vector 250 // 251 for (const Argument &I : F->args()) 252 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet? 253 ArgTypes.push_back(I.getType()); 254 255 // Create a new function type... 256 FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(), 257 ArgTypes, F->getFunctionType()->isVarArg()); 258 259 // Create the new function... 260 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(), 261 F->getName(), F->getParent()); 262 263 // Loop over the arguments, copying the names of the mapped arguments over... 264 Function::arg_iterator DestI = NewF->arg_begin(); 265 for (const Argument & I : F->args()) 266 if (VMap.count(&I) == 0) { // Is this argument preserved? 267 DestI->setName(I.getName()); // Copy the name over... 268 VMap[&I] = &*DestI++; // Add mapping to VMap 269 } 270 271 SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned. 272 CloneFunctionInto(NewF, F, VMap, F->getSubprogram() != nullptr, Returns, "", 273 CodeInfo); 274 275 return NewF; 276 } 277 278 279 280 namespace { 281 /// This is a private class used to implement CloneAndPruneFunctionInto. 282 struct PruningFunctionCloner { 283 Function *NewFunc; 284 const Function *OldFunc; 285 ValueToValueMapTy &VMap; 286 bool ModuleLevelChanges; 287 const char *NameSuffix; 288 ClonedCodeInfo *CodeInfo; 289 290 public: 291 PruningFunctionCloner(Function *newFunc, const Function *oldFunc, 292 ValueToValueMapTy &valueMap, bool moduleLevelChanges, 293 const char *nameSuffix, ClonedCodeInfo *codeInfo) 294 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap), 295 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix), 296 CodeInfo(codeInfo) {} 297 298 /// The specified block is found to be reachable, clone it and 299 /// anything that it can reach. 300 void CloneBlock(const BasicBlock *BB, 301 BasicBlock::const_iterator StartingInst, 302 std::vector<const BasicBlock*> &ToClone); 303 }; 304 } 305 306 /// The specified block is found to be reachable, clone it and 307 /// anything that it can reach. 308 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB, 309 BasicBlock::const_iterator StartingInst, 310 std::vector<const BasicBlock*> &ToClone){ 311 WeakTrackingVH &BBEntry = VMap[BB]; 312 313 // Have we already cloned this block? 314 if (BBEntry) return; 315 316 // Nope, clone it now. 317 BasicBlock *NewBB; 318 BBEntry = NewBB = BasicBlock::Create(BB->getContext()); 319 if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); 320 321 // It is only legal to clone a function if a block address within that 322 // function is never referenced outside of the function. Given that, we 323 // want to map block addresses from the old function to block addresses in 324 // the clone. (This is different from the generic ValueMapper 325 // implementation, which generates an invalid blockaddress when 326 // cloning a function.) 327 // 328 // Note that we don't need to fix the mapping for unreachable blocks; 329 // the default mapping there is safe. 330 if (BB->hasAddressTaken()) { 331 Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc), 332 const_cast<BasicBlock*>(BB)); 333 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB); 334 } 335 336 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 337 338 // Loop over all instructions, and copy them over, DCE'ing as we go. This 339 // loop doesn't include the terminator. 340 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); 341 II != IE; ++II) { 342 343 Instruction *NewInst = II->clone(); 344 345 // Eagerly remap operands to the newly cloned instruction, except for PHI 346 // nodes for which we defer processing until we update the CFG. 347 if (!isa<PHINode>(NewInst)) { 348 RemapInstruction(NewInst, VMap, 349 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 350 351 // If we can simplify this instruction to some other value, simply add 352 // a mapping to that value rather than inserting a new instruction into 353 // the basic block. 354 if (Value *V = 355 SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) { 356 // On the off-chance that this simplifies to an instruction in the old 357 // function, map it back into the new function. 358 if (NewFunc != OldFunc) 359 if (Value *MappedV = VMap.lookup(V)) 360 V = MappedV; 361 362 if (!NewInst->mayHaveSideEffects()) { 363 VMap[&*II] = V; 364 NewInst->deleteValue(); 365 continue; 366 } 367 } 368 } 369 370 if (II->hasName()) 371 NewInst->setName(II->getName()+NameSuffix); 372 VMap[&*II] = NewInst; // Add instruction map to value. 373 NewBB->getInstList().push_back(NewInst); 374 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II)); 375 376 if (CodeInfo) 377 if (auto *CB = dyn_cast<CallBase>(&*II)) 378 if (CB->hasOperandBundles()) 379 CodeInfo->OperandBundleCallSites.push_back(NewInst); 380 381 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 382 if (isa<ConstantInt>(AI->getArraySize())) 383 hasStaticAllocas = true; 384 else 385 hasDynamicAllocas = true; 386 } 387 } 388 389 // Finally, clone over the terminator. 390 const Instruction *OldTI = BB->getTerminator(); 391 bool TerminatorDone = false; 392 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) { 393 if (BI->isConditional()) { 394 // If the condition was a known constant in the callee... 395 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 396 // Or is a known constant in the caller... 397 if (!Cond) { 398 Value *V = VMap.lookup(BI->getCondition()); 399 Cond = dyn_cast_or_null<ConstantInt>(V); 400 } 401 402 // Constant fold to uncond branch! 403 if (Cond) { 404 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue()); 405 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 406 ToClone.push_back(Dest); 407 TerminatorDone = true; 408 } 409 } 410 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) { 411 // If switching on a value known constant in the caller. 412 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition()); 413 if (!Cond) { // Or known constant after constant prop in the callee... 414 Value *V = VMap.lookup(SI->getCondition()); 415 Cond = dyn_cast_or_null<ConstantInt>(V); 416 } 417 if (Cond) { // Constant fold to uncond branch! 418 SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond); 419 BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor()); 420 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 421 ToClone.push_back(Dest); 422 TerminatorDone = true; 423 } 424 } 425 426 if (!TerminatorDone) { 427 Instruction *NewInst = OldTI->clone(); 428 if (OldTI->hasName()) 429 NewInst->setName(OldTI->getName()+NameSuffix); 430 NewBB->getInstList().push_back(NewInst); 431 VMap[OldTI] = NewInst; // Add instruction map to value. 432 433 if (CodeInfo) 434 if (auto *CB = dyn_cast<CallBase>(OldTI)) 435 if (CB->hasOperandBundles()) 436 CodeInfo->OperandBundleCallSites.push_back(NewInst); 437 438 // Recursively clone any reachable successor blocks. 439 append_range(ToClone, successors(BB->getTerminator())); 440 } 441 442 if (CodeInfo) { 443 CodeInfo->ContainsCalls |= hasCalls; 444 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 445 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas && 446 BB != &BB->getParent()->front(); 447 } 448 } 449 450 /// This works like CloneAndPruneFunctionInto, except that it does not clone the 451 /// entire function. Instead it starts at an instruction provided by the caller 452 /// and copies (and prunes) only the code reachable from that instruction. 453 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, 454 const Instruction *StartingInst, 455 ValueToValueMapTy &VMap, 456 bool ModuleLevelChanges, 457 SmallVectorImpl<ReturnInst *> &Returns, 458 const char *NameSuffix, 459 ClonedCodeInfo *CodeInfo) { 460 assert(NameSuffix && "NameSuffix cannot be null!"); 461 462 ValueMapTypeRemapper *TypeMapper = nullptr; 463 ValueMaterializer *Materializer = nullptr; 464 465 #ifndef NDEBUG 466 // If the cloning starts at the beginning of the function, verify that 467 // the function arguments are mapped. 468 if (!StartingInst) 469 for (const Argument &II : OldFunc->args()) 470 assert(VMap.count(&II) && "No mapping from source argument specified!"); 471 #endif 472 473 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges, 474 NameSuffix, CodeInfo); 475 const BasicBlock *StartingBB; 476 if (StartingInst) 477 StartingBB = StartingInst->getParent(); 478 else { 479 StartingBB = &OldFunc->getEntryBlock(); 480 StartingInst = &StartingBB->front(); 481 } 482 483 // Clone the entry block, and anything recursively reachable from it. 484 std::vector<const BasicBlock*> CloneWorklist; 485 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist); 486 while (!CloneWorklist.empty()) { 487 const BasicBlock *BB = CloneWorklist.back(); 488 CloneWorklist.pop_back(); 489 PFC.CloneBlock(BB, BB->begin(), CloneWorklist); 490 } 491 492 // Loop over all of the basic blocks in the old function. If the block was 493 // reachable, we have cloned it and the old block is now in the value map: 494 // insert it into the new function in the right order. If not, ignore it. 495 // 496 // Defer PHI resolution until rest of function is resolved. 497 SmallVector<const PHINode*, 16> PHIToResolve; 498 for (const BasicBlock &BI : *OldFunc) { 499 Value *V = VMap.lookup(&BI); 500 BasicBlock *NewBB = cast_or_null<BasicBlock>(V); 501 if (!NewBB) continue; // Dead block. 502 503 // Add the new block to the new function. 504 NewFunc->getBasicBlockList().push_back(NewBB); 505 506 // Handle PHI nodes specially, as we have to remove references to dead 507 // blocks. 508 for (const PHINode &PN : BI.phis()) { 509 // PHI nodes may have been remapped to non-PHI nodes by the caller or 510 // during the cloning process. 511 if (isa<PHINode>(VMap[&PN])) 512 PHIToResolve.push_back(&PN); 513 else 514 break; 515 } 516 517 // Finally, remap the terminator instructions, as those can't be remapped 518 // until all BBs are mapped. 519 RemapInstruction(NewBB->getTerminator(), VMap, 520 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 521 TypeMapper, Materializer); 522 } 523 524 // Defer PHI resolution until rest of function is resolved, PHI resolution 525 // requires the CFG to be up-to-date. 526 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) { 527 const PHINode *OPN = PHIToResolve[phino]; 528 unsigned NumPreds = OPN->getNumIncomingValues(); 529 const BasicBlock *OldBB = OPN->getParent(); 530 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]); 531 532 // Map operands for blocks that are live and remove operands for blocks 533 // that are dead. 534 for (; phino != PHIToResolve.size() && 535 PHIToResolve[phino]->getParent() == OldBB; ++phino) { 536 OPN = PHIToResolve[phino]; 537 PHINode *PN = cast<PHINode>(VMap[OPN]); 538 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) { 539 Value *V = VMap.lookup(PN->getIncomingBlock(pred)); 540 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) { 541 Value *InVal = MapValue(PN->getIncomingValue(pred), 542 VMap, 543 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 544 assert(InVal && "Unknown input value?"); 545 PN->setIncomingValue(pred, InVal); 546 PN->setIncomingBlock(pred, MappedBlock); 547 } else { 548 PN->removeIncomingValue(pred, false); 549 --pred; // Revisit the next entry. 550 --e; 551 } 552 } 553 } 554 555 // The loop above has removed PHI entries for those blocks that are dead 556 // and has updated others. However, if a block is live (i.e. copied over) 557 // but its terminator has been changed to not go to this block, then our 558 // phi nodes will have invalid entries. Update the PHI nodes in this 559 // case. 560 PHINode *PN = cast<PHINode>(NewBB->begin()); 561 NumPreds = pred_size(NewBB); 562 if (NumPreds != PN->getNumIncomingValues()) { 563 assert(NumPreds < PN->getNumIncomingValues()); 564 // Count how many times each predecessor comes to this block. 565 std::map<BasicBlock*, unsigned> PredCount; 566 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); 567 PI != E; ++PI) 568 --PredCount[*PI]; 569 570 // Figure out how many entries to remove from each PHI. 571 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 572 ++PredCount[PN->getIncomingBlock(i)]; 573 574 // At this point, the excess predecessor entries are positive in the 575 // map. Loop over all of the PHIs and remove excess predecessor 576 // entries. 577 BasicBlock::iterator I = NewBB->begin(); 578 for (; (PN = dyn_cast<PHINode>(I)); ++I) { 579 for (const auto &PCI : PredCount) { 580 BasicBlock *Pred = PCI.first; 581 for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove) 582 PN->removeIncomingValue(Pred, false); 583 } 584 } 585 } 586 587 // If the loops above have made these phi nodes have 0 or 1 operand, 588 // replace them with undef or the input value. We must do this for 589 // correctness, because 0-operand phis are not valid. 590 PN = cast<PHINode>(NewBB->begin()); 591 if (PN->getNumIncomingValues() == 0) { 592 BasicBlock::iterator I = NewBB->begin(); 593 BasicBlock::const_iterator OldI = OldBB->begin(); 594 while ((PN = dyn_cast<PHINode>(I++))) { 595 Value *NV = UndefValue::get(PN->getType()); 596 PN->replaceAllUsesWith(NV); 597 assert(VMap[&*OldI] == PN && "VMap mismatch"); 598 VMap[&*OldI] = NV; 599 PN->eraseFromParent(); 600 ++OldI; 601 } 602 } 603 } 604 605 // Make a second pass over the PHINodes now that all of them have been 606 // remapped into the new function, simplifying the PHINode and performing any 607 // recursive simplifications exposed. This will transparently update the 608 // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce 609 // two PHINodes, the iteration over the old PHIs remains valid, and the 610 // mapping will just map us to the new node (which may not even be a PHI 611 // node). 612 const DataLayout &DL = NewFunc->getParent()->getDataLayout(); 613 SmallSetVector<const Value *, 8> Worklist; 614 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx) 615 if (isa<PHINode>(VMap[PHIToResolve[Idx]])) 616 Worklist.insert(PHIToResolve[Idx]); 617 618 // Note that we must test the size on each iteration, the worklist can grow. 619 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 620 const Value *OrigV = Worklist[Idx]; 621 auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV)); 622 if (!I) 623 continue; 624 625 // Skip over non-intrinsic callsites, we don't want to remove any nodes from 626 // the CGSCC. 627 CallBase *CB = dyn_cast<CallBase>(I); 628 if (CB && CB->getCalledFunction() && 629 !CB->getCalledFunction()->isIntrinsic()) 630 continue; 631 632 // See if this instruction simplifies. 633 Value *SimpleV = SimplifyInstruction(I, DL); 634 if (!SimpleV) 635 continue; 636 637 // Stash away all the uses of the old instruction so we can check them for 638 // recursive simplifications after a RAUW. This is cheaper than checking all 639 // uses of To on the recursive step in most cases. 640 for (const User *U : OrigV->users()) 641 Worklist.insert(cast<Instruction>(U)); 642 643 // Replace the instruction with its simplified value. 644 I->replaceAllUsesWith(SimpleV); 645 646 // If the original instruction had no side effects, remove it. 647 if (isInstructionTriviallyDead(I)) 648 I->eraseFromParent(); 649 else 650 VMap[OrigV] = I; 651 } 652 653 // Now that the inlined function body has been fully constructed, go through 654 // and zap unconditional fall-through branches. This happens all the time when 655 // specializing code: code specialization turns conditional branches into 656 // uncond branches, and this code folds them. 657 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator(); 658 Function::iterator I = Begin; 659 while (I != NewFunc->end()) { 660 // We need to simplify conditional branches and switches with a constant 661 // operand. We try to prune these out when cloning, but if the 662 // simplification required looking through PHI nodes, those are only 663 // available after forming the full basic block. That may leave some here, 664 // and we still want to prune the dead code as early as possible. 665 // 666 // Do the folding before we check if the block is dead since we want code 667 // like 668 // bb: 669 // br i1 undef, label %bb, label %bb 670 // to be simplified to 671 // bb: 672 // br label %bb 673 // before we call I->getSinglePredecessor(). 674 ConstantFoldTerminator(&*I); 675 676 // Check if this block has become dead during inlining or other 677 // simplifications. Note that the first block will appear dead, as it has 678 // not yet been wired up properly. 679 if (I != Begin && (pred_empty(&*I) || 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 888 void llvm::cloneNoAliasScopes( 889 ArrayRef<MDNode *> NoAliasDeclScopes, 890 DenseMap<MDNode *, MDNode *> &ClonedScopes, 891 StringRef Ext, LLVMContext &Context) { 892 MDBuilder MDB(Context); 893 894 for (auto *ScopeList : NoAliasDeclScopes) { 895 for (auto &MDOperand : ScopeList->operands()) { 896 if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) { 897 AliasScopeNode SNANode(MD); 898 899 std::string Name; 900 auto ScopeName = SNANode.getName(); 901 if (!ScopeName.empty()) 902 Name = (Twine(ScopeName) + ":" + Ext).str(); 903 else 904 Name = std::string(Ext); 905 906 MDNode *NewScope = MDB.createAnonymousAliasScope( 907 const_cast<MDNode *>(SNANode.getDomain()), Name); 908 ClonedScopes.insert(std::make_pair(MD, NewScope)); 909 } 910 } 911 } 912 } 913 914 void llvm::adaptNoAliasScopes( 915 Instruction *I, const DenseMap<MDNode *, MDNode *> &ClonedScopes, 916 LLVMContext &Context) { 917 auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * { 918 bool NeedsReplacement = false; 919 SmallVector<Metadata *, 8> NewScopeList; 920 for (auto &MDOp : ScopeList->operands()) { 921 if (MDNode *MD = dyn_cast<MDNode>(MDOp)) { 922 if (auto *NewMD = ClonedScopes.lookup(MD)) { 923 NewScopeList.push_back(NewMD); 924 NeedsReplacement = true; 925 continue; 926 } 927 NewScopeList.push_back(MD); 928 } 929 } 930 if (NeedsReplacement) 931 return MDNode::get(Context, NewScopeList); 932 return nullptr; 933 }; 934 935 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I)) 936 if (auto *NewScopeList = CloneScopeList(Decl->getScopeList())) 937 Decl->setScopeList(NewScopeList); 938 939 auto replaceWhenNeeded = [&](unsigned MD_ID) { 940 if (const MDNode *CSNoAlias = I->getMetadata(MD_ID)) 941 if (auto *NewScopeList = CloneScopeList(CSNoAlias)) 942 I->setMetadata(MD_ID, NewScopeList); 943 }; 944 replaceWhenNeeded(LLVMContext::MD_noalias); 945 replaceWhenNeeded(LLVMContext::MD_alias_scope); 946 } 947 948 void llvm::cloneAndAdaptNoAliasScopes( 949 ArrayRef<MDNode *> NoAliasDeclScopes, 950 ArrayRef<BasicBlock *> NewBlocks, LLVMContext &Context, StringRef Ext) { 951 if (NoAliasDeclScopes.empty()) 952 return; 953 954 DenseMap<MDNode *, MDNode *> ClonedScopes; 955 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning " 956 << NoAliasDeclScopes.size() << " node(s)\n"); 957 958 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context); 959 // Identify instructions using metadata that needs adaptation 960 for (BasicBlock *NewBlock : NewBlocks) 961 for (Instruction &I : *NewBlock) 962 adaptNoAliasScopes(&I, ClonedScopes, Context); 963 } 964 965 void llvm::cloneAndAdaptNoAliasScopes( 966 ArrayRef<MDNode *> NoAliasDeclScopes, Instruction *IStart, 967 Instruction *IEnd, LLVMContext &Context, StringRef Ext) { 968 if (NoAliasDeclScopes.empty()) 969 return; 970 971 DenseMap<MDNode *, MDNode *> ClonedScopes; 972 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning " 973 << NoAliasDeclScopes.size() << " node(s)\n"); 974 975 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context); 976 // Identify instructions using metadata that needs adaptation 977 assert(IStart->getParent() == IEnd->getParent() && "different basic block ?"); 978 auto ItStart = IStart->getIterator(); 979 auto ItEnd = IEnd->getIterator(); 980 ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range 981 for (auto &I : llvm::make_range(ItStart, ItEnd)) 982 adaptNoAliasScopes(&I, ClonedScopes, Context); 983 } 984 985 void llvm::identifyNoAliasScopesToClone( 986 ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) { 987 for (BasicBlock *BB : BBs) 988 for (Instruction &I : *BB) 989 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 990 NoAliasDeclScopes.push_back(Decl->getScopeList()); 991 } 992 993 void llvm::identifyNoAliasScopesToClone( 994 BasicBlock::iterator Start, BasicBlock::iterator End, 995 SmallVectorImpl<MDNode *> &NoAliasDeclScopes) { 996 for (Instruction &I : make_range(Start, End)) 997 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 998 NoAliasDeclScopes.push_back(Decl->getScopeList()); 999 } 1000