45 #define DEBUG_TYPE "mem2reg"
47 STATISTIC(NumLocalPromoted,
"Number of alloca's promoted within one block");
48 STATISTIC(NumSingleStore,
"Number of alloca's promoted with a single store");
49 STATISTIC(NumDeadAlloca,
"Number of dead alloca's removed");
50 STATISTIC(NumPHIInsert,
"Number of PHI nodes inserted");
59 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
64 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(U)) {
65 if (
SI->getOperand(0) == AI)
71 }
else if (
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
72 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
73 II->getIntrinsicID() != Intrinsic::lifetime_end)
75 }
else if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
83 if (!GEPI->hasAllZeroIndices())
103 bool OnlyUsedInOneBlock;
105 Value *AllocaPointerVal;
109 DefiningBlocks.clear();
113 OnlyUsedInOneBlock =
true;
114 AllocaPointerVal =
nullptr;
115 DbgDeclare =
nullptr;
129 if (
StoreInst *SI = dyn_cast<StoreInst>(User)) {
131 DefiningBlocks.push_back(
SI->getParent());
132 AllocaPointerVal =
SI->getOperand(0);
135 LoadInst *LI = cast<LoadInst>(User);
139 AllocaPointerVal = LI;
142 if (OnlyUsedInOneBlock) {
146 OnlyUsedInOneBlock =
false;
155 class RenamePassData {
157 typedef std::vector<Value *> ValVector;
159 RenamePassData() : BB(nullptr), Pred(nullptr), Values() {}
161 : BB(B), Pred(P), Values(V) {}
166 void swap(RenamePassData &RHS) {
169 Values.swap(RHS.Values);
178 class LargeBlockInfo {
189 static bool isInterestingInstruction(
const Instruction *
I) {
190 return (isa<LoadInst>(I) && isa<AllocaInst>(I->
getOperand(0))) ||
191 (isa<StoreInst>(
I) && isa<AllocaInst>(I->
getOperand(1)));
195 unsigned getInstructionIndex(
const Instruction *I) {
196 assert(isInterestingInstruction(I) &&
197 "Not a load/store to/from an alloca?");
201 if (It != InstNumbers.
end())
210 if (isInterestingInstruction(&BBI))
211 InstNumbers[&BBI] = InstNo++;
212 It = InstNumbers.
find(I);
214 assert(It != InstNumbers.
end() &&
"Didn't insert instruction?");
220 void clear() { InstNumbers.clear(); }
223 struct PromoteMem2Reg {
225 std::vector<AllocaInst *> Allocas;
250 std::vector<Value *> PointerAllocaValues;
271 : Allocas(Allocas.
begin(), Allocas.
end()), DT(DT),
279 void RemoveFromAllocasList(
unsigned &AllocaIdx) {
280 Allocas[AllocaIdx] = Allocas.back();
286 unsigned &NP = BBNumPreds[BB];
292 void ComputeLiveInBlocks(
AllocaInst *AI, AllocaInfo &Info,
296 RenamePassData::ValVector &IncVals,
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 (!isa<LoadInst>(UserInst)) {
361 assert(UserInst == OnlyStore &&
"Should only have load/stores");
364 LoadInst *LI = cast<LoadInst>(UserInst);
370 if (!StoringGlobalVal) {
375 if (StoreIndex == -1)
376 StoreIndex = LBI.getInstructionIndex(OnlyStore);
378 if (
unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
380 Info.UsingBlocks.push_back(StoreBB);
389 Info.UsingBlocks.push_back(LI->
getParent());
414 if (!Info.UsingBlocks.empty())
422 DDI->eraseFromParent();
423 LBI.deleteValue(DDI);
426 Info.OnlyStore->eraseFromParent();
427 LBI.deleteValue(Info.OnlyStore);
461 StoresByIndexTy StoresByIndex;
463 for (User *U : AI->
users())
465 StoresByIndex.
push_back(std::make_pair(LBI.getInstructionIndex(
SI),
SI));
478 unsigned LoadIdx = LBI.getInstructionIndex(LI);
481 StoresByIndexTy::iterator I =
482 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
483 std::make_pair(LoadIdx,
484 static_cast<StoreInst *>(
nullptr)),
486 if (I == StoresByIndex.begin()) {
487 if (StoresByIndex.empty())
498 Value *ReplVal = std::prev(I)->second->getOperand(0);
527 DDI->eraseFromParent();
528 LBI.deleteValue(DDI);
535 void PromoteMem2Reg::run() {
536 Function &
F = *DT.getRoot()->getParent();
538 AllocaDbgDeclares.resize(Allocas.size());
544 for (
unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
549 "All allocas should be in the same function, which is same as DF!");
558 RemoveFromAllocasList(AllocaNum);
565 Info.AnalyzeAlloca(AI);
569 if (Info.DefiningBlocks.size() == 1) {
572 RemoveFromAllocasList(AllocaNum);
580 if (Info.OnlyUsedInOneBlock &&
583 RemoveFromAllocasList(AllocaNum);
589 if (BBNumbers.empty()) {
592 BBNumbers[&BB] = ID++;
597 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
600 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
610 DefBlocks.
insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
615 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
621 IDF.setLiveInBlocks(LiveInBlocks);
622 IDF.setDefiningBlocks(DefBlocks);
624 IDF.calculate(PHIBlocks);
625 if (PHIBlocks.
size() > 1)
628 return BBNumbers.lookup(A) < BBNumbers.lookup(
B);
632 for (
unsigned i = 0, e = PHIBlocks.
size(); i != e; ++i)
633 QueuePhiNode(PHIBlocks[i], AllocaNum, CurrentVersion);
645 RenamePassData::ValVector Values(Allocas.size());
646 for (
unsigned i = 0, e = Allocas.size(); i != e; ++i)
652 std::vector<RenamePassData> RenamePassWorkList;
653 RenamePassWorkList.emplace_back(&F.
front(),
nullptr, std::move(Values));
656 RPD.swap(RenamePassWorkList.back());
657 RenamePassWorkList.pop_back();
659 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
660 }
while (!RenamePassWorkList.empty());
666 for (
unsigned i = 0, e = Allocas.size(); i != e; ++i) {
678 for (
unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
680 DDI->eraseFromParent();
686 bool EliminatedAPHI =
true;
687 while (EliminatedAPHI) {
688 EliminatedAPHI =
false;
695 I = NewPhiNodes.begin(),
696 E = NewPhiNodes.end();
704 NewPhiNodes.
erase(I++);
705 EliminatedAPHI =
true;
719 I = NewPhiNodes.begin(),
720 E = NewPhiNodes.end();
726 if (&BB->
front() != SomePHI)
750 "PHI node has entry for a block which is not a predecessor!");
762 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
765 for (
unsigned pred = 0, e = Preds.size();
pred != e; ++
pred)
778 void PromoteMem2Reg::ComputeLiveInBlocks(
787 Info.UsingBlocks.end());
792 for (
unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
794 if (!DefBlocks.
count(BB))
800 if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
801 if (
SI->getOperand(1) != AI)
806 LiveInBlockWorklist[i] = LiveInBlockWorklist.
back();
807 LiveInBlockWorklist.pop_back();
813 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
826 while (!LiveInBlockWorklist.empty()) {
827 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
831 if (!LiveInBlocks.
insert(BB).second)
841 if (DefBlocks.
count(P))
845 LiveInBlockWorklist.push_back(P);
853 bool PromoteMem2Reg::QueuePhiNode(
BasicBlock *BB,
unsigned AllocaNo,
856 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
864 PN =
PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
868 PhiToAllocaMap[PN] = AllocaNo;
878 RenamePassData::ValVector &IncomingVals,
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];
904 for (
unsigned i = 0; i != NumEdges; ++i)
905 APN->addIncoming(IncomingVals[AllocaNo], Pred);
908 IncomingVals[AllocaNo] = APN;
920 }
while (APN->getNumOperands() == NewPHINumOperands);
925 if (!Visited.insert(BB).second)
931 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
937 if (AI == AllocaLookup.
end())
940 Value *V = IncomingVals[AI->second];
952 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
960 if (ai == AllocaLookup.
end())
964 IncomingVals[ai->second] =
SI->getOperand(0);
987 if (VisitedSuccs.
insert(*I).second)
988 Worklist.emplace_back(*I, Pred, IncomingVals);
999 PromoteMem2Reg(Allocas, DT, AC).run();
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
const_iterator end(StringRef path)
Get end iterator over path.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
const Instruction & back() const
STATISTIC(NumFunctions,"Total number of functions")
iterator erase(iterator where)
DbgDeclareInst * FindAllocaDbgDeclare(Value *V)
Finds the llvm.dbg.declare intrinsic corresponding to an alloca, if any.
This class represents a function call, abstracting a target machine's calling convention.
A cache of .assume calls within a function.
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
unsigned getAddressSpace() const
Return the address space of the Pointer type.
An instruction for reading from memory.
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.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
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...
This class represents a no-op cast from one type to another.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
An instruction for storing to memory.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
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...
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
iterator find(const_arg_type_t< KeyT > Val)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Function Alias Analysis false
bool erase(const KeyT &Val)
LLVM Basic Block Representation.
void ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, StoreInst *SI, DIBuilder &Builder)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
PointerType * getType() const
Overload to return most specific pointer type.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
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.
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...
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const InstListType & getInstList() const
Return the underlying instruction list container.
This instruction compares its operands according to the predicate given to the constructor.
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
Value * getPointerOperand()
bool empty() const
empty - Check if the array is empty.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
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...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
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.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
static void clear(coro::Shape &Shape)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void registerAssumption(CallInst *CI)
Add an .assume intrinsic to this function's cache.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isKnownNonNullAt(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if this pointer couldn't possibly be null.
Determine the iterated dominance frontier, given a set of defining blocks, and optionally, a set of live-in blocks.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
LLVM Value Representation.
static const Function * getParent(const Value *V)
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
This represents the llvm.dbg.declare instruction.
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...
const BasicBlock * getParent() const
A wrapper class for inspecting calls to intrinsic functions.
bool isVoidTy() const
Return true if this is 'void'.
an instruction to allocate memory on the stack