29 #include "llvm/Config/llvm-config.h" 60 #define DEBUG_TYPE "memoryssa" 73 "
Memory SSA Printer", false, false)
76 "
memssa-check-limit", cl::Hidden, cl::
init(100),
78 "will consider trying to walk past (default = 100)"));
81 #ifdef EXPENSIVE_CHECKS 84 bool llvm::VerifyMemorySSA =
false;
89 cl::desc(
"Enable MemorySSA dependency for loop pass manager"));
110 OS <<
"; " << *MA <<
"\n";
116 OS <<
"; " << *MA <<
"\n";
129 class MemoryLocOrCall {
139 if (
auto *
C = dyn_cast<CallBase>(Inst)) {
146 if (!isa<FenceInst>(Inst))
164 if (IsCall != Other.IsCall)
168 return Loc == Other.Loc;
170 if (Call->getCalledValue() != Other.Call->getCalledValue())
173 return Call->arg_size() == Other.Call->arg_size() &&
174 std::equal(Call->arg_begin(), Call->arg_end(),
175 Other.Call->arg_begin());
206 MLOC.getCall()->getCalledValue()));
208 for (
const Value *
Arg : MLOC.getCall()->args())
213 static bool isEqual(
const MemoryLocOrCall &LHS,
const MemoryLocOrCall &RHS) {
229 bool VolatileClobber = MayClobber->
isVolatile();
231 if (VolatileUse && VolatileClobber)
247 return !(SeqCstUse || MayClobberIsAcquire);
252 struct ClobberAlias {
261 template <
typename AliasAnalysisType>
264 const Instruction *UseInst, AliasAnalysisType &AA) {
266 assert(DefInst &&
"Defining instruction not actually an instruction");
270 if (
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
278 switch (II->getIntrinsicID()) {
279 case Intrinsic::lifetime_start:
284 case Intrinsic::lifetime_end:
285 case Intrinsic::invariant_start:
286 case Intrinsic::invariant_end:
287 case Intrinsic::assume:
289 case Intrinsic::dbg_addr:
290 case Intrinsic::dbg_declare:
291 case Intrinsic::dbg_label:
292 case Intrinsic::dbg_value:
305 if (
auto *DefLoad = dyn_cast<LoadInst>(DefInst))
306 if (
auto *UseLoad = dyn_cast<LoadInst>(UseInst))
314 template <
typename AliasAnalysisType>
317 const MemoryLocOrCall &UseMLOC,
318 AliasAnalysisType &AA) {
336 struct UpwardsMemoryQuery {
347 bool SkipSelfAccess =
false;
349 UpwardsMemoryQuery() =
default;
352 : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
364 switch (II->getIntrinsicID()) {
365 case Intrinsic::lifetime_end:
374 template <
typename AliasAnalysisType>
379 return isa<LoadInst>(
I) && (I->
hasMetadata(LLVMContext::MD_invariant_load) ||
398 template <
typename AliasAnalysisType>
402 const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
403 bool AllowImpreciseClobber =
false) {
404 assert(MSSA.
dominates(ClobberAt, Start) &&
"Clobber doesn't dominate start?");
408 "liveOnEntry must clobber itself");
412 bool FoundClobber =
false;
418 while (!Worklist.
empty()) {
426 if (MA == ClobberAt) {
427 if (
const auto *MD = dyn_cast<MemoryDef>(MA)) {
449 if (
const auto *MD = dyn_cast<MemoryDef>(MA)) {
456 "Found clobber before reaching ClobberAt!");
460 if (
const auto *MU = dyn_cast<MemoryUse>(MA)) {
463 "Can only find use in def chain if Start is a use");
467 assert(isa<MemoryPhi>(MA));
479 if (AllowImpreciseClobber)
484 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
485 "ClobberAt never acted as a clobber");
492 template <
class AliasAnalysisType>
class ClobberWalker {
508 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
512 : DefPath(Loc, Init, Init, Previous) {}
516 AliasAnalysisType &AA;
518 UpwardsMemoryQuery *Query;
519 unsigned *UpwardWalkLimit;
532 while ((Node = Node->
getIDom())) {
541 struct UpwardsWalkResult {
555 walkToPhiOrClobber(DefPath &Desc,
const MemoryAccess *StopAt =
nullptr,
557 assert(!isa<MemoryUse>(Desc.Last) &&
"Uses don't exist in my world");
558 assert(UpwardWalkLimit &&
"Need a valid walk limit");
559 bool LimitAlreadyReached =
false;
564 if (!*UpwardWalkLimit) {
565 *UpwardWalkLimit = 1;
566 LimitAlreadyReached =
true;
571 if (Current == StopAt || Current == SkipStopAt)
574 if (
auto *MD = dyn_cast<MemoryDef>(Current)) {
578 if (!--*UpwardWalkLimit)
579 return {Current,
true, MayAlias};
584 return {MD,
true, CA.AR};
588 if (LimitAlreadyReached)
589 *UpwardWalkLimit = 0;
591 assert(isa<MemoryPhi>(Desc.Last) &&
592 "Ended at a non-clobber that's not a phi?");
593 return {Desc.Last,
false,
MayAlias};
597 ListIndex PriorNode) {
609 struct TerminatedPath {
627 assert(!PausedSearches.
empty() &&
"No searches to continue?");
631 while (!PausedSearches.
empty()) {
633 DefPath &Node = Paths[PathIndex];
653 if (!VisitedPhis.
insert({Node.Last, Node.Loc}).second)
657 if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
658 assert(isa<MemoryDef>(Query->OriginalAccess));
659 SkipStopWhere = Query->OriginalAccess;
662 UpwardsWalkResult Res = walkToPhiOrClobber(Node,
665 if (Res.IsKnownClobber) {
666 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
670 TerminatedPath Term{Res.Result, PathIndex};
671 if (!MSSA.
dominates(Res.Result, StopWhere))
679 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
684 if (Res.Result != SkipStopWhere)
690 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
696 template <
typename T,
typename Walker>
697 struct generic_def_path_iterator
699 std::forward_iterator_tag, T *> {
700 generic_def_path_iterator() {}
701 generic_def_path_iterator(Walker *
W, ListIndex
N) :
W(W),
N(N) {}
705 generic_def_path_iterator &operator++() {
706 N = curNode().Previous;
710 bool operator==(
const generic_def_path_iterator &
O)
const {
711 if (N.hasValue() != O.N.hasValue())
713 return !N.hasValue() || *N == *O.N;
717 T &curNode()
const {
return W->Paths[*
N]; }
723 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
724 using const_def_path_iterator =
725 generic_def_path_iterator<const DefPath, const ClobberWalker>;
728 return make_range(def_path_iterator(
this, From), def_path_iterator());
732 return make_range(const_def_path_iterator(
this, From),
733 const_def_path_iterator());
738 TerminatedPath PrimaryClobber;
744 ListIndex defPathIndex(
const DefPath &
N)
const {
746 const DefPath *NP = &
N;
748 "Out of bounds DefPath!");
749 return NP - &Paths.
front();
768 "Reset the optimization state.");
773 auto PriorPathsSize = Paths.
size();
779 addSearches(Phi, PausedSearches, 0);
785 auto Dom = Paths.
begin();
786 for (
auto I = std::next(Dom),
E = Paths.
end();
I !=
E; ++
I)
787 if (!MSSA.
dominates(
I->Clobber, Dom->Clobber))
789 auto Last = Paths.
end() - 1;
791 std::iter_swap(Last, Dom);
797 "liveOnEntry wasn't treated as a clobber?");
799 const auto *
Target = getWalkTarget(Current);
802 assert(
all_of(TerminatedPaths, [&](
const TerminatedPath &
P) {
803 return MSSA.
dominates(P.Clobber, Target);
810 Target, PausedSearches, NewPaused, TerminatedPaths)) {
814 auto Iter =
find_if(def_path(Blocker->LastNode), [&](
const DefPath &N) {
815 return defPathIndex(N) < PriorPathsSize;
817 assert(Iter != def_path_iterator());
819 DefPath &CurNode = *Iter;
820 assert(CurNode.Last == Current);
847 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
854 if (NewPaused.
empty()) {
855 MoveDominatedPathToEnd(TerminatedPaths);
857 return {Result, std::move(TerminatedPaths)};
862 for (ListIndex Paused : NewPaused) {
863 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
864 if (WR.IsKnownClobber)
868 DefChainEnd = WR.Result;
871 if (!TerminatedPaths.
empty()) {
875 for (
auto *MA :
def_chain(const_cast<MemoryAccess *>(Target)))
877 assert(DefChainEnd &&
"Failed to find dominating phi/liveOnEntry");
882 for (
const TerminatedPath &TP : TerminatedPaths) {
885 if (DT.
dominates(ChainBB, TP.Clobber->getBlock()))
892 if (!Clobbers.
empty()) {
893 MoveDominatedPathToEnd(Clobbers);
895 return {Result, std::move(Clobbers)};
899 [&](ListIndex
I) {
return Paths[
I].Last == DefChainEnd; }));
902 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
904 PriorPathsSize = Paths.
size();
905 PausedSearches.
clear();
906 for (ListIndex I : NewPaused)
907 addSearches(DefChainPhi, PausedSearches, I);
910 Current = DefChainPhi;
914 void verifyOptResult(
const OptznResult &R)
const {
915 assert(
all_of(R.OtherClobbers, [&](
const TerminatedPath &
P) {
916 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
920 void resetPhiOptznState() {
927 : MSSA(MSSA), AA(AA), DT(DT) {}
929 AliasAnalysisType *getAA() {
return &AA; }
933 unsigned &UpWalkLimit) {
935 UpwardWalkLimit = &UpWalkLimit;
943 if (
auto *MU = dyn_cast<MemoryUse>(Start))
944 Current = MU->getDefiningAccess();
946 DefPath FirstDesc(Q.StartingLoc, Current, Current,
None);
949 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
951 if (WalkResult.IsKnownClobber) {
952 Result = WalkResult.Result;
953 Q.AR = WalkResult.AR;
955 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
956 Current, Q.StartingLoc);
957 verifyOptResult(OptRes);
958 resetPhiOptznState();
959 Result = OptRes.PrimaryClobber.Clobber;
962 #ifdef EXPENSIVE_CHECKS 963 if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
970 struct RenamePassData {
977 : DTN(D), ChildIt(It), IncomingVal(M) {}
979 void swap(RenamePassData &RHS) {
990 template <
class AliasAnalysisType>
class MemorySSA::ClobberWalkerBase {
991 ClobberWalker<AliasAnalysisType> Walker;
996 : Walker(*M, *A, *D), MSSA(M) {}
1013 template <
class AliasAnalysisType>
1015 ClobberWalkerBase<AliasAnalysisType> *Walker;
1018 CachingWalker(
MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *
W)
1020 ~CachingWalker()
override =
default;
1025 return Walker->getClobberingMemoryAccessBase(MA, UWL,
false);
1030 return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1035 return getClobberingMemoryAccess(MA, UpwardWalkLimit);
1040 return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
1044 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1045 MUD->resetOptimized();
1049 template <
class AliasAnalysisType>
1051 ClobberWalkerBase<AliasAnalysisType> *Walker;
1054 SkipSelfWalker(
MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *
W)
1056 ~SkipSelfWalker()
override =
default;
1061 return Walker->getClobberingMemoryAccessBase(MA, UWL,
true);
1066 return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1071 return getClobberingMemoryAccess(MA, UpwardWalkLimit);
1076 return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
1080 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1081 MUD->resetOptimized();
1088 bool RenameAllUses) {
1091 auto It = PerBlockAccesses.find(S);
1093 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1095 AccessList *Accesses = It->second.get();
1096 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1097 if (RenameAllUses) {
1098 bool ReplacementDone =
false;
1099 for (
unsigned I = 0,
E = Phi->getNumIncomingValues();
I !=
E; ++
I)
1100 if (Phi->getIncomingBlock(
I) == BB) {
1101 Phi->setIncomingValue(
I, IncomingVal);
1102 ReplacementDone =
true;
1104 (void) ReplacementDone;
1105 assert(ReplacementDone &&
"Incomplete phi during partial rename");
1107 Phi->addIncoming(IncomingVal, BB);
1115 bool RenameAllUses) {
1116 auto It = PerBlockAccesses.find(BB);
1118 if (It != PerBlockAccesses.end()) {
1119 AccessList *Accesses = It->second.get();
1122 if (MUD->getDefiningAccess() ==
nullptr || RenameAllUses)
1123 MUD->setDefiningAccess(IncomingVal);
1124 if (isa<MemoryDef>(&L))
1140 bool SkipVisited,
bool RenameAllUses) {
1141 assert(Root &&
"Trying to rename accesses in an unreachable block");
1148 if (SkipVisited && AlreadyVisited)
1151 IncomingVal = renameBlock(Root->
getBlock(), IncomingVal, RenameAllUses);
1152 renameSuccessorPhis(Root->
getBlock(), IncomingVal, RenameAllUses);
1155 while (!WorkStack.
empty()) {
1158 IncomingVal = WorkStack.
back().IncomingVal;
1160 if (ChildIt == Node->
end()) {
1164 ++WorkStack.
back().ChildIt;
1168 AlreadyVisited = !Visited.
insert(BB).second;
1169 if (SkipVisited && AlreadyVisited) {
1175 if (
auto *BlockDefs = getWritableBlockDefs(BB))
1176 IncomingVal = &*BlockDefs->rbegin();
1178 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1179 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
1188 void MemorySSA::markUnreachableAsLiveOnEntry(
BasicBlock *BB) {
1189 assert(!DT->isReachableFromEntry(BB) &&
1190 "Reachable block found while handling unreachable blocks");
1197 if (!DT->isReachableFromEntry(S))
1199 auto It = PerBlockAccesses.find(S);
1201 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1203 AccessList *Accesses = It->second.get();
1204 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1205 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1208 auto It = PerBlockAccesses.find(BB);
1209 if (It == PerBlockAccesses.end())
1212 auto &Accesses = It->second;
1213 for (
auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1214 auto Next = std::next(AI);
1217 if (
auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1218 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1220 Accesses->erase(AI);
1226 : AA(nullptr), DT(DT),
F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1227 SkipWalker(nullptr), NextID(0) {
1233 assert(AA &&
"No alias analysis?");
1235 buildMemorySSA(BatchAA);
1245 for (
const auto &Pair : PerBlockAccesses)
1251 auto Res = PerBlockAccesses.
insert(std::make_pair(BB,
nullptr));
1254 Res.first->second = std::make_unique<AccessList>();
1255 return Res.first->second.get();
1259 auto Res = PerBlockDefs.
insert(std::make_pair(BB,
nullptr));
1262 Res.first->second = std::make_unique<DefsList>();
1263 return Res.first->second.get();
1279 : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
1281 void optimizeUses();
1285 struct MemlocStackInfo {
1288 unsigned long StackEpoch;
1289 unsigned long PopEpoch;
1294 unsigned long LowerBound;
1297 unsigned long LastKill;
1302 void optimizeUsesInBlock(
const BasicBlock *,
unsigned long &,
unsigned long &,
1307 CachingWalker<BatchAAResults> *Walker;
1326 void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1327 const BasicBlock *BB,
unsigned long &StackEpoch,
unsigned long &PopEpoch,
1333 if (Accesses ==
nullptr)
1340 !VersionStack.
empty() &&
1341 "Version stack should have liveOnEntry sentinel dominating everything");
1343 if (DT->dominates(BackBlock, BB))
1345 while (VersionStack.
back()->getBlock() == BackBlock)
1359 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(),
true,
None);
1363 MemoryLocOrCall UseMLOC(MU);
1364 auto &LocInfo = LocStackInfo[UseMLOC];
1368 if (LocInfo.PopEpoch != PopEpoch) {
1369 LocInfo.PopEpoch = PopEpoch;
1370 LocInfo.StackEpoch = StackEpoch;
1382 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
1383 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
1387 LocInfo.LowerBound = 0;
1388 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
1389 LocInfo.LastKillValid =
false;
1391 }
else if (LocInfo.StackEpoch != StackEpoch) {
1395 LocInfo.PopEpoch = PopEpoch;
1396 LocInfo.StackEpoch = StackEpoch;
1398 if (!LocInfo.LastKillValid) {
1399 LocInfo.LastKill = VersionStack.
size() - 1;
1400 LocInfo.LastKillValid =
true;
1406 assert(LocInfo.LowerBound < VersionStack.
size() &&
1407 "Lower bound out of range");
1408 assert(LocInfo.LastKill < VersionStack.
size() &&
1409 "Last kill info out of range");
1411 unsigned long UpperBound = VersionStack.
size() - 1;
1414 LLVM_DEBUG(
dbgs() <<
"MemorySSA skipping optimization of " << *MU <<
" (" 1415 << *(MU->getMemoryInst()) <<
")" 1416 <<
" because there are " 1417 << UpperBound - LocInfo.LowerBound
1418 <<
" stores to disambiguate\n");
1421 LocInfo.LastKillValid =
false;
1424 bool FoundClobberResult =
false;
1426 while (UpperBound > LocInfo.LowerBound) {
1427 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1430 Walker->getClobberingMemoryAccess(MU, UpwardWalkLimit);
1432 while (VersionStack[UpperBound] != Result) {
1436 FoundClobberResult =
true;
1440 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
1443 if (!UseMLOC.IsCall &&
lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1446 FoundClobberResult =
true;
1452 FoundClobberResult =
true;
1463 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1465 if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1467 MU->setDefiningAccess(VersionStack[UpperBound],
true, LocInfo.AR);
1468 LocInfo.LastKill = UpperBound;
1472 MU->setDefiningAccess(VersionStack[LocInfo.LastKill],
true, LocInfo.AR);
1474 LocInfo.LowerBound = VersionStack.
size() - 1;
1475 LocInfo.LowerBoundBlock = BB;
1483 VersionStack.
push_back(MSSA->getLiveOnEntryDef());
1485 unsigned long StackEpoch = 1;
1486 unsigned long PopEpoch = 1;
1488 for (
const auto *DomNode :
depth_first(DT->getRootNode()))
1489 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1493 void MemorySSA::placePHINodes(
1502 for (
auto &BB : IDFBlocks)
1503 createMemoryPhi(BB);
1514 LiveOnEntryDef.reset(
new MemoryDef(
F.getContext(),
nullptr,
nullptr,
1515 &StartingPoint, NextID++));
1524 bool InsertIntoDef =
false;
1533 Accesses = getOrCreateAccessList(&B);
1535 if (isa<MemoryDef>(MUD)) {
1536 InsertIntoDef =
true;
1538 Defs = getOrCreateDefsList(&B);
1543 DefiningBlocks.
insert(&B);
1545 placePHINodes(DefiningBlocks);
1550 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1552 ClobberWalkerBase<BatchAAResults> WalkerBase(
this, &BAA, DT);
1553 CachingWalker<BatchAAResults> WalkerLocal(
this, &WalkerBase);
1559 if (!Visited.
count(&BB))
1560 markUnreachableAsLiveOnEntry(&BB);
1565 MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() {
1567 return Walker.get();
1571 std::make_unique<ClobberWalkerBase<AliasAnalysis>>(
this, AA, DT);
1574 std::make_unique<CachingWalker<AliasAnalysis>>(
this, WalkerBase.get());
1575 return Walker.get();
1580 return SkipWalker.get();
1584 std::make_unique<ClobberWalkerBase<AliasAnalysis>>(
this, AA, DT);
1587 std::make_unique<SkipSelfWalker<AliasAnalysis>>(
this, WalkerBase.get());
1588 return SkipWalker.get();
1598 auto *Accesses = getOrCreateAccessList(BB);
1602 if (isa<MemoryPhi>(NewAccess)) {
1603 Accesses->push_front(NewAccess);
1604 auto *Defs = getOrCreateDefsList(BB);
1605 Defs->push_front(*NewAccess);
1608 *Accesses, [](
const MemoryAccess &MA) {
return isa<MemoryPhi>(MA); });
1609 Accesses->insert(AI, NewAccess);
1610 if (!isa<MemoryUse>(NewAccess)) {
1611 auto *Defs = getOrCreateDefsList(BB);
1613 *Defs, [](
const MemoryAccess &MA) {
return isa<MemoryPhi>(MA); });
1614 Defs->insert(DI, *NewAccess);
1618 Accesses->push_back(NewAccess);
1619 if (!isa<MemoryUse>(NewAccess)) {
1620 auto *Defs = getOrCreateDefsList(BB);
1621 Defs->push_back(*NewAccess);
1624 BlockNumberingValid.erase(BB);
1630 bool WasEnd = InsertPt == Accesses->end();
1632 if (!isa<MemoryUse>(What)) {
1633 auto *Defs = getOrCreateDefsList(BB);
1639 Defs->push_back(*What);
1640 }
else if (isa<MemoryDef>(InsertPt)) {
1641 Defs->insert(InsertPt->getDefsIterator(), *What);
1643 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1646 if (InsertPt == Accesses->end())
1647 Defs->push_back(*What);
1649 Defs->insert(InsertPt->getDefsIterator(), *What);
1652 BlockNumberingValid.erase(BB);
1662 if (
auto *MD = dyn_cast<MemoryDef>(What))
1663 MD->resetOptimized();
1673 prepareForMoveTo(What, BB);
1679 if (isa<MemoryPhi>(What)) {
1681 "Can only move a Phi at the beginning of the block");
1683 ValueToMemoryAccess.erase(What->
getBlock());
1684 bool Inserted = ValueToMemoryAccess.insert({BB, What}).
second;
1686 assert(Inserted &&
"Cannot move a Phi to a block that already has one");
1689 prepareForMoveTo(What, BB);
1698 ValueToMemoryAccess[BB] = Phi;
1705 bool CreationMustSucceed) {
1706 assert(!isa<PHINode>(I) &&
"Cannot create a defined access for a PHI");
1708 if (CreationMustSucceed)
1709 assert(NewAccess !=
nullptr &&
"Tried to create a memory access for a " 1710 "non-memory touching instruction");
1720 if (
auto *
SI = dyn_cast<StoreInst>(I)) {
1721 if (!
SI->isUnordered())
1723 }
else if (
auto *LI = dyn_cast<LoadInst>(I)) {
1724 if (!LI->isUnordered())
1731 template <
typename AliasAnalysisType>
1733 AliasAnalysisType *AAP,
1742 if (II->getIntrinsicID() == Intrinsic::assume)
1753 Def = dyn_cast_or_null<MemoryDef>(Template) !=
nullptr;
1754 Use = dyn_cast_or_null<MemoryUse>(Template) !=
nullptr;
1755 #if !defined(NDEBUG) 1757 bool DefCheck, UseCheck;
1760 assert(Def == DefCheck && (Def || Use == UseCheck) &&
"Invalid template");
1787 ValueToMemoryAccess[
I] = MUD;
1792 bool MemorySSA::dominatesUse(
const MemoryAccess *Replacer,
1794 if (isa<MemoryUseOrDef>(Replacee))
1796 const auto *MP = cast<MemoryPhi>(Replacee);
1800 for (
const Use &
Arg : MP->operands()) {
1801 if (
Arg.get() != Replacee &&
1802 !DT->dominates(Replacer->
getBlock(), MP->getIncomingBlock(
Arg)))
1811 "Trying to remove memory access that still has uses");
1812 BlockNumbering.erase(MA);
1813 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1814 MUD->setDefiningAccess(
nullptr);
1816 if (!isa<MemoryUse>(MA))
1820 if (
const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1821 MemoryInst = MUD->getMemoryInst();
1825 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1826 if (VMA->second == MA)
1827 ValueToMemoryAccess.erase(VMA);
1840 if (!isa<MemoryUse>(MA)) {
1841 auto DefsIt = PerBlockDefs.find(BB);
1842 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1845 PerBlockDefs.erase(DefsIt);
1850 auto AccessIt = PerBlockAccesses.find(BB);
1851 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
1853 Accesses->erase(MA);
1855 Accesses->remove(MA);
1857 if (Accesses->empty()) {
1858 PerBlockAccesses.erase(AccessIt);
1859 BlockNumberingValid.erase(BB);
1865 F.print(OS, &Writer);
1868 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1889 #if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS) 1892 for (
unsigned I = 0,
E = Phi->getNumIncomingValues(); I !=
E; ++
I) {
1893 auto *Pred = Phi->getIncomingBlock(I);
1894 auto *IncAcc = Phi->getIncomingValue(I);
1898 if (
auto *DTNode = DT->getNode(Pred)) {
1900 if (
auto *DefList =
getBlockDefs(DTNode->getBlock())) {
1901 auto *LastAcc = &*(--DefList->end());
1902 assert(LastAcc == IncAcc &&
1903 "Incorrect incoming access into phi.");
1906 DTNode = DTNode->getIDom();
1926 if (BlockNumberingValid.empty())
1931 if (!ValidBlocks.
count(&BB))
1934 ValidBlocks.
erase(&BB);
1942 unsigned long LastNumber = 0;
1944 auto ThisNumberIter = BlockNumbering.find(&MA);
1945 assert(ThisNumberIter != BlockNumbering.end() &&
1946 "MemoryAccess has no domination number in a valid block!");
1948 unsigned long ThisNumber = ThisNumberIter->second;
1949 assert(ThisNumber > LastNumber &&
1950 "Domination numbers should be strictly increasing!");
1951 LastNumber = ThisNumber;
1956 "All valid BasicBlocks should exist in F -- dangling pointers?");
1967 #if !defined(NDEBUG) 1982 for (
const Use &U : Phi->
uses())
1983 assert(
dominates(Phi, U) &&
"Memory PHI does not dominate it's uses");
1984 #if defined(EXPENSIVE_CHECKS) 1988 "Incomplete MemoryPhi Node");
1993 "Incoming phi block not a block predecessor");
2000 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
2001 "We have memory affecting instructions " 2002 "in this block but they are not in the " 2003 "access list or defs list");
2011 for (
const Use &U : MD->
uses())
2013 "Memory Def does not dominate it's uses");
2015 #if defined(EXPENSIVE_CHECKS) 2026 assert(AL->size() == ActualAccesses.
size() &&
2027 "We don't have the same number of accesses in the block as on the " 2030 "Either we should have a defs list, or we should have no defs");
2031 assert((!DL || DL->size() == ActualDefs.
size()) &&
2032 "We don't have the same number of defs in the block as on the " 2034 auto ALI = AL->begin();
2035 auto AAI = ActualAccesses.
begin();
2036 while (ALI != AL->end() && AAI != ActualAccesses.
end()) {
2037 assert(&*ALI == *AAI &&
"Not the same accesses in the same order");
2041 ActualAccesses.
clear();
2043 auto DLI = DL->begin();
2044 auto ADI = ActualDefs.
begin();
2045 while (DLI != DL->end() && ADI != ActualDefs.
end()) {
2046 assert(&*DLI == *ADI &&
"Not the same defs in the same order");
2063 "Null def but use not point to live on entry def");
2066 "Did not find use in def's use list");
2076 void MemorySSA::renumberBlock(
const BasicBlock *
B)
const {
2078 unsigned long CurrentNumber = 0;
2080 assert(AL !=
nullptr &&
"Asking to renumber an empty block");
2081 for (
const auto &I : *AL)
2082 BlockNumbering[&
I] = ++CurrentNumber;
2083 BlockNumberingValid.insert(B);
2094 "Asking for local domination when accesses are in different blocks!");
2096 if (Dominatee == Dominator)
2109 if (!BlockNumberingValid.count(DominatorBlock))
2110 renumberBlock(DominatorBlock);
2112 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2114 assert(DominatorNum != 0 &&
"Block was not numbered properly");
2115 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2116 assert(DominateeNum != 0 &&
"Block was not numbered properly");
2117 return DominatorNum < DominateeNum;
2122 if (Dominator == Dominatee)
2134 const Use &Dominatee)
const {
2136 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2138 if (UseBB != Dominator->
getBlock())
2139 return DT->dominates(Dominator->
getBlock(), UseBB);
2150 switch (getValueID()) {
2151 case MemoryPhiVal:
return static_cast<const MemoryPhi *
>(
this)->
print(OS);
2152 case MemoryDefVal:
return static_cast<const MemoryDef *
>(
this)->
print(OS);
2153 case MemoryUseVal:
return static_cast<const MemoryUse *
>(
this)->
print(OS);
2162 if (A && A->getID())
2168 OS << getID() <<
" = MemoryDef(";
2172 if (isOptimized()) {
2174 printID(getOptimized());
2183 OS << getID() <<
" = MemoryPhi(";
2184 for (
const auto &
Op : operands()) {
2198 if (
unsigned ID = MA->
getID())
2210 if (UO && UO->
getID())
2222 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2240 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2243 MSSA.verifyMemorySSA();
2267 OS <<
"MemorySSA for function: " << F.
getName() <<
"\n";
2295 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2296 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2303 MSSA->verifyMemorySSA();
2316 template <
typename AliasAnalysisType>
2318 MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
2320 unsigned &UpwardWalkLimit) {
2321 if (isa<MemoryPhi>(StartingAccess))
2322 return StartingAccess;
2324 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2326 return StartingUseOrDef;
2328 Instruction *I = StartingUseOrDef->getMemoryInst();
2333 return StartingUseOrDef;
2335 UpwardsMemoryQuery Q;
2336 Q.OriginalAccess = StartingUseOrDef;
2337 Q.StartingLoc = Loc;
2344 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2345 ? StartingUseOrDef->getDefiningAccess()
2349 Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2350 LLVM_DEBUG(
dbgs() <<
"Starting Memory SSA clobber for " << *I <<
" is ");
2352 LLVM_DEBUG(
dbgs() <<
"Final Memory SSA clobber for " << *I <<
" is ");
2357 template <
typename AliasAnalysisType>
2359 MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
2360 MemoryAccess *MA,
unsigned &UpwardWalkLimit,
bool SkipSelf) {
2363 if (!StartingAccess)
2366 bool IsOptimized =
false;
2371 if (StartingAccess->isOptimized()) {
2372 if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2373 return StartingAccess->getOptimized();
2377 const Instruction *I = StartingAccess->getMemoryInst();
2382 return StartingAccess;
2384 UpwardsMemoryQuery Q(I, StartingAccess);
2388 StartingAccess->setOptimized(LiveOnEntry);
2389 StartingAccess->setOptimizedAccessType(
None);
2396 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2401 StartingAccess->setOptimized(DefiningAccess);
2402 StartingAccess->setOptimizedAccessType(
None);
2403 return DefiningAccess;
2406 OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2407 StartingAccess->setOptimized(OptimizedAccess);
2409 StartingAccess->setOptimizedAccessType(
None);
2411 StartingAccess->setOptimizedAccessType(
MustAlias);
2413 OptimizedAccess = StartingAccess->getOptimized();
2415 LLVM_DEBUG(
dbgs() <<
"Starting Memory SSA clobber for " << *I <<
" is ");
2417 LLVM_DEBUG(
dbgs() <<
"Optimized Memory SSA clobber for " << *I <<
" is ");
2421 if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
2422 isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
2423 assert(isa<MemoryDef>(Q.OriginalAccess));
2424 Q.SkipSelfAccess =
true;
2425 Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
2427 Result = OptimizedAccess;
2429 LLVM_DEBUG(
dbgs() <<
"Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2430 LLVM_DEBUG(
dbgs() <<
"] for " << *I <<
" is " << *Result <<
"\n");
2437 if (
auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2438 return Use->getDefiningAccess();
2444 if (
auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2445 return Use->getDefiningAccess();
2446 return StartingAccess;
MemorySSAWalker * getWalker()
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
The access may reference and may modify the value stored in memory.
void initializeMemorySSAWrapperPassPass(PassRegistry &)
AccessList * getWritableBlockAccesses(const BasicBlock *BB) const
reference emplace_back(ArgTypes &&... Args)
typename std::vector< DomTreeNodeBase *>::const_iterator const_iterator
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
iterator_range< use_iterator > uses()
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void dropAllReferences()
Drop all references to operands.
Atomic ordering constants.
MemorySSAPrinterLegacyPass()
bool VerifyMemorySSA
Enables verification of MemorySSA.
bool isFenceLike() const
Return true if this instruction behaves like a memory fence: it can load or store to memory location ...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void print(raw_ostream &OS) const
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
A Module instance is used to store all the information related to an LLVM module. ...
void push_back(reference Node)
Insert a node at the back; never copies.
This class provides various memory handling functions that manipulate MemoryBlock instances...
void push_back(const T &Elt)
const AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
The two locations do not alias at all.
Extension point for the Value hierarchy.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
static const char LiveOnEntryStr[]
LLVMContext & getContext() const
All values hold a context through their type.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Analysis pass which computes a DominatorTree.
block Block Frequency true
An instruction for reading from memory.
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 maximum semantics.
This defines the Use class.
void print(raw_ostream &OS) const
void calculate(SmallVectorImpl< NodeTy *> &IDFBlocks)
Calculate iterated dominance frontiers.
MemorySSA(Function &, AliasAnalysis *, DominatorTree *)
LLVMContext & getContext() const
Get the context in which this basic block lives.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false, true) INITIALIZE_PASS_END(MemorySSAWrapperPass
OptimizeUses(MemorySSA *MSSA, CachingWalker< BatchAAResults > *Walker, BatchAAResults *BAA, DominatorTree *DT)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Represents read-only accesses to memory.
This class is a batch walker of all MemoryUse's in the program, and points their defining access at t...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc, BatchAAResults &AA)
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, SmallPtrSetImpl< BasicBlock *> &Visited)
MemoryUseOrDef * createDefinedAccess(Instruction *, MemoryAccess *, const MemoryUseOrDef *Template=nullptr, bool CreationMustSucceed=true)
A Use represents the edge between a Value definition and its users.
static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
MemorySSAAnnotatedWriter(const MemorySSA *M)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Encapsulates MemorySSA, including all data associated with memory accesses.
const DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *, InsertionPlace)
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
static bool isOrdered(const Instruction *I)
APInt operator*(APInt a, uint64_t RHS)
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
A simple intrusive list implementation.
LLVM_NODISCARD bool isMustSet(const ModRefInfo MRI)
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
upward_defs_iterator upward_defs_end()
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
void emitBasicBlockStartAnnot(const BasicBlock *BB, formatted_raw_ostream &OS) override
emitBasicBlockStartAnnot - This may be implemented to emit a string right after the basic block label...
static cl::opt< bool, true > VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA), cl::Hidden, cl::desc("Enable verification of MemorySSA."))
This is the generic walker interface for walkers of MemorySSA.
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
MemoryAccess * getIncomingValue(unsigned I) const
Return incoming value number x.
bool isAtLeastOrStrongerThan(AtomicOrdering ao, AtomicOrdering other)
An assembly annotator class to print Memory SSA information in comments.
void removeFromLookups(MemoryAccess *)
Properly remove MA from all of MemorySSA's lookup tables.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
MemorySSAWalker * getSkipSelfWalker()
void verifyOrderingDominationAndDefUses(Function &F) const
Verify ordering: the order and existence of MemoryAccesses matches the order and existence of memory ...
LLVM Basic Block Representation.
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_NODISCARD bool empty() const
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
early cse Early CSE w MemorySSA
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
InsertionPlace
Used in various insertion functions to specify whether we are talking about the beginning or end of a...
Represent the analysis usage information of a pass.
void print(raw_ostream &OS) const
#define LLVM_ATTRIBUTE_UNUSED
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Interval::pred_iterator pred_end(Interval *I)
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Memory true print Memory SSA Printer
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
virtual void invalidateInfo(MemoryAccess *)
Given a memory access, invalidate anything this walker knows about that access.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
An intrusive list with ownership and callbacks specified/controlled by ilist_traits, only with API safe for polymorphic types.
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Memory true print Memory SSA static false 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)"))
void optimizeUses()
Optimize uses to point to their actual clobbering definitions.
The two locations may or may not alias. This is the least precise result.
static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA, const Instruction *I)
void setDefiningBlocks(const SmallPtrSetImpl< NodeTy *> &Blocks)
Give the IDF calculator the set of blocks in which the value is defined.
Representation for a specific memory location.
The two locations precisely alias each other.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void setDefiningAccess(MemoryAccess *DMA, bool Optimized=false, Optional< AliasResult > AR=MayAlias)
unsigned getNumOperands() const
base_list_type::iterator iterator
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
BlockVerifier::State From
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
static LLVM_ATTRIBUTE_UNUSED void checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt, const MemoryLocation &StartLoc, const MemorySSA &MSSA, const UpwardsMemoryQuery &Query, AliasAnalysisType &AA, bool AllowImpreciseClobber=false)
Verifies that Start is clobbered by ClobberAt, and that nothing inbetween Start and ClobberAt can clo...
bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
An analysis that produces MemorySSA for a function.
LLVM_NODISCARD T pop_back_val()
BasicBlock * getBlock() const
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
pred_range predecessors(BasicBlock *BB)
void emitInstructionAnnot(const Instruction *I, formatted_raw_ostream &OS) override
emitInstructionAnnot - This may be implemented to emit a string right before an instruction is emitte...
MemoryAccess * getLiveOnEntryDef() const
void print(raw_ostream &OS) const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A range adaptor for a pair of iterators.
void removeFromLists(MemoryAccess *, bool ShouldDelete=true)
Properly remove MA from all of MemorySSA's lists.
Target - Wrapper for Target specific information.
void push_back(pointer val)
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Class that has the common methods + fields of memory uses/defs.
void setPreservesAll()
Set by analyses that do not transform their input at all.
iterator_range< user_iterator > users()
unsigned getNumIncomingValues() const
Return the number of incoming edges.
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
An opaque object representing a hash code.
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
void initializeMemorySSAPrinterLegacyPassPass(PassRegistry &)
LLVM_NODISCARD bool isModSet(const ModRefInfo MRI)
MemorySSAWalker(MemorySSA *)
iterator_range< def_chain_iterator< T > > def_chain(T MA, MemoryAccess *UpTo=nullptr)
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
LLVM_NODISCARD bool empty() const
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
This file provides utility analysis objects describing memory locations.
StringRef getName() const
Return a constant reference to the value's name.
void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where)
bool mayReadFromMemory() const
Return true if this instruction may read memory.
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
AnalysisUsage & addRequiredTransitive()
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
API to communicate dependencies between analyses during invalidation.
iterator_range< df_iterator< T > > depth_first(const T &G)
MemoryAccess * getClobberingMemoryAccess(const Instruction *I)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over <a particular IR unit>" (e...
Result run(Function &F, FunctionAnalysisManager &AM)
static bool areLoadsReorderable(const LoadInst *Use, const LoadInst *MayClobber)
This does one-way checks to see if Use could theoretically be hoisted above MayClobber.
LLVM Value Representation.
static MemoryLocOrCall getTombstoneKey()
succ_range successors(Instruction *I)
upward_defs_iterator upward_defs_begin(const MemoryAccessPair &Pair)
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
unsigned getID() const
Used for debugging and tracking things about MemoryAccesses.
This class implements an extremely fast bulk output stream that can only output to a stream...
static ClobberAlias instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc, const Instruction *UseInst, AliasAnalysisType &AA)
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
static unsigned getHashValue(const MemoryLocOrCall &MLOC)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void setBlock(BasicBlock *BB)
Used by MemorySSA to change the block of a MemoryAccess when it is moved.
LLVM_NODISCARD bool isModOrRefSet(const ModRefInfo MRI)
bool operator==(uint64_t V1, const APInt &V2)
void verifyPrevDefInPhis(Function &F) const
void verifyDominationNumbers(const Function &F) const
Verify that all of the blocks we believe to have valid domination numbers actually have valid dominat...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Represents phi nodes for memory accesses.
void print(raw_ostream &) const
This header defines various interfaces for pass management in LLVM.
static MemoryLocOrCall getEmptyKey()
void insertIntoListsBefore(MemoryAccess *, const BasicBlock *, AccessList::iterator)
A special type used by analysis passes to provide an address that identifies that particular analysis...
LocationClass< Ty > location(Ty &L)
reverse_iterator rbegin()
std::pair< MemoryAccess *, MemoryLocation > MemoryAccessPair
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
LLVM_NODISCARD bool isRefSet(const ModRefInfo MRI)