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