<div dir="ltr">Thanks for bringing this up! And yeah, the first thing that `def_chain` should iterate over is `Target` itself. So, as long as `Target != nullptr` (which should always be true), we should be fine here.<br><div><br></div><div>Is there something we could add to make coverity happy?</div><div class="gmail_extra"><br><div class="gmail_quote">On Thu, Jul 21, 2016 at 3:50 PM, Mehdi Amini <span dir="ltr"><<a href="mailto:mehdi.amini@apple.com" target="_blank">mehdi.amini@apple.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div><div><br>
> On Jul 18, 2016, at 6:29 PM, George Burgess IV via llvm-commits <<a href="mailto:llvm-commits@lists.llvm.org" target="_blank">llvm-commits@lists.llvm.org</a>> wrote:<br>
><br>
> Author: gbiv<br>
> Date: Mon Jul 18 20:29:15 2016<br>
> New Revision: 275940<br>
><br>
> URL: <a href="http://llvm.org/viewvc/llvm-project?rev=275940&view=rev" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project?rev=275940&view=rev</a><br>
> Log:<br>
> [MemorySSA] Update to the new shiny walker.<br>
><br>
> This patch updates MemorySSA's use-optimizing walker to be more<br>
> accurate and, in some cases, faster.<br>
><br>
> Essentially, this changed our core walking algorithm from a<br>
> cache-as-you-go DFS to an iteratively expanded DFS, with all of the<br>
> caching happening at the end. Said expansion happens when we hit a Phi,<br>
> P; we'll try to do the smallest amount of work possible to see if<br>
> optimizing above that Phi is legal in the first place. If so, we'll<br>
> expand the search to see if we can optimize to the next phi, etc.<br>
><br>
> An iteratively expanded DFS lets us potentially quit earlier (because we<br>
> don't assume that we can optimize above all phis) than our old walker.<br>
> Additionally, because we don't cache as we go, we can now optimize above<br>
> loops.<br>
><br>
> As an added bonus, this patch adds a ton of verification (if<br>
> EXPENSIVE_CHECKS are enabled), so finding bugs is easier.<br>
><br>
> Differential Revision: <a href="https://reviews.llvm.org/D21777" rel="noreferrer" target="_blank">https://reviews.llvm.org/D21777</a><br>
><br>
> Modified:<br>
> llvm/trunk/include/llvm/Transforms/Utils/MemorySSA.h<br>
> llvm/trunk/lib/Transforms/Utils/MemorySSA.cpp<br>
> llvm/trunk/test/Transforms/Util/MemorySSA/cyclicphi.ll<br>
> llvm/trunk/test/Transforms/Util/MemorySSA/phi-translation.ll<br>
><br>
> Modified: llvm/trunk/include/llvm/Transforms/Utils/MemorySSA.h<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Transforms/Utils/MemorySSA.h?rev=275940&r1=275939&r2=275940&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Transforms/Utils/MemorySSA.h?rev=275940&r1=275939&r2=275940&view=diff</a><br>
> ==============================================================================<br>
> --- llvm/trunk/include/llvm/Transforms/Utils/MemorySSA.h (original)<br>
> +++ llvm/trunk/include/llvm/Transforms/Utils/MemorySSA.h Mon Jul 18 20:29:15 2016<br>
> @@ -580,6 +580,10 @@ public:<br>
> /// whether MemoryAccess \p A dominates MemoryAccess \p B.<br>
> bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;<br>
><br>
> + /// \brief Given two memory accesses in potentially different blocks,<br>
> + /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.<br>
> + bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;<br>
> +<br>
> /// \brief Verify that MemorySSA is self consistent (IE definitions dominate<br>
> /// all uses, uses appear in the right places). This is used by unit tests.<br>
> void verifyMemorySSA() const;<br>
> @@ -594,6 +598,8 @@ protected:<br>
><br>
> private:<br>
> class CachingWalker;<br>
> +<br>
> + CachingWalker *getWalkerImpl();<br>
> void buildMemorySSA();<br>
> void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;<br>
> using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;<br>
><br>
> Modified: llvm/trunk/lib/Transforms/Utils/MemorySSA.cpp<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/MemorySSA.cpp?rev=275940&r1=275939&r2=275940&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/MemorySSA.cpp?rev=275940&r1=275939&r2=275940&view=diff</a><br>
> ==============================================================================<br>
> --- llvm/trunk/lib/Transforms/Utils/MemorySSA.cpp (original)<br>
> +++ llvm/trunk/lib/Transforms/Utils/MemorySSA.cpp Mon Jul 18 20:29:15 2016<br>
> @@ -17,6 +17,7 @@<br>
> #include "llvm/ADT/GraphTraits.h"<br>
> #include "llvm/ADT/PostOrderIterator.h"<br>
> #include "llvm/ADT/STLExtras.h"<br>
> +#include "llvm/ADT/SmallBitVector.h"<br>
> #include "llvm/ADT/SmallPtrSet.h"<br>
> #include "llvm/ADT/SmallSet.h"<br>
> #include "llvm/ADT/Statistic.h"<br>
> @@ -86,7 +87,777 @@ public:<br>
> OS << "; " << *MA << "\n";<br>
> }<br>
> };<br>
> +}<br>
> +<br>
> +namespace {<br>
> +struct UpwardsMemoryQuery {<br>
> + // True if our original query started off as a call<br>
> + bool IsCall;<br>
> + // The pointer location we started the query with. This will be empty if<br>
> + // IsCall is true.<br>
> + MemoryLocation StartingLoc;<br>
> + // This is the instruction we were querying about.<br>
> + const Instruction *Inst;<br>
> + // The MemoryAccess we actually got called with, used to test local domination<br>
> + const MemoryAccess *OriginalAccess;<br>
> +<br>
> + UpwardsMemoryQuery()<br>
> + : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}<br>
> +<br>
> + UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)<br>
> + : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {<br>
> + if (!IsCall)<br>
> + StartingLoc = MemoryLocation::get(Inst);<br>
> + }<br>
> +};<br>
> +<br>
> +static bool instructionClobbersQuery(MemoryDef *MD, const MemoryLocation &Loc,<br>
> + const UpwardsMemoryQuery &Query,<br>
> + AliasAnalysis &AA) {<br>
> + Instruction *DefMemoryInst = MD->getMemoryInst();<br>
> + assert(DefMemoryInst && "Defining instruction not actually an instruction");<br>
> +<br>
> + if (!Query.IsCall)<br>
> + return AA.getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;<br>
> +<br>
> + ModRefInfo I = AA.getModRefInfo(DefMemoryInst, ImmutableCallSite(Query.Inst));<br>
> + return I != MRI_NoModRef;<br>
> +}<br>
> +<br>
> +/// Cache for our caching MemorySSA walker.<br>
> +class WalkerCache {<br>
> + DenseMap<ConstMemoryAccessPair, MemoryAccess *> Accesses;<br>
> + DenseMap<const MemoryAccess *, MemoryAccess *> Calls;<br>
> +<br>
> +public:<br>
> + MemoryAccess *lookup(const MemoryAccess *MA, const MemoryLocation &Loc,<br>
> + bool IsCall) const {<br>
> + ++NumClobberCacheLookups;<br>
> + MemoryAccess *R = IsCall ? Calls.lookup(MA) : Accesses.lookup({MA, Loc});<br>
> + if (R)<br>
> + ++NumClobberCacheHits;<br>
> + return R;<br>
> + }<br>
> +<br>
> + bool insert(const MemoryAccess *MA, MemoryAccess *To,<br>
> + const MemoryLocation &Loc, bool IsCall) {<br>
> + // This is fine for Phis, since there are times where we can't optimize<br>
> + // them. Making a def its own clobber is never correct, though.<br>
> + assert((MA != To || isa<MemoryPhi>(MA)) &&<br>
> + "Something can't clobber itself!");<br>
> +<br>
> + ++NumClobberCacheInserts;<br>
> + bool Inserted;<br>
> + if (IsCall)<br>
> + Inserted = Calls.insert({MA, To}).second;<br>
> + else<br>
> + Inserted = Accesses.insert({{MA, Loc}, To}).second;<br>
> +<br>
> + return Inserted;<br>
> + }<br>
> +<br>
> + bool remove(const MemoryAccess *MA, const MemoryLocation &Loc, bool IsCall) {<br>
> + return IsCall ? Calls.erase(MA) : Accesses.erase({MA, Loc});<br>
> + }<br>
> +<br>
> + void clear() {<br>
> + Accesses.clear();<br>
> + Calls.clear();<br>
> + }<br>
> +<br>
> + bool contains(const MemoryAccess *MA) const {<br>
> + for (auto &P : Accesses)<br>
> + if (P.first.first == MA || P.second == MA)<br>
> + return true;<br>
> + for (auto &P : Calls)<br>
> + if (P.first == MA || P.second == MA)<br>
> + return true;<br>
> + return false;<br>
> + }<br>
> +};<br>
> +<br>
> +/// Walks the defining uses of MemoryDefs. Stops after we hit something that has<br>
> +/// no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when comparing<br>
> +/// against a null def_chain_iterator, this will compare equal only after<br>
> +/// walking said Phi/liveOnEntry.<br>
> +struct def_chain_iterator<br>
> + : public iterator_facade_base<def_chain_iterator, std::forward_iterator_tag,<br>
> + MemoryAccess *> {<br>
> + def_chain_iterator() : MA(nullptr) {}<br>
> + def_chain_iterator(MemoryAccess *MA) : MA(MA) {}<br>
> +<br>
> + MemoryAccess *operator*() const { return MA; }<br>
> +<br>
> + def_chain_iterator &operator++() {<br>
> + // N.B. liveOnEntry has a null defining access.<br>
> + if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))<br>
> + MA = MUD->getDefiningAccess();<br>
> + else<br>
> + MA = nullptr;<br>
> + return *this;<br>
> + }<br>
> +<br>
> + bool operator==(const def_chain_iterator &O) const { return MA == <a href="http://O.MA" rel="noreferrer" target="_blank">O.MA</a>; }<br>
> +<br>
> +private:<br>
> + MemoryAccess *MA;<br>
> +};<br>
> +<br>
> +static iterator_range<def_chain_iterator><br>
> +def_chain(MemoryAccess *MA, MemoryAccess *UpTo = nullptr) {<br>
> +#ifdef EXPENSIVE_CHECKS<br>
> + assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator()) &&<br>
> + "UpTo isn't in the def chain!");<br>
> +#endif<br>
> + return make_range(def_chain_iterator(MA), def_chain_iterator(UpTo));<br>
> +}<br>
> +<br>
> +/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing<br>
> +/// inbetween `Start` and `ClobberAt` can clobbers `Start`.<br>
> +///<br>
> +/// This is meant to be as simple and self-contained as possible. Because it<br>
> +/// uses no cache, etc., it can be relatively expensive.<br>
> +///<br>
> +/// \param Start The MemoryAccess that we want to walk from.<br>
> +/// \param ClobberAt A clobber for Start.<br>
> +/// \param StartLoc The MemoryLocation for Start.<br>
> +/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.<br>
> +/// \param Query The UpwardsMemoryQuery we used for our search.<br>
> +/// \param AA The AliasAnalysis we used for our search.<br>
> +static void LLVM_ATTRIBUTE_UNUSED<br>
> +checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,<br>
> + const MemoryLocation &StartLoc, const MemorySSA &MSSA,<br>
> + const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {<br>
> + assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");<br>
> +<br>
> + if (MSSA.isLiveOnEntryDef(Start)) {<br>
> + assert(MSSA.isLiveOnEntryDef(ClobberAt) &&<br>
> + "liveOnEntry must clobber itself");<br>
> + return;<br>
> + }<br>
> +<br>
> + assert((isa<MemoryPhi>(Start) || Start != ClobberAt) &&<br>
> + "Start can't clobber itself!");<br>
> +<br>
> + bool FoundClobber = false;<br>
> + DenseSet<MemoryAccessPair> VisitedPhis;<br>
> + SmallVector<MemoryAccessPair, 8> Worklist;<br>
> + Worklist.emplace_back(Start, StartLoc);<br>
> + // Walk all paths from Start to ClobberAt, while looking for clobbers. If one<br>
> + // is found, complain.<br>
> + while (!Worklist.empty()) {<br>
> + MemoryAccessPair MAP = Worklist.pop_back_val();<br>
> + // All we care about is that nothing from Start to ClobberAt clobbers Start.<br>
> + // We learn nothing from revisiting nodes.<br>
> + if (!VisitedPhis.insert(MAP).second)<br>
> + continue;<br>
> +<br>
> + for (MemoryAccess *MA : def_chain(MAP.first)) {<br>
> + if (MA == ClobberAt) {<br>
> + if (auto *MD = dyn_cast<MemoryDef>(MA)) {<br>
> + // instructionClobbersQuery isn't essentially free, so don't use `|=`,<br>
> + // since it won't let us short-circuit.<br>
> + //<br>
> + // Also, note that this can't be hoisted out of the `Worklist` loop,<br>
> + // since MD may only act as a clobber for 1 of N MemoryLocations.<br>
> + FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD) ||<br>
> + instructionClobbersQuery(MD, MAP.second, Query, AA);<br>
> + }<br>
> + break;<br>
> + }<br>
> +<br>
> + // We should never hit liveOnEntry, unless it's the clobber.<br>
> + assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");<br>
> +<br>
> + if (auto *MD = dyn_cast<MemoryDef>(MA)) {<br>
> + (void)MD;<br>
> + assert(!instructionClobbersQuery(MD, MAP.second, Query, AA) &&<br>
> + "Found clobber before reaching ClobberAt!");<br>
> + continue;<br>
> + }<br>
> +<br>
> + assert(isa<MemoryPhi>(MA));<br>
> + Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());<br>
> + }<br>
> + }<br>
> +<br>
> + // If ClobberAt is a MemoryPhi, we can assume something above it acted as a<br>
> + // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.<br>
> + assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&<br>
> + "ClobberAt never acted as a clobber");<br>
> +}<br>
> +<br>
> +/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up<br>
> +/// in one class.<br>
> +class ClobberWalker {<br>
> + /// Save a few bytes by using unsigned instead of size_t.<br>
> + using ListIndex = unsigned;<br>
> +<br>
> + /// Represents a span of contiguous MemoryDefs, potentially ending in a<br>
> + /// MemoryPhi.<br>
> + struct DefPath {<br>
> + MemoryLocation Loc;<br>
> + // Note that, because we always walk in reverse, Last will always dominate<br>
> + // First. Also note that First and Last are inclusive.<br>
> + MemoryAccess *First;<br>
> + MemoryAccess *Last;<br>
> + // N.B. Blocker is currently basically unused. The goal is to use it to make<br>
> + // cache invalidation better, but we're not there yet.<br>
> + MemoryAccess *Blocker;<br>
> + Optional<ListIndex> Previous;<br>
> +<br>
> + DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,<br>
> + Optional<ListIndex> Previous)<br>
> + : Loc(Loc), First(First), Last(Last), Previous(Previous) {}<br>
> +<br>
> + DefPath(const MemoryLocation &Loc, MemoryAccess *Init,<br>
> + Optional<ListIndex> Previous)<br>
> + : DefPath(Loc, Init, Init, Previous) {}<br>
> + };<br>
> +<br>
> + const MemorySSA &MSSA;<br>
> + AliasAnalysis &AA;<br>
> + DominatorTree &DT;<br>
> + WalkerCache &WC;<br>
> + UpwardsMemoryQuery *Query;<br>
> + bool UseCache;<br>
> +<br>
> + // Phi optimization bookkeeping<br>
> + SmallVector<DefPath, 32> Paths;<br>
> + DenseSet<ConstMemoryAccessPair> VisitedPhis;<br>
> + DenseMap<const BasicBlock *, MemoryAccess *> WalkTargetCache;<br>
> +<br>
> + void setUseCache(bool Use) { UseCache = Use; }<br>
> + bool shouldIgnoreCache() const {<br>
> + // UseCache will only be false when we're debugging, or when expensive<br>
> + // checks are enabled. In either case, we don't care deeply about speed.<br>
> + return LLVM_UNLIKELY(!UseCache);<br>
> + }<br>
> +<br>
> + void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,<br>
> + const MemoryLocation &Loc) const {<br>
> +// EXPENSIVE_CHECKS because most of these queries are redundant, and if What<br>
> +// and To are in the same BB, that gives us n^2 behavior.<br>
> +#ifdef EXPENSIVE_CHECKS<br>
> + assert(MSSA.dominates(To, What));<br>
> +#endif<br>
> + if (shouldIgnoreCache())<br>
> + return;<br>
> + WC.insert(What, To, Loc, Query->IsCall);<br>
> + }<br>
> +<br>
> + MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {<br>
> + return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);<br>
> + }<br>
> +<br>
> + void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {<br>
> + if (shouldIgnoreCache())<br>
> + return;<br>
> +<br>
> + for (MemoryAccess *MA : def_chain(DN.First, DN.Last))<br>
> + addCacheEntry(MA, Target, DN.Loc);<br>
> +<br>
> + // DefPaths only express the path we walked. So, DN.Last could either be a<br>
> + // thing we want to cache, or not.<br>
> + if (DN.Last != Target)<br>
> + addCacheEntry(DN.Last, Target, DN.Loc);<br>
> + }<br>
> +<br>
> + /// Find the nearest def or phi that `From` can legally be optimized to.<br>
> + ///<br>
> + /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should<br>
> + /// keep track of this information for us, and allow us O(1) lookups of this<br>
> + /// info.<br>
> + MemoryAccess *getWalkTarget(const MemoryPhi *From) {<br>
> + assert(!MSSA.isLiveOnEntryDef(From) && "liveOnEntry has no target.");<br>
> + assert(From->getNumOperands() && "Phi with no operands?");<br>
> +<br>
> + BasicBlock *BB = From->getBlock();<br>
> + auto At = WalkTargetCache.find(BB);<br>
> + if (At != WalkTargetCache.end())<br>
> + return At->second;<br>
> +<br>
> + SmallVector<const BasicBlock *, 8> ToCache;<br>
> + ToCache.push_back(BB);<br>
> +<br>
> + MemoryAccess *Result = MSSA.getLiveOnEntryDef();<br>
> + DomTreeNode *Node = DT.getNode(BB);<br>
> + while ((Node = Node->getIDom())) {<br>
> + auto At = WalkTargetCache.find(BB);<br>
> + if (At != WalkTargetCache.end()) {<br>
> + Result = At->second;<br>
> + break;<br>
> + }<br>
> +<br>
> + auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());<br>
> + if (Accesses) {<br>
> + auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {<br>
> + return !isa<MemoryUse>(MA);<br>
> + });<br>
> + if (Iter != Accesses->rend()) {<br>
> + Result = const_cast<MemoryAccess *>(&*Iter);<br>
> + break;<br>
> + }<br>
> + }<br>
> +<br>
> + ToCache.push_back(Node->getBlock());<br>
> + }<br>
> +<br>
> + for (const BasicBlock *BB : ToCache)<br>
> + WalkTargetCache.insert({BB, Result});<br>
> + return Result;<br>
> + }<br>
> +<br>
> + /// Result of calling walkToPhiOrClobber.<br>
> + struct UpwardsWalkResult {<br>
> + /// The "Result" of the walk. Either a clobber, the last thing we walked, or<br>
> + /// both.<br>
> + MemoryAccess *Result;<br>
> + bool IsKnownClobber;<br>
> + bool FromCache;<br>
> + };<br>
> +<br>
> + /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.<br>
> + /// This will update Desc.Last as it walks. It will (optionally) also stop at<br>
> + /// StopAt.<br>
> + ///<br>
> + /// This does not test for whether StopAt is a clobber<br>
> + UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,<br>
> + MemoryAccess *StopAt = nullptr) {<br>
> + assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");<br>
> +<br>
> + for (MemoryAccess *Current : def_chain(Desc.Last)) {<br>
> + Desc.Last = Current;<br>
> + if (Current == StopAt)<br>
> + return {Current, false, false};<br>
> +<br>
> + if (auto *MD = dyn_cast<MemoryDef>(Current))<br>
> + if (MSSA.isLiveOnEntryDef(MD) ||<br>
> + instructionClobbersQuery(MD, Desc.Loc, *Query, AA))<br>
> + return {MD, true, false};<br>
> +<br>
> + // Cache checks must be done last, because if Current is a clobber, the<br>
> + // cache will contain the clobber for Current.<br>
> + if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))<br>
> + return {MA, true, true};<br>
> + }<br>
> +<br>
> + assert(isa<MemoryPhi>(Desc.Last) &&<br>
> + "Ended at a non-clobber that's not a phi?");<br>
> + return {Desc.Last, false, false};<br>
> + }<br>
> +<br>
> + void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,<br>
> + ListIndex PriorNode) {<br>
> + auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),<br>
> + upward_defs_end());<br>
> + for (const MemoryAccessPair &P : UpwardDefs) {<br>
> + PausedSearches.push_back(Paths.size());<br>
> + Paths.emplace_back(P.second, P.first, PriorNode);<br>
> + }<br>
> + }<br>
> +<br>
> + /// Represents a search that terminated after finding a clobber. This clobber<br>
> + /// may or may not be present in the path of defs from LastNode..SearchStart,<br>
> + /// since it may have been retrieved from cache.<br>
> + struct TerminatedPath {<br>
> + MemoryAccess *Clobber;<br>
> + ListIndex LastNode;<br>
> + };<br>
> +<br>
> + /// Get an access that keeps us from optimizing to the given phi.<br>
> + ///<br>
> + /// PausedSearches is an array of indices into the Paths array. Its incoming<br>
> + /// value is the indices of searches that stopped at the last phi optimization<br>
> + /// target. It's left in an unspecified state.<br>
> + ///<br>
> + /// If this returns None, NewPaused is a vector of searches that terminated<br>
> + /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.<br>
> + Optional<ListIndex><br>
> + getBlockingAccess(MemoryAccess *StopWhere,<br>
> + SmallVectorImpl<ListIndex> &PausedSearches,<br>
> + SmallVectorImpl<ListIndex> &NewPaused,<br>
> + SmallVectorImpl<TerminatedPath> &Terminated) {<br>
> + assert(!PausedSearches.empty() && "No searches to continue?");<br>
> +<br>
> + // BFS vs DFS really doesn't make a difference here, so just do a DFS with<br>
> + // PausedSearches as our stack.<br>
> + while (!PausedSearches.empty()) {<br>
> + ListIndex PathIndex = PausedSearches.pop_back_val();<br>
> + DefPath &Node = Paths[PathIndex];<br>
> +<br>
> + // If we've already visited this path with this MemoryLocation, we don't<br>
> + // need to do so again.<br>
> + //<br>
> + // NOTE: That we just drop these paths on the ground makes caching<br>
> + // behavior sporadic. e.g. given a diamond:<br>
> + // A<br>
> + // B C<br>
> + // D<br>
> + //<br>
> + // ...If we walk D, B, A, C, we'll only cache the result of phi<br>
> + // optimization for A, B, and D; C will be skipped because it dies here.<br>
> + // This arguably isn't the worst thing ever, since:<br>
> + // - We generally query things in a top-down order, so if we got below D<br>
> + // without needing cache entries for {C, MemLoc}, then chances are<br>
> + // that those cache entries would end up ultimately unused.<br>
> + // - We still cache things for A, so C only needs to walk up a bit.<br>
> + // If this behavior becomes problematic, we can fix without a ton of extra<br>
> + // work.<br>
> + if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)<br>
> + continue;<br>
> +<br>
> + UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);<br>
> + if (Res.IsKnownClobber) {<br>
> + assert(Res.Result != StopWhere || Res.FromCache);<br>
> + // If this wasn't a cache hit, we hit a clobber when walking. That's a<br>
> + // failure.<br>
> + if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))<br>
> + return PathIndex;<br>
> +<br>
> + // Otherwise, it's a valid thing to potentially optimize to.<br>
> + Terminated.push_back({Res.Result, PathIndex});<br>
> + continue;<br>
> + }<br>
> +<br>
> + if (Res.Result == StopWhere) {<br>
> + // We've hit our target. Save this path off for if we want to continue<br>
> + // walking.<br>
> + NewPaused.push_back(PathIndex);<br>
> + continue;<br>
> + }<br>
> +<br>
> + assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");<br>
> + addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);<br>
> + }<br>
> +<br>
> + return None;<br>
> + }<br>
> +<br>
> + template <typename T, typename Walker><br>
> + struct generic_def_path_iterator<br>
> + : public iterator_facade_base<generic_def_path_iterator<T, Walker>,<br>
> + std::forward_iterator_tag, T *> {<br>
> + generic_def_path_iterator() : W(nullptr), N(None) {}<br>
> + generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}<br>
> +<br>
> + T &operator*() const { return curNode(); }<br>
> +<br>
> + generic_def_path_iterator &operator++() {<br>
> + N = curNode().Previous;<br>
> + return *this;<br>
> + }<br>
> +<br>
> + bool operator==(const generic_def_path_iterator &O) const {<br>
> + if (N.hasValue() != O.N.hasValue())<br>
> + return false;<br>
> + return !N.hasValue() || *N == *O.N;<br>
> + }<br>
> +<br>
> + private:<br>
> + T &curNode() const { return W->Paths[*N]; }<br>
> +<br>
> + Walker *W;<br>
> + Optional<ListIndex> N;<br>
> + };<br>
> +<br>
> + using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;<br>
> + using const_def_path_iterator =<br>
> + generic_def_path_iterator<const DefPath, const ClobberWalker>;<br>
> +<br>
> + iterator_range<def_path_iterator> def_path(ListIndex From) {<br>
> + return make_range(def_path_iterator(this, From), def_path_iterator());<br>
> + }<br>
> +<br>
> + iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {<br>
> + return make_range(const_def_path_iterator(this, From),<br>
> + const_def_path_iterator());<br>
> + }<br>
> +<br>
> + struct OptznResult {<br>
> + /// The path that contains our result.<br>
> + TerminatedPath PrimaryClobber;<br>
> + /// The paths that we can legally cache back from, but that aren't<br>
> + /// necessarily the result of the Phi optimization.<br>
> + SmallVector<TerminatedPath, 4> OtherClobbers;<br>
> + };<br>
> +<br>
> + ListIndex defPathIndex(const DefPath &N) const {<br>
> + // The assert looks nicer if we don't need to do &N<br>
> + const DefPath *NP = &N;<br>
> + assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&<br>
> + "Out of bounds DefPath!");<br>
> + return NP - &Paths.front();<br>
> + }<br>
> +<br>
> + /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths<br>
> + /// that act as legal clobbers. Note that this won't return *all* clobbers.<br>
> + ///<br>
> + /// Phi optimization algorithm tl;dr:<br>
> + /// - Find the earliest def/phi, A, we can optimize to<br>
> + /// - Find if all paths from the starting memory access ultimately reach A<br>
> + /// - If not, optimization isn't possible.<br>
> + /// - Otherwise, walk from A to another clobber or phi, A'.<br>
> + /// - If A' is a def, we're done.<br>
> + /// - If A' is a phi, try to optimize it.<br>
> + ///<br>
> + /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path<br>
> + /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.<br>
> + OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,<br>
> + const MemoryLocation &Loc) {<br>
> + assert(Paths.empty() && VisitedPhis.empty() &&<br>
> + "Reset the optimization state.");<br>
> +<br>
> + Paths.emplace_back(Loc, Start, Phi, None);<br>
> + // Stores how many "valid" optimization nodes we had prior to calling<br>
> + // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.<br>
> + auto PriorPathsSize = Paths.size();<br>
> +<br>
> + SmallVector<ListIndex, 16> PausedSearches;<br>
> + SmallVector<ListIndex, 8> NewPaused;<br>
> + SmallVector<TerminatedPath, 4> TerminatedPaths;<br>
> +<br>
> + addSearches(Phi, PausedSearches, 0);<br>
> +<br>
> + // Moves the TerminatedPath with the "most dominated" Clobber to the end of<br>
> + // Paths.<br>
> + auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {<br>
> + assert(!Paths.empty() && "Need a path to move");<br>
> + // FIXME: This is technically n^2 (n = distance(DefPath.First,<br>
> + // DefPath.Last)) because of local dominance checks.<br>
> + auto Dom = Paths.begin();<br>
> + for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)<br>
> + if (!MSSA.dominates(I->Clobber, Dom->Clobber))<br>
> + Dom = I;<br>
> + auto Last = Paths.end() - 1;<br>
> + if (Last != Dom)<br>
> + std::iter_swap(Last, Dom);<br>
> + };<br>
> +<br>
> + MemoryPhi *Current = Phi;<br>
> + while (1) {<br>
> + assert(!MSSA.isLiveOnEntryDef(Current) &&<br>
> + "liveOnEntry wasn't treated as a clobber?");<br>
> +<br>
> + MemoryAccess *Target = getWalkTarget(Current);<br>
> + // If a TerminatedPath doesn't dominate Target, then it wasn't a legal<br>
> + // optimization for the prior phi.<br>
> + assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {<br>
> + return MSSA.dominates(P.Clobber, Target);<br>
> + }));<br>
> +<br>
> + // FIXME: This is broken, because the Blocker may be reported to be<br>
> + // liveOnEntry, and we'll happily wait for that to disappear (read: never)<br>
> + // For the moment, this is fine, since we do basically nothing with<br>
> + // blocker info.<br>
> + if (Optional<ListIndex> Blocker = getBlockingAccess(<br>
> + Target, PausedSearches, NewPaused, TerminatedPaths)) {<br>
> + MemoryAccess *BlockingAccess = Paths[*Blocker].Last;<br>
> + // Cache our work on the blocking node, since we know that's correct.<br>
> + cacheDefPath(Paths[*Blocker], BlockingAccess);<br>
> +<br>
> + // Find the node we started at. We can't search based on N->Last, since<br>
> + // we may have gone around a loop with a different MemoryLocation.<br>
> + auto Iter = find_if(def_path(*Blocker), [&](const DefPath &N) {<br>
> + return defPathIndex(N) < PriorPathsSize;<br>
> + });<br>
> + assert(Iter != def_path_iterator());<br>
> +<br>
> + DefPath &CurNode = *Iter;<br>
> + assert(CurNode.Last == Current);<br>
> + CurNode.Blocker = BlockingAccess;<br>
> +<br>
> + // Two things:<br>
> + // A. We can't reliably cache all of NewPaused back. Consider a case<br>
> + // where we have two paths in NewPaused; one of which can't optimize<br>
> + // above this phi, whereas the other can. If we cache the second path<br>
> + // back, we'll end up with suboptimal cache entries. We can handle<br>
> + // cases like this a bit better when we either try to find all<br>
> + // clobbers that block phi optimization, or when our cache starts<br>
> + // supporting unfinished searches.<br>
> + // B. We can't reliably cache TerminatedPaths back here without doing<br>
> + // extra checks; consider a case like:<br>
> + // T<br>
> + // / \<br>
> + // D C<br>
> + // \ /<br>
> + // S<br>
> + // Where T is our target, C is a node with a clobber on it, D is a<br>
> + // diamond (with a clobber *only* on the left or right node, N), and<br>
> + // S is our start. Say we walk to D, through the node opposite N<br>
> + // (read: ignoring the clobber), and see a cache entry in the top<br>
> + // node of D. That cache entry gets put into TerminatedPaths. We then<br>
> + // walk up to C (N is later in our worklist), find the clobber, and<br>
> + // quit. If we append TerminatedPaths to OtherClobbers, we'll cache<br>
> + // the bottom part of D to the cached clobber, ignoring the clobber<br>
> + // in N. Again, this problem goes away if we start tracking all<br>
> + // blockers for a given phi optimization.<br>
> + TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};<br>
> + return {Result, {}};<br>
> + }<br>
> +<br>
> + // If there's nothing left to search, then all paths led to valid clobbers<br>
> + // that we got from our cache; pick the nearest to the start, and allow<br>
> + // the rest to be cached back.<br>
> + if (NewPaused.empty()) {<br>
> + MoveDominatedPathToEnd(TerminatedPaths);<br>
> + TerminatedPath Result = TerminatedPaths.pop_back_val();<br>
> + return {Result, std::move(TerminatedPaths)};<br>
> + }<br>
> +<br>
> + MemoryAccess *DefChainEnd = nullptr;<br>
> + SmallVector<TerminatedPath, 4> Clobbers;<br>
> + for (ListIndex Paused : NewPaused) {<br>
> + UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);<br>
> + if (WR.IsKnownClobber)<br>
> + Clobbers.push_back({WR.Result, Paused});<br>
> + else<br>
> + // Micro-opt: If we hit the end of the chain, save it.<br>
> + DefChainEnd = WR.Result;<br>
> + }<br>
> +<br>
> + if (!TerminatedPaths.empty()) {<br>
> + // If we couldn't find the dominating phi/liveOnEntry in the above loop,<br>
> + // do it now.<br>
> + if (!DefChainEnd)<br>
</div></div>> + for (MemoryAccess *MA : def_chain(Target)))<br>
> + DefChainEnd = MA;<br>
<br>
Is it guaranteed that `def_chain(Target)` isn’t empty?<br>
Otherwise you have nullptr deref on the next line (Reported by coverity who can’t know this invariant).<br>
<br>
—<br>
<span><font color="#888888">Mehdi<br>
</font></span><div><div><br>
> +<br>
> + // If any of the terminated paths don't dominate the phi we'll try to<br>
> + // optimize, we need to figure out what they are and quit.<br>
> + const BasicBlock *ChainBB = DefChainEnd->getBlock();<br>
> + for (const TerminatedPath &TP : TerminatedPaths) {<br>
> + // Because we know that DefChainEnd is as "high" as we can go, we<br>
> + // don't need local dominance checks; BB dominance is sufficient.<br>
> + if (DT.dominates(ChainBB, TP.Clobber->getBlock()))<br>
> + Clobbers.push_back(TP);<br>
> + }<br>
> + }<br>
> +<br>
> + // If we have clobbers in the def chain, find the one closest to Current<br>
> + // and quit.<br>
> + if (!Clobbers.empty()) {<br>
> + MoveDominatedPathToEnd(Clobbers);<br>
> + TerminatedPath Result = Clobbers.pop_back_val();<br>
> + return {Result, std::move(Clobbers)};<br>
> + }<br>
> +<br>
> + assert(all_of(NewPaused,<br>
> + [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));<br>
> +<br>
> + // Because liveOnEntry is a clobber, this must be a phi.<br>
> + auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);<br>
> +<br>
> + PriorPathsSize = Paths.size();<br>
> + PausedSearches.clear();<br>
> + for (ListIndex I : NewPaused)<br>
> + addSearches(DefChainPhi, PausedSearches, I);<br>
> + NewPaused.clear();<br>
> +<br>
> + Current = DefChainPhi;<br>
> + }<br>
> + }<br>
> +<br>
> + /// Caches everything in an OptznResult.<br>
> + void cacheOptResult(const OptznResult &R) {<br>
> + if (R.OtherClobbers.empty()) {<br>
> + // If we're not going to be caching OtherClobbers, don't bother with<br>
> + // marking visited/etc.<br>
> + for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))<br>
> + cacheDefPath(N, R.PrimaryClobber.Clobber);<br>
> + return;<br>
> + }<br>
> +<br>
> + // PrimaryClobber is our answer. If we can cache anything back, we need to<br>
> + // stop caching when we visit PrimaryClobber.<br>
> + SmallBitVector Visited(Paths.size());<br>
> + for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {<br>
> + Visited[defPathIndex(N)] = true;<br>
> + cacheDefPath(N, R.PrimaryClobber.Clobber);<br>
> + }<br>
> +<br>
> + for (const TerminatedPath &P : R.OtherClobbers) {<br>
> + for (const DefPath &N : const_def_path(P.LastNode)) {<br>
> + ListIndex NIndex = defPathIndex(N);<br>
> + if (Visited[NIndex])<br>
> + break;<br>
> + Visited[NIndex] = true;<br>
> + cacheDefPath(N, P.Clobber);<br>
> + }<br>
> + }<br>
> + }<br>
> +<br>
> + void verifyOptResult(const OptznResult &R) const {<br>
> + assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {<br>
> + return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);<br>
> + }));<br>
> + }<br>
> +<br>
> + void resetPhiOptznState() {<br>
> + Paths.clear();<br>
> + VisitedPhis.clear();<br>
> + }<br>
> +<br>
> +public:<br>
> + ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,<br>
> + WalkerCache &WC)<br>
> + : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}<br>
> +<br>
> + void reset() { WalkTargetCache.clear(); }<br>
> +<br>
> + /// Finds the nearest clobber for the given query, optimizing phis if<br>
> + /// possible.<br>
> + MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,<br>
> + bool UseWalkerCache = true) {<br>
> + setUseCache(UseWalkerCache);<br>
> + Query = &Q;<br>
> +<br>
> + MemoryAccess *Current = Start;<br>
> + // This walker pretends uses don't exist. If we're handed one, silently grab<br>
> + // its def. (This has the nice side-effect of ensuring we never cache uses)<br>
> + if (auto *MU = dyn_cast<MemoryUse>(Start))<br>
> + Current = MU->getDefiningAccess();<br>
> +<br>
> + DefPath FirstDesc(Q.StartingLoc, Current, Current, None);<br>
> + // Fast path for the overly-common case (no crazy phi optimization<br>
> + // necessary)<br>
> + UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);<br>
> + if (WalkResult.IsKnownClobber) {<br>
> + cacheDefPath(FirstDesc, WalkResult.Result);<br>
> + return WalkResult.Result;<br>
> + }<br>
> +<br>
> + OptznResult OptRes =<br>
> + tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last), Current, Q.StartingLoc);<br>
> + verifyOptResult(OptRes);<br>
> + cacheOptResult(OptRes);<br>
> + resetPhiOptznState();<br>
> +<br>
> +#ifdef EXPENSIVE_CHECKS<br>
> + checkClobberSanity(Current, OptRes.PrimaryClobber.Clobber, Q.StartingLoc,<br>
> + MSSA, Q, AA);<br>
> +#endif<br>
> + return OptRes.PrimaryClobber.Clobber;<br>
> + }<br>
> +};<br>
> +<br>
> +struct RenamePassData {<br>
> + DomTreeNode *DTN;<br>
> + DomTreeNode::const_iterator ChildIt;<br>
> + MemoryAccess *IncomingVal;<br>
><br>
> + RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,<br>
> + MemoryAccess *M)<br>
> + : DTN(D), ChildIt(It), IncomingVal(M) {}<br>
> + void swap(RenamePassData &RHS) {<br>
> + std::swap(DTN, RHS.DTN);<br>
> + std::swap(ChildIt, RHS.ChildIt);<br>
> + std::swap(IncomingVal, RHS.IncomingVal);<br>
> + }<br>
> +};<br>
> +} // anonymous namespace<br>
> +<br>
> +namespace llvm {<br>
> /// \brief A MemorySSAWalker that does AA walks and caching of lookups to<br>
> /// disambiguate accesses.<br>
> ///<br>
> @@ -121,6 +892,13 @@ public:<br>
> /// ret i32 %r<br>
> /// }<br>
> class MemorySSA::CachingWalker final : public MemorySSAWalker {<br>
> + WalkerCache Cache;<br>
> + ClobberWalker Walker;<br>
> + bool AutoResetWalker;<br>
> +<br>
> + MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);<br>
> + void verifyRemoved(MemoryAccess *);<br>
> +<br>
> public:<br>
> CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);<br>
> ~CachingWalker() override;<br>
> @@ -130,50 +908,17 @@ public:<br>
> MemoryLocation &) override;<br>
> void invalidateInfo(MemoryAccess *) override;<br>
><br>
> -protected:<br>
> - struct UpwardsMemoryQuery;<br>
> - MemoryAccess *doCacheLookup(const MemoryAccess *, const UpwardsMemoryQuery &,<br>
> - const MemoryLocation &);<br>
> -<br>
> - void doCacheInsert(const MemoryAccess *, MemoryAccess *,<br>
> - const UpwardsMemoryQuery &, const MemoryLocation &);<br>
> -<br>
> - void doCacheRemove(const MemoryAccess *, const UpwardsMemoryQuery &,<br>
> - const MemoryLocation &);<br>
> -<br>
> -private:<br>
> - MemoryAccessPair UpwardsDFSWalk(MemoryAccess *, const MemoryLocation &,<br>
> - UpwardsMemoryQuery &, bool);<br>
> - MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);<br>
> - bool instructionClobbersQuery(const MemoryDef *, UpwardsMemoryQuery &,<br>
> - const MemoryLocation &Loc) const;<br>
> - void verifyRemoved(MemoryAccess *);<br>
> - SmallDenseMap<ConstMemoryAccessPair, MemoryAccess *><br>
> - CachedUpwardsClobberingAccess;<br>
> - DenseMap<const MemoryAccess *, MemoryAccess *> CachedUpwardsClobberingCall;<br>
> - AliasAnalysis *AA;<br>
> - DominatorTree *DT;<br>
> + /// Whether we call resetClobberWalker() after each time we *actually* walk to<br>
> + /// answer a clobber query.<br>
> + void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }<br>
> +<br>
> + /// Drop the walker's persistent data structures. At the moment, this means<br>
> + /// "drop the walker's cache of BasicBlocks -><br>
> + /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're<br>
> + /// going to have DT updates, if we remove MemoryAccesses, etc.<br>
> + void resetClobberWalker() { Walker.reset(); }<br>
> };<br>
> -}<br>
><br>
> -namespace {<br>
> -struct RenamePassData {<br>
> - DomTreeNode *DTN;<br>
> - DomTreeNode::const_iterator ChildIt;<br>
> - MemoryAccess *IncomingVal;<br>
> -<br>
> - RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,<br>
> - MemoryAccess *M)<br>
> - : DTN(D), ChildIt(It), IncomingVal(M) {}<br>
> - void swap(RenamePassData &RHS) {<br>
> - std::swap(DTN, RHS.DTN);<br>
> - std::swap(ChildIt, RHS.ChildIt);<br>
> - std::swap(IncomingVal, RHS.IncomingVal);<br>
> - }<br>
> -};<br>
> -}<br>
> -<br>
> -namespace llvm {<br>
> /// \brief Rename a single basic block into MemorySSA form.<br>
> /// Uses the standard SSA renaming algorithm.<br>
> /// \returns The new incoming value.<br>
> @@ -417,7 +1162,10 @@ void MemorySSA::buildMemorySSA() {<br>
> SmallPtrSet<BasicBlock *, 16> Visited;<br>
> renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);<br>
><br>
> - MemorySSAWalker *Walker = getWalker();<br>
> + CachingWalker *Walker = getWalkerImpl();<br>
> +<br>
> + // We're doing a batch of updates; don't drop useful caches between them.<br>
> + Walker->setAutoResetWalker(false);<br>
><br>
> // Now optimize the MemoryUse's defining access to point to the nearest<br>
> // dominating clobbering def.<br>
> @@ -437,6 +1185,9 @@ void MemorySSA::buildMemorySSA() {<br>
> }<br>
> }<br>
><br>
> + Walker->setAutoResetWalker(true);<br>
> + Walker->resetClobberWalker();<br>
> +<br>
> // Mark the uses in unreachable blocks as live on entry, so that they go<br>
> // somewhere.<br>
> for (auto &BB : F)<br>
> @@ -444,7 +1195,9 @@ void MemorySSA::buildMemorySSA() {<br>
> markUnreachableAsLiveOnEntry(&BB);<br>
> }<br>
><br>
> -MemorySSAWalker *MemorySSA::getWalker() {<br>
> +MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }<br>
> +<br>
> +MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {<br>
> if (Walker)<br>
> return Walker.get();<br>
><br>
> @@ -820,7 +1573,6 @@ MemoryPhi *MemorySSA::getMemoryAccess(co<br>
> /// \returns True if \p Dominator dominates \p Dominatee.<br>
> bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,<br>
> const MemoryAccess *Dominatee) const {<br>
> -<br>
> assert((Dominator->getBlock() == Dominatee->getBlock()) &&<br>
> "Asking for local domination when accesses are in different blocks!");<br>
><br>
> @@ -848,6 +1600,19 @@ bool MemorySSA::locallyDominates(const M<br>
> [&](const MemoryAccess &MA) { return &MA == Dominatee; });<br>
> }<br>
><br>
> +bool MemorySSA::dominates(const MemoryAccess *Dominator,<br>
> + const MemoryAccess *Dominatee) const {<br>
> + if (Dominator == Dominatee)<br>
> + return true;<br>
> +<br>
> + if (isLiveOnEntryDef(Dominatee))<br>
> + return false;<br>
> +<br>
> + if (Dominator->getBlock() != Dominatee->getBlock())<br>
> + return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());<br>
> + return locallyDominates(Dominator, Dominatee);<br>
> +}<br>
> +<br>
> const static char LiveOnEntryStr[] = "liveOnEntry";<br>
><br>
> void MemoryDef::print(raw_ostream &OS) const {<br>
> @@ -978,41 +1743,12 @@ MemorySSAWalker::MemorySSAWalker(MemoryS<br>
><br>
> MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,<br>
> DominatorTree *D)<br>
> - : MemorySSAWalker(M), AA(A), DT(D) {}<br>
> + : MemorySSAWalker(M), Walker(*M, *A, *D, Cache),<br>
> + AutoResetWalker(true) {}<br>
><br>
> MemorySSA::CachingWalker::~CachingWalker() {}<br>
><br>
> -struct MemorySSA::CachingWalker::UpwardsMemoryQuery {<br>
> - // True if we saw a phi whose predecessor was a backedge<br>
> - bool SawBackedgePhi;<br>
> - // True if our original query started off as a call<br>
> - bool IsCall;<br>
> - // The pointer location we started the query with. This will be empty if<br>
> - // IsCall is true.<br>
> - MemoryLocation StartingLoc;<br>
> - // This is the instruction we were querying about.<br>
> - const Instruction *Inst;<br>
> - // Set of visited Instructions for this query.<br>
> - DenseSet<MemoryAccessPair> Visited;<br>
> - // Vector of visited call accesses for this query. This is separated out<br>
> - // because you can always cache and lookup the result of call queries (IE when<br>
> - // IsCall == true) for every call in the chain. The calls have no AA location<br>
> - // associated with them with them, and thus, no context dependence.<br>
> - SmallVector<const MemoryAccess *, 32> VisitedCalls;<br>
> - // The MemoryAccess we actually got called with, used to test local domination<br>
> - const MemoryAccess *OriginalAccess;<br>
> -<br>
> - UpwardsMemoryQuery()<br>
> - : SawBackedgePhi(false), IsCall(false), Inst(nullptr),<br>
> - OriginalAccess(nullptr) {}<br>
> -<br>
> - UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)<br>
> - : SawBackedgePhi(false), IsCall(ImmutableCallSite(Inst)), Inst(Inst),<br>
> - OriginalAccess(Access) {}<br>
> -};<br>
> -<br>
> void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {<br>
> -<br>
> // TODO: We can do much better cache invalidation with differently stored<br>
> // caches. For now, for MemoryUses, we simply remove them<br>
> // from the cache, and kill the entire call/non-call cache for everything<br>
> @@ -1026,217 +1762,33 @@ void MemorySSA::CachingWalker::invalidat<br>
> // itself.<br>
><br>
> if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {<br>
> - UpwardsMemoryQuery Q;<br>
> - Instruction *I = MU->getMemoryInst();<br>
> - Q.IsCall = bool(ImmutableCallSite(I));<br>
> - Q.Inst = I;<br>
> - if (!Q.IsCall)<br>
> - Q.StartingLoc = MemoryLocation::get(I);<br>
> - doCacheRemove(MA, Q, Q.StartingLoc);<br>
> + UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);<br>
> + Cache.remove(MU, Q.StartingLoc, Q.IsCall);<br>
> } else {<br>
> // If it is not a use, the best we can do right now is destroy the cache.<br>
> - CachedUpwardsClobberingCall.clear();<br>
> - CachedUpwardsClobberingAccess.clear();<br>
> + Cache.clear();<br>
> }<br>
><br>
> #ifdef EXPENSIVE_CHECKS<br>
> - // Run this only when expensive checks are enabled.<br>
> verifyRemoved(MA);<br>
> #endif<br>
> }<br>
><br>
> -void MemorySSA::CachingWalker::doCacheRemove(const MemoryAccess *M,<br>
> - const UpwardsMemoryQuery &Q,<br>
> - const MemoryLocation &Loc) {<br>
> - if (Q.IsCall)<br>
> - CachedUpwardsClobberingCall.erase(M);<br>
> - else<br>
> - CachedUpwardsClobberingAccess.erase({M, Loc});<br>
> -}<br>
> -<br>
> -void MemorySSA::CachingWalker::doCacheInsert(const MemoryAccess *M,<br>
> - MemoryAccess *Result,<br>
> - const UpwardsMemoryQuery &Q,<br>
> - const MemoryLocation &Loc) {<br>
> - // This is fine for Phis, since there are times where we can't optimize them.<br>
> - // Making a def its own clobber is never correct, though.<br>
> - assert((Result != M || isa<MemoryPhi>(M)) &&<br>
> - "Something can't clobber itself!");<br>
> - ++NumClobberCacheInserts;<br>
> - if (Q.IsCall)<br>
> - CachedUpwardsClobberingCall[M] = Result;<br>
> - else<br>
> - CachedUpwardsClobberingAccess[{M, Loc}] = Result;<br>
> -}<br>
> -<br>
> -MemoryAccess *<br>
> -MemorySSA::CachingWalker::doCacheLookup(const MemoryAccess *M,<br>
> - const UpwardsMemoryQuery &Q,<br>
> - const MemoryLocation &Loc) {<br>
> - ++NumClobberCacheLookups;<br>
> - MemoryAccess *Result;<br>
> -<br>
> - if (Q.IsCall)<br>
> - Result = CachedUpwardsClobberingCall.lookup(M);<br>
> - else<br>
> - Result = CachedUpwardsClobberingAccess.lookup({M, Loc});<br>
> -<br>
> - if (Result)<br>
> - ++NumClobberCacheHits;<br>
> - return Result;<br>
> -}<br>
> -<br>
> -bool MemorySSA::CachingWalker::instructionClobbersQuery(<br>
> - const MemoryDef *MD, UpwardsMemoryQuery &Q,<br>
> - const MemoryLocation &Loc) const {<br>
> - Instruction *DefMemoryInst = MD->getMemoryInst();<br>
> - assert(DefMemoryInst && "Defining instruction not actually an instruction");<br>
> -<br>
> - if (!Q.IsCall)<br>
> - return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;<br>
> -<br>
> - // If this is a call, mark it for caching<br>
> - if (ImmutableCallSite(DefMemoryInst))<br>
> - Q.VisitedCalls.push_back(MD);<br>
> - ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst));<br>
> - return I != MRI_NoModRef;<br>
> -}<br>
> -<br>
> -MemoryAccessPair MemorySSA::CachingWalker::UpwardsDFSWalk(<br>
> - MemoryAccess *StartingAccess, const MemoryLocation &Loc,<br>
> - UpwardsMemoryQuery &Q, bool FollowingBackedge) {<br>
> - MemoryAccess *ModifyingAccess = nullptr;<br>
> -<br>
> - auto DFI = df_begin(StartingAccess);<br>
> - for (auto DFE = df_end(StartingAccess); DFI != DFE;) {<br>
> - MemoryAccess *CurrAccess = *DFI;<br>
> - if (MSSA->isLiveOnEntryDef(CurrAccess))<br>
> - return {CurrAccess, Loc};<br>
> - // If this is a MemoryDef, check whether it clobbers our current query. This<br>
> - // needs to be done before consulting the cache, because the cache reports<br>
> - // the clobber for CurrAccess. If CurrAccess is a clobber for this query,<br>
> - // and we ask the cache for information first, then we might skip this<br>
> - // clobber, which is bad.<br>
> - if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) {<br>
> - // If we hit the top, stop following this path.<br>
> - // While we can do lookups, we can't sanely do inserts here unless we were<br>
> - // to track everything we saw along the way, since we don't know where we<br>
> - // will stop.<br>
> - if (instructionClobbersQuery(MD, Q, Loc)) {<br>
> - ModifyingAccess = CurrAccess;<br>
> - break;<br>
> - }<br>
> - }<br>
> - if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc))<br>
> - return {CacheResult, Loc};<br>
> -<br>
> - // We need to know whether it is a phi so we can track backedges.<br>
> - // Otherwise, walk all upward defs.<br>
> - if (!isa<MemoryPhi>(CurrAccess)) {<br>
> - ++DFI;<br>
> - continue;<br>
> - }<br>
> -<br>
> -#ifndef NDEBUG<br>
> - // The loop below visits the phi's children for us. Because phis are the<br>
> - // only things with multiple edges, skipping the children should always lead<br>
> - // us to the end of the loop.<br>
> - //<br>
> - // Use a copy of DFI because skipChildren would kill our search stack, which<br>
> - // would make caching anything on the way back impossible.<br>
> - auto DFICopy = DFI;<br>
> - assert(DFICopy.skipChildren() == DFE &&<br>
> - "Skipping phi's children doesn't end the DFS?");<br>
> -#endif<br>
> -<br>
> - const MemoryAccessPair PHIPair(CurrAccess, Loc);<br>
> -<br>
> - // Don't try to optimize this phi again if we've already tried to do so.<br>
> - if (!Q.Visited.insert(PHIPair).second) {<br>
> - ModifyingAccess = CurrAccess;<br>
> - break;<br>
> - }<br>
> -<br>
> - std::size_t InitialVisitedCallSize = Q.VisitedCalls.size();<br>
> -<br>
> - // Recurse on PHI nodes, since we need to change locations.<br>
> - // TODO: Allow graphtraits on pairs, which would turn this whole function<br>
> - // into a normal single depth first walk.<br>
> - MemoryAccess *FirstDef = nullptr;<br>
> - for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end();<br>
> - MPI != MPE; ++MPI) {<br>
> - bool Backedge =<br>
> - !FollowingBackedge &&<br>
> - DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock());<br>
> -<br>
> - MemoryAccessPair CurrentPair =<br>
> - UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge);<br>
> - // All the phi arguments should reach the same point if we can bypass<br>
> - // this phi. The alternative is that they hit this phi node, which<br>
> - // means we can skip this argument.<br>
> - if (FirstDef && CurrentPair.first != PHIPair.first &&<br>
> - CurrentPair.first != FirstDef) {<br>
> - ModifyingAccess = CurrAccess;<br>
> - break;<br>
> - }<br>
> -<br>
> - if (!FirstDef)<br>
> - FirstDef = CurrentPair.first;<br>
> - }<br>
> -<br>
> - // If we exited the loop early, go with the result it gave us.<br>
> - if (!ModifyingAccess) {<br>
> - assert(FirstDef && "Found a Phi with no upward defs?");<br>
> - ModifyingAccess = FirstDef;<br>
> - } else {<br>
> - // If we can't optimize this Phi, then we can't safely cache any of the<br>
> - // calls we visited when trying to optimize it. Wipe them out now.<br>
> - Q.VisitedCalls.resize(InitialVisitedCallSize);<br>
> - }<br>
> - break;<br>
> - }<br>
> -<br>
> - if (!ModifyingAccess)<br>
> - return {MSSA->getLiveOnEntryDef(), Q.StartingLoc};<br>
> -<br>
> - const BasicBlock *OriginalBlock = StartingAccess->getBlock();<br>
> - assert(DFI.getPathLength() > 0 && "We dropped our path?");<br>
> - unsigned N = DFI.getPathLength();<br>
> - // If we found a clobbering def, the last element in the path will be our<br>
> - // clobber, so we don't want to cache that to itself. OTOH, if we optimized a<br>
> - // phi, we can add the last thing in the path to the cache, since that won't<br>
> - // be the result.<br>
> - if (DFI.getPath(N - 1) == ModifyingAccess)<br>
> - --N;<br>
> - for (; N > 1; --N) {<br>
> - MemoryAccess *CacheAccess = DFI.getPath(N - 1);<br>
> - BasicBlock *CurrBlock = CacheAccess->getBlock();<br>
> - if (!FollowingBackedge)<br>
> - doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);<br>
> - if (DT->dominates(CurrBlock, OriginalBlock) &&<br>
> - (CurrBlock != OriginalBlock || !FollowingBackedge ||<br>
> - MSSA->locallyDominates(CacheAccess, StartingAccess)))<br>
> - break;<br>
> - }<br>
> -<br>
> - // Cache everything else on the way back. The caller should cache<br>
> - // StartingAccess for us.<br>
> - for (; N > 1; --N) {<br>
> - MemoryAccess *CacheAccess = DFI.getPath(N - 1);<br>
> - doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);<br>
> - }<br>
> - assert(Q.Visited.size() < 1000 && "Visited too much");<br>
> -<br>
> - return {ModifyingAccess, Loc};<br>
> -}<br>
> -<br>
> /// \brief Walk the use-def chains starting at \p MA and find<br>
> /// the MemoryAccess that actually clobbers Loc.<br>
> ///<br>
> /// \returns our clobbering memory access<br>
> MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(<br>
> MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {<br>
> - return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first;<br>
> + MemoryAccess *New = Walker.findClobber(StartingAccess, Q);<br>
> +#ifdef EXPENSIVE_CHECKS<br>
> + MemoryAccess *NewNoCache =<br>
> + Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);<br>
> + assert(NewNoCache == New && "Cache made us hand back a different result?");<br>
> +#endif<br>
> + if (AutoResetWalker)<br>
> + resetClobberWalker();<br>
> + return New;<br>
> }<br>
><br>
> MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(<br>
> @@ -1258,10 +1810,10 @@ MemoryAccess *MemorySSA::CachingWalker::<br>
> UpwardsMemoryQuery Q;<br>
> Q.OriginalAccess = StartingUseOrDef;<br>
> Q.StartingLoc = Loc;<br>
> - Q.Inst = StartingUseOrDef->getMemoryInst();<br>
> + Q.Inst = I;<br>
> Q.IsCall = false;<br>
><br>
> - if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc))<br>
> + if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))<br>
> return CacheResult;<br>
><br>
> // Unlike the other function, do not walk to the def of a def, because we are<br>
> @@ -1271,9 +1823,6 @@ MemoryAccess *MemorySSA::CachingWalker::<br>
> : StartingUseOrDef;<br>
><br>
> MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);<br>
> - // Only cache this if it wouldn't make Clobber point to itself.<br>
> - if (Clobber != StartingAccess)<br>
> - doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc);<br>
> DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");<br>
> DEBUG(dbgs() << *StartingUseOrDef << "\n");<br>
> DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");<br>
> @@ -1287,21 +1836,14 @@ MemorySSA::CachingWalker::getClobberingM<br>
> // access, since we only map BB's to PHI's. So, this must be a use or def.<br>
> auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));<br>
><br>
> - bool IsCall = bool(ImmutableCallSite(I));<br>
> -<br>
> + UpwardsMemoryQuery Q(I, StartingAccess);<br>
> // We can't sanely do anything with a fences, they conservatively<br>
> // clobber all memory, and have no locations to get pointers from to<br>
> // try to disambiguate.<br>
> - if (!IsCall && I->isFenceLike())<br>
> + if (!Q.IsCall && I->isFenceLike())<br>
> return StartingAccess;<br>
><br>
> - UpwardsMemoryQuery Q;<br>
> - Q.OriginalAccess = StartingAccess;<br>
> - Q.IsCall = IsCall;<br>
> - if (!Q.IsCall)<br>
> - Q.StartingLoc = MemoryLocation::get(I);<br>
> - Q.Inst = I;<br>
> - if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc))<br>
> + if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))<br>
> return CacheResult;<br>
><br>
> // Start with the thing we already think clobbers this location<br>
> @@ -1313,18 +1855,6 @@ MemorySSA::CachingWalker::getClobberingM<br>
> return DefiningAccess;<br>
><br>
> MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);<br>
> - // DFS won't cache a result for DefiningAccess. So, if DefiningAccess isn't<br>
> - // our clobber, be sure that it gets a cache entry, too.<br>
> - if (Result != DefiningAccess)<br>
> - doCacheInsert(DefiningAccess, Result, Q, Q.StartingLoc);<br>
> - doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc);<br>
> - // TODO: When this implementation is more mature, we may want to figure out<br>
> - // what this additional caching buys us. It's most likely A Good Thing.<br>
> - if (Q.IsCall)<br>
> - for (const MemoryAccess *MA : Q.VisitedCalls)<br>
> - if (MA != Result)<br>
> - doCacheInsert(MA, Result, Q, Q.StartingLoc);<br>
> -<br>
> DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");<br>
> DEBUG(dbgs() << *DefiningAccess << "\n");<br>
> DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");<br>
> @@ -1335,14 +1865,7 @@ MemorySSA::CachingWalker::getClobberingM<br>
><br>
> // Verify that MA doesn't exist in any of the caches.<br>
> void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {<br>
> -#ifndef NDEBUG<br>
> - for (auto &P : CachedUpwardsClobberingAccess)<br>
> - assert(P.first.first != MA && P.second != MA &&<br>
> - "Found removed MemoryAccess in cache.");<br>
> - for (auto &P : CachedUpwardsClobberingCall)<br>
> - assert(P.first != MA && P.second != MA &&<br>
> - "Found removed MemoryAccess in cache.");<br>
> -#endif // !NDEBUG<br>
> + assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");<br>
> }<br>
><br>
> MemoryAccess *<br>
> @@ -1359,4 +1882,4 @@ MemoryAccess *DoNothingMemorySSAWalker::<br>
> return Use->getDefiningAccess();<br>
> return StartingAccess;<br>
> }<br>
> -}<br>
> +} // namespace llvm<br>
><br>
> Modified: llvm/trunk/test/Transforms/Util/MemorySSA/cyclicphi.ll<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Util/MemorySSA/cyclicphi.ll?rev=275940&r1=275939&r2=275940&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Util/MemorySSA/cyclicphi.ll?rev=275940&r1=275939&r2=275940&view=diff</a><br>
> ==============================================================================<br>
> --- llvm/trunk/test/Transforms/Util/MemorySSA/cyclicphi.ll (original)<br>
> +++ llvm/trunk/test/Transforms/Util/MemorySSA/cyclicphi.ll Mon Jul 18 20:29:15 2016<br>
> @@ -56,8 +56,7 @@ bb68:<br>
><br>
> bb77: ; preds = %bb68, %bb26<br>
> ; CHECK: 2 = MemoryPhi({bb26,3},{bb68,1})<br>
> -; FIXME: This should be MemoryUse(liveOnEntry)<br>
> -; CHECK: MemoryUse(3)<br>
> +; CHECK: MemoryUse(liveOnEntry)<br>
> ; CHECK-NEXT: %tmp78 = load i64*, i64** %tmp25, align 8<br>
> %tmp78 = load i64*, i64** %tmp25, align 8<br>
> br label %bb26<br>
><br>
> Modified: llvm/trunk/test/Transforms/Util/MemorySSA/phi-translation.ll<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Util/MemorySSA/phi-translation.ll?rev=275940&r1=275939&r2=275940&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Util/MemorySSA/phi-translation.ll?rev=275940&r1=275939&r2=275940&view=diff</a><br>
> ==============================================================================<br>
> --- llvm/trunk/test/Transforms/Util/MemorySSA/phi-translation.ll (original)<br>
> +++ llvm/trunk/test/Transforms/Util/MemorySSA/phi-translation.ll Mon Jul 18 20:29:15 2016<br>
> @@ -138,8 +138,7 @@ loop.3:<br>
> ; CHECK: 4 = MemoryDef(5)<br>
> ; CHECK-NEXT: store i8 2, i8* %p2<br>
> store i8 2, i8* %p2<br>
> -; FIXME: This should be MemoryUse(1)<br>
> -; CHECK: MemoryUse(5)<br>
> +; CHECK: MemoryUse(1)<br>
> ; CHECK-NEXT: load i8, i8* %p1<br>
> load i8, i8* %p1<br>
> br i1 undef, label %loop.2, label %loop.1<br>
><br>
><br>
> _______________________________________________<br>
> llvm-commits mailing list<br>
> <a href="mailto:llvm-commits@lists.llvm.org" target="_blank">llvm-commits@lists.llvm.org</a><br>
> <a href="http://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-commits" rel="noreferrer" target="_blank">http://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-commits</a><br>
<br>
</div></div></blockquote></div><br></div></div>