CloneFunction.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. #include "llvm/Transforms/Utils/Cloning.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/ConstantFolding.h"
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/IR/CFG.h"
  20. #include "llvm/IR/Constants.h"
  21. #include "llvm/IR/DebugInfo.h"
  22. #include "llvm/IR/DerivedTypes.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/GlobalVariable.h"
  25. #include "llvm/IR/Instructions.h"
  26. #include "llvm/IR/IntrinsicInst.h"
  27. #include "llvm/IR/LLVMContext.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  31. #include "llvm/Transforms/Utils/Local.h"
  32. #include "llvm/Transforms/Utils/ValueMapper.h"
  33. #include <map>
  34. using namespace llvm;
  35. /// See comments in Cloning.h.
  36. BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
  37. ValueToValueMapTy &VMap,
  38. const Twine &NameSuffix, Function *F,
  39. ClonedCodeInfo *CodeInfo) {
  40. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
  41. if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
  42. bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
  43. // Loop over all instructions, and copy them over.
  44. for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
  45. II != IE; ++II) {
  46. Instruction *NewInst = II->clone();
  47. if (II->hasName())
  48. NewInst->setName(II->getName()+NameSuffix);
  49. NewBB->getInstList().push_back(NewInst);
  50. VMap[II] = NewInst; // Add instruction map to value.
  51. hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
  52. if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  53. if (isa<ConstantInt>(AI->getArraySize()))
  54. hasStaticAllocas = true;
  55. else
  56. hasDynamicAllocas = true;
  57. }
  58. }
  59. if (CodeInfo) {
  60. CodeInfo->ContainsCalls |= hasCalls;
  61. CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
  62. CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
  63. BB != &BB->getParent()->getEntryBlock();
  64. }
  65. return NewBB;
  66. }
  67. // Clone OldFunc into NewFunc, transforming the old arguments into references to
  68. // VMap values.
  69. //
  70. void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
  71. ValueToValueMapTy &VMap,
  72. bool ModuleLevelChanges,
  73. SmallVectorImpl<ReturnInst*> &Returns,
  74. const char *NameSuffix, ClonedCodeInfo *CodeInfo,
  75. ValueMapTypeRemapper *TypeMapper,
  76. ValueMaterializer *Materializer) {
  77. assert(NameSuffix && "NameSuffix cannot be null!");
  78. #ifndef NDEBUG
  79. for (Function::const_arg_iterator I = OldFunc->arg_begin(),
  80. E = OldFunc->arg_end(); I != E; ++I)
  81. assert(VMap.count(I) && "No mapping from source argument specified!");
  82. #endif
  83. // Copy all attributes other than those stored in the AttributeSet. We need
  84. // to remap the parameter indices of the AttributeSet.
  85. AttributeSet NewAttrs = NewFunc->getAttributes();
  86. NewFunc->copyAttributesFrom(OldFunc);
  87. NewFunc->setAttributes(NewAttrs);
  88. AttributeSet OldAttrs = OldFunc->getAttributes();
  89. // Clone any argument attributes that are present in the VMap.
  90. for (const Argument &OldArg : OldFunc->args())
  91. if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
  92. AttributeSet attrs =
  93. OldAttrs.getParamAttributes(OldArg.getArgNo() + 1);
  94. if (attrs.getNumSlots() > 0)
  95. NewArg->addAttr(attrs);
  96. }
  97. NewFunc->setAttributes(
  98. NewFunc->getAttributes()
  99. .addAttributes(NewFunc->getContext(), AttributeSet::ReturnIndex,
  100. OldAttrs.getRetAttributes())
  101. .addAttributes(NewFunc->getContext(), AttributeSet::FunctionIndex,
  102. OldAttrs.getFnAttributes()));
  103. // Loop over all of the basic blocks in the function, cloning them as
  104. // appropriate. Note that we save BE this way in order to handle cloning of
  105. // recursive functions into themselves.
  106. //
  107. for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
  108. BI != BE; ++BI) {
  109. const BasicBlock &BB = *BI;
  110. // Create a new basic block and copy instructions into it!
  111. BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
  112. // Add basic block mapping.
  113. VMap[&BB] = CBB;
  114. // It is only legal to clone a function if a block address within that
  115. // function is never referenced outside of the function. Given that, we
  116. // want to map block addresses from the old function to block addresses in
  117. // the clone. (This is different from the generic ValueMapper
  118. // implementation, which generates an invalid blockaddress when
  119. // cloning a function.)
  120. if (BB.hasAddressTaken()) {
  121. Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
  122. const_cast<BasicBlock*>(&BB));
  123. VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
  124. }
  125. // Note return instructions for the caller.
  126. if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
  127. Returns.push_back(RI);
  128. }
  129. // Loop over all of the instructions in the function, fixing up operand
  130. // references as we go. This uses VMap to do all the hard work.
  131. for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
  132. BE = NewFunc->end(); BB != BE; ++BB)
  133. // Loop over all instructions, fixing each one as we find it...
  134. for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
  135. RemapInstruction(II, VMap,
  136. ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
  137. TypeMapper, Materializer);
  138. }
  139. // Find the MDNode which corresponds to the DISubprogram data that described F.
  140. static MDNode* FindSubprogram(const Function *F, DebugInfoFinder &Finder) {
  141. for (DISubprogram Subprogram : Finder.subprograms()) {
  142. if (Subprogram->describes(F))
  143. return Subprogram;
  144. }
  145. return nullptr;
  146. }
  147. // Add an operand to an existing MDNode. The new operand will be added at the
  148. // back of the operand list.
  149. static void AddOperand(DICompileUnit CU, MDSubprogramArray SPs, Metadata *NewSP) {
  150. SmallVector<Metadata *, 16> NewSPs;
  151. NewSPs.reserve(SPs.size() + 1);
  152. for (auto *SP : SPs)
  153. NewSPs.push_back(SP);
  154. NewSPs.push_back(NewSP);
  155. CU.replaceSubprograms(DIArray(MDNode::get(CU->getContext(), NewSPs)));
  156. }
  157. // Clone the module-level debug info associated with OldFunc. The cloned data
  158. // will point to NewFunc instead.
  159. static void CloneDebugInfoMetadata(Function *NewFunc, const Function *OldFunc,
  160. ValueToValueMapTy &VMap) {
  161. DebugInfoFinder Finder;
  162. Finder.processModule(*OldFunc->getParent());
  163. const MDNode *OldSubprogramMDNode = FindSubprogram(OldFunc, Finder);
  164. if (!OldSubprogramMDNode) return;
  165. // Ensure that OldFunc appears in the map.
  166. // (if it's already there it must point to NewFunc anyway)
  167. VMap[OldFunc] = NewFunc;
  168. DISubprogram NewSubprogram =
  169. cast<MDSubprogram>(MapMetadata(OldSubprogramMDNode, VMap));
  170. for (DICompileUnit CU : Finder.compile_units()) {
  171. auto Subprograms = CU->getSubprograms();
  172. // If the compile unit's function list contains the old function, it should
  173. // also contain the new one.
  174. for (auto *SP : Subprograms) {
  175. if (SP == OldSubprogramMDNode) {
  176. AddOperand(CU, Subprograms, NewSubprogram);
  177. break;
  178. }
  179. }
  180. }
  181. }
  182. /// Return a copy of the specified function, but without
  183. /// embedding the function into another module. Also, any references specified
  184. /// in the VMap are changed to refer to their mapped value instead of the
  185. /// original one. If any of the arguments to the function are in the VMap,
  186. /// the arguments are deleted from the resultant function. The VMap is
  187. /// updated to include mappings from all of the instructions and basicblocks in
  188. /// the function from their old to new values.
  189. ///
  190. Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
  191. bool ModuleLevelChanges,
  192. ClonedCodeInfo *CodeInfo) {
  193. std::vector<Type*> ArgTypes;
  194. // The user might be deleting arguments to the function by specifying them in
  195. // the VMap. If so, we need to not add the arguments to the arg ty vector
  196. //
  197. for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  198. I != E; ++I)
  199. if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
  200. ArgTypes.push_back(I->getType());
  201. // Create a new function type...
  202. FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
  203. ArgTypes, F->getFunctionType()->isVarArg());
  204. // Create the new function...
  205. Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
  206. // Loop over the arguments, copying the names of the mapped arguments over...
  207. Function::arg_iterator DestI = NewF->arg_begin();
  208. for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  209. I != E; ++I)
  210. if (VMap.count(I) == 0) { // Is this argument preserved?
  211. DestI->setName(I->getName()); // Copy the name over...
  212. VMap[I] = DestI++; // Add mapping to VMap
  213. }
  214. if (ModuleLevelChanges)
  215. CloneDebugInfoMetadata(NewF, F, VMap);
  216. SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
  217. CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
  218. return NewF;
  219. }
  220. namespace {
  221. /// This is a private class used to implement CloneAndPruneFunctionInto.
  222. struct PruningFunctionCloner {
  223. Function *NewFunc;
  224. const Function *OldFunc;
  225. ValueToValueMapTy &VMap;
  226. bool ModuleLevelChanges;
  227. const char *NameSuffix;
  228. ClonedCodeInfo *CodeInfo;
  229. CloningDirector *Director;
  230. ValueMapTypeRemapper *TypeMapper;
  231. ValueMaterializer *Materializer;
  232. public:
  233. PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
  234. ValueToValueMapTy &valueMap, bool moduleLevelChanges,
  235. const char *nameSuffix, ClonedCodeInfo *codeInfo,
  236. CloningDirector *Director)
  237. : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
  238. ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
  239. CodeInfo(codeInfo), Director(Director) {
  240. // These are optional components. The Director may return null.
  241. if (Director) {
  242. TypeMapper = Director->getTypeRemapper();
  243. Materializer = Director->getValueMaterializer();
  244. } else {
  245. TypeMapper = nullptr;
  246. Materializer = nullptr;
  247. }
  248. }
  249. /// The specified block is found to be reachable, clone it and
  250. /// anything that it can reach.
  251. void CloneBlock(const BasicBlock *BB,
  252. BasicBlock::const_iterator StartingInst,
  253. std::vector<const BasicBlock*> &ToClone);
  254. };
  255. }
  256. /// The specified block is found to be reachable, clone it and
  257. /// anything that it can reach.
  258. void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
  259. BasicBlock::const_iterator StartingInst,
  260. std::vector<const BasicBlock*> &ToClone){
  261. WeakVH &BBEntry = VMap[BB];
  262. // Have we already cloned this block?
  263. if (BBEntry) return;
  264. // Nope, clone it now.
  265. BasicBlock *NewBB;
  266. BBEntry = NewBB = BasicBlock::Create(BB->getContext());
  267. if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
  268. // It is only legal to clone a function if a block address within that
  269. // function is never referenced outside of the function. Given that, we
  270. // want to map block addresses from the old function to block addresses in
  271. // the clone. (This is different from the generic ValueMapper
  272. // implementation, which generates an invalid blockaddress when
  273. // cloning a function.)
  274. //
  275. // Note that we don't need to fix the mapping for unreachable blocks;
  276. // the default mapping there is safe.
  277. if (BB->hasAddressTaken()) {
  278. Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
  279. const_cast<BasicBlock*>(BB));
  280. VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
  281. }
  282. bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
  283. // Loop over all instructions, and copy them over, DCE'ing as we go. This
  284. // loop doesn't include the terminator.
  285. for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
  286. II != IE; ++II) {
  287. // If the "Director" remaps the instruction, don't clone it.
  288. if (Director) {
  289. CloningDirector::CloningAction Action
  290. = Director->handleInstruction(VMap, II, NewBB);
  291. // If the cloning director says stop, we want to stop everything, not
  292. // just break out of the loop (which would cause the terminator to be
  293. // cloned). The cloning director is responsible for inserting a proper
  294. // terminator into the new basic block in this case.
  295. if (Action == CloningDirector::StopCloningBB)
  296. return;
  297. // If the cloning director says skip, continue to the next instruction.
  298. // In this case, the cloning director is responsible for mapping the
  299. // skipped instruction to some value that is defined in the new
  300. // basic block.
  301. if (Action == CloningDirector::SkipInstruction)
  302. continue;
  303. }
  304. Instruction *NewInst = II->clone();
  305. // Eagerly remap operands to the newly cloned instruction, except for PHI
  306. // nodes for which we defer processing until we update the CFG.
  307. if (!isa<PHINode>(NewInst)) {
  308. RemapInstruction(NewInst, VMap,
  309. ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
  310. TypeMapper, Materializer);
  311. // If we can simplify this instruction to some other value, simply add
  312. // a mapping to that value rather than inserting a new instruction into
  313. // the basic block.
  314. if (Value *V =
  315. SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
  316. // On the off-chance that this simplifies to an instruction in the old
  317. // function, map it back into the new function.
  318. if (Value *MappedV = VMap.lookup(V))
  319. V = MappedV;
  320. VMap[II] = V;
  321. delete NewInst;
  322. continue;
  323. }
  324. }
  325. if (II->hasName())
  326. NewInst->setName(II->getName()+NameSuffix);
  327. VMap[II] = NewInst; // Add instruction map to value.
  328. NewBB->getInstList().push_back(NewInst);
  329. hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
  330. if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  331. if (isa<ConstantInt>(AI->getArraySize()))
  332. hasStaticAllocas = true;
  333. else
  334. hasDynamicAllocas = true;
  335. }
  336. }
  337. // Finally, clone over the terminator.
  338. const TerminatorInst *OldTI = BB->getTerminator();
  339. bool TerminatorDone = false;
  340. if (Director) {
  341. CloningDirector::CloningAction Action
  342. = Director->handleInstruction(VMap, OldTI, NewBB);
  343. // If the cloning director says stop, we want to stop everything, not
  344. // just break out of the loop (which would cause the terminator to be
  345. // cloned). The cloning director is responsible for inserting a proper
  346. // terminator into the new basic block in this case.
  347. if (Action == CloningDirector::StopCloningBB)
  348. return;
  349. if (Action == CloningDirector::CloneSuccessors) {
  350. // If the director says to skip with a terminate instruction, we still
  351. // need to clone this block's successors.
  352. const TerminatorInst *TI = NewBB->getTerminator();
  353. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  354. ToClone.push_back(TI->getSuccessor(i));
  355. return;
  356. }
  357. assert(Action != CloningDirector::SkipInstruction &&
  358. "SkipInstruction is not valid for terminators.");
  359. }
  360. if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
  361. if (BI->isConditional()) {
  362. // If the condition was a known constant in the callee...
  363. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  364. // Or is a known constant in the caller...
  365. if (!Cond) {
  366. Value *V = VMap[BI->getCondition()];
  367. Cond = dyn_cast_or_null<ConstantInt>(V);
  368. }
  369. // Constant fold to uncond branch!
  370. if (Cond) {
  371. BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
  372. VMap[OldTI] = BranchInst::Create(Dest, NewBB);
  373. ToClone.push_back(Dest);
  374. TerminatorDone = true;
  375. }
  376. }
  377. } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
  378. // If switching on a value known constant in the caller.
  379. ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
  380. if (!Cond) { // Or known constant after constant prop in the callee...
  381. Value *V = VMap[SI->getCondition()];
  382. Cond = dyn_cast_or_null<ConstantInt>(V);
  383. }
  384. if (Cond) { // Constant fold to uncond branch!
  385. SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
  386. BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
  387. VMap[OldTI] = BranchInst::Create(Dest, NewBB);
  388. ToClone.push_back(Dest);
  389. TerminatorDone = true;
  390. }
  391. }
  392. if (!TerminatorDone) {
  393. Instruction *NewInst = OldTI->clone();
  394. if (OldTI->hasName())
  395. NewInst->setName(OldTI->getName()+NameSuffix);
  396. NewBB->getInstList().push_back(NewInst);
  397. VMap[OldTI] = NewInst; // Add instruction map to value.
  398. // Recursively clone any reachable successor blocks.
  399. const TerminatorInst *TI = BB->getTerminator();
  400. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  401. ToClone.push_back(TI->getSuccessor(i));
  402. }
  403. if (CodeInfo) {
  404. CodeInfo->ContainsCalls |= hasCalls;
  405. CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
  406. CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
  407. BB != &BB->getParent()->front();
  408. }
  409. }
  410. /// This works like CloneAndPruneFunctionInto, except that it does not clone the
  411. /// entire function. Instead it starts at an instruction provided by the caller
  412. /// and copies (and prunes) only the code reachable from that instruction.
  413. void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
  414. const Instruction *StartingInst,
  415. ValueToValueMapTy &VMap,
  416. bool ModuleLevelChanges,
  417. SmallVectorImpl<ReturnInst *> &Returns,
  418. const char *NameSuffix,
  419. ClonedCodeInfo *CodeInfo,
  420. CloningDirector *Director) {
  421. assert(NameSuffix && "NameSuffix cannot be null!");
  422. ValueMapTypeRemapper *TypeMapper = nullptr;
  423. ValueMaterializer *Materializer = nullptr;
  424. if (Director) {
  425. TypeMapper = Director->getTypeRemapper();
  426. Materializer = Director->getValueMaterializer();
  427. }
  428. #ifndef NDEBUG
  429. // If the cloning starts at the begining of the function, verify that
  430. // the function arguments are mapped.
  431. if (!StartingInst)
  432. for (Function::const_arg_iterator II = OldFunc->arg_begin(),
  433. E = OldFunc->arg_end(); II != E; ++II)
  434. assert(VMap.count(II) && "No mapping from source argument specified!");
  435. #endif
  436. PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
  437. NameSuffix, CodeInfo, Director);
  438. const BasicBlock *StartingBB;
  439. if (StartingInst)
  440. StartingBB = StartingInst->getParent();
  441. else {
  442. StartingBB = &OldFunc->getEntryBlock();
  443. StartingInst = StartingBB->begin();
  444. }
  445. // Clone the entry block, and anything recursively reachable from it.
  446. std::vector<const BasicBlock*> CloneWorklist;
  447. PFC.CloneBlock(StartingBB, StartingInst, CloneWorklist);
  448. while (!CloneWorklist.empty()) {
  449. const BasicBlock *BB = CloneWorklist.back();
  450. CloneWorklist.pop_back();
  451. PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
  452. }
  453. // Loop over all of the basic blocks in the old function. If the block was
  454. // reachable, we have cloned it and the old block is now in the value map:
  455. // insert it into the new function in the right order. If not, ignore it.
  456. //
  457. // Defer PHI resolution until rest of function is resolved.
  458. SmallVector<const PHINode*, 16> PHIToResolve;
  459. for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
  460. BI != BE; ++BI) {
  461. Value *V = VMap[BI];
  462. BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
  463. if (!NewBB) continue; // Dead block.
  464. // Add the new block to the new function.
  465. NewFunc->getBasicBlockList().push_back(NewBB);
  466. // Handle PHI nodes specially, as we have to remove references to dead
  467. // blocks.
  468. for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
  469. // PHI nodes may have been remapped to non-PHI nodes by the caller or
  470. // during the cloning process.
  471. if (const PHINode *PN = dyn_cast<PHINode>(I)) {
  472. if (isa<PHINode>(VMap[PN]))
  473. PHIToResolve.push_back(PN);
  474. else
  475. break;
  476. } else {
  477. break;
  478. }
  479. }
  480. // Finally, remap the terminator instructions, as those can't be remapped
  481. // until all BBs are mapped.
  482. RemapInstruction(NewBB->getTerminator(), VMap,
  483. ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
  484. TypeMapper, Materializer);
  485. }
  486. // Defer PHI resolution until rest of function is resolved, PHI resolution
  487. // requires the CFG to be up-to-date.
  488. for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
  489. const PHINode *OPN = PHIToResolve[phino];
  490. unsigned NumPreds = OPN->getNumIncomingValues();
  491. const BasicBlock *OldBB = OPN->getParent();
  492. BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
  493. // Map operands for blocks that are live and remove operands for blocks
  494. // that are dead.
  495. for (; phino != PHIToResolve.size() &&
  496. PHIToResolve[phino]->getParent() == OldBB; ++phino) {
  497. OPN = PHIToResolve[phino];
  498. PHINode *PN = cast<PHINode>(VMap[OPN]);
  499. for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
  500. Value *V = VMap[PN->getIncomingBlock(pred)];
  501. if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
  502. Value *InVal = MapValue(PN->getIncomingValue(pred),
  503. VMap,
  504. ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
  505. assert(InVal && "Unknown input value?");
  506. PN->setIncomingValue(pred, InVal);
  507. PN->setIncomingBlock(pred, MappedBlock);
  508. } else {
  509. PN->removeIncomingValue(pred, false);
  510. --pred, --e; // Revisit the next entry.
  511. }
  512. }
  513. }
  514. // The loop above has removed PHI entries for those blocks that are dead
  515. // and has updated others. However, if a block is live (i.e. copied over)
  516. // but its terminator has been changed to not go to this block, then our
  517. // phi nodes will have invalid entries. Update the PHI nodes in this
  518. // case.
  519. PHINode *PN = cast<PHINode>(NewBB->begin());
  520. NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
  521. if (NumPreds != PN->getNumIncomingValues()) {
  522. assert(NumPreds < PN->getNumIncomingValues());
  523. // Count how many times each predecessor comes to this block.
  524. std::map<BasicBlock*, unsigned> PredCount;
  525. for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
  526. PI != E; ++PI)
  527. --PredCount[*PI];
  528. // Figure out how many entries to remove from each PHI.
  529. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  530. ++PredCount[PN->getIncomingBlock(i)];
  531. // At this point, the excess predecessor entries are positive in the
  532. // map. Loop over all of the PHIs and remove excess predecessor
  533. // entries.
  534. BasicBlock::iterator I = NewBB->begin();
  535. for (; (PN = dyn_cast<PHINode>(I)); ++I) {
  536. for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
  537. E = PredCount.end(); PCI != E; ++PCI) {
  538. BasicBlock *Pred = PCI->first;
  539. for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
  540. PN->removeIncomingValue(Pred, false);
  541. }
  542. }
  543. }
  544. // If the loops above have made these phi nodes have 0 or 1 operand,
  545. // replace them with undef or the input value. We must do this for
  546. // correctness, because 0-operand phis are not valid.
  547. PN = cast<PHINode>(NewBB->begin());
  548. if (PN->getNumIncomingValues() == 0) {
  549. BasicBlock::iterator I = NewBB->begin();
  550. BasicBlock::const_iterator OldI = OldBB->begin();
  551. while ((PN = dyn_cast<PHINode>(I++))) {
  552. Value *NV = UndefValue::get(PN->getType());
  553. PN->replaceAllUsesWith(NV);
  554. assert(VMap[OldI] == PN && "VMap mismatch");
  555. VMap[OldI] = NV;
  556. PN->eraseFromParent();
  557. ++OldI;
  558. }
  559. }
  560. }
  561. // Make a second pass over the PHINodes now that all of them have been
  562. // remapped into the new function, simplifying the PHINode and performing any
  563. // recursive simplifications exposed. This will transparently update the
  564. // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
  565. // two PHINodes, the iteration over the old PHIs remains valid, and the
  566. // mapping will just map us to the new node (which may not even be a PHI
  567. // node).
  568. for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
  569. if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
  570. recursivelySimplifyInstruction(PN);
  571. // Now that the inlined function body has been fully constructed, go through
  572. // and zap unconditional fall-through branches. This happens all the time when
  573. // specializing code: code specialization turns conditional branches into
  574. // uncond branches, and this code folds them.
  575. Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB]);
  576. Function::iterator I = Begin;
  577. while (I != NewFunc->end()) {
  578. // Check if this block has become dead during inlining or other
  579. // simplifications. Note that the first block will appear dead, as it has
  580. // not yet been wired up properly.
  581. if (I != Begin && (pred_begin(I) == pred_end(I) ||
  582. I->getSinglePredecessor() == I)) {
  583. BasicBlock *DeadBB = I++;
  584. DeleteDeadBlock(DeadBB);
  585. continue;
  586. }
  587. // We need to simplify conditional branches and switches with a constant
  588. // operand. We try to prune these out when cloning, but if the
  589. // simplification required looking through PHI nodes, those are only
  590. // available after forming the full basic block. That may leave some here,
  591. // and we still want to prune the dead code as early as possible.
  592. ConstantFoldTerminator(I);
  593. BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
  594. if (!BI || BI->isConditional()) { ++I; continue; }
  595. BasicBlock *Dest = BI->getSuccessor(0);
  596. if (!Dest->getSinglePredecessor()) {
  597. ++I; continue;
  598. }
  599. // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
  600. // above should have zapped all of them..
  601. assert(!isa<PHINode>(Dest->begin()));
  602. // We know all single-entry PHI nodes in the inlined function have been
  603. // removed, so we just need to splice the blocks.
  604. BI->eraseFromParent();
  605. // Make all PHI nodes that referred to Dest now refer to I as their source.
  606. Dest->replaceAllUsesWith(I);
  607. // Move all the instructions in the succ to the pred.
  608. I->getInstList().splice(I->end(), Dest->getInstList());
  609. // Remove the dest block.
  610. Dest->eraseFromParent();
  611. // Do not increment I, iteratively merge all things this block branches to.
  612. }
  613. // Make a final pass over the basic blocks from the old function to gather
  614. // any return instructions which survived folding. We have to do this here
  615. // because we can iteratively remove and merge returns above.
  616. for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB]),
  617. E = NewFunc->end();
  618. I != E; ++I)
  619. if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
  620. Returns.push_back(RI);
  621. }
  622. /// This works exactly like CloneFunctionInto,
  623. /// except that it does some simple constant prop and DCE on the fly. The
  624. /// effect of this is to copy significantly less code in cases where (for
  625. /// example) a function call with constant arguments is inlined, and those
  626. /// constant arguments cause a significant amount of code in the callee to be
  627. /// dead. Since this doesn't produce an exact copy of the input, it can't be
  628. /// used for things like CloneFunction or CloneModule.
  629. void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
  630. ValueToValueMapTy &VMap,
  631. bool ModuleLevelChanges,
  632. SmallVectorImpl<ReturnInst*> &Returns,
  633. const char *NameSuffix,
  634. ClonedCodeInfo *CodeInfo,
  635. Instruction *TheCall) {
  636. CloneAndPruneIntoFromInst(NewFunc, OldFunc, OldFunc->front().begin(), VMap,
  637. ModuleLevelChanges, Returns, NameSuffix, CodeInfo,
  638. nullptr);
  639. }