46 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
53 NewInst->
setName(II->getName()+NameSuffix);
57 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
58 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
59 if (isa<ConstantInt>(AI->getArraySize()))
60 hasStaticAllocas =
true;
62 hasDynamicAllocas =
true;
80 bool ModuleLevelChanges,
85 assert(NameSuffix &&
"NameSuffix cannot be null!");
90 assert(VMap.
count(
I) &&
"No mapping from source argument specified!");
102 if (
Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
106 NewArg->addAttr(attrs);
138 const_cast<BasicBlock*>(&BB));
150 BE = NewFunc->
end(); BB != BE; ++BB)
155 TypeMapper, Materializer);
162 if (Subprogram->describes(F))
173 NewSPs.
reserve(SPs.size() + 1);
188 if (!OldSubprogramMDNode)
return;
192 VMap[OldFunc] = NewFunc;
193 auto *NewSubprogram =
194 cast<DISubprogram>(
MapMetadata(OldSubprogramMDNode, VMap));
197 auto Subprograms = CU->getSubprograms();
200 for (
auto *
SP : Subprograms) {
201 if (
SP == OldSubprogramMDNode) {
218 bool ModuleLevelChanges,
220 std::vector<Type*> ArgTypes;
228 ArgTypes.push_back(
I->getType());
242 DestI->setName(
I->getName());
246 if (ModuleLevelChanges)
258 struct PruningFunctionCloner {
262 bool ModuleLevelChanges;
263 const char *NameSuffix;
274 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
275 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
276 CodeInfo(codeInfo), Director(Director) {
282 TypeMapper =
nullptr;
283 Materializer =
nullptr;
291 std::vector<const BasicBlock*> &ToClone);
297 void PruningFunctionCloner::CloneBlock(
const BasicBlock *BB,
299 std::vector<const BasicBlock*> &ToClone){
300 WeakVH &BBEntry = VMap[BB];
321 const_cast<BasicBlock*>(BB));
325 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
353 if (!isa<PHINode>(NewInst)) {
356 TypeMapper, Materializer);
365 if (
Value *MappedV = VMap.lookup(V))
375 NewInst->
setName(II->getName()+NameSuffix);
378 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
379 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
380 if (isa<ConstantInt>(AI->getArraySize()))
381 hasStaticAllocas =
true;
383 hasDynamicAllocas =
true;
389 bool TerminatorDone =
false;
408 "SkipInstruction is not valid for terminators.");
410 if (
const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
411 if (BI->isConditional()) {
416 Value *V = VMap[BI->getCondition()];
417 Cond = dyn_cast_or_null<ConstantInt>(V);
424 ToClone.push_back(Dest);
425 TerminatorDone =
true;
428 }
else if (
const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
432 Value *V = VMap[
SI->getCondition()];
433 Cond = dyn_cast_or_null<ConstantInt>(V);
439 ToClone.push_back(Dest);
440 TerminatorDone =
true;
444 if (!TerminatorDone) {
449 VMap[OldTI] = NewInst;
458 CodeInfo->ContainsCalls |= hasCalls;
459 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
460 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
471 bool ModuleLevelChanges,
473 const char *NameSuffix,
476 assert(NameSuffix &&
"NameSuffix cannot be null!");
491 E = OldFunc->
arg_end(); II != E; ++II)
492 assert(VMap.
count(II) &&
"No mapping from source argument specified!");
495 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
496 NameSuffix, CodeInfo, Director);
502 StartingInst = StartingBB->
begin();
506 std::vector<const BasicBlock*> CloneWorklist;
507 PFC.CloneBlock(StartingBB, StartingInst, CloneWorklist);
508 while (!CloneWorklist.empty()) {
510 CloneWorklist.pop_back();
511 PFC.CloneBlock(BB, BB->
begin(), CloneWorklist);
523 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
524 if (!NewBB)
continue;
534 if (
const PHINode *PN = dyn_cast<PHINode>(
I)) {
535 if (isa<PHINode>(VMap[PN]))
548 TypeMapper, Materializer);
553 for (
unsigned phino = 0, e = PHIToResolve.
size(); phino != e; ) {
554 const PHINode *OPN = PHIToResolve[phino];
557 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
561 for (; phino != PHIToResolve.
size() &&
562 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
563 OPN = PHIToResolve[phino];
564 PHINode *PN = cast<PHINode>(VMap[OPN]);
565 for (
unsigned pred = 0, e = NumPreds;
pred != e; ++
pred) {
567 if (
BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
571 assert(InVal &&
"Unknown input value?");
589 assert(NumPreds < PN->getNumIncomingValues());
591 std::map<BasicBlock*, unsigned> PredCount;
605 for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
606 E = PredCount.end(); PCI != E; ++PCI) {
608 for (
unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
617 PN = cast<PHINode>(NewBB->
begin());
621 while ((PN = dyn_cast<PHINode>(I++))) {
624 assert(VMap[OldI] == PN &&
"VMap mismatch");
639 for (
unsigned Idx = 0, Size = PHIToResolve.
size(); Idx != Size; ++Idx)
640 if (
PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
649 while (I != NewFunc->
end()) {
654 I->getSinglePredecessor() ==
I)) {
677 assert(!isa<PHINode>(Dest->
begin()));
687 I->getInstList().splice(I->end(), Dest->
getInstList());
701 if (
ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
715 bool ModuleLevelChanges,
717 const char *NameSuffix,
721 ModuleLevelChanges, Returns, NameSuffix, CodeInfo,
729 for (
auto *BB : Blocks)
730 for (
auto &Inst : *BB)
755 assert(OrigPH &&
"No preheader");
758 VMap[OrigPH] = NewPH;
777 DT->
addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
addNewBlock - Add a new node to the dominator tree information.
ReturnInst - Return a value (possibly void), from a function.
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
void push_back(const T &Elt)
LinkageTypes getLinkage() const
void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, const Instruction *StartingInst, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, CloningDirector *Director=nullptr)
This works like CloneAndPruneFunctionInto, except that it does not clone the entire function...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
LLVM Argument representation.
const Instruction & back() const
AttributeSet getParamAttributes(unsigned Index) const
The attributes for the specified index are returned.
void DeleteDeadBlock(BasicBlock *BB)
DeleteDeadBlock - Delete the specified block, which must have no predecessors.
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
static void CloneDebugInfoMetadata(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap)
void reserve(size_type N)
const std::vector< BlockT * > & getBlocks() const
getBlocks - Get a list of the basic blocks which make up this loop.
virtual ValueMaterializer * getValueMaterializer()
BlockT * getHeader() const
void processModule(const Module &M)
Process entire module and collect debug info anchors.
void remapInstructionsInBlocks(const SmallVectorImpl< BasicBlock * > &Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
void push_back(NodeTy *val)
static DISubprogram * FindSubprogram(const Function *F, DebugInfoFinder &Finder)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
removeIncomingValue - Remove an incoming value.
void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, Instruction *TheCall=nullptr)
CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto, except that it does some simpl...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldTerminator - If a terminator instruction is predicated on a constant value, convert it into an unconditional branch to the constant destination.
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
virtual CloningAction handleInstruction(ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB)=0
Subclasses must override this function to customize cloning behavior.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Utility to find all debug info in a module.
void setName(const Twine &Name)
Change the name of the value.
Instruction * clone() const
clone() - Create a copy of 'this' instruction that is identical in all ways except the following: ...
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
FunctionType - Class to represent function types.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
addBasicBlockToLoop - This method is used by other analyses to update loop information.
virtual ValueMapTypeRemapper * getTypeRemapper()
Value handle that is nullable, but tries to track the Value.
void addChildLoop(LoopT *NewChild)
addChildLoop - Add the specified loop to be a child of this loop.
BasicBlock * getSuccessor(unsigned i) const
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
FunctionType::get - This static method is the primary way of constructing a FunctionType.
iterator_range< compile_unit_iterator > compile_units() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
RF_NoModuleLevelChanges - If this flag is set, the remapper knows that only local values within a fun...
iterator_range< subprogram_iterator > subprograms() const
RF_IgnoreMissingEntries - If this flag is set, the remapper ignores entries that are not in the value...
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
A helper class used with CloneAndPruneIntoFromInst to change the default behavior while instructions ...
unsigned getNumSlots() const
Return the number of slots used in this attribute list.
ValueMaterializer - This is a class that can be implemented by clients to materialize Values on deman...
Subclasses of this class are all able to terminate a basic block.
BlockT * getLoopPreheader() const
getLoopPreheader - If there is a preheader for this loop, return it.
static void AddOperand(DICompileUnit *CU, DISubprogramArray SPs, Metadata *NewSP)
LLVM Basic Block Representation.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
BranchInst - Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
get - Return a BlockAddress for the specified function and basic block.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
void replaceSubprograms(DISubprogramArray N)
This is an important base class in LLVM.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
const InstListType & getInstList() const
Return the underlying instruction list container.
void copyAttributesFrom(const GlobalValue *Src) override
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static UndefValue * get(Type *T)
get() - Static factory methods - Return an 'undef' object of the specified type.
bool recursivelySimplifyInstruction(Instruction *I, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
Recursively attempt to simplify an instruction.
bool isConditional() const
const BasicBlockListType & getBasicBlockList() const
DomTreeNodeBase< NodeT > * getIDom() const
This is the shared class of boolean and integer constants.
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
BasicBlockTy * getCaseSuccessor()
Resolves successor for current case.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
const BasicBlock & getEntryBlock() const
void addTopLevelLoop(LoopT *New)
addTopLevelLoop - This adds the specified loop to the collection of top-level loops.
void splice(iterator where, iplist &L2)
AttributeSet getAttributes() const
Return the attribute list for this Function.
BasicBlock * getSinglePredecessor()
Return the predecessor of this block if it has a single predecessor block.
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
RemapInstruction - Convert the instruction operands from referencing the current values into those sp...
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Skip this instruction and stop cloning the current basic block.
Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
ValueMapTypeRemapper - This is a class that can be implemented by clients to remap types when cloning...
Don't clone the terminator but clone the current block's successors.
bool ContainsCalls
ContainsCalls - This is set to true if the cloned code contains a normal call instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
iplist< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
FunctionType * getFunctionType() const
ClonedCodeInfo - This struct can be used to capture information about code being cloned, while it is being cloned.
LLVMContext & getContext() const
void setAttributes(AttributeSet attrs)
Set the attribute list for this Function.
SwitchInst - Multiway switch.
CloningAction
This enumeration describes the way CloneAndPruneIntoFromInst should proceed after the CloningDirector...
Type * getReturnType() const
bool ContainsDynamicAllocas
ContainsDynamicAllocas - This is set to true if the cloned code contains a 'dynamic' alloca...
const BasicBlock & front() const
LLVMContext & getContext() const
Get the context in which this basic block lives.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Function * CloneFunction(const Function *F, ValueToValueMapTy &VMap, bool ModuleLevelChanges, ClonedCodeInfo *CodeInfo=nullptr)
CloneFunction - Return a copy of the specified function, but without embedding the function into anot...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Value * SimplifyInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
SimplifyInstruction - See if we can compute a simplified version of this instruction.
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void setIncomingValue(unsigned i, Value *V)
AttributeSet addAttributes(LLVMContext &C, unsigned Index, AttributeSet Attrs) const
Add attributes to the attribute set at the given index.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
const BasicBlock * getParent() const
iterator_range< arg_iterator > args()
AllocaInst - an instruction to allocate memory on the stack.
AttributeSet getFnAttributes() const
The function attributes are returned.