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