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