57 #define DEBUG_TYPE "mem2reg" 59 STATISTIC(NumLocalPromoted,
"Number of alloca's promoted within one block");
60 STATISTIC(NumSingleStore,
"Number of alloca's promoted with a single store");
61 STATISTIC(NumDeadAlloca,
"Number of dead alloca's removed");
62 STATISTIC(NumPHIInsert,
"Number of PHI nodes inserted");
71 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
76 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(U)) {
77 if (
SI->getOperand(0) == AI)
83 }
else if (
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
84 if (!II->isLifetimeStartOrEnd())
86 }
else if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
94 if (!GEPI->hasAllZeroIndices())
114 bool OnlyUsedInOneBlock;
119 DefiningBlocks.
clear();
123 OnlyUsedInOneBlock =
true;
143 LoadInst *LI = cast<LoadInst>(User);
149 if (OnlyUsedInOneBlock) {
153 OnlyUsedInOneBlock =
false;
162 struct RenamePassData {
163 using ValVector = std::vector<Value *>;
164 using LocationVector = std::vector<DebugLoc>;
167 : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
172 LocationVector Locations;
180 class LargeBlockInfo {
191 static bool isInterestingInstruction(
const Instruction *
I) {
192 return (isa<LoadInst>(I) && isa<AllocaInst>(I->
getOperand(0))) ||
193 (isa<StoreInst>(
I) && isa<AllocaInst>(I->
getOperand(1)));
197 unsigned getInstructionIndex(
const Instruction *I) {
198 assert(isInterestingInstruction(I) &&
199 "Not a load/store to/from an alloca?");
203 if (It != InstNumbers.
end())
212 if (isInterestingInstruction(&BBI))
213 InstNumbers[&BBI] = InstNo++;
214 It = InstNumbers.
find(I);
216 assert(It != InstNumbers.
end() &&
"Didn't insert instruction?");
225 struct PromoteMem2Reg {
227 std::vector<AllocaInst *> Allocas;
270 : Allocas(Allocas.
begin(), Allocas.
end()), DT(DT),
278 void RemoveFromAllocasList(
unsigned &AllocaIdx) {
279 Allocas[AllocaIdx] = Allocas.
back();
285 unsigned &NP = BBNumPreds[BB];
295 RenamePassData::ValVector &IncVals,
296 RenamePassData::LocationVector &IncLocs,
297 std::vector<RenamePassData> &Worklist);
309 LoadNotNull->insertAfter(LI);
322 if (isa<LoadInst>(I) || isa<StoreInst>(
I))
351 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->
getOperand(0));
356 Info.UsingBlocks.clear();
360 if (UserInst == OnlyStore)
362 LoadInst *LI = cast<LoadInst>(UserInst);
368 if (!StoringGlobalVal) {
373 if (StoreIndex == -1)
374 StoreIndex = LBI.getInstructionIndex(OnlyStore);
376 if (
unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
378 Info.UsingBlocks.push_back(StoreBB);
385 Info.UsingBlocks.push_back(LI->
getParent());
400 if (AC && LI->
getMetadata(LLVMContext::MD_nonnull) &&
410 if (!Info.UsingBlocks.empty())
421 Info.OnlyStore->eraseFromParent();
422 LBI.deleteValue(Info.OnlyStore);
456 StoresByIndexTy StoresByIndex;
460 StoresByIndex.
push_back(std::make_pair(LBI.getInstructionIndex(
SI),
SI));
473 unsigned LoadIdx = LBI.getInstructionIndex(LI);
478 std::make_pair(LoadIdx, static_cast<StoreInst *>(
nullptr)),
480 if (I == StoresByIndex.begin()) {
481 if (StoresByIndex.empty())
492 Value *ReplVal = std::prev(I)->second->getOperand(0);
493 if (AC && LI->
getMetadata(LLVMContext::MD_nonnull) &&
531 void PromoteMem2Reg::run() {
532 Function &
F = *DT.getRoot()->getParent();
534 AllocaDbgDeclares.resize(Allocas.size());
540 for (
unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
545 "All allocas should be in the same function, which is same as DF!");
554 RemoveFromAllocasList(AllocaNum);
561 Info.AnalyzeAlloca(AI);
565 if (Info.DefiningBlocks.size() == 1) {
568 RemoveFromAllocasList(AllocaNum);
576 if (Info.OnlyUsedInOneBlock &&
579 RemoveFromAllocasList(AllocaNum);
585 if (BBNumbers.empty()) {
588 BBNumbers[&BB] = ID++;
592 if (!Info.DbgDeclares.empty())
593 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclares;
596 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
605 Info.DefiningBlocks.end());
621 return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
626 QueuePhiNode(BB, AllocaNum, CurrentVersion);
637 RenamePassData::ValVector Values(Allocas.size());
638 for (
unsigned i = 0,
e = Allocas.size(); i !=
e; ++i)
643 RenamePassData::LocationVector Locations(Allocas.size());
647 std::vector<RenamePassData> RenamePassWorkList;
648 RenamePassWorkList.emplace_back(&F.
front(),
nullptr, std::move(Values),
649 std::move(Locations));
651 RenamePassData RPD = std::move(RenamePassWorkList.back());
652 RenamePassWorkList.pop_back();
654 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
655 }
while (!RenamePassWorkList.empty());
667 A->eraseFromParent();
671 for (
auto &Declares : AllocaDbgDeclares)
672 for (
auto *DII : Declares)
673 DII->eraseFromParent();
679 bool EliminatedAPHI =
true;
680 while (EliminatedAPHI) {
681 EliminatedAPHI =
false;
688 I = NewPhiNodes.begin(),
689 E = NewPhiNodes.end();
698 EliminatedAPHI =
true;
711 I = NewPhiNodes.begin(),
712 E = NewPhiNodes.end();
718 if (&BB->
front() != SomePHI)
734 return BBNumbers.find(A)->second < BBNumbers.find(
B)->second;
745 "PHI node has entry for a block which is not a predecessor!");
757 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
781 Info.UsingBlocks.end());
786 for (
unsigned i = 0,
e = LiveInBlockWorklist.size(); i !=
e; ++i) {
788 if (!DefBlocks.
count(BB))
795 if (
SI->getOperand(1) != AI)
800 LiveInBlockWorklist[i] = LiveInBlockWorklist.
back();
801 LiveInBlockWorklist.pop_back();
807 if (
LoadInst *LI = dyn_cast<LoadInst>(
I))
810 if (LI->getOperand(0) == AI)
817 while (!LiveInBlockWorklist.empty()) {
818 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
822 if (!LiveInBlocks.
insert(BB).second)
834 LiveInBlockWorklist.push_back(
P);
842 bool PromoteMem2Reg::QueuePhiNode(
BasicBlock *BB,
unsigned AllocaNo,
845 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
853 PN =
PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
857 PhiToAllocaMap[PN] = AllocaNo;
864 bool ApplyMergedLoc) {
877 RenamePassData::ValVector &IncomingVals,
878 RenamePassData::LocationVector &IncomingLocs,
879 std::vector<RenamePassData> &Worklist) {
886 if (PhiToAllocaMap.count(APN)) {
893 unsigned NewPHINumOperands = APN->getNumOperands();
896 assert(NumEdges &&
"Must be at least one edge from Pred to BB!");
901 unsigned AllocaNo = PhiToAllocaMap[APN];
905 APN->getNumIncomingValues() > 0);
908 for (
unsigned i = 0; i != NumEdges; ++i)
909 APN->addIncoming(IncomingVals[AllocaNo], Pred);
912 IncomingVals[AllocaNo] = APN;
924 }
while (APN->getNumOperands() == NewPHINumOperands);
929 if (!Visited.insert(BB).second)
935 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
941 if (AI == AllocaLookup.
end())
944 Value *V = IncomingVals[AI->second];
949 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
954 LI->replaceAllUsesWith(V);
956 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
964 if (ai == AllocaLookup.
end())
968 unsigned AllocaNo = ai->second;
969 IncomingVals[AllocaNo] =
SI->getOperand(0);
972 IncomingLocs[AllocaNo] =
SI->getDebugLoc();
994 if (VisitedSuccs.
insert(*I).second)
995 Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
1003 if (Allocas.
empty())
1006 PromoteMem2Reg(Allocas, DT, AC).run();
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
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 addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
const T & back() const
back - Get the last element.
iterator erase(iterator where)
This class represents lattice values for constants.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void push_back(const T &Elt)
This class represents a function call, abstracting a target machine's calling convention.
A cache of @llvm.assume calls within a function.
STATISTIC(NumFunctions, "Total number of functions")
An instruction for reading from memory.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
void calculate(SmallVectorImpl< NodeTy *> &IDFBlocks)
Calculate iterated dominance frontiers.
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
PointerType * getType() const
Overload to return most specific pointer type.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static StringRef getName(Value *V)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Type * getType() const
All values are typed, get the type of this value.
This is the common base class for debug info intrinsics for variables.
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
An instruction for storing to memory.
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...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
Analysis containing CSE Info
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...
Interval::succ_iterator succ_end(Interval *I)
iterator find(const_arg_type_t< KeyT > Val)
bool isVoidTy() const
Return true if this is 'void'.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
bool erase(const KeyT &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
void setLiveInBlocks(const SmallPtrSetImpl< NodeTy *> &Blocks)
Give the IDF calculator the set of blocks in which the value is live on entry to the block...
static void ComputeLiveInBlocks(const SmallPtrSetImpl< BasicBlock *> &UsingBlocks, const SmallPtrSetImpl< BasicBlock *> &DefBlocks, SmallPtrSetImpl< BasicBlock *> &LiveInBlocks, PredIteratorCache &PredCache)
Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
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.
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...
const Instruction & back() const
This instruction compares its operands according to the predicate given to the constructor.
Interval::pred_iterator pred_end(Interval *I)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
void sort(IteratorTy Start, IteratorTy End)
void setDefiningBlocks(const SmallPtrSetImpl< NodeTy *> &Blocks)
Give the IDF calculator the set of blocks in which the value is defined.
const InstListType & getInstList() const
Return the underlying instruction list container.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
TinyPtrVector< DbgVariableIntrinsic * > FindDbgAddrUses(Value *V)
Finds all intrinsics declaring local variables as living in the memory that 'V' points to...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
void applyMergedLocation(const DILocation *LocA, const DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to be non-zero when defined.
iterator_range< user_iterator > users()
static void clear(coro::Shape &Shape)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
void ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII, StoreInst *SI, DIBuilder &Builder)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
void PromoteMemToReg(ArrayRef< AllocaInst *> Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Function object to check whether the first component of a std::pair compares less than the first comp...
bool empty() const
empty - Check if the array is empty.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack