48 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
55 if (DIFinder && TheModule) {
56 if (
auto *DDI = dyn_cast<DbgDeclareInst>(II))
58 else if (
auto *DVI = dyn_cast<DbgValueInst>(II))
61 if (
auto DbgLoc = II->getDebugLoc())
67 NewInst->
setName(II->getName()+NameSuffix);
71 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
72 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
73 if (isa<ConstantInt>(AI->getArraySize()))
74 hasStaticAllocas =
true;
76 hasDynamicAllocas =
true;
94 bool ModuleLevelChanges,
99 assert(NameSuffix &&
"NameSuffix cannot be null!");
103 assert(VMap.
count(&
I) &&
"No mapping from source argument specified!");
117 TypeMapper, Materializer));
124 if (
Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
125 NewArgAttrs[NewArg->getArgNo()] =
126 OldAttrs.getParamAttributes(OldArg.getArgNo());
132 OldAttrs.getRetAttributes(), NewArgAttrs));
138 assert(!MustCloneSP || ModuleLevelChanges);
141 auto &MD = VMap.
MD();
142 MD[SP->getUnit()].reset(SP->getUnit());
143 MD[SP->getType()].reset(SP->getType());
153 for (
auto MD : MDs) {
158 TypeMapper, Materializer));
178 SP ? &DIFinder :
nullptr);
191 const_cast<BasicBlock*>(&BB));
202 VMap.
MD()[ISP].reset(ISP);
213 cast<BasicBlock>(VMap[&OldFunc->
front()])->getIterator(),
220 TypeMapper, Materializer);
232 std::vector<Type*> ArgTypes;
239 ArgTypes.push_back(
I.getType());
252 if (VMap.
count(&
I) == 0) {
254 VMap[&
I] = &*DestI++;
268 struct PruningFunctionCloner {
272 bool ModuleLevelChanges;
273 const char *NameSuffix;
280 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
281 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
282 CodeInfo(codeInfo) {}
288 std::vector<const BasicBlock*> &ToClone);
294 void PruningFunctionCloner::CloneBlock(
const BasicBlock *BB,
296 std::vector<const BasicBlock*> &ToClone){
318 const_cast<BasicBlock*>(BB));
322 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
333 if (!isa<PHINode>(NewInst)) {
344 if (NewFunc != OldFunc)
345 if (
Value *MappedV = VMap.lookup(V))
357 NewInst->
setName(II->getName()+NameSuffix);
358 VMap[&*II] = NewInst;
360 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
364 if (
CS.hasOperandBundles())
365 CodeInfo->OperandBundleCallSites.push_back(NewInst);
367 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
368 if (isa<ConstantInt>(AI->getArraySize()))
369 hasStaticAllocas =
true;
371 hasDynamicAllocas =
true;
377 bool TerminatorDone =
false;
378 if (
const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
379 if (BI->isConditional()) {
384 Value *V = VMap.lookup(BI->getCondition());
385 Cond = dyn_cast_or_null<ConstantInt>(V);
392 ToClone.push_back(Dest);
393 TerminatorDone =
true;
396 }
else if (
const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
400 Value *V = VMap.lookup(
SI->getCondition());
401 Cond = dyn_cast_or_null<ConstantInt>(V);
407 ToClone.push_back(Dest);
408 TerminatorDone =
true;
412 if (!TerminatorDone) {
417 VMap[OldTI] = NewInst;
421 if (
CS.hasOperandBundles())
422 CodeInfo->OperandBundleCallSites.push_back(NewInst);
427 ToClone.push_back(Succ);
431 CodeInfo->ContainsCalls |= hasCalls;
432 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
433 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
444 bool ModuleLevelChanges,
446 const char *NameSuffix,
448 assert(NameSuffix &&
"NameSuffix cannot be null!");
458 assert(VMap.
count(&II) &&
"No mapping from source argument specified!");
461 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
462 NameSuffix, CodeInfo);
468 StartingInst = &StartingBB->
front();
472 std::vector<const BasicBlock*> CloneWorklist;
473 PFC.CloneBlock(StartingBB, StartingInst->
getIterator(), CloneWorklist);
474 while (!CloneWorklist.empty()) {
476 CloneWorklist.pop_back();
477 PFC.CloneBlock(BB, BB->
begin(), CloneWorklist);
488 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
489 if (!NewBB)
continue;
499 if (
const PHINode *PN = dyn_cast<PHINode>(
I)) {
500 if (isa<PHINode>(VMap[PN]))
513 TypeMapper, Materializer);
518 for (
unsigned phino = 0, e = PHIToResolve.
size(); phino != e; ) {
519 const PHINode *OPN = PHIToResolve[phino];
522 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
526 for (; phino != PHIToResolve.
size() &&
527 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
528 OPN = PHIToResolve[phino];
529 PHINode *PN = cast<PHINode>(VMap[OPN]);
530 for (
unsigned pred = 0, e = NumPreds;
pred != e; ++
pred) {
532 if (
BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
536 assert(InVal &&
"Unknown input value?");
555 assert(NumPreds < PN->getNumIncomingValues());
557 std::map<BasicBlock*, unsigned> PredCount;
571 for (
const auto &PCI : PredCount) {
573 for (
unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
582 PN = cast<PHINode>(NewBB->
begin());
586 while ((PN = dyn_cast<PHINode>(I++))) {
589 assert(VMap[&*OldI] == PN &&
"VMap mismatch");
606 for (
unsigned Idx = 0,
Size = PHIToResolve.
size(); Idx !=
Size; ++Idx)
607 if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
608 Worklist.
insert(PHIToResolve[Idx]);
611 for (
unsigned Idx = 0; Idx != Worklist.
size(); ++Idx) {
612 const Value *OrigV = Worklist[Idx];
613 auto *
I = dyn_cast_or_null<Instruction>(VMap.
lookup(OrigV));
632 Worklist.
insert(cast<Instruction>(U));
635 I->replaceAllUsesWith(SimpleV);
639 I->eraseFromParent();
650 while (I != NewFunc->
end()) {
655 I->getSinglePredecessor() == &*
I)) {
688 I->getInstList().splice(I->end(), Dest->
getInstList());
702 if (
ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
716 bool ModuleLevelChanges,
718 const char *NameSuffix,
722 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
729 for (
auto *BB : Blocks)
730 for (
auto &Inst : *BB)
746 "Loop to be cloned cannot have inner loop");
757 assert(OrigPH &&
"No preheader");
760 VMap[OrigPH] = NewPH;
787 cast<BasicBlock>(VMap[IDomBB]));
791 F->getBasicBlockList().splice(Before->
getIterator(), F->getBasicBlockList(),
793 F->getBasicBlockList().splice(Before->
getIterator(), F->getBasicBlockList(),
794 NewLoop->
getHeader()->getIterator(), F->end());
818 for (; StopAt != &*BI; ++BI) {
822 ValueMapping[&*BI] = New;
827 auto I = ValueMapping.
find(Inst);
828 if (
I != ValueMapping.
end())
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
void processLocation(const Module &M, const DILocation *Loc)
Process debug info location.
A parsed version of the target data layout string in and methods for querying it. ...
LinkageTypes getLinkage() const
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
This class represents an incoming formal argument to a Function.
DiagnosticInfoOptimizationBase::Argument NV
const Instruction & back() const
A Module instance is used to store all the information related to an LLVM module. ...
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
unsigned getNumOperands() const
void DeleteDeadBlock(BasicBlock *BB)
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.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
CloneFunction - Return a copy of the specified function and add it to that function's module...
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
void deleteValue()
Delete a pointer to a generic Value.
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
size_type size() const
Determine the number of elements in the SetVector.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Lookup or compute a mapping for a piece of metadata.
BlockT * getHeader() const
void remapInstructionsInBlocks(const SmallVectorImpl< BasicBlock * > &Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
AttributeList getAttributes() const
Return the attribute list for this Function.
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
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)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
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...
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.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void setName(const Twine &Name)
Change the name of the value.
Instruction * clone() const
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...
Class to represent function types.
void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, const Instruction *StartingInst, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr)
This works like CloneAndPruneFunctionInto, except that it does not clone the entire function...
Value handle that is nullable, but tries to track the Value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BasicBlock * getSuccessor(unsigned i) const
iterator find(const KeyT &Val)
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
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...
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
iterator_range< subprogram_iterator > subprograms() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
This is a class that can be implemented by clients to materialize Values on demand.
Subclasses of this class are all able to terminate a basic block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
This is an important base class in LLVM.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
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...
bool hasPersonalityFn() const
Check whether this function has a personality function.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const InstListType & getInstList() const
Return the underlying instruction list container.
Value * getOperand(unsigned i) const
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.
void processValue(const Module &M, const DbgValueInst *DVI)
Process DbgValueInst.
self_iterator getIterator()
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Look up or compute a value in the value map.
bool isConditional() const
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
This is the shared class of boolean and integer constants.
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
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.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
const BasicBlock & getEntryBlock() const
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
void setOperand(unsigned i, Value *Val)
void push_back(pointer val)
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
DISubprogram * getSubprogram() const
Get the attached subprogram.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified 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.
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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.
Represents a single loop in the control flow graph.
void processDeclare(const Module &M, const DbgDeclareInst *DDI)
Process DbgDeclareInst.
Establish a view to a call site for examination.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
ClonedCodeInfo - This struct can be used to capture information about code being cloned, while it is being cloned.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Helper struct that represents how a value is mapped through different register banks.
Type * getReturnType() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
A handle to a particular switch case.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
void setPersonalityFn(Constant *Fn)
iterator_range< type_iterator > types() const
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setIncomingValue(unsigned i, Value *V)
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
const BasicBlock * getParent() const
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
iterator_range< arg_iterator > args()
an instruction to allocate memory on the stack