59#define DEBUG_TYPE "mem2reg"
61STATISTIC(NumLocalPromoted,
"Number of alloca's promoted within one block");
62STATISTIC(NumSingleStore,
"Number of alloca's promoted with a single store");
63STATISTIC(NumDeadAlloca,
"Number of dead alloca's removed");
64STATISTIC(NumPHIInsert,
"Number of PHI nodes inserted");
69 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
74 }
else if (
const StoreInst *SI = dyn_cast<StoreInst>(U)) {
75 if (SI->getValueOperand() == AI ||
83 if (!
II->isLifetimeStartOrEnd() && !
II->isDroppable() &&
84 II->getIntrinsicID() != Intrinsic::fake_use)
86 }
else if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
90 if (!GEPI->hasAllZeroIndices())
120class AssignmentTrackingInfo {
137 void updateForDeletedStore(
142 if (DVRAssigns.
empty())
152 auto InsertValueForAssign = [&](
auto *DbgAssign,
auto *&AssignList) {
154 AssignList->insert(DbgAssign);
155 createDebugValue(DIB, DbgAssign->getValue(), DbgAssign->getVariable(),
156 DbgAssign->getExpression(), DbgAssign->getDebugLoc(),
160 InsertValueForAssign(Assign, DVRAssignsToDelete);
175 for_each(DVRAssigns, ConvertUnlinkedAssignToValue);
184 for (
auto *DVR : DVRAssigns)
188 void clear() { DVRAssigns.
clear(); }
189 bool empty() {
return DVRAssigns.
empty(); }
200 bool OnlyUsedInOneBlock;
205 AssignmentTrackingInfo AssignmentTracking;
208 DefiningBlocks.
clear();
212 OnlyUsedInOneBlock =
true;
214 AssignmentTracking.clear();
239 if (OnlyUsedInOneBlock) {
241 OnlyBlock =
User->getParent();
242 else if (OnlyBlock !=
User->getParent())
243 OnlyUsedInOneBlock =
false;
248 std::copy_if(AllDPUsers.
begin(), AllDPUsers.
end(),
249 std::back_inserter(DPUsers),
251 AssignmentTracking.init(AI);
255template <
typename T>
class VectorWithUndo {
260 void undo(
size_t S) {
262 while (S < Undo.
size()) {
263 Vals[Undo.
back().first] = Undo.
back().second;
268 void resize(
size_t Sz) { Vals.
resize(Sz); }
270 size_t undoSize()
const {
return Undo.
size(); }
272 const T &operator[](
size_t Idx)
const {
return Vals[
Idx]; }
274 void set(
size_t Idx,
const T &Val) {
275 if (Vals[
Idx] == Val)
281 void init(
size_t Idx,
const T &Val) {
288struct RenamePassData {
290 : BB(
B), Pred(
P), UndoVals(
V), UndoLocs(
L) {}
304class LargeBlockInfo {
315 static bool isInterestingInstruction(
const Instruction *
I) {
316 return (isa<LoadInst>(
I) && isa<AllocaInst>(
I->getOperand(0))) ||
317 (isa<StoreInst>(
I) && isa<AllocaInst>(
I->getOperand(1)));
322 assert(isInterestingInstruction(
I) &&
323 "Not a load/store to/from an alloca?");
327 if (It != InstNumbers.
end())
336 if (isInterestingInstruction(&BBI))
337 InstNumbers[&BBI] = InstNo++;
338 It = InstNumbers.
find(
I);
340 assert(It != InstNumbers.
end() &&
"Didn't insert instruction?");
346 void clear() { InstNumbers.
clear(); }
349struct PromoteMem2Reg {
351 std::vector<AllocaInst *> Allocas;
395 VectorWithUndo<Value *> IncomingVals;
398 VectorWithUndo<DebugLoc> IncomingLocs;
409 : Allocas(Allocas.
begin(), Allocas.
end()), DT(DT),
411 AC(AC), SQ(DT.
getRoot()->getDataLayout(),
417 void RemoveFromAllocasList(
unsigned &AllocaIdx) {
418 Allocas[AllocaIdx] = Allocas.back();
425 unsigned &NP = BBNumPreds[BB->
getNumber()];
435 bool QueuePhiNode(
BasicBlock *BB,
unsigned AllocaIdx,
unsigned &Version);
438 void cleanUpDbgAssigns() {
439 for (
auto *DVR : DVRAssignsToDelete)
440 DVR->eraseFromParent();
441 DVRAssignsToDelete.clear();
445 Worklist.
emplace_back(BB, Pred, IncomingVals.undoSize(),
446 IncomingLocs.undoSize());
449 RenamePassData popFromWorklist() {
450 RenamePassData
R = Worklist.
back();
452 IncomingVals.undo(
R.UndoVals);
453 IncomingLocs.undo(
R.UndoLocs);
475 if (isa<UndefValue>(Val) && LI->
hasMetadata(LLVMContext::MD_noundef)) {
488 if (AC && LI->
getMetadata(LLVMContext::MD_nonnull) &&
500 if (isa<LoadInst>(
I) || isa<StoreInst>(
I))
504 if (
I->isDroppable()) {
505 I->dropDroppableUse(U);
509 if (!
I->getType()->isVoidTy()) {
514 Instruction *Inst = cast<Instruction>(UU.getUser());
524 I->eraseFromParent();
546 bool RequireDominatingStore =
552 Info.UsingBlocks.clear();
556 if (UserInst == OnlyStore)
558 LoadInst *LI = cast<LoadInst>(UserInst);
564 if (RequireDominatingStore) {
569 if (StoreIndex == -1)
570 StoreIndex = LBI.getInstructionIndex(OnlyStore);
572 if (
unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
574 Info.UsingBlocks.push_back(StoreBB);
599 if (!
Info.UsingBlocks.empty())
604 Info.AssignmentTracking.updateForDeletedStore(
Info.OnlyStore, DIB,
626 Info.OnlyStore->eraseFromParent();
627 LBI.deleteValue(
Info.OnlyStore);
650 AllocaInst *AI,
const AllocaInfo &Info, LargeBlockInfo &LBI,
660 StoresByIndexTy StoresByIndex;
663 if (
StoreInst *SI = dyn_cast<StoreInst>(U))
664 StoresByIndex.
push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
673 LoadInst *LI = dyn_cast<LoadInst>(U);
677 unsigned LoadIdx = LBI.getInstructionIndex(LI);
682 std::make_pair(LoadIdx,
static_cast<StoreInst *
>(
nullptr)),
685 if (
I == StoresByIndex.begin()) {
686 if (StoresByIndex.empty())
696 ReplVal = std::prev(
I)->second->getOperand(0);
716 Info.AssignmentTracking.updateForDeletedStore(SI, DIB, DVRAssignsToDelete);
724 SI->eraseFromParent();
743void PromoteMem2Reg::run() {
746 AllocaATInfo.
resize(Allocas.size());
747 AllocaDPUsers.
resize(Allocas.size());
753 NoSignedZeros =
F.getFnAttribute(
"no-signed-zeros-fp-math").getValueAsBool();
755 for (
unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
760 "All allocas should be in the same function, which is same as DF!");
769 RemoveFromAllocasList(AllocaNum);
776 Info.AnalyzeAlloca(AI);
780 if (
Info.DefiningBlocks.size() == 1) {
782 &DVRAssignsToDelete)) {
784 RemoveFromAllocasList(AllocaNum);
792 if (
Info.OnlyUsedInOneBlock &&
794 &DVRAssignsToDelete)) {
796 RemoveFromAllocasList(AllocaNum);
801 if (BBNumPreds.
empty())
802 BBNumPreds.
resize(
F.getMaxBlockNumber());
805 if (!
Info.AssignmentTracking.empty())
806 AllocaATInfo[AllocaNum] =
Info.AssignmentTracking;
807 if (!
Info.DPUsers.empty())
808 AllocaDPUsers[AllocaNum] =
Info.DPUsers;
811 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
815 Info.DefiningBlocks);
826 IDF.setLiveInBlocks(LiveInBlocks);
827 IDF.setDefiningBlocks(DefBlocks);
829 IDF.calculate(PHIBlocks);
831 return A->getNumber() <
B->getNumber();
836 QueuePhiNode(BB, AllocaNum, CurrentVersion);
839 if (Allocas.empty()) {
848 IncomingVals.resize(Allocas.size());
849 for (
unsigned i = 0, e = Allocas.size(); i != e; ++i)
854 IncomingLocs.resize(Allocas.size());
857 Visited.
resize(
F.getMaxBlockNumber(),
false);
860 pushToWorklist(&
F.front(),
nullptr);
863 RenamePassData RPD = popFromWorklist();
864 RenamePass(RPD.BB, RPD.Pred);
865 }
while (!Worklist.
empty());
876 A->eraseFromParent();
880 for (
auto &DbgUsers : AllocaDPUsers) {
882 if (DbgItem->isAddressOfVariable() ||
883 DbgItem->getExpression()->startsWithDeref())
884 DbgItem->eraseFromParent();
891 bool EliminatedAPHI =
true;
892 while (EliminatedAPHI) {
893 EliminatedAPHI =
false;
901 E = NewPhiNodes.
end();
910 EliminatedAPHI =
true;
922 for (
const auto &PhiNode : NewPhiNodes) {
925 PHINode *SomePHI = PhiNode.second;
927 if (&BB->
front() != SomePHI)
943 return A->getNumber() <
B->getNumber();
954 "PHI node has entry for a block which is not a predecessor!");
966 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
983void PromoteMem2Reg::ComputeLiveInBlocks(
991 Info.UsingBlocks.end());
996 for (
unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
998 if (!DefBlocks.
count(BB))
1004 if (
StoreInst *SI = dyn_cast<StoreInst>(
I)) {
1005 if (
SI->getOperand(1) != AI)
1010 LiveInBlockWorklist[i] = LiveInBlockWorklist.
back();
1011 LiveInBlockWorklist.pop_back();
1017 if (
LoadInst *LI = dyn_cast<LoadInst>(
I))
1027 while (!LiveInBlockWorklist.empty()) {
1028 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1032 if (!LiveInBlocks.
insert(BB).second)
1044 LiveInBlockWorklist.push_back(
P);
1052bool PromoteMem2Reg::QueuePhiNode(
BasicBlock *BB,
unsigned AllocaNo,
1053 unsigned &Version) {
1063 PN =
PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
1064 Allocas[AllocaNo]->
getName() +
"." +
Twine(Version++));
1067 PhiToAllocaMap[PN] = AllocaNo;
1074 bool ApplyMergedLoc) {
1092 if (PhiToAllocaMap.
count(APN)) {
1099 unsigned NewPHINumOperands = APN->getNumOperands();
1102 assert(NumEdges &&
"Must be at least one edge from Pred to BB!");
1107 unsigned AllocaNo = PhiToAllocaMap[APN];
1111 APN->getNumIncomingValues() > 0);
1114 for (
unsigned i = 0; i != NumEdges; ++i)
1115 APN->addIncoming(IncomingVals[AllocaNo], Pred);
1122 if (isa<FPMathOperator>(APN) && NoSignedZeros)
1123 APN->setHasNoSignedZeros(
true);
1126 IncomingVals.set(AllocaNo, APN);
1127 AllocaATInfo[AllocaNo].updateForNewPhi(APN, DIB);
1129 if (DbgItem->isAddressOfVariable())
1134 APN = dyn_cast<PHINode>(PNI);
1140 }
while (APN->getNumOperands() == NewPHINumOperands);
1152 if (
LoadInst *LI = dyn_cast<LoadInst>(
I)) {
1158 if (AI == AllocaLookup.
end())
1161 Value *
V = IncomingVals[AI->second];
1167 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(
I)) {
1170 AllocaInst *Dest = dyn_cast<AllocaInst>(
SI->getPointerOperand());
1175 if (ai == AllocaLookup.
end())
1179 unsigned AllocaNo = ai->second;
1180 IncomingVals.set(AllocaNo,
SI->getOperand(0));
1183 IncomingLocs.set(AllocaNo,
SI->getDebugLoc());
1184 AllocaATInfo[AllocaNo].updateForDeletedStore(SI, DIB,
1185 &DVRAssignsToDelete);
1187 if (DbgItem->isAddressOfVariable())
1189 SI->eraseFromParent();
1199 if (VisitedSuccs.
insert(S).second)
1200 pushToWorklist(S, BB);
1206 if (Allocas.
empty())
1209 PromoteMem2Reg(Allocas, DT, AC).run();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
This file implements the BitVector class.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static DeltaTreeNode * getRoot(void *Root)
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
uint64_t IntrinsicInst * II
static StringRef getName(Value *V)
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.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
empty - Check if the array is empty.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
unsigned getNumber() const
iterator begin()
Instruction iterator methods.
const Instruction & front() const
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
const Instruction & back() const
This class represents a no-op cast from one type to another.
bool test(unsigned Idx) const
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
A parsed version of the target data layout string in and methods for querying it.
LLVM_ABI void eraseFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
bool isValueOfVariable() const
Determine if this describes the value of a local variable.
bool isAddressOfVariable() const
Does this describe the address of a local variable.
static LLVM_ABI DbgVariableRecord * createDbgVariableRecord(Value *Location, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
DIExpression * getExpression() const
Identifies a unique instance of a whole variable (discards/ignores fragment information).
Identifies a unique instance of a variable.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Class representing an expression and its matching format.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
Value * getPointerOperand()
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
bool contains(const T &V) const
Check if the SmallSet contains the given element.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
reference emplace_back(ArgTypes &&... Args)
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
static LLVM_ABI void dropDroppableUse(Use &U)
Remove the droppable use U.
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< use_iterator > uses()
const ParentTy * getParent() const
self_iterator getIterator()
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
LLVM_ABI const_iterator begin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get begin iterator over path.
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
This is an optimization pass for GlobalISel generic memory operations.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI 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...
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
constexpr from_range_t from_range
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Function object to check whether the first component of a container supported by std::get (like std::...