49 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
54 if (DIFinder && TheModule)
59 NewInst->
setName(
I.getName() + NameSuffix);
63 hasCalls |= (isa<CallInst>(
I) && !isa<DbgInfoIntrinsic>(
I));
64 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&
I)) {
65 if (isa<ConstantInt>(AI->getArraySize()))
66 hasStaticAllocas =
true;
68 hasDynamicAllocas =
true;
76 BB != &BB->getParent()->getEntryBlock();
86 bool ModuleLevelChanges,
91 assert(NameSuffix &&
"NameSuffix cannot be null!");
95 assert(VMap.
count(&
I) &&
"No mapping from source argument specified!");
109 TypeMapper, Materializer));
116 if (
Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
117 NewArgAttrs[NewArg->getArgNo()] =
118 OldAttrs.getParamAttributes(OldArg.getArgNo());
124 OldAttrs.getRetAttributes(), NewArgAttrs));
130 assert(!MustCloneSP || ModuleLevelChanges);
133 auto &MD = VMap.
MD();
134 MD[SP->getUnit()].reset(SP->getUnit());
135 MD[SP->getType()].reset(SP->getType());
145 for (
auto MD : MDs) {
150 TypeMapper, Materializer));
170 ModuleLevelChanges ? &DIFinder :
nullptr);
183 const_cast<BasicBlock*>(&BB));
194 VMap.
MD()[ISP].reset(ISP);
205 cast<BasicBlock>(VMap[&OldFunc->
front()])->getIterator(),
212 TypeMapper, Materializer);
217 if (OldModule && NewModule && OldModule != NewModule && DIFinder.
compile_unit_count()) {
221 for (
auto* Operand : NMD->operands())
225 if (Visited.
insert(Unit).second)
226 NMD->addOperand(Unit);
239 std::vector<Type*> ArgTypes;
246 ArgTypes.push_back(
I.getType());
259 if (VMap.
count(&
I) == 0) {
261 VMap[&
I] = &*DestI++;
275 struct PruningFunctionCloner {
279 bool ModuleLevelChanges;
280 const char *NameSuffix;
287 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
288 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
289 CodeInfo(codeInfo) {}
295 std::vector<const BasicBlock*> &ToClone);
301 void PruningFunctionCloner::CloneBlock(
const BasicBlock *BB,
303 std::vector<const BasicBlock*> &ToClone){
325 const_cast<BasicBlock*>(BB));
329 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
340 if (!isa<PHINode>(NewInst)) {
351 if (NewFunc != OldFunc)
352 if (
Value *MappedV = VMap.lookup(V))
364 NewInst->
setName(II->getName()+NameSuffix);
365 VMap[&*II] = NewInst;
367 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
371 if (CS.hasOperandBundles())
372 CodeInfo->OperandBundleCallSites.push_back(NewInst);
374 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
375 if (isa<ConstantInt>(AI->getArraySize()))
376 hasStaticAllocas =
true;
378 hasDynamicAllocas =
true;
384 bool TerminatorDone =
false;
385 if (
const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
386 if (BI->isConditional()) {
391 Value *V = VMap.lookup(BI->getCondition());
392 Cond = dyn_cast_or_null<ConstantInt>(V);
399 ToClone.push_back(Dest);
400 TerminatorDone =
true;
403 }
else if (
const SwitchInst *
SI = dyn_cast<SwitchInst>(OldTI)) {
407 Value *V = VMap.lookup(
SI->getCondition());
408 Cond = dyn_cast_or_null<ConstantInt>(V);
414 ToClone.push_back(Dest);
415 TerminatorDone =
true;
419 if (!TerminatorDone) {
424 VMap[OldTI] = NewInst;
428 if (CS.hasOperandBundles())
429 CodeInfo->OperandBundleCallSites.push_back(NewInst);
434 ToClone.push_back(Succ);
438 CodeInfo->ContainsCalls |= hasCalls;
439 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
440 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
451 bool ModuleLevelChanges,
453 const char *NameSuffix,
455 assert(NameSuffix &&
"NameSuffix cannot be null!");
465 assert(VMap.
count(&II) &&
"No mapping from source argument specified!");
468 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
469 NameSuffix, CodeInfo);
475 StartingInst = &StartingBB->
front();
479 std::vector<const BasicBlock*> CloneWorklist;
480 PFC.CloneBlock(StartingBB, StartingInst->
getIterator(), CloneWorklist);
481 while (!CloneWorklist.empty()) {
483 CloneWorklist.pop_back();
484 PFC.CloneBlock(BB, BB->
begin(), CloneWorklist);
495 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
496 if (!NewBB)
continue;
503 for (
const PHINode &PN : BI.phis()) {
506 if (isa<PHINode>(VMap[&PN]))
516 TypeMapper, Materializer);
521 for (
unsigned phino = 0,
e = PHIToResolve.
size(); phino !=
e; ) {
522 const PHINode *OPN = PHIToResolve[phino];
525 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
529 for (; phino != PHIToResolve.
size() &&
530 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
531 OPN = PHIToResolve[phino];
532 PHINode *PN = cast<PHINode>(VMap[OPN]);
535 if (
BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
539 assert(InVal &&
"Unknown input value?");
558 assert(NumPreds < PN->getNumIncomingValues());
560 std::map<BasicBlock*, unsigned> PredCount;
574 for (
const auto &PCI : PredCount) {
576 for (
unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
585 PN = cast<PHINode>(NewBB->
begin());
589 while ((PN = dyn_cast<PHINode>(I++))) {
592 assert(VMap[&*OldI] == PN &&
"VMap mismatch");
609 for (
unsigned Idx = 0,
Size = PHIToResolve.
size(); Idx !=
Size; ++Idx)
610 if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
611 Worklist.
insert(PHIToResolve[Idx]);
614 for (
unsigned Idx = 0; Idx != Worklist.
size(); ++Idx) {
615 const Value *OrigV = Worklist[Idx];
616 auto *
I = dyn_cast_or_null<Instruction>(VMap.
lookup(OrigV));
635 Worklist.
insert(cast<Instruction>(U));
638 I->replaceAllUsesWith(SimpleV);
642 I->eraseFromParent();
653 while (I != NewFunc->
end()) {
674 I->getSinglePredecessor() == &*
I)) {
700 I->getInstList().splice(I->end(), Dest->
getInstList());
714 if (
ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
728 bool ModuleLevelChanges,
730 const char *NameSuffix,
734 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
741 for (
auto *BB : Blocks)
742 for (
auto &Inst : *BB)
762 LMap[OrigLoop] = NewLoop;
769 assert(OrigPH &&
"No preheader");
772 VMap[OrigPH] = NewPH;
783 Loop *&NewLoop = LMap[CurLoop];
789 assert(OrigParent &&
"Could not find the original parent loop");
790 Loop *NewParentLoop = LMap[OrigParent];
791 assert(NewParentLoop &&
"Could not find the new parent loop");
799 Loop *&NewLoop = LMap[CurLoop];
800 assert(NewLoop &&
"Expecting new loop to be allocated");
821 cast<BasicBlock>(VMap[IDomBB]));
840 "There must be a single edge between PredBB and BB!");
862 for (; StopAt != &*BI && BB->
getTerminator() != &*BI; ++BI) {
866 ValueMapping[&*BI] = New;
871 auto I = ValueMapping.
find(Inst);
872 if (
I != ValueMapping.
end())
SmallVector< const LoopT *, 4 > getLoopsInPreorder() const
Return all loops in the loop nest rooted by the loop in preorder, with siblings in forward program or...
Return a value (possibly void), from a function.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
This class represents an incoming formal argument to a Function.
DiagnosticInfoOptimizationBase::Argument NV
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
This class represents lattice values for constants.
size_type size() const
Determine the number of elements in the SetVector.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
A Module instance is used to store all the information related to an LLVM module. ...
void push_back(const T &Elt)
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
void deleteValue()
Delete a pointer to a generic Value.
BasicBlock * getSuccessor(unsigned i) const
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
LLVMContext & getContext() const
Get the context in which this basic block lives.
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.
iterator begin()
Instruction iterator methods.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
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...
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static constexpr UpdateKind Delete
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Utility to find all debug info in a module.
void setName(const Twine &Name)
Change the name of the value.
BlockT * getHeader() const
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst *> &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, Instruction *TheCall=nullptr)
This works exactly like CloneFunctionInto, except that it does some simple constant prop and DCE on t...
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
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 addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
iterator find(const KeyT &Val)
iterator_range< type_iterator > types() const
AttributeList getAttributes() const
Return the attribute list for this Function.
bool hasPersonalityFn() const
Check whether this function has a personality function.
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
const BasicBlock & getEntryBlock() const
unsigned compile_unit_count() const
This is a class that can be implemented by clients to materialize Values on demand.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
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...
DISubprogram * getSubprogram() const
Get the attached subprogram.
Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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 ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
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...
void splice(iterator where, iplist_impl &L2)
const Instruction & back() const
unsigned getAddressSpace() const
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
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.
self_iterator getIterator()
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...
iterator_range< compile_unit_iterator > compile_units() const
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
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.
void processInstruction(const Module &M, const Instruction &I)
Process a single instruction and collect debug info anchors.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
const InstListType & getInstList() const
Return the underlying instruction list container.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
void setIncomingBlock(unsigned i, BasicBlock *BB)
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
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.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LoopT * AllocateLoop(ArgsTy &&... Args)
Type * getReturnType() const
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setOperand(unsigned i, Value *Val)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
void push_back(pointer val)
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
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...
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.
bool ContainsCalls
This is set to true if the cloned code contains a normal call instruction.
LoopT * getParentLoop() const
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
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)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
Helper struct that represents how a value is mapped through different register banks.
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool ContainsDynamicAllocas
This is set to true if the cloned code contains a 'dynamic' alloca.
const BasicBlock & front() const
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.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
succ_range successors(Instruction *I)
iterator_range< subprogram_iterator > subprograms() const
Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock *> &Blocks)
Clones a loop OrigLoop.
A handle to a particular switch case.
void setPersonalityFn(Constant *Fn)
void setIncomingValue(unsigned i, Value *V)
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
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()
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
void remapInstructionsInBlocks(const SmallVectorImpl< BasicBlock *> &Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.