#ifndef LLVM_ANALYSIS_MEMORYSSA_H
#define LLVM_ANALYSIS_MEMORYSSA_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/ilist_node.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/PHITransAddr.h"
#include "llvm/IR/DerivedUser.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/Pass.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <memory>
#include <utility>
namespace llvm {
template <class GraphType> struct GraphTraits;
class BasicBlock;
class Function;
class Instruction;
class LLVMContext;
class MemoryAccess;
class MemorySSAWalker;
class Module;
class Use;
class Value;
class raw_ostream;
namespace MSSAHelpers {
struct AllAccessTag {};
struct DefsOnlyTag {};
}
enum : unsigned {
INVALID_MEMORYACCESS_ID = -1U
};
template <class T> class memoryaccess_def_iterator_base;
using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
using const_memoryaccess_def_iterator =
memoryaccess_def_iterator_base<const MemoryAccess>;
class MemoryAccess
: public DerivedUser,
public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
public:
using AllAccessType =
ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
using DefsOnlyType =
ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
MemoryAccess(const MemoryAccess &) = delete;
MemoryAccess &operator=(const MemoryAccess &) = delete;
void *operator new(size_t) = delete;
static bool classof(const Value *V) {
unsigned ID = V->getValueID();
return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
}
BasicBlock *getBlock() const { return Block; }
void print(raw_ostream &OS) const;
void dump() const;
using iterator = user_iterator;
using const_iterator = const_user_iterator;
memoryaccess_def_iterator defs_begin();
const_memoryaccess_def_iterator defs_begin() const;
memoryaccess_def_iterator defs_end();
const_memoryaccess_def_iterator defs_end() const;
AllAccessType::self_iterator getIterator() {
return this->AllAccessType::getIterator();
}
AllAccessType::const_self_iterator getIterator() const {
return this->AllAccessType::getIterator();
}
AllAccessType::reverse_self_iterator getReverseIterator() {
return this->AllAccessType::getReverseIterator();
}
AllAccessType::const_reverse_self_iterator getReverseIterator() const {
return this->AllAccessType::getReverseIterator();
}
DefsOnlyType::self_iterator getDefsIterator() {
return this->DefsOnlyType::getIterator();
}
DefsOnlyType::const_self_iterator getDefsIterator() const {
return this->DefsOnlyType::getIterator();
}
DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
return this->DefsOnlyType::getReverseIterator();
}
DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
return this->DefsOnlyType::getReverseIterator();
}
protected:
friend class MemoryDef;
friend class MemoryPhi;
friend class MemorySSA;
friend class MemoryUse;
friend class MemoryUseOrDef;
void setBlock(BasicBlock *BB) { Block = BB; }
inline unsigned getID() const;
MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
BasicBlock *BB, unsigned NumOperands)
: DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue),
Block(BB) {}
~MemoryAccess() = default;
private:
BasicBlock *Block;
};
template <>
struct ilist_alloc_traits<MemoryAccess> {
static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
};
inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
MA.print(OS);
return OS;
}
class MemoryUseOrDef : public MemoryAccess {
public:
void *operator new(size_t) = delete;
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
Instruction *getMemoryInst() const { return MemoryInstruction; }
MemoryAccess *getDefiningAccess() const { return getOperand(0); }
static bool classof(const Value *MA) {
return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
}
inline bool isOptimized() const;
inline MemoryAccess *getOptimized() const;
inline void setOptimized(MemoryAccess *);
Optional<AliasResult> getOptimizedAccessType() const {
return isOptimized() ? OptimizedAccessAlias : None;
}
inline void resetOptimized();
protected:
friend class MemorySSA;
friend class MemorySSAUpdater;
MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
unsigned NumOperands)
: MemoryAccess(C, Vty, DeleteValue, BB, NumOperands),
MemoryInstruction(MI), OptimizedAccessAlias(AliasResult::MayAlias) {
setDefiningAccess(DMA);
}
~MemoryUseOrDef() = default;
void setOptimizedAccessType(Optional<AliasResult> AR) {
OptimizedAccessAlias = AR;
}
void setDefiningAccess(
MemoryAccess *DMA, bool Optimized = false,
Optional<AliasResult> AR = AliasResult(AliasResult::MayAlias)) {
if (!Optimized) {
setOperand(0, DMA);
return;
}
setOptimized(DMA);
setOptimizedAccessType(AR);
}
private:
Instruction *MemoryInstruction;
Optional<AliasResult> OptimizedAccessAlias;
};
class MemoryUse final : public MemoryUseOrDef {
public:
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
: MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB,
1) {}
void *operator new(size_t S) { return User::operator new(S, 1); }
void operator delete(void *Ptr) { User::operator delete(Ptr); }
static bool classof(const Value *MA) {
return MA->getValueID() == MemoryUseVal;
}
void print(raw_ostream &OS) const;
void setOptimized(MemoryAccess *DMA) {
OptimizedID = DMA->getID();
setOperand(0, DMA);
}
bool isOptimized() const {
return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
}
MemoryAccess *getOptimized() const {
return getDefiningAccess();
}
void resetOptimized() {
OptimizedID = INVALID_MEMORYACCESS_ID;
}
protected:
friend class MemorySSA;
private:
static void deleteMe(DerivedUser *Self);
unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
};
template <>
struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)
class MemoryDef final : public MemoryUseOrDef {
public:
friend class MemorySSA;
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
unsigned Ver)
: MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB,
2),
ID(Ver) {}
void *operator new(size_t S) { return User::operator new(S, 2); }
void operator delete(void *Ptr) { User::operator delete(Ptr); }
static bool classof(const Value *MA) {
return MA->getValueID() == MemoryDefVal;
}
void setOptimized(MemoryAccess *MA) {
setOperand(1, MA);
OptimizedID = MA->getID();
}
MemoryAccess *getOptimized() const {
return cast_or_null<MemoryAccess>(getOperand(1));
}
bool isOptimized() const {
return getOptimized() && OptimizedID == getOptimized()->getID();
}
void resetOptimized() {
OptimizedID = INVALID_MEMORYACCESS_ID;
setOperand(1, nullptr);
}
void print(raw_ostream &OS) const;
unsigned getID() const { return ID; }
private:
static void deleteMe(DerivedUser *Self);
const unsigned ID;
unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
};
template <>
struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)
template <>
struct OperandTraits<MemoryUseOrDef> {
static Use *op_begin(MemoryUseOrDef *MUD) {
if (auto *MU = dyn_cast<MemoryUse>(MUD))
return OperandTraits<MemoryUse>::op_begin(MU);
return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
}
static Use *op_end(MemoryUseOrDef *MUD) {
if (auto *MU = dyn_cast<MemoryUse>(MUD))
return OperandTraits<MemoryUse>::op_end(MU);
return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
}
static unsigned operands(const MemoryUseOrDef *MUD) {
if (const auto *MU = dyn_cast<MemoryUse>(MUD))
return OperandTraits<MemoryUse>::operands(MU);
return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
}
};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
class MemoryPhi final : public MemoryAccess {
void *operator new(size_t S) { return User::operator new(S); }
public:
void operator delete(void *Ptr) { User::operator delete(Ptr); }
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
: MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
ReservedSpace(NumPreds) {
allocHungoffUses(ReservedSpace);
}
using block_iterator = BasicBlock **;
using const_block_iterator = BasicBlock *const *;
block_iterator block_begin() {
return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
}
const_block_iterator block_begin() const {
return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
}
block_iterator block_end() { return block_begin() + getNumOperands(); }
const_block_iterator block_end() const {
return block_begin() + getNumOperands();
}
iterator_range<block_iterator> blocks() {
return make_range(block_begin(), block_end());
}
iterator_range<const_block_iterator> blocks() const {
return make_range(block_begin(), block_end());
}
op_range incoming_values() { return operands(); }
const_op_range incoming_values() const { return operands(); }
unsigned getNumIncomingValues() const { return getNumOperands(); }
MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
void setIncomingValue(unsigned I, MemoryAccess *V) {
assert(V && "PHI node got a null value!");
setOperand(I, V);
}
static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
BasicBlock *getIncomingBlock(const Use &U) const {
assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
return getIncomingBlock(unsigned(&U - op_begin()));
}
BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
return getIncomingBlock(I.getUse());
}
void setIncomingBlock(unsigned I, BasicBlock *BB) {
assert(BB && "PHI node got a null basic block!");
block_begin()[I] = BB;
}
void addIncoming(MemoryAccess *V, BasicBlock *BB) {
if (getNumOperands() == ReservedSpace)
growOperands(); setNumHungOffUseOperands(getNumOperands() + 1);
setIncomingValue(getNumOperands() - 1, V);
setIncomingBlock(getNumOperands() - 1, BB);
}
int getBasicBlockIndex(const BasicBlock *BB) const {
for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
if (block_begin()[I] == BB)
return I;
return -1;
}
MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
int Idx = getBasicBlockIndex(BB);
assert(Idx >= 0 && "Invalid basic block argument!");
return getIncomingValue(Idx);
}
void unorderedDeleteIncoming(unsigned I) {
unsigned E = getNumOperands();
assert(I < E && "Cannot remove out of bounds Phi entry.");
assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
"at least 2 values.");
setIncomingValue(I, getIncomingValue(E - 1));
setIncomingBlock(I, block_begin()[E - 1]);
setOperand(E - 1, nullptr);
block_begin()[E - 1] = nullptr;
setNumHungOffUseOperands(getNumOperands() - 1);
}
template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
unorderedDeleteIncoming(I);
E = getNumOperands();
--I;
}
assert(getNumOperands() >= 1 &&
"Cannot remove all incoming blocks in a MemoryPhi.");
}
void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
unorderedDeleteIncomingIf(
[&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
}
void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
unorderedDeleteIncomingIf(
[&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
}
static bool classof(const Value *V) {
return V->getValueID() == MemoryPhiVal;
}
void print(raw_ostream &OS) const;
unsigned getID() const { return ID; }
protected:
friend class MemorySSA;
void allocHungoffUses(unsigned N) {
User::allocHungoffUses(N, true);
}
private:
const unsigned ID;
unsigned ReservedSpace;
void growOperands() {
unsigned E = getNumOperands();
ReservedSpace = std::max(E + E / 2, 2u);
growHungoffUses(ReservedSpace, true);
}
static void deleteMe(DerivedUser *Self);
};
inline unsigned MemoryAccess::getID() const {
assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
"only memory defs and phis have ids");
if (const auto *MD = dyn_cast<MemoryDef>(this))
return MD->getID();
return cast<MemoryPhi>(this)->getID();
}
inline bool MemoryUseOrDef::isOptimized() const {
if (const auto *MD = dyn_cast<MemoryDef>(this))
return MD->isOptimized();
return cast<MemoryUse>(this)->isOptimized();
}
inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
if (const auto *MD = dyn_cast<MemoryDef>(this))
return MD->getOptimized();
return cast<MemoryUse>(this)->getOptimized();
}
inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
if (auto *MD = dyn_cast<MemoryDef>(this))
MD->setOptimized(MA);
else
cast<MemoryUse>(this)->setOptimized(MA);
}
inline void MemoryUseOrDef::resetOptimized() {
if (auto *MD = dyn_cast<MemoryDef>(this))
MD->resetOptimized();
else
cast<MemoryUse>(this)->resetOptimized();
}
template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)
class MemorySSA {
public:
MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
MemorySSA(MemorySSA &&) = delete;
~MemorySSA();
MemorySSAWalker *getWalker();
MemorySSAWalker *getSkipSelfWalker();
MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
}
MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
}
DominatorTree &getDomTree() const { return *DT; }
void dump() const;
void print(raw_ostream &) const;
inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
return MA == LiveOnEntryDef.get();
}
inline MemoryAccess *getLiveOnEntryDef() const {
return LiveOnEntryDef.get();
}
using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
using DefsList =
simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
const AccessList *getBlockAccesses(const BasicBlock *BB) const {
return getWritableBlockAccesses(BB);
}
const DefsList *getBlockDefs(const BasicBlock *BB) const {
return getWritableBlockDefs(BB);
}
bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
bool dominates(const MemoryAccess *A, const Use &B) const;
enum class VerificationLevel { Fast, Full };
void verifyMemorySSA(VerificationLevel = VerificationLevel::Fast) const;
enum InsertionPlace { Beginning, End, BeforeTerminator };
void ensureOptimizedUses();
protected:
friend class MemorySSAPrinterLegacyPass;
friend class MemorySSAUpdater;
void verifyOrderingDominationAndDefUses(
Function &F, VerificationLevel = VerificationLevel::Fast) const;
void verifyDominationNumbers(const Function &F) const;
void verifyPrevDefInPhis(Function &F) const;
AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
auto It = PerBlockAccesses.find(BB);
return It == PerBlockAccesses.end() ? nullptr : It->second.get();
}
DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
auto It = PerBlockDefs.find(BB);
return It == PerBlockDefs.end() ? nullptr : It->second.get();
}
void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
SmallPtrSetImpl<BasicBlock *> &Visited) {
renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
}
void removeFromLookups(MemoryAccess *);
void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
InsertionPlace);
void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
AccessList::iterator);
MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
const MemoryUseOrDef *Template = nullptr,
bool CreationMustSucceed = true);
private:
template <class AliasAnalysisType> class ClobberWalkerBase;
template <class AliasAnalysisType> class CachingWalker;
template <class AliasAnalysisType> class SkipSelfWalker;
class OptimizeUses;
CachingWalker<AliasAnalysis> *getWalkerImpl();
void buildMemorySSA(BatchAAResults &BAA);
void prepareForMoveTo(MemoryAccess *, BasicBlock *);
void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
void markUnreachableAsLiveOnEntry(BasicBlock *BB);
MemoryPhi *createMemoryPhi(BasicBlock *BB);
template <typename AliasAnalysisType>
MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
const MemoryUseOrDef *Template = nullptr);
void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
SmallPtrSetImpl<BasicBlock *> &Visited,
bool SkipVisited = false, bool RenameAllUses = false);
AccessList *getOrCreateAccessList(const BasicBlock *);
DefsList *getOrCreateDefsList(const BasicBlock *);
void renumberBlock(const BasicBlock *) const;
AliasAnalysis *AA = nullptr;
DominatorTree *DT;
Function &F;
DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
AccessMap PerBlockAccesses;
DefsMap PerBlockDefs;
std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
std::unique_ptr<ClobberWalkerBase<AliasAnalysis>> WalkerBase;
std::unique_ptr<CachingWalker<AliasAnalysis>> Walker;
std::unique_ptr<SkipSelfWalker<AliasAnalysis>> SkipWalker;
unsigned NextID = 0;
bool IsOptimized = false;
};
extern bool VerifyMemorySSA;
class MemorySSAUtil {
protected:
friend class GVNHoist;
friend class MemorySSAWalker;
static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
AliasAnalysis &AA);
};
class MemorySSAPrinterLegacyPass : public FunctionPass {
public:
MemorySSAPrinterLegacyPass();
bool runOnFunction(Function &) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
static char ID;
};
class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
friend AnalysisInfoMixin<MemorySSAAnalysis>;
static AnalysisKey Key;
public:
struct Result {
Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
MemorySSA &getMSSA() { return *MSSA.get(); }
std::unique_ptr<MemorySSA> MSSA;
bool invalidate(Function &F, const PreservedAnalyses &PA,
FunctionAnalysisManager::Invalidator &Inv);
};
Result run(Function &F, FunctionAnalysisManager &AM);
};
class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
raw_ostream &OS;
public:
explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
};
class MemorySSAWalkerPrinterPass
: public PassInfoMixin<MemorySSAWalkerPrinterPass> {
raw_ostream &OS;
public:
explicit MemorySSAWalkerPrinterPass(raw_ostream &OS) : OS(OS) {}
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
};
struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
};
class MemorySSAWrapperPass : public FunctionPass {
public:
MemorySSAWrapperPass();
static char ID;
bool runOnFunction(Function &) override;
void releaseMemory() override;
MemorySSA &getMSSA() { return *MSSA; }
const MemorySSA &getMSSA() const { return *MSSA; }
void getAnalysisUsage(AnalysisUsage &AU) const override;
void verifyAnalysis() const override;
void print(raw_ostream &OS, const Module *M = nullptr) const override;
private:
std::unique_ptr<MemorySSA> MSSA;
};
class MemorySSAWalker {
public:
MemorySSAWalker(MemorySSA *);
virtual ~MemorySSAWalker() = default;
using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
MemoryAccess *MA = MSSA->getMemoryAccess(I);
assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
return getClobberingMemoryAccess(MA);
}
virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) = 0;
virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
const MemoryLocation &) = 0;
virtual void invalidateInfo(MemoryAccess *) {}
protected:
friend class MemorySSA; MemorySSA *MSSA;
};
class DoNothingMemorySSAWalker final : public MemorySSAWalker {
public:
using MemorySSAWalker::getClobberingMemoryAccess;
MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
const MemoryLocation &) override;
};
using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
template <class T>
class memoryaccess_def_iterator_base
: public iterator_facade_base<memoryaccess_def_iterator_base<T>,
std::forward_iterator_tag, T, ptrdiff_t, T *,
T *> {
using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
public:
memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
memoryaccess_def_iterator_base() = default;
bool operator==(const memoryaccess_def_iterator_base &Other) const {
return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
}
BasicBlock *getPhiArgBlock() const {
MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
assert(MP && "Tried to get phi arg block when not iterating over a PHI");
return MP->getIncomingBlock(ArgNo);
}
typename std::iterator_traits<BaseT>::pointer operator*() const {
assert(Access && "Tried to access past the end of our iterator");
if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
return MP->getIncomingValue(ArgNo);
return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
}
using BaseT::operator++;
memoryaccess_def_iterator_base &operator++() {
assert(Access && "Hit end of iterator");
if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
if (++ArgNo >= MP->getNumIncomingValues()) {
ArgNo = 0;
Access = nullptr;
}
} else {
Access = nullptr;
}
return *this;
}
private:
T *Access = nullptr;
unsigned ArgNo = 0;
};
inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
return memoryaccess_def_iterator(this);
}
inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
return const_memoryaccess_def_iterator(this);
}
inline memoryaccess_def_iterator MemoryAccess::defs_end() {
return memoryaccess_def_iterator();
}
inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
return const_memoryaccess_def_iterator();
}
template <> struct GraphTraits<MemoryAccess *> {
using NodeRef = MemoryAccess *;
using ChildIteratorType = memoryaccess_def_iterator;
static NodeRef getEntryNode(NodeRef N) { return N; }
static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
};
template <> struct GraphTraits<Inverse<MemoryAccess *>> {
using NodeRef = MemoryAccess *;
using ChildIteratorType = MemoryAccess::iterator;
static NodeRef getEntryNode(NodeRef N) { return N; }
static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
};
class upward_defs_iterator
: public iterator_facade_base<upward_defs_iterator,
std::forward_iterator_tag,
const MemoryAccessPair> {
using BaseT = upward_defs_iterator::iterator_facade_base;
public:
upward_defs_iterator(const MemoryAccessPair &Info, DominatorTree *DT,
bool *PerformedPhiTranslation = nullptr)
: DefIterator(Info.first), Location(Info.second),
OriginalAccess(Info.first), DT(DT),
PerformedPhiTranslation(PerformedPhiTranslation) {
CurrentPair.first = nullptr;
WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
fillInCurrentPair();
}
upward_defs_iterator() { CurrentPair.first = nullptr; }
bool operator==(const upward_defs_iterator &Other) const {
return DefIterator == Other.DefIterator;
}
typename std::iterator_traits<BaseT>::reference operator*() const {
assert(DefIterator != OriginalAccess->defs_end() &&
"Tried to access past the end of our iterator");
return CurrentPair;
}
using BaseT::operator++;
upward_defs_iterator &operator++() {
assert(DefIterator != OriginalAccess->defs_end() &&
"Tried to access past the end of the iterator");
++DefIterator;
if (DefIterator != OriginalAccess->defs_end())
fillInCurrentPair();
return *this;
}
BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
private:
bool IsGuaranteedLoopInvariant(Value *Ptr) const;
void fillInCurrentPair() {
CurrentPair.first = *DefIterator;
CurrentPair.second = Location;
if (WalkingPhi && Location.Ptr) {
if (Location.Ptr &&
!IsGuaranteedLoopInvariant(const_cast<Value *>(Location.Ptr)))
CurrentPair.second =
Location.getWithNewSize(LocationSize::beforeOrAfterPointer());
PHITransAddr Translator(
const_cast<Value *>(Location.Ptr),
OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
DefIterator.getPhiArgBlock(), DT,
true)) {
Value *TransAddr = Translator.getAddr();
if (TransAddr != Location.Ptr) {
CurrentPair.second = CurrentPair.second.getWithNewPtr(TransAddr);
if (TransAddr &&
!IsGuaranteedLoopInvariant(const_cast<Value *>(TransAddr)))
CurrentPair.second = CurrentPair.second.getWithNewSize(
LocationSize::beforeOrAfterPointer());
if (PerformedPhiTranslation)
*PerformedPhiTranslation = true;
}
}
}
}
MemoryAccessPair CurrentPair;
memoryaccess_def_iterator DefIterator;
MemoryLocation Location;
MemoryAccess *OriginalAccess = nullptr;
DominatorTree *DT = nullptr;
bool WalkingPhi = false;
bool *PerformedPhiTranslation = nullptr;
};
inline upward_defs_iterator
upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT,
bool *PerformedPhiTranslation = nullptr) {
return upward_defs_iterator(Pair, &DT, PerformedPhiTranslation);
}
inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
inline iterator_range<upward_defs_iterator>
upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) {
return make_range(upward_defs_begin(Pair, DT), upward_defs_end());
}
template <class T, bool UseOptimizedChain = false>
struct def_chain_iterator
: public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
std::forward_iterator_tag, MemoryAccess *> {
def_chain_iterator() : MA(nullptr) {}
def_chain_iterator(T MA) : MA(MA) {}
T operator*() const { return MA; }
def_chain_iterator &operator++() {
if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
if (UseOptimizedChain && MUD->isOptimized())
MA = MUD->getOptimized();
else
MA = MUD->getDefiningAccess();
} else {
MA = nullptr;
}
return *this;
}
bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
private:
T MA;
};
template <class T>
inline iterator_range<def_chain_iterator<T>>
def_chain(T MA, MemoryAccess *UpTo = nullptr) {
#ifdef EXPENSIVE_CHECKS
assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
"UpTo isn't in the def chain!");
#endif
return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
}
template <class T>
inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
return make_range(def_chain_iterator<T, true>(MA),
def_chain_iterator<T, true>(nullptr));
}
}
#endif