31#include "llvm/Config/llvm-config.h"
62#define DEBUG_TYPE "memoryssa"
77 "memssa-check-limit",
cl::Hidden,
cl::init(100),
78 cl::desc(
"The maximum number of stores/phis MemorySSA"
79 "will consider trying to walk past (default = 100)"));
82#ifdef EXPENSIVE_CHECKS
102 MemorySSAAnnotatedWriter(
const MemorySSA *M) : MSSA(M) {}
104 void emitBasicBlockStartAnnot(
const BasicBlock *BB,
107 OS <<
"; " << *MA <<
"\n";
113 OS <<
"; " << *MA <<
"\n";
125 MemorySSAWalkerAnnotatedWriter(
MemorySSA *M)
126 : MSSA(M), Walker(M->getWalker()), BAA(M->getAA()) {}
128 void emitBasicBlockStartAnnot(
const BasicBlock *BB,
131 OS <<
"; " << *MA <<
"\n";
140 OS <<
" - clobbered by ";
160class MemoryLocOrCall {
164 MemoryLocOrCall(MemoryUseOrDef *MUD)
165 : MemoryLocOrCall(MUD->getMemoryInst()) {}
166 MemoryLocOrCall(
const MemoryUseOrDef *MUD)
167 : MemoryLocOrCall(MUD->getMemoryInst()) {}
169 MemoryLocOrCall(Instruction *Inst) {
182 explicit MemoryLocOrCall(
const MemoryLocation &Loc) : Loc(Loc) {}
184 const CallBase *getCall()
const {
189 MemoryLocation getLoc()
const {
195 if (IsCall !=
Other.IsCall)
199 return Loc ==
Other.Loc;
206 Other.Call->arg_begin());
211 const CallBase *
Call;
229 MLOC.getCall()->getCalledOperand()));
231 for (
const Value *Arg : MLOC.getCall()->args())
236 static bool isEqual(
const MemoryLocOrCall &LHS,
const MemoryLocOrCall &RHS) {
251 bool VolatileUse =
Use->isVolatile();
252 bool VolatileClobber = MayClobber->
isVolatile();
254 if (VolatileUse && VolatileClobber)
270 return !(SeqCstUse || MayClobberIsAcquire);
273template <
typename AliasAnalysisType>
278 assert(DefInst &&
"Defining instruction not actually an instruction");
288 switch (
II->getIntrinsicID()) {
289 case Intrinsic::allow_runtime_check:
290 case Intrinsic::allow_ubsan_check:
291 case Intrinsic::invariant_start:
292 case Intrinsic::invariant_end:
293 case Intrinsic::assume:
294 case Intrinsic::experimental_noalias_scope_decl:
295 case Intrinsic::pseudoprobe:
315template <
typename AliasAnalysisType>
317 const MemoryLocOrCall &UseMLOC,
318 AliasAnalysisType &
AA) {
336struct UpwardsMemoryQuery {
346 bool SkipSelfAccess =
false;
348 UpwardsMemoryQuery() =
default;
359template <
typename AliasAnalysisType>
364 if (
I->hasMetadata(LLVMContext::MD_invariant_load))
385[[maybe_unused]]
static void
389 bool AllowImpreciseClobber =
false) {
390 assert(MSSA.
dominates(ClobberAt, Start) &&
"Clobber doesn't dominate start?");
394 "liveOnEntry must clobber itself");
398 bool FoundClobber =
false;
401 Worklist.
push_back({Start, StartLoc,
false});
404 while (!Worklist.
empty()) {
412 if (MA == ClobberAt) {
439 "Found clobber before reaching ClobberAt!");
446 "Can only find use in def chain if Start is a use");
467 if (AllowImpreciseClobber)
473 "ClobberAt never acted as a clobber");
482 using ListIndex = unsigned;
492 std::optional<ListIndex> Previous;
493 bool MayBeCrossIteration;
495 DefPath(
const MemoryLocation &Loc, MemoryAccess *
First, MemoryAccess *
Last,
496 bool MayBeCrossIteration, std::optional<ListIndex> Previous)
498 MayBeCrossIteration(MayBeCrossIteration) {}
500 DefPath(
const MemoryLocation &Loc, MemoryAccess *Init,
501 bool MayBeCrossIteration, std::optional<ListIndex> Previous)
502 : DefPath(Loc, Init, Init, MayBeCrossIteration, Previous) {}
508 UpwardsMemoryQuery *Query;
509 unsigned *UpwardWalkLimit;
516 DenseSet<UpwardDefsElem> VisitedPhis;
519 const MemoryAccess *getWalkTarget(
const MemoryPhi *From)
const {
525 while ((Node =
Node->getIDom())) {
534 struct UpwardsWalkResult {
547 walkToPhiOrClobber(DefPath &
Desc,
const MemoryAccess *StopAt =
nullptr,
548 const MemoryAccess *SkipStopAt =
nullptr)
const {
550 assert(UpwardWalkLimit &&
"Need a valid walk limit");
551 bool LimitAlreadyReached =
false;
556 if (!*UpwardWalkLimit) {
557 *UpwardWalkLimit = 1;
558 LimitAlreadyReached =
true;
563 if (Current == StopAt || Current == SkipStopAt)
564 return {Current,
false};
570 if (!--*UpwardWalkLimit)
571 return {Current,
true};
573 BatchAACrossIterationScope
_(*AA,
Desc.MayBeCrossIteration);
579 if (LimitAlreadyReached)
580 *UpwardWalkLimit = 0;
583 "Ended at a non-clobber that's not a phi?");
584 return {
Desc.Last,
false};
587 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
588 ListIndex PriorNode,
bool MayBeCrossIteration) {
589 auto UpwardDefsBegin =
592 for (
const UpwardDefsElem &
E : UpwardDefs) {
601 struct TerminatedPath {
602 MemoryAccess *Clobber;
615 std::optional<TerminatedPath>
616 getBlockingAccess(
const MemoryAccess *StopWhere,
617 SmallVectorImpl<ListIndex> &PausedSearches,
618 SmallVectorImpl<ListIndex> &NewPaused,
619 SmallVectorImpl<TerminatedPath> &Terminated) {
620 assert(!PausedSearches.
empty() &&
"No searches to continue?");
624 while (!PausedSearches.
empty()) {
626 DefPath &
Node = Paths[PathIndex];
646 if (!VisitedPhis.
insert({Node.Last, Node.Loc, Node.MayBeCrossIteration})
650 const MemoryAccess *SkipStopWhere =
nullptr;
651 if (Query->SkipSelfAccess &&
Node.Loc == Query->StartingLoc) {
653 SkipStopWhere = Query->OriginalAccess;
656 UpwardsWalkResult Res = walkToPhiOrClobber(Node,
659 if (Res.IsKnownClobber) {
660 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
664 TerminatedPath
Term{Res.Result, PathIndex};
665 if (!MSSA.
dominates(Res.Result, StopWhere))
673 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
678 if (Res.Result != SkipStopWhere)
685 Node.MayBeCrossIteration);
691 template <
typename T,
typename Walker>
692 struct generic_def_path_iterator
693 :
public iterator_facade_base<generic_def_path_iterator<T, Walker>,
694 std::forward_iterator_tag, T *> {
695 generic_def_path_iterator() =
default;
696 generic_def_path_iterator(Walker *W, ListIndex
N) :
W(
W),
N(
N) {}
700 generic_def_path_iterator &operator++() {
701 N = curNode().Previous;
705 bool operator==(
const generic_def_path_iterator &O)
const {
706 if (
N.has_value() !=
O.N.has_value())
708 return !
N || *
N == *
O.N;
712 T &curNode()
const {
return W->Paths[*
N]; }
715 std::optional<ListIndex>
N;
718 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
719 using const_def_path_iterator =
720 generic_def_path_iterator<const DefPath, const ClobberWalker>;
723 return make_range(def_path_iterator(
this, From), def_path_iterator());
727 return make_range(const_def_path_iterator(
this, From),
728 const_def_path_iterator());
733 TerminatedPath PrimaryClobber;
739 ListIndex defPathIndex(
const DefPath &
N)
const {
741 const DefPath *NP = &
N;
743 "Out of bounds DefPath!");
744 return NP - &Paths.
front();
760 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
761 const MemoryLocation &Loc) {
763 "Reset the optimization state.");
769 auto PriorPathsSize = Paths.
size();
775 addSearches(Phi, PausedSearches, 0,
false);
779 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
781 auto Dom = Paths.
begin();
782 for (
auto I = std::next(Dom),
E = Paths.
end();
I !=
E; ++
I)
783 if (!MSSA.
dominates(
I->Clobber, Dom->Clobber))
787 std::iter_swap(
Last, Dom);
790 MemoryPhi *Current =
Phi;
793 "liveOnEntry wasn't treated as a clobber?");
795 const auto *
Target = getWalkTarget(Current);
798 assert(
all_of(TerminatedPaths, [&](
const TerminatedPath &
P) {
805 if (std::optional<TerminatedPath> Blocker = getBlockingAccess(
806 Target, PausedSearches, NewPaused, TerminatedPaths)) {
810 auto Iter =
find_if(def_path(Blocker->LastNode), [&](
const DefPath &
N) {
811 return defPathIndex(N) < PriorPathsSize;
813 assert(Iter != def_path_iterator());
815 DefPath &CurNode = *Iter;
816 assert(CurNode.Last == Current);
843 TerminatedPath
Result{CurNode.Last, defPathIndex(CurNode)};
850 if (NewPaused.
empty()) {
851 MoveDominatedPathToEnd(TerminatedPaths);
853 return {
Result, std::move(TerminatedPaths)};
856 MemoryAccess *DefChainEnd =
nullptr;
858 for (ListIndex Paused : NewPaused) {
859 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
860 if (WR.IsKnownClobber)
864 DefChainEnd = WR.Result;
867 if (!TerminatedPaths.
empty()) {
871 for (
auto *MA :
def_chain(
const_cast<MemoryAccess *
>(Target)))
873 assert(DefChainEnd &&
"Failed to find dominating phi/liveOnEntry");
878 for (
const TerminatedPath &TP : TerminatedPaths) {
881 if (DT.
dominates(ChainBB, TP.Clobber->getBlock()))
888 if (!Clobbers.
empty()) {
889 MoveDominatedPathToEnd(Clobbers);
891 return {
Result, std::move(Clobbers)};
895 [&](ListIndex
I) {
return Paths[
I].Last == DefChainEnd; }));
900 PriorPathsSize = Paths.
size();
901 PausedSearches.
clear();
902 for (ListIndex
I : NewPaused)
903 addSearches(DefChainPhi, PausedSearches,
I,
904 Paths[
I].MayBeCrossIteration);
907 Current = DefChainPhi;
911 void verifyOptResult(
const OptznResult &R)
const {
913 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
917 void resetPhiOptznState() {
923 ClobberWalker(
const MemorySSA &MSSA, DominatorTree &DT)
924 : MSSA(MSSA), DT(DT) {}
928 MemoryAccess *findClobber(BatchAAResults &BAA, MemoryAccess *Start,
929 UpwardsMemoryQuery &Q,
unsigned &UpWalkLimit) {
932 UpwardWalkLimit = &UpWalkLimit;
937 MemoryAccess *Current =
Start;
941 Current = MU->getDefiningAccess();
943 DefPath FirstDesc(Q.StartingLoc, Current, Current,
944 false, std::nullopt);
947 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
949 if (WalkResult.IsKnownClobber) {
950 Result = WalkResult.Result;
953 Current, Q.StartingLoc);
954 verifyOptResult(OptRes);
955 resetPhiOptznState();
956 Result = OptRes.PrimaryClobber.Clobber;
959#ifdef EXPENSIVE_CHECKS
960 if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
967struct RenamePassData {
969 DomTreeNode::const_iterator ChildIt;
970 MemoryAccess *IncomingVal;
972 RenamePassData(
DomTreeNode *
D, DomTreeNode::const_iterator It,
974 : DTN(
D), ChildIt(It), IncomingVal(
M) {}
976 void swap(RenamePassData &
RHS) {
988 ClobberWalker Walker;
1005 bool UseInvariantGroup =
true);
1023 return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL,
false);
1028 return Walker->getClobberingMemoryAccessBase(MA,
Loc, BAA, UWL);
1033 return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL,
false,
false);
1050 MUD->resetOptimized();
1066 return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL,
true);
1071 return Walker->getClobberingMemoryAccessBase(MA,
Loc, BAA, UWL);
1088 MUD->resetOptimized();
1095 bool RenameAllUses) {
1098 auto It = PerBlockAccesses.find(S);
1100 if (It == PerBlockAccesses.end() || !
isa<MemoryPhi>(It->second->front()))
1104 if (RenameAllUses) {
1105 bool ReplacementDone =
false;
1106 for (
unsigned I = 0,
E = Phi->getNumIncomingValues();
I !=
E; ++
I)
1107 if (Phi->getIncomingBlock(
I) == BB) {
1108 Phi->setIncomingValue(
I, IncomingVal);
1109 ReplacementDone =
true;
1111 (void) ReplacementDone;
1112 assert(ReplacementDone &&
"Incomplete phi during partial rename");
1114 Phi->addIncoming(IncomingVal, BB);
1122 bool RenameAllUses) {
1123 auto It = PerBlockAccesses.find(BB);
1125 if (It != PerBlockAccesses.end()) {
1127 for (MemoryAccess &L : *
Accesses) {
1129 if (MUD->getDefiningAccess() ==
nullptr || RenameAllUses)
1130 MUD->setDefiningAccess(IncomingVal);
1147 bool SkipVisited,
bool RenameAllUses) {
1148 assert(Root &&
"Trying to rename accesses in an unreachable block");
1155 if (SkipVisited && AlreadyVisited)
1158 IncomingVal = renameBlock(Root->
getBlock(), IncomingVal, RenameAllUses);
1159 renameSuccessorPhis(Root->
getBlock(), IncomingVal, RenameAllUses);
1162 while (!WorkStack.
empty()) {
1164 DomTreeNode::const_iterator ChildIt = WorkStack.
back().ChildIt;
1165 IncomingVal = WorkStack.
back().IncomingVal;
1167 if (ChildIt ==
Node->end()) {
1171 ++WorkStack.
back().ChildIt;
1175 AlreadyVisited = !Visited.
insert(BB).second;
1176 if (SkipVisited && AlreadyVisited) {
1183 IncomingVal = &*BlockDefs->rbegin();
1185 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1186 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
1195void MemorySSA::markUnreachableAsLiveOnEntry(
BasicBlock *BB) {
1196 assert(!DT->isReachableFromEntry(BB) &&
1197 "Reachable block found while handling unreachable blocks");
1204 if (!DT->isReachableFromEntry(S))
1206 auto It = PerBlockAccesses.find(S);
1208 if (It == PerBlockAccesses.end() || !
isa<MemoryPhi>(It->second->front()))
1212 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1215 auto It = PerBlockAccesses.find(BB);
1216 if (It == PerBlockAccesses.end())
1221 auto Next = std::next(AI);
1225 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1233 : DT(DT), F(&Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1234 SkipWalker(nullptr) {
1240 assert(AA &&
"No alias analysis?");
1251 : DT(DT), L(&L), LiveOnEntryDef(nullptr), Walker(nullptr),
1252 SkipWalker(nullptr) {
1258 assert(AA &&
"No alias analysis?");
1262 return *const_cast<BasicBlock *>(BB);
1273 for (
const auto &Pair : PerBlockAccesses)
1279 auto Res = PerBlockAccesses.try_emplace(BB);
1282 Res.first->second = std::make_unique<AccessList>();
1283 return Res.first->second.get();
1287 auto Res = PerBlockDefs.try_emplace(BB);
1290 Res.first->second = std::make_unique<DefsList>();
1291 return Res.first->second.get();
1307 : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
1313 struct MemlocStackInfo {
1316 unsigned long StackEpoch;
1317 unsigned long PopEpoch;
1322 unsigned long LowerBound;
1325 unsigned long LastKill;
1329 void optimizeUsesInBlock(
const BasicBlock *,
unsigned long &,
unsigned long &,
1334 CachingWalker *Walker;
1353void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1354 const BasicBlock *BB,
unsigned long &StackEpoch,
unsigned long &PopEpoch,
1367 !VersionStack.
empty() &&
1368 "Version stack should have liveOnEntry sentinel dominating everything");
1370 if (DT->dominates(BackBlock, BB))
1372 while (VersionStack.
back()->getBlock() == BackBlock)
1377 for (MemoryAccess &MA : *
Accesses) {
1385 if (MU->isOptimized())
1388 MemoryLocOrCall UseMLOC(MU);
1389 auto &LocInfo = LocStackInfo[UseMLOC];
1393 if (LocInfo.PopEpoch != PopEpoch) {
1394 LocInfo.PopEpoch = PopEpoch;
1395 LocInfo.StackEpoch = StackEpoch;
1407 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
1408 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
1412 LocInfo.LowerBound = 0;
1413 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
1414 LocInfo.LastKillValid =
false;
1416 }
else if (LocInfo.StackEpoch != StackEpoch) {
1420 LocInfo.PopEpoch = PopEpoch;
1421 LocInfo.StackEpoch = StackEpoch;
1423 if (!LocInfo.LastKillValid) {
1424 LocInfo.LastKill = VersionStack.
size() - 1;
1425 LocInfo.LastKillValid =
true;
1430 assert(LocInfo.LowerBound < VersionStack.
size() &&
1431 "Lower bound out of range");
1432 assert(LocInfo.LastKill < VersionStack.
size() &&
1433 "Last kill info out of range");
1435 unsigned long UpperBound = VersionStack.
size() - 1;
1438 LLVM_DEBUG(
dbgs() <<
"MemorySSA skipping optimization of " << *MU <<
" ("
1439 << *(MU->getMemoryInst()) <<
")"
1440 <<
" because there are "
1441 << UpperBound - LocInfo.LowerBound
1442 <<
" stores to disambiguate\n");
1445 LocInfo.LastKillValid =
false;
1448 bool FoundClobberResult =
false;
1450 while (UpperBound > LocInfo.LowerBound) {
1456 Walker->getClobberingMemoryAccessWithoutInvariantGroup(
1457 MU, *AA, UpwardWalkLimit);
1459 while (VersionStack[UpperBound] != Result) {
1463 FoundClobberResult =
true;
1469 FoundClobberResult =
true;
1477 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1478 MU->setDefiningAccess(VersionStack[UpperBound],
true);
1479 LocInfo.LastKill = UpperBound;
1483 MU->setDefiningAccess(VersionStack[LocInfo.LastKill],
true);
1485 LocInfo.LowerBound = VersionStack.
size() - 1;
1486 LocInfo.LowerBoundBlock = BB;
1494 VersionStack.
push_back(MSSA->getLiveOnEntryDef());
1496 unsigned long StackEpoch = 1;
1497 unsigned long PopEpoch = 1;
1499 for (
const auto *DomNode :
depth_first(DT->getRootNode()))
1500 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1504void MemorySSA::placePHINodes(
1508 IDFs.setDefiningBlocks(DefiningBlocks);
1510 IDFs.calculate(IDFBlocks);
1513 for (
auto &BB : IDFBlocks)
1514 createMemoryPhi(BB);
1517template <
typename IterT>
1518void MemorySSA::buildMemorySSA(
BatchAAResults &BAA, IterT Blocks) {
1527 nullptr, &StartingPoint, NextID++));
1536 bool InsertIntoDef =
false;
1548 InsertIntoDef =
true;
1550 Defs = getOrCreateDefsList(&
B);
1551 Defs->push_back(*MUD);
1557 placePHINodes(DefiningBlocks);
1561 SmallPtrSet<BasicBlock *, 16> Visited;
1568 U.set(LiveOnEntryDef.get());
1574 L->getExitBlocks(ExitBlocks);
1576 renamePass(DT->getNode(L->getLoopPreheader()), LiveOnEntryDef.get(),
1579 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1584 for (
auto &BB : Blocks)
1585 if (!Visited.
count(&BB))
1586 markUnreachableAsLiveOnEntry(&BB);
1593 return Walker.get();
1596 WalkerBase = std::make_unique<ClobberWalkerBase>(
this, DT);
1598 Walker = std::make_unique<CachingWalker>(
this, WalkerBase.get());
1599 return Walker.get();
1604 return SkipWalker.get();
1607 WalkerBase = std::make_unique<ClobberWalkerBase>(
this, DT);
1609 SkipWalker = std::make_unique<SkipSelfWalker>(
this, WalkerBase.get());
1610 return SkipWalker.get();
1620 auto *
Accesses = getOrCreateAccessList(BB);
1626 auto *Defs = getOrCreateDefsList(BB);
1627 Defs->push_front(*NewAccess);
1633 auto *Defs = getOrCreateDefsList(BB);
1636 Defs->insert(DI, *NewAccess);
1642 auto *Defs = getOrCreateDefsList(BB);
1643 Defs->push_back(*NewAccess);
1646 BlockNumberingValid.erase(BB);
1652 bool WasEnd = InsertPt ==
Accesses->end();
1655 auto *Defs = getOrCreateDefsList(BB);
1661 Defs->push_back(*What);
1663 Defs->insert(InsertPt->getDefsIterator(), *What);
1669 Defs->push_back(*What);
1671 Defs->insert(InsertPt->getDefsIterator(), *What);
1674 BlockNumberingValid.erase(BB);
1695 prepareForMoveTo(What, BB);
1703 "Can only move a Phi at the beginning of the block");
1705 ValueToMemoryAccess.erase(What->
getBlock());
1706 bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1708 assert(Inserted &&
"Cannot move a Phi to a block that already has one");
1711 prepareForMoveTo(What, BB);
1720 ValueToMemoryAccess[BB] = Phi;
1727 bool CreationMustSucceed) {
1730 if (CreationMustSucceed)
1731 assert(NewAccess !=
nullptr &&
"Tried to create a memory access for a "
1732 "non-memory touching instruction");
1735 "A use cannot be a defining access");
1746 if (!
SI->isUnordered())
1749 if (!LI->isUnordered())
1756template <
typename AliasAnalysisType>
1757MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *
I,
1758 AliasAnalysisType *AAP,
1767 switch (
II->getIntrinsicID()) {
1770 case Intrinsic::allow_runtime_check:
1771 case Intrinsic::allow_ubsan_check:
1772 case Intrinsic::assume:
1773 case Intrinsic::experimental_noalias_scope_decl:
1774 case Intrinsic::pseudoprobe:
1782 if (!
I->mayReadFromMemory() && !
I->mayWriteToMemory())
1791 bool DefCheck, UseCheck;
1796 assert((Def == DefCheck || !DefCheck) &&
1797 "Memory accesses should only be reduced");
1798 if (!Def && Use != UseCheck) {
1800 assert(!UseCheck &&
"Invalid template");
1823 MemoryUseOrDef *MUD;
1825 MUD =
new MemoryDef(
I->getContext(),
nullptr,
I,
I->getParent(), NextID++);
1827 MUD =
new MemoryUse(
I->getContext(),
nullptr,
I,
I->getParent());
1833 ValueToMemoryAccess[
I] = MUD;
1840 "Trying to remove memory access that still has uses");
1841 BlockNumbering.erase(MA);
1854 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1855 if (VMA->second == MA)
1856 ValueToMemoryAccess.
erase(VMA);
1870 auto DefsIt = PerBlockDefs.find(BB);
1871 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1874 PerBlockDefs.erase(DefsIt);
1879 auto AccessIt = PerBlockAccesses.find(BB);
1880 std::unique_ptr<AccessList> &
Accesses = AccessIt->second;
1887 PerBlockAccesses.erase(AccessIt);
1888 BlockNumberingValid.erase(BB);
1893 MemorySSAAnnotatedWriter Writer(
this);
1897 F->
print(OS, &Writer);
1900#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1905#if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
1917 assert(L &&
"must either have loop or function");
1920 return *const_cast<BasicBlock *>(BB);
1940template <
typename IterT>
1944 for (
unsigned I = 0, E = Phi->getNumIncomingValues();
I != E; ++
I) {
1945 auto *Pred = Phi->getIncomingBlock(
I);
1946 auto *IncAcc = Phi->getIncomingValue(
I);
1950 if (
auto *DTNode = DT->getNode(Pred)) {
1952 if (
auto *DefList =
getBlockDefs(DTNode->getBlock())) {
1953 auto *LastAcc = &*(--DefList->end());
1954 assert(LastAcc == IncAcc &&
1955 "Incorrect incoming access into phi.");
1960 DTNode = DTNode->getIDom();
1977template <
typename IterT>
1979 if (BlockNumberingValid.empty())
1984 if (!ValidBlocks.
count(&BB))
1987 ValidBlocks.
erase(&BB);
1995 unsigned long LastNumber = 0;
1997 auto ThisNumberIter = BlockNumbering.find(&MA);
1998 assert(ThisNumberIter != BlockNumbering.end() &&
1999 "MemoryAccess has no domination number in a valid block!");
2001 unsigned long ThisNumber = ThisNumberIter->second;
2002 assert(ThisNumber > LastNumber &&
2003 "Domination numbers should be strictly increasing!");
2005 LastNumber = ThisNumber;
2010 "All valid BasicBlocks should exist in F -- dangling pointers?");
2019template <
typename IterT>
2036 for (
const Use &U : Phi->uses()) {
2037 assert(
dominates(Phi, U) &&
"Memory PHI does not dominate it's uses");
2043 "Incomplete MemoryPhi Node");
2044 for (
unsigned I = 0, E = Phi->getNumIncomingValues();
I != E; ++
I) {
2045 verifyUseInDefs(Phi->getIncomingValue(
I), Phi);
2047 "Incoming phi block not a block predecessor");
2055 "We have memory affecting instructions "
2056 "in this block but they are not in the "
2057 "access list or defs list");
2065 for (
const Use &U : MD->
uses()) {
2067 "Memory Def does not dominate it's uses");
2081 assert(AL->size() == ActualAccesses.
size() &&
2082 "We don't have the same number of accesses in the block as on the "
2085 "Either we should have a defs list, or we should have no defs");
2087 "We don't have the same number of defs in the block as on the "
2089 auto ALI = AL->begin();
2090 auto AAI = ActualAccesses.
begin();
2091 while (ALI != AL->end() && AAI != ActualAccesses.
end()) {
2092 assert(&*ALI == *AAI &&
"Not the same accesses in the same order");
2096 ActualAccesses.
clear();
2098 auto DLI =
DL->begin();
2099 auto ADI = ActualDefs.
begin();
2100 while (DLI !=
DL->end() && ADI != ActualDefs.
end()) {
2101 assert(&*DLI == *ADI &&
"Not the same defs in the same order");
2116 "Null def but use not point to live on entry def");
2119 "Did not find use in def's use list");
2128void MemorySSA::renumberBlock(
const BasicBlock *
B)
const {
2130 unsigned long CurrentNumber = 0;
2132 assert(AL !=
nullptr &&
"Asking to renumber an empty block");
2133 for (
const auto &
I : *AL)
2134 BlockNumbering[&
I] = ++CurrentNumber;
2135 BlockNumberingValid.insert(
B);
2146 "Asking for local domination when accesses are in different blocks!");
2148 if (Dominatee == Dominator)
2161 if (!BlockNumberingValid.count(DominatorBlock))
2162 renumberBlock(DominatorBlock);
2164 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2166 assert(DominatorNum != 0 &&
"Block was not numbered properly");
2167 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2168 assert(DominateeNum != 0 &&
"Block was not numbered properly");
2169 return DominatorNum < DominateeNum;
2174 if (Dominator == Dominatee)
2186 const Use &Dominatee)
const {
2188 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2190 if (UseBB != Dominator->
getBlock())
2191 return DT->dominates(Dominator->
getBlock(), UseBB);
2212 case MemoryPhiVal:
return static_cast<const MemoryPhi *
>(
this)->
print(OS);
2213 case MemoryDefVal:
return static_cast<const MemoryDef *
>(
this)->
print(OS);
2214 case MemoryUseVal:
return static_cast<const MemoryUse *
>(
this)->
print(OS);
2223 if (
A &&
A->getID())
2229 OS <<
getID() <<
" = MemoryDef(";
2241 OS <<
getID() <<
" = MemoryPhi(";
2252 if (
unsigned ID = MA->
getID())
2264 if (UO && UO->
getID())
2273#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2282 MemorySSAAnnotatedWriter MSSAWriter;
2286 : F(F), MSSAWriter(&MSSA) {}
2289 MemorySSAAnnotatedWriter &
getWriter() {
return MSSAWriter; }
2297 return &(CFGInfo->
getFunction()->getEntryBlock());
2332 [](std::string &S,
unsigned &
I,
unsigned Idx) ->
void {
2333 std::string Str = S.substr(
I, Idx -
I);
2335 if (SR.
count(
" = MemoryDef(") || SR.
count(
" = MemoryPhi(") ||
2336 SR.
count(
"MemoryUse("))
2356 ?
"style=filled, fillcolor=lightpink"
2363AnalysisKey MemorySSAAnalysis::Key;
2374 FunctionAnalysisManager::Invalidator &Inv) {
2384 if (EnsureOptimizedUses)
2390 OS <<
"MemorySSA for function: " <<
F.getName() <<
"\n";
2400 OS <<
"MemorySSA (walker) for function: " <<
F.getName() <<
"\n";
2401 MemorySSAWalkerAnnotatedWriter Writer(&MSSA);
2402 F.print(OS, &Writer);
2435 MSSA->verifyMemorySSA();
2454 if (
Loc.Ptr ==
nullptr)
2455 return StartingAccess;
2460 return StartingUseOrDef;
2462 I = StartingUseOrDef->getMemoryInst();
2467 return StartingUseOrDef;
2470 UpwardsMemoryQuery Q;
2471 Q.OriginalAccess = StartingAccess;
2472 Q.StartingLoc =
Loc;
2480 Walker.findClobber(BAA, StartingAccess, Q, UpwardWalkLimit);
2482 dbgs() <<
"Clobber starting at access " << *StartingAccess <<
"\n";
2484 dbgs() <<
" for instruction " << *
I <<
"\n";
2485 dbgs() <<
" is " << *Clobber <<
"\n";
2492 if (!
I.hasMetadata(LLVMContext::MD_invariant_group) ||
I.isVolatile())
2509 for (
const User *Us : PointerOperand->
users()) {
2511 if (!U || U == &
I || !DT.
dominates(U, MostDominatingInstruction))
2517 if (U->hasMetadata(LLVMContext::MD_invariant_group) &&
2519 MostDominatingInstruction = U;
2523 return MostDominatingInstruction == &
I ? nullptr : MostDominatingInstruction;
2527 MemoryAccess *MA, BatchAAResults &BAA,
unsigned &UpwardWalkLimit,
2528 bool SkipSelf,
bool UseInvariantGroup) {
2531 if (!StartingAccess)
2534 if (UseInvariantGroup) {
2536 *StartingAccess->getMemoryInst(), MSSA->
getDomTree())) {
2542 return ClobberMA->getDefiningAccess();
2547 bool IsOptimized =
false;
2552 if (StartingAccess->isOptimized()) {
2554 return StartingAccess->getOptimized();
2558 const Instruction *
I = StartingAccess->getMemoryInst();
2563 return StartingAccess;
2565 UpwardsMemoryQuery Q(
I, StartingAccess);
2569 StartingAccess->setOptimized(LiveOnEntry);
2573 MemoryAccess *OptimizedAccess;
2576 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2581 StartingAccess->setOptimized(DefiningAccess);
2582 return DefiningAccess;
2586 Walker.findClobber(BAA, DefiningAccess, Q, UpwardWalkLimit);
2587 StartingAccess->setOptimized(OptimizedAccess);
2589 OptimizedAccess = StartingAccess->getOptimized();
2591 LLVM_DEBUG(
dbgs() <<
"Starting Memory SSA clobber for " << *
I <<
" is ");
2593 LLVM_DEBUG(
dbgs() <<
"Optimized Memory SSA clobber for " << *
I <<
" is ");
2600 Q.SkipSelfAccess =
true;
2601 Result = Walker.findClobber(BAA, OptimizedAccess, Q, UpwardWalkLimit);
2603 Result = OptimizedAccess;
2605 LLVM_DEBUG(
dbgs() <<
"Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2615 return Use->getDefiningAccess();
2622 return Use->getDefiningAccess();
2623 return StartingAccess;
2634void MemoryUse::deleteMe(DerivedUser *Self) {
2635 delete static_cast<MemoryUse *
>(Self);
2638bool upward_defs_iterator::IsGuaranteedLoopInvariant(
const Value *Ptr)
const {
2639 auto IsGuaranteedLoopInvariantBase = [](
const Value *Ptr) {
2648 if (
I->getParent()->isEntryBlock())
2652 return IsGuaranteedLoopInvariantBase(
GEP->getPointerOperand()) &&
2653 GEP->hasAllConstantIndices();
2655 return IsGuaranteedLoopInvariantBase(Ptr);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
DXIL Forward Handle Accesses
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
early cse Early CSE w MemorySSA
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
This file provides utility analysis objects describing memory locations.
static bool instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc, const Instruction *UseInst, AliasAnalysisType &AA)
Memory static true cl::opt< unsigned > MaxCheckLimit("memssa-check-limit", cl::Hidden, cl::init(100), cl::desc("The maximum number of stores/phis MemorySSA" "will consider trying to walk past (default = 100)"))
static void checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt, const MemoryLocation &StartLoc, const MemorySSA &MSSA, const UpwardsMemoryQuery &Query, BatchAAResults &AA, bool AllowImpreciseClobber=false)
Verifies that Start is clobbered by ClobberAt, and that nothing inbetween Start and ClobberAt can clo...
static cl::opt< bool, true > VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA), cl::Hidden, cl::desc("Enable verification of MemorySSA."))
static const char LiveOnEntryStr[]
static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA, const Instruction *I)
static bool areLoadsReorderable(const LoadInst *Use, const LoadInst *MayClobber)
This does one-way checks to see if Use could theoretically be hoisted above MayClobber.
static const Instruction * getInvariantGroupClobberingInstruction(Instruction &I, DominatorTree &DT)
static cl::opt< std::string > DotCFGMSSA("dot-cfg-mssa", cl::value_desc("file name for generated dot file"), cl::desc("file name for generated dot file"), cl::init(""))
static bool isOrdered(const Instruction *I)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS)
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
DOTFuncMSSAInfo(const Function &F, MemorySSA &MSSA)
const Function * getFunction()
MemorySSAAnnotatedWriter & getWriter()
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
LLVM Basic Block Representation.
LLVM_ABI BasicBlock::iterator erase(BasicBlock::iterator FromIt, BasicBlock::iterator ToIt)
Erases a range of instructions from FromIt to (not including) ToIt.
iterator begin()
Instruction iterator methods.
LLVM_ABI void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the basic block to an output stream with an optional AssemblyAnnotationWriter.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
Temporarily set the cross iteration mode on a BatchAA instance.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getCalledOperand() const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
unsigned arg_size() const
Implements a dense probed hash-table based set.
Extension point for the Value hierarchy.
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *, BatchAAResults &) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
Analysis pass which computes a DominatorTree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
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.
Module * getParent()
Get the module that this global value is contained inside of...
A wrapper class for inspecting calls to intrinsic functions.
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
Represents a single loop in the control flow graph.
LLVM_ABI void dump() const
MemoryAccess(const MemoryAccess &)=delete
BasicBlock * getBlock() const
LLVM_ABI void print(raw_ostream &OS) const
unsigned getID() const
Used for debugging and tracking things about MemoryAccesses.
void setBlock(BasicBlock *BB)
Used by MemorySSA to change the block of a MemoryAccess when it is moved.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
LLVM_ABI void print(raw_ostream &OS) const
MemoryAccess * getOptimized() const
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Represents phi nodes for memory accesses.
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
LLVM_ABI void print(raw_ostream &OS) const
An analysis that produces MemorySSA for a function.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static LLVM_ABI bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This is the generic walker interface for walkers of MemorySSA.
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
LLVM_ABI MemorySSAWalker(MemorySSA *)
virtual void invalidateInfo(MemoryAccess *)
Given a memory access, invalidate anything this walker knows about that access.
Legacy analysis pass which computes MemorySSA.
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
A MemorySSAWalker that does AA walks to disambiguate accesses.
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
MemoryAccess * getClobberingMemoryAccessWithoutInvariantGroup(MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA, unsigned &UWL)
void invalidateInfo(MemoryAccess *MA) override
Given a memory access, invalidate anything this walker knows about that access.
~CachingWalker() override=default
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL)
CachingWalker(MemorySSA *M, ClobberWalkerBase *W)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA) override
Given a potentially clobbering memory access and a new location, calling this will give you the neare...
ClobberWalkerBase(MemorySSA *M, DominatorTree *D)
MemoryAccess * getClobberingMemoryAccessBase(MemoryAccess *, BatchAAResults &, unsigned &, bool, bool UseInvariantGroup=true)
MemoryAccess * getClobberingMemoryAccessBase(MemoryAccess *, const MemoryLocation &, BatchAAResults &, unsigned &)
This class is a batch walker of all MemoryUse's in the program, and points their defining access at t...
void optimizeUses()
Optimize uses to point to their actual clobbering definitions.
OptimizeUses(MemorySSA *MSSA, CachingWalker *Walker, BatchAAResults *BAA, DominatorTree *DT)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA) override
Given a potentially clobbering memory access and a new location, calling this will give you the neare...
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA, unsigned &UWL)
~SkipSelfWalker() override=default
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL)
SkipSelfWalker(MemorySSA *M, ClobberWalkerBase *W)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
void invalidateInfo(MemoryAccess *MA) override
Given a memory access, invalidate anything this walker knows about that access.
Encapsulates MemorySSA, including all data associated with memory accesses.
LLVM_ABI void dump() const
simple_ilist< MemoryAccess, ilist_tag< MSSAHelpers::DefsOnlyTag > > DefsList
LLVM_ABI void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where)
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, SmallPtrSetImpl< BasicBlock * > &Visited)
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
LLVM_ABI MemorySSA(Function &, AliasAnalysis *, DominatorTree *)
iplist< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag > > AccessList
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
void verifyOrderingDominationAndDefUses(IterT Blocks, VerificationLevel=VerificationLevel::Fast) const
Verify ordering: the order and existence of MemoryAccesses matches the order and existence of memory ...
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
LLVM_ABI void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *, InsertionPlace)
LLVM_ABI MemorySSAWalker * getWalker()
InsertionPlace
Used in various insertion functions to specify whether we are talking about the beginning or end of a...
LLVM_ABI void insertIntoListsBefore(MemoryAccess *, const BasicBlock *, AccessList::iterator)
LLVM_ABI MemoryUseOrDef * createDefinedAccess(Instruction *, MemoryAccess *, const MemoryUseOrDef *Template=nullptr, bool CreationMustSucceed=true)
DominatorTree & getDomTree() const
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
MemoryAccess * getLiveOnEntryDef() const
LLVM_ABI void removeFromLookups(MemoryAccess *)
Properly remove MA from all of MemorySSA's lookup tables.
LLVM_ABI void ensureOptimizedUses()
By default, uses are not optimized during MemorySSA construction.
void verifyDominationNumbers(IterT Blocks) const
Verify that all of the blocks we believe to have valid domination numbers actually have valid dominat...
void verifyPrevDefInPhis(IterT Blocks) const
LLVM_ABI bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
LLVM_ABI void removeFromLists(MemoryAccess *, bool ShouldDelete=true)
Properly remove MA from all of MemorySSA's lists.
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
LLVM_ABI void print(raw_ostream &) const
Class that has the common methods + fields of memory uses/defs.
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
void setDefiningAccess(MemoryAccess *DMA, bool Optimized=false)
void setOptimized(MemoryAccess *)
Sets the optimized use for a MemoryDef.
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
LLVM_ABI void print(raw_ostream &OS) const
A Module instance is used to store all the information related to an LLVM module.
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the module to an output stream with an optional AssemblyAnnotationWriter.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
size_t count(char C) const
Return the number of occurrences of C in the string.
A Use represents the edge between a Value definition and its users.
User * getUser() const
Returns the User that contains this Use.
void dropAllReferences()
Drop all references to operands.
unsigned getNumOperands() const
LLVM Value Representation.
iterator_range< user_iterator > users()
unsigned getValueID() const
Return an ID for the concrete type of this object.
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
An opaque object representing a hash code.
typename base_list_type::iterator iterator
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
reverse_iterator rbegin()
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
@ BasicBlock
Various leaf nodes.
This namespace contains all of the command line option processing machinery.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
NodeAddr< DefNode * > Def
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
APInt operator*(APInt a, uint64_t RHS)
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
DomTreeNodeBase< BasicBlock > DomTreeNode
auto dyn_cast_or_null(const Y &Val)
iterator_range< def_chain_iterator< T > > def_chain(T MA, MemoryAccess *UpTo=nullptr)
bool isModSet(const ModRefInfo MRI)
auto find_if_not(R &&Range, UnaryPredicate P)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isAtLeastOrStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IDFCalculator< false > ForwardIDFCalculator
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
upward_defs_iterator upward_defs_end()
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Instruction::const_succ_iterator const_succ_iterator
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
upward_defs_iterator upward_defs_begin(const UpwardDefsElem &Pair, DominatorTree &DT)
bool isRefSet(const ModRefInfo MRI)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
std::string getEdgeAttributes(const BasicBlock *Node, const_succ_iterator I, DOTFuncMSSAInfo *CFGInfo)
Display the raw branch weights from PGO.
std::string getNodeAttributes(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo)
static std::string getEdgeSourceLabel(const BasicBlock *Node, const_succ_iterator I)
std::string getNodeLabel(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo)
static std::string getGraphName(DOTFuncMSSAInfo *CFGInfo)
DOTGraphTraits(bool IsSimple=false)
DefaultDOTGraphTraits(bool simple=false)
static std::string getEdgeSourceLabel(const void *, EdgeIter)
getEdgeSourceLabel - If you want to label the edge source itself, implement this method.
static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS)
static unsigned getHashValue(const MemoryLocOrCall &MLOC)
An information struct used to provide DenseMap with the various necessary components for a given valu...
pointer_iterator< Function::const_iterator > nodes_iterator
static size_t size(DOTFuncMSSAInfo *CFGInfo)
static NodeRef getEntryNode(DOTFuncMSSAInfo *CFGInfo)
static nodes_iterator nodes_begin(DOTFuncMSSAInfo *CFGInfo)
static nodes_iterator nodes_end(DOTFuncMSSAInfo *CFGInfo)
typename DOTFuncMSSAInfo *::UnknownGraphTypeError NodeRef
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)