47 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
54 NewInst->
setName(II->getName()+NameSuffix);
58 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
59 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
60 if (isa<ConstantInt>(AI->getArraySize()))
61 hasStaticAllocas =
true;
63 hasDynamicAllocas =
true;
81 bool ModuleLevelChanges,
86 assert(NameSuffix &&
"NameSuffix cannot be null!");
90 assert(VMap.
count(&
I) &&
"No mapping from source argument specified!");
104 TypeMapper, Materializer));
109 if (
Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
113 NewArg->addAttr(attrs);
130 TypeMapper, Materializer));
154 const_cast<BasicBlock*>(&BB));
166 cast<BasicBlock>(VMap[&OldFunc->
front()])->getIterator(),
172 ModuleLevelChanges ?
RF_None : RF_NoModuleLevelChanges,
173 TypeMapper, Materializer);
185 std::vector<Type*> ArgTypes;
192 ArgTypes.push_back(
I.getType());
205 if (VMap.
count(&
I) == 0) {
206 DestI->setName(
I.getName());
207 VMap[&
I] = &*DestI++;
221 struct PruningFunctionCloner {
225 bool ModuleLevelChanges;
226 const char *NameSuffix;
233 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
234 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
235 CodeInfo(codeInfo) {}
241 std::vector<const BasicBlock*> &ToClone);
247 void PruningFunctionCloner::CloneBlock(
const BasicBlock *BB,
249 std::vector<const BasicBlock*> &ToClone){
250 WeakVH &BBEntry = VMap[BB];
271 const_cast<BasicBlock*>(BB));
275 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
286 if (!isa<PHINode>(NewInst)) {
297 if (
Value *MappedV = VMap.lookup(V))
309 NewInst->
setName(II->getName()+NameSuffix);
310 VMap[&*II] = NewInst;
312 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
316 if (
CS.hasOperandBundles())
317 CodeInfo->OperandBundleCallSites.push_back(NewInst);
319 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
320 if (isa<ConstantInt>(AI->getArraySize()))
321 hasStaticAllocas =
true;
323 hasDynamicAllocas =
true;
329 bool TerminatorDone =
false;
330 if (
const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
331 if (BI->isConditional()) {
336 Value *V = VMap.lookup(BI->getCondition());
337 Cond = dyn_cast_or_null<ConstantInt>(V);
344 ToClone.push_back(Dest);
345 TerminatorDone =
true;
348 }
else if (
const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
352 Value *V = VMap.lookup(
SI->getCondition());
353 Cond = dyn_cast_or_null<ConstantInt>(V);
359 ToClone.push_back(Dest);
360 TerminatorDone =
true;
364 if (!TerminatorDone) {
369 VMap[OldTI] = NewInst;
373 if (
CS.hasOperandBundles())
374 CodeInfo->OperandBundleCallSites.push_back(NewInst);
379 ToClone.push_back(Succ);
383 CodeInfo->ContainsCalls |= hasCalls;
384 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
385 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
396 bool ModuleLevelChanges,
398 const char *NameSuffix,
400 assert(NameSuffix &&
"NameSuffix cannot be null!");
410 assert(VMap.
count(&II) &&
"No mapping from source argument specified!");
413 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
414 NameSuffix, CodeInfo);
420 StartingInst = &StartingBB->
front();
424 std::vector<const BasicBlock*> CloneWorklist;
425 PFC.CloneBlock(StartingBB, StartingInst->
getIterator(), CloneWorklist);
426 while (!CloneWorklist.empty()) {
428 CloneWorklist.pop_back();
429 PFC.CloneBlock(BB, BB->
begin(), CloneWorklist);
440 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
441 if (!NewBB)
continue;
451 if (
const PHINode *PN = dyn_cast<PHINode>(
I)) {
452 if (isa<PHINode>(VMap[PN]))
465 TypeMapper, Materializer);
470 for (
unsigned phino = 0, e = PHIToResolve.
size(); phino != e; ) {
471 const PHINode *OPN = PHIToResolve[phino];
474 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
478 for (; phino != PHIToResolve.
size() &&
479 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
480 OPN = PHIToResolve[phino];
481 PHINode *PN = cast<PHINode>(VMap[OPN]);
482 for (
unsigned pred = 0, e = NumPreds;
pred != e; ++
pred) {
484 if (
BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
488 assert(InVal &&
"Unknown input value?");
507 assert(NumPreds < PN->getNumIncomingValues());
509 std::map<BasicBlock*, unsigned> PredCount;
523 for (
const auto &PCI : PredCount) {
525 for (
unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
534 PN = cast<PHINode>(NewBB->
begin());
538 while ((PN = dyn_cast<PHINode>(I++))) {
541 assert(VMap[&*OldI] == PN &&
"VMap mismatch");
558 for (
unsigned Idx = 0, Size = PHIToResolve.
size(); Idx != Size; ++Idx)
559 if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
560 Worklist.
insert(PHIToResolve[Idx]);
563 for (
unsigned Idx = 0; Idx != Worklist.
size(); ++Idx) {
564 const Value *OrigV = Worklist[Idx];
565 auto *
I = dyn_cast_or_null<Instruction>(VMap.
lookup(OrigV));
584 Worklist.
insert(cast<Instruction>(U));
587 I->replaceAllUsesWith(SimpleV);
591 I->eraseFromParent();
602 while (I != NewFunc->
end()) {
607 I->getSinglePredecessor() == &*
I)) {
640 I->getInstList().splice(I->end(), Dest->
getInstList());
654 if (
ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
668 bool ModuleLevelChanges,
670 const char *NameSuffix,
674 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
681 for (
auto *BB : Blocks)
682 for (
auto &Inst : *BB)
698 "Loop to be cloned cannot have inner loop");
709 assert(OrigPH &&
"No preheader");
712 VMap[OrigPH] = NewPH;
739 cast<BasicBlock>(VMap[IDomBB]));
743 F->getBasicBlockList().splice(Before->
getIterator(), F->getBasicBlockList(),
745 F->getBasicBlockList().splice(Before->
getIterator(), F->getBasicBlockList(),
746 NewLoop->
getHeader()->getIterator(), F->end());
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
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)
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. ...
LLVM Argument representation.
DiagnosticInfoOptimizationBase::Argument NV
const Instruction & back() const
AttributeSet getParamAttributes(unsigned Index) const
The attributes for the specified index are returned.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
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.
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.
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.
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.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
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...
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.
Value handle that is nullable, but tries to track the Value.
void addChildLoop(LoopT *NewChild)
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)
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...
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
unsigned getNumIncomingValues() const
Return the number of incoming edges.
unsigned getNumSlots() const
Return the number of slots used in this attribute list.
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.
LLVM Basic Block Representation.
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.
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.
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.
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
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.
BasicBlockTy * getCaseSuccessor()
Resolves successor for current case.
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.
AttributeSet getAttributes() const
Return the attribute list for this Function.
void push_back(pointer val)
iterator_range< user_iterator > users()
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)
Convert the instruction operands from referencing the current values into those specified by VM...
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...
void setAttributes(AttributeSet Attrs)
Set the attribute list for this Function.
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
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.
ImmutableCallSite - establish a view to a call site for examination.
SymbolTableList< 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...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
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)
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
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
getCalledFunction - Return the function being called if this is a direct call, otherwise return null ...
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.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
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)
See if we can compute a simplified version of this instruction.
void setPersonalityFn(Constant *Fn)
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()
an instruction to allocate memory on the stack
AttributeSet getFnAttributes() const
The function attributes are returned.