George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1 | //===-- MemorySSA.cpp - Memory SSA Builder---------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements the MemorySSA class. |
| 11 | // |
| 12 | //===----------------------------------------------------------------===// |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 13 | #include "llvm/Transforms/Utils/MemorySSA.h" |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 14 | #include "llvm/ADT/DenseMap.h" |
| 15 | #include "llvm/ADT/DenseSet.h" |
| 16 | #include "llvm/ADT/DepthFirstIterator.h" |
| 17 | #include "llvm/ADT/GraphTraits.h" |
| 18 | #include "llvm/ADT/PostOrderIterator.h" |
| 19 | #include "llvm/ADT/STLExtras.h" |
| 20 | #include "llvm/ADT/SmallPtrSet.h" |
| 21 | #include "llvm/ADT/SmallSet.h" |
| 22 | #include "llvm/ADT/Statistic.h" |
| 23 | #include "llvm/Analysis/AliasAnalysis.h" |
| 24 | #include "llvm/Analysis/CFG.h" |
| 25 | #include "llvm/Analysis/GlobalsModRef.h" |
| 26 | #include "llvm/Analysis/IteratedDominanceFrontier.h" |
| 27 | #include "llvm/Analysis/MemoryLocation.h" |
| 28 | #include "llvm/Analysis/PHITransAddr.h" |
| 29 | #include "llvm/IR/AssemblyAnnotationWriter.h" |
| 30 | #include "llvm/IR/DataLayout.h" |
| 31 | #include "llvm/IR/Dominators.h" |
| 32 | #include "llvm/IR/GlobalVariable.h" |
| 33 | #include "llvm/IR/IRBuilder.h" |
| 34 | #include "llvm/IR/IntrinsicInst.h" |
| 35 | #include "llvm/IR/LLVMContext.h" |
| 36 | #include "llvm/IR/Metadata.h" |
| 37 | #include "llvm/IR/Module.h" |
| 38 | #include "llvm/IR/PatternMatch.h" |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 39 | #include "llvm/Support/Debug.h" |
| 40 | #include "llvm/Support/FormattedStream.h" |
| 41 | #include "llvm/Transforms/Scalar.h" |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 42 | #include <algorithm> |
| 43 | |
| 44 | #define DEBUG_TYPE "memoryssa" |
| 45 | using namespace llvm; |
| 46 | STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups"); |
| 47 | STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits"); |
| 48 | STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts"); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 49 | |
Geoff Berry | efb0dd1 | 2016-06-14 21:19:40 +0000 | [diff] [blame] | 50 | INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false, |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 51 | true) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 52 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 53 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
Geoff Berry | efb0dd1 | 2016-06-14 21:19:40 +0000 | [diff] [blame] | 54 | INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false, |
| 55 | true) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 56 | |
| 57 | namespace llvm { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 58 | /// \brief An assembly annotator class to print Memory SSA information in |
| 59 | /// comments. |
| 60 | class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter { |
| 61 | friend class MemorySSA; |
| 62 | const MemorySSA *MSSA; |
| 63 | |
| 64 | public: |
| 65 | MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {} |
| 66 | |
| 67 | virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, |
| 68 | formatted_raw_ostream &OS) { |
| 69 | if (MemoryAccess *MA = MSSA->getMemoryAccess(BB)) |
| 70 | OS << "; " << *MA << "\n"; |
| 71 | } |
| 72 | |
| 73 | virtual void emitInstructionAnnot(const Instruction *I, |
| 74 | formatted_raw_ostream &OS) { |
| 75 | if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) |
| 76 | OS << "; " << *MA << "\n"; |
| 77 | } |
| 78 | }; |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 79 | |
| 80 | /// \brief A MemorySSAWalker that does AA walks and caching of lookups to |
| 81 | /// disambiguate accesses. |
| 82 | /// |
| 83 | /// FIXME: The current implementation of this can take quadratic space in rare |
| 84 | /// cases. This can be fixed, but it is something to note until it is fixed. |
| 85 | /// |
| 86 | /// In order to trigger this behavior, you need to store to N distinct locations |
| 87 | /// (that AA can prove don't alias), perform M stores to other memory |
| 88 | /// locations that AA can prove don't alias any of the initial N locations, and |
| 89 | /// then load from all of the N locations. In this case, we insert M cache |
| 90 | /// entries for each of the N loads. |
| 91 | /// |
| 92 | /// For example: |
| 93 | /// define i32 @foo() { |
| 94 | /// %a = alloca i32, align 4 |
| 95 | /// %b = alloca i32, align 4 |
| 96 | /// store i32 0, i32* %a, align 4 |
| 97 | /// store i32 0, i32* %b, align 4 |
| 98 | /// |
| 99 | /// ; Insert M stores to other memory that doesn't alias %a or %b here |
| 100 | /// |
| 101 | /// %c = load i32, i32* %a, align 4 ; Caches M entries in |
| 102 | /// ; CachedUpwardsClobberingAccess for the |
| 103 | /// ; MemoryLocation %a |
| 104 | /// %d = load i32, i32* %b, align 4 ; Caches M entries in |
| 105 | /// ; CachedUpwardsClobberingAccess for the |
| 106 | /// ; MemoryLocation %b |
| 107 | /// |
| 108 | /// ; For completeness' sake, loading %a or %b again would not cache *another* |
| 109 | /// ; M entries. |
| 110 | /// %r = add i32 %c, %d |
| 111 | /// ret i32 %r |
| 112 | /// } |
| 113 | class MemorySSA::CachingWalker final : public MemorySSAWalker { |
| 114 | public: |
| 115 | CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *); |
| 116 | ~CachingWalker() override; |
| 117 | |
| 118 | MemoryAccess *getClobberingMemoryAccess(const Instruction *) override; |
| 119 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, |
| 120 | MemoryLocation &) override; |
| 121 | void invalidateInfo(MemoryAccess *) override; |
| 122 | |
| 123 | protected: |
| 124 | struct UpwardsMemoryQuery; |
| 125 | MemoryAccess *doCacheLookup(const MemoryAccess *, const UpwardsMemoryQuery &, |
| 126 | const MemoryLocation &); |
| 127 | |
| 128 | void doCacheInsert(const MemoryAccess *, MemoryAccess *, |
| 129 | const UpwardsMemoryQuery &, const MemoryLocation &); |
| 130 | |
| 131 | void doCacheRemove(const MemoryAccess *, const UpwardsMemoryQuery &, |
| 132 | const MemoryLocation &); |
| 133 | |
| 134 | private: |
| 135 | MemoryAccessPair UpwardsDFSWalk(MemoryAccess *, const MemoryLocation &, |
| 136 | UpwardsMemoryQuery &, bool); |
| 137 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &); |
| 138 | bool instructionClobbersQuery(const MemoryDef *, UpwardsMemoryQuery &, |
| 139 | const MemoryLocation &Loc) const; |
| 140 | void verifyRemoved(MemoryAccess *); |
| 141 | SmallDenseMap<ConstMemoryAccessPair, MemoryAccess *> |
| 142 | CachedUpwardsClobberingAccess; |
| 143 | DenseMap<const MemoryAccess *, MemoryAccess *> CachedUpwardsClobberingCall; |
| 144 | AliasAnalysis *AA; |
| 145 | DominatorTree *DT; |
| 146 | }; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 147 | } |
| 148 | |
| 149 | namespace { |
| 150 | struct RenamePassData { |
| 151 | DomTreeNode *DTN; |
| 152 | DomTreeNode::const_iterator ChildIt; |
| 153 | MemoryAccess *IncomingVal; |
| 154 | |
| 155 | RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It, |
| 156 | MemoryAccess *M) |
| 157 | : DTN(D), ChildIt(It), IncomingVal(M) {} |
| 158 | void swap(RenamePassData &RHS) { |
| 159 | std::swap(DTN, RHS.DTN); |
| 160 | std::swap(ChildIt, RHS.ChildIt); |
| 161 | std::swap(IncomingVal, RHS.IncomingVal); |
| 162 | } |
| 163 | }; |
| 164 | } |
| 165 | |
| 166 | namespace llvm { |
| 167 | /// \brief Rename a single basic block into MemorySSA form. |
| 168 | /// Uses the standard SSA renaming algorithm. |
| 169 | /// \returns The new incoming value. |
| 170 | MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, |
| 171 | MemoryAccess *IncomingVal) { |
| 172 | auto It = PerBlockAccesses.find(BB); |
| 173 | // Skip most processing if the list is empty. |
| 174 | if (It != PerBlockAccesses.end()) { |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 175 | AccessList *Accesses = It->second.get(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 176 | for (MemoryAccess &L : *Accesses) { |
| 177 | switch (L.getValueID()) { |
| 178 | case Value::MemoryUseVal: |
| 179 | cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal); |
| 180 | break; |
| 181 | case Value::MemoryDefVal: |
| 182 | // We can't legally optimize defs, because we only allow single |
| 183 | // memory phis/uses on operations, and if we optimize these, we can |
| 184 | // end up with multiple reaching defs. Uses do not have this |
| 185 | // problem, since they do not produce a value |
| 186 | cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal); |
| 187 | IncomingVal = &L; |
| 188 | break; |
| 189 | case Value::MemoryPhiVal: |
| 190 | IncomingVal = &L; |
| 191 | break; |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // Pass through values to our successors |
| 197 | for (const BasicBlock *S : successors(BB)) { |
| 198 | auto It = PerBlockAccesses.find(S); |
| 199 | // Rename the phi nodes in our successor block |
| 200 | if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front())) |
| 201 | continue; |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 202 | AccessList *Accesses = It->second.get(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 203 | auto *Phi = cast<MemoryPhi>(&Accesses->front()); |
| 204 | assert(std::find(succ_begin(BB), succ_end(BB), S) != succ_end(BB) && |
| 205 | "Must be at least one edge from Succ to BB!"); |
| 206 | Phi->addIncoming(IncomingVal, BB); |
| 207 | } |
| 208 | |
| 209 | return IncomingVal; |
| 210 | } |
| 211 | |
| 212 | /// \brief This is the standard SSA renaming algorithm. |
| 213 | /// |
| 214 | /// We walk the dominator tree in preorder, renaming accesses, and then filling |
| 215 | /// in phi nodes in our successors. |
| 216 | void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal, |
| 217 | SmallPtrSet<BasicBlock *, 16> &Visited) { |
| 218 | SmallVector<RenamePassData, 32> WorkStack; |
| 219 | IncomingVal = renameBlock(Root->getBlock(), IncomingVal); |
| 220 | WorkStack.push_back({Root, Root->begin(), IncomingVal}); |
| 221 | Visited.insert(Root->getBlock()); |
| 222 | |
| 223 | while (!WorkStack.empty()) { |
| 224 | DomTreeNode *Node = WorkStack.back().DTN; |
| 225 | DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt; |
| 226 | IncomingVal = WorkStack.back().IncomingVal; |
| 227 | |
| 228 | if (ChildIt == Node->end()) { |
| 229 | WorkStack.pop_back(); |
| 230 | } else { |
| 231 | DomTreeNode *Child = *ChildIt; |
| 232 | ++WorkStack.back().ChildIt; |
| 233 | BasicBlock *BB = Child->getBlock(); |
| 234 | Visited.insert(BB); |
| 235 | IncomingVal = renameBlock(BB, IncomingVal); |
| 236 | WorkStack.push_back({Child, Child->begin(), IncomingVal}); |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | /// \brief Compute dominator levels, used by the phi insertion algorithm above. |
| 242 | void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) { |
| 243 | for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode()); |
| 244 | DFI != DFE; ++DFI) |
| 245 | DomLevels[*DFI] = DFI.getPathLength() - 1; |
| 246 | } |
| 247 | |
| 248 | /// \brief This handles unreachable block acccesses by deleting phi nodes in |
| 249 | /// unreachable blocks, and marking all other unreachable MemoryAccess's as |
| 250 | /// being uses of the live on entry definition. |
| 251 | void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) { |
| 252 | assert(!DT->isReachableFromEntry(BB) && |
| 253 | "Reachable block found while handling unreachable blocks"); |
| 254 | |
| 255 | auto It = PerBlockAccesses.find(BB); |
| 256 | if (It == PerBlockAccesses.end()) |
| 257 | return; |
| 258 | |
| 259 | auto &Accesses = It->second; |
| 260 | for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) { |
| 261 | auto Next = std::next(AI); |
| 262 | // If we have a phi, just remove it. We are going to replace all |
| 263 | // users with live on entry. |
| 264 | if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI)) |
| 265 | UseOrDef->setDefiningAccess(LiveOnEntryDef.get()); |
| 266 | else |
| 267 | Accesses->erase(AI); |
| 268 | AI = Next; |
| 269 | } |
| 270 | } |
| 271 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 272 | MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT) |
| 273 | : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr), |
| 274 | NextID(0) { |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 275 | buildMemorySSA(); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 276 | } |
| 277 | |
| 278 | MemorySSA::MemorySSA(MemorySSA &&MSSA) |
| 279 | : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F), |
| 280 | ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)), |
| 281 | PerBlockAccesses(std::move(MSSA.PerBlockAccesses)), |
| 282 | LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)), |
| 283 | Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) { |
| 284 | // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA |
| 285 | // object any more. |
| 286 | Walker->MSSA = this; |
| 287 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 288 | |
| 289 | MemorySSA::~MemorySSA() { |
| 290 | // Drop all our references |
| 291 | for (const auto &Pair : PerBlockAccesses) |
| 292 | for (MemoryAccess &MA : *Pair.second) |
| 293 | MA.dropAllReferences(); |
| 294 | } |
| 295 | |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 296 | MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 297 | auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr)); |
| 298 | |
| 299 | if (Res.second) |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 300 | Res.first->second = make_unique<AccessList>(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 301 | return Res.first->second.get(); |
| 302 | } |
| 303 | |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 304 | void MemorySSA::buildMemorySSA() { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 305 | // We create an access to represent "live on entry", for things like |
| 306 | // arguments or users of globals, where the memory they use is defined before |
| 307 | // the beginning of the function. We do not actually insert it into the IR. |
| 308 | // We do not define a live on exit for the immediate uses, and thus our |
| 309 | // semantics do *not* imply that something with no immediate uses can simply |
| 310 | // be removed. |
| 311 | BasicBlock &StartingPoint = F.getEntryBlock(); |
| 312 | LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr, |
| 313 | &StartingPoint, NextID++); |
| 314 | |
| 315 | // We maintain lists of memory accesses per-block, trading memory for time. We |
| 316 | // could just look up the memory access for every possible instruction in the |
| 317 | // stream. |
| 318 | SmallPtrSet<BasicBlock *, 32> DefiningBlocks; |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 319 | SmallPtrSet<BasicBlock *, 32> DefUseBlocks; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 320 | // Go through each block, figure out where defs occur, and chain together all |
| 321 | // the accesses. |
| 322 | for (BasicBlock &B : F) { |
Daniel Berlin | 7898ca6 | 2016-02-07 01:52:15 +0000 | [diff] [blame] | 323 | bool InsertIntoDef = false; |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 324 | AccessList *Accesses = nullptr; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 325 | for (Instruction &I : B) { |
Peter Collingbourne | ffecb14 | 2016-05-26 01:19:17 +0000 | [diff] [blame] | 326 | MemoryUseOrDef *MUD = createNewAccess(&I); |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 327 | if (!MUD) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 328 | continue; |
George Burgess IV | 3887a41 | 2016-03-21 21:25:39 +0000 | [diff] [blame] | 329 | InsertIntoDef |= isa<MemoryDef>(MUD); |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 330 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 331 | if (!Accesses) |
| 332 | Accesses = getOrCreateAccessList(&B); |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 333 | Accesses->push_back(MUD); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 334 | } |
Daniel Berlin | 7898ca6 | 2016-02-07 01:52:15 +0000 | [diff] [blame] | 335 | if (InsertIntoDef) |
| 336 | DefiningBlocks.insert(&B); |
George Burgess IV | 3887a41 | 2016-03-21 21:25:39 +0000 | [diff] [blame] | 337 | if (Accesses) |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 338 | DefUseBlocks.insert(&B); |
| 339 | } |
| 340 | |
| 341 | // Compute live-in. |
| 342 | // Live in is normally defined as "all the blocks on the path from each def to |
| 343 | // each of it's uses". |
| 344 | // MemoryDef's are implicit uses of previous state, so they are also uses. |
| 345 | // This means we don't really have def-only instructions. The only |
| 346 | // MemoryDef's that are not really uses are those that are of the LiveOnEntry |
| 347 | // variable (because LiveOnEntry can reach anywhere, and every def is a |
| 348 | // must-kill of LiveOnEntry). |
| 349 | // In theory, you could precisely compute live-in by using alias-analysis to |
| 350 | // disambiguate defs and uses to see which really pair up with which. |
| 351 | // In practice, this would be really expensive and difficult. So we simply |
| 352 | // assume all defs are also uses that need to be kept live. |
| 353 | // Because of this, the end result of this live-in computation will be "the |
| 354 | // entire set of basic blocks that reach any use". |
| 355 | |
| 356 | SmallPtrSet<BasicBlock *, 32> LiveInBlocks; |
| 357 | SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(), |
| 358 | DefUseBlocks.end()); |
| 359 | // Now that we have a set of blocks where a value is live-in, recursively add |
| 360 | // predecessors until we find the full region the value is live. |
| 361 | while (!LiveInBlockWorklist.empty()) { |
| 362 | BasicBlock *BB = LiveInBlockWorklist.pop_back_val(); |
| 363 | |
| 364 | // The block really is live in here, insert it into the set. If already in |
| 365 | // the set, then it has already been processed. |
| 366 | if (!LiveInBlocks.insert(BB).second) |
| 367 | continue; |
| 368 | |
| 369 | // Since the value is live into BB, it is either defined in a predecessor or |
| 370 | // live into it to. |
| 371 | LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 372 | } |
| 373 | |
| 374 | // Determine where our MemoryPhi's should go |
Daniel Berlin | 77fa84e | 2016-04-19 06:13:28 +0000 | [diff] [blame] | 375 | ForwardIDFCalculator IDFs(*DT); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 376 | IDFs.setDefiningBlocks(DefiningBlocks); |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 377 | IDFs.setLiveInBlocks(LiveInBlocks); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 378 | SmallVector<BasicBlock *, 32> IDFBlocks; |
| 379 | IDFs.calculate(IDFBlocks); |
| 380 | |
| 381 | // Now place MemoryPhi nodes. |
| 382 | for (auto &BB : IDFBlocks) { |
| 383 | // Insert phi node |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 384 | AccessList *Accesses = getOrCreateAccessList(BB); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 385 | MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++); |
Daniel Berlin | f6c9ae9 | 2016-02-10 17:41:25 +0000 | [diff] [blame] | 386 | ValueToMemoryAccess.insert(std::make_pair(BB, Phi)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 387 | // Phi's always are placed at the front of the block. |
| 388 | Accesses->push_front(Phi); |
| 389 | } |
| 390 | |
| 391 | // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get |
| 392 | // filled in with all blocks. |
| 393 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 394 | renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited); |
| 395 | |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 396 | MemorySSAWalker *Walker = getWalker(); |
| 397 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 398 | // Now optimize the MemoryUse's defining access to point to the nearest |
| 399 | // dominating clobbering def. |
| 400 | // This ensures that MemoryUse's that are killed by the same store are |
| 401 | // immediate users of that store, one of the invariants we guarantee. |
| 402 | for (auto DomNode : depth_first(DT)) { |
| 403 | BasicBlock *BB = DomNode->getBlock(); |
| 404 | auto AI = PerBlockAccesses.find(BB); |
| 405 | if (AI == PerBlockAccesses.end()) |
| 406 | continue; |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 407 | AccessList *Accesses = AI->second.get(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 408 | for (auto &MA : *Accesses) { |
| 409 | if (auto *MU = dyn_cast<MemoryUse>(&MA)) { |
| 410 | Instruction *Inst = MU->getMemoryInst(); |
Daniel Berlin | 6412002 | 2016-03-02 21:16:28 +0000 | [diff] [blame] | 411 | MU->setDefiningAccess(Walker->getClobberingMemoryAccess(Inst)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 412 | } |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | // Mark the uses in unreachable blocks as live on entry, so that they go |
| 417 | // somewhere. |
| 418 | for (auto &BB : F) |
| 419 | if (!Visited.count(&BB)) |
| 420 | markUnreachableAsLiveOnEntry(&BB); |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 421 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 422 | |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 423 | MemorySSAWalker *MemorySSA::getWalker() { |
| 424 | if (Walker) |
| 425 | return Walker.get(); |
| 426 | |
| 427 | Walker = make_unique<CachingWalker>(this, AA, DT); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 428 | return Walker.get(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 429 | } |
| 430 | |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 431 | MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) { |
| 432 | assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB"); |
| 433 | AccessList *Accesses = getOrCreateAccessList(BB); |
| 434 | MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++); |
| 435 | ValueToMemoryAccess.insert(std::make_pair(BB, Phi)); |
| 436 | // Phi's always are placed at the front of the block. |
| 437 | Accesses->push_front(Phi); |
| 438 | return Phi; |
| 439 | } |
| 440 | |
| 441 | MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I, |
| 442 | MemoryAccess *Definition) { |
| 443 | assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI"); |
| 444 | MemoryUseOrDef *NewAccess = createNewAccess(I); |
| 445 | assert( |
| 446 | NewAccess != nullptr && |
| 447 | "Tried to create a memory access for a non-memory touching instruction"); |
| 448 | NewAccess->setDefiningAccess(Definition); |
| 449 | return NewAccess; |
| 450 | } |
| 451 | |
| 452 | MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I, |
| 453 | MemoryAccess *Definition, |
| 454 | const BasicBlock *BB, |
| 455 | InsertionPlace Point) { |
| 456 | MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition); |
| 457 | auto *Accesses = getOrCreateAccessList(BB); |
| 458 | if (Point == Beginning) { |
| 459 | // It goes after any phi nodes |
| 460 | auto AI = std::find_if( |
| 461 | Accesses->begin(), Accesses->end(), |
| 462 | [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); }); |
| 463 | |
| 464 | Accesses->insert(AI, NewAccess); |
| 465 | } else { |
| 466 | Accesses->push_back(NewAccess); |
| 467 | } |
| 468 | |
| 469 | return NewAccess; |
| 470 | } |
| 471 | MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I, |
| 472 | MemoryAccess *Definition, |
| 473 | MemoryAccess *InsertPt) { |
| 474 | assert(I->getParent() == InsertPt->getBlock() && |
| 475 | "New and old access must be in the same block"); |
| 476 | MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition); |
| 477 | auto *Accesses = getOrCreateAccessList(InsertPt->getBlock()); |
| 478 | Accesses->insert(AccessList::iterator(InsertPt), NewAccess); |
| 479 | return NewAccess; |
| 480 | } |
| 481 | |
| 482 | MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I, |
| 483 | MemoryAccess *Definition, |
| 484 | MemoryAccess *InsertPt) { |
| 485 | assert(I->getParent() == InsertPt->getBlock() && |
| 486 | "New and old access must be in the same block"); |
| 487 | MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition); |
| 488 | auto *Accesses = getOrCreateAccessList(InsertPt->getBlock()); |
| 489 | Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess); |
| 490 | return NewAccess; |
| 491 | } |
| 492 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 493 | /// \brief Helper function to create new memory accesses |
Peter Collingbourne | ffecb14 | 2016-05-26 01:19:17 +0000 | [diff] [blame] | 494 | MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) { |
Peter Collingbourne | b9aa1f4 | 2016-05-26 04:58:46 +0000 | [diff] [blame] | 495 | // The assume intrinsic has a control dependency which we model by claiming |
| 496 | // that it writes arbitrarily. Ignore that fake memory dependency here. |
| 497 | // FIXME: Replace this special casing with a more accurate modelling of |
| 498 | // assume's control dependency. |
| 499 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) |
| 500 | if (II->getIntrinsicID() == Intrinsic::assume) |
| 501 | return nullptr; |
| 502 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 503 | // Find out what affect this instruction has on memory. |
| 504 | ModRefInfo ModRef = AA->getModRefInfo(I); |
| 505 | bool Def = bool(ModRef & MRI_Mod); |
| 506 | bool Use = bool(ModRef & MRI_Ref); |
| 507 | |
| 508 | // It's possible for an instruction to not modify memory at all. During |
| 509 | // construction, we ignore them. |
Peter Collingbourne | ffecb14 | 2016-05-26 01:19:17 +0000 | [diff] [blame] | 510 | if (!Def && !Use) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 511 | return nullptr; |
| 512 | |
| 513 | assert((Def || Use) && |
| 514 | "Trying to create a memory access with a non-memory instruction"); |
| 515 | |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 516 | MemoryUseOrDef *MUD; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 517 | if (Def) |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 518 | MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 519 | else |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 520 | MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent()); |
| 521 | ValueToMemoryAccess.insert(std::make_pair(I, MUD)); |
| 522 | return MUD; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 523 | } |
| 524 | |
| 525 | MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock, |
| 526 | enum InsertionPlace Where) { |
| 527 | // Handle the initial case |
| 528 | if (Where == Beginning) |
| 529 | // The only thing that could define us at the beginning is a phi node |
| 530 | if (MemoryPhi *Phi = getMemoryAccess(UseBlock)) |
| 531 | return Phi; |
| 532 | |
| 533 | DomTreeNode *CurrNode = DT->getNode(UseBlock); |
| 534 | // Need to be defined by our dominator |
| 535 | if (Where == Beginning) |
| 536 | CurrNode = CurrNode->getIDom(); |
| 537 | Where = End; |
| 538 | while (CurrNode) { |
| 539 | auto It = PerBlockAccesses.find(CurrNode->getBlock()); |
| 540 | if (It != PerBlockAccesses.end()) { |
| 541 | auto &Accesses = It->second; |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 542 | for (MemoryAccess &RA : reverse(*Accesses)) { |
| 543 | if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA)) |
| 544 | return &RA; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 545 | } |
| 546 | } |
| 547 | CurrNode = CurrNode->getIDom(); |
| 548 | } |
| 549 | return LiveOnEntryDef.get(); |
| 550 | } |
| 551 | |
| 552 | /// \brief Returns true if \p Replacer dominates \p Replacee . |
| 553 | bool MemorySSA::dominatesUse(const MemoryAccess *Replacer, |
| 554 | const MemoryAccess *Replacee) const { |
| 555 | if (isa<MemoryUseOrDef>(Replacee)) |
| 556 | return DT->dominates(Replacer->getBlock(), Replacee->getBlock()); |
| 557 | const auto *MP = cast<MemoryPhi>(Replacee); |
| 558 | // For a phi node, the use occurs in the predecessor block of the phi node. |
| 559 | // Since we may occur multiple times in the phi node, we have to check each |
| 560 | // operand to ensure Replacer dominates each operand where Replacee occurs. |
| 561 | for (const Use &Arg : MP->operands()) { |
George Burgess IV | b5a229f | 2016-02-02 23:15:26 +0000 | [diff] [blame] | 562 | if (Arg.get() != Replacee && |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 563 | !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg))) |
| 564 | return false; |
| 565 | } |
| 566 | return true; |
| 567 | } |
| 568 | |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 569 | /// \brief If all arguments of a MemoryPHI are defined by the same incoming |
| 570 | /// argument, return that argument. |
| 571 | static MemoryAccess *onlySingleValue(MemoryPhi *MP) { |
| 572 | MemoryAccess *MA = nullptr; |
| 573 | |
| 574 | for (auto &Arg : MP->operands()) { |
| 575 | if (!MA) |
| 576 | MA = cast<MemoryAccess>(Arg); |
| 577 | else if (MA != Arg) |
| 578 | return nullptr; |
| 579 | } |
| 580 | return MA; |
| 581 | } |
| 582 | |
| 583 | /// \brief Properly remove \p MA from all of MemorySSA's lookup tables. |
| 584 | /// |
| 585 | /// Because of the way the intrusive list and use lists work, it is important to |
| 586 | /// do removal in the right order. |
| 587 | void MemorySSA::removeFromLookups(MemoryAccess *MA) { |
| 588 | assert(MA->use_empty() && |
| 589 | "Trying to remove memory access that still has uses"); |
| 590 | if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) |
| 591 | MUD->setDefiningAccess(nullptr); |
| 592 | // Invalidate our walker's cache if necessary |
| 593 | if (!isa<MemoryUse>(MA)) |
| 594 | Walker->invalidateInfo(MA); |
| 595 | // The call below to erase will destroy MA, so we can't change the order we |
| 596 | // are doing things here |
| 597 | Value *MemoryInst; |
| 598 | if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) { |
| 599 | MemoryInst = MUD->getMemoryInst(); |
| 600 | } else { |
| 601 | MemoryInst = MA->getBlock(); |
| 602 | } |
| 603 | ValueToMemoryAccess.erase(MemoryInst); |
| 604 | |
George Burgess IV | e0e6e48 | 2016-03-02 02:35:04 +0000 | [diff] [blame] | 605 | auto AccessIt = PerBlockAccesses.find(MA->getBlock()); |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 606 | std::unique_ptr<AccessList> &Accesses = AccessIt->second; |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 607 | Accesses->erase(MA); |
George Burgess IV | e0e6e48 | 2016-03-02 02:35:04 +0000 | [diff] [blame] | 608 | if (Accesses->empty()) |
| 609 | PerBlockAccesses.erase(AccessIt); |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 610 | } |
| 611 | |
| 612 | void MemorySSA::removeMemoryAccess(MemoryAccess *MA) { |
| 613 | assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def"); |
| 614 | // We can only delete phi nodes if they have no uses, or we can replace all |
| 615 | // uses with a single definition. |
| 616 | MemoryAccess *NewDefTarget = nullptr; |
| 617 | if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) { |
| 618 | // Note that it is sufficient to know that all edges of the phi node have |
| 619 | // the same argument. If they do, by the definition of dominance frontiers |
| 620 | // (which we used to place this phi), that argument must dominate this phi, |
| 621 | // and thus, must dominate the phi's uses, and so we will not hit the assert |
| 622 | // below. |
| 623 | NewDefTarget = onlySingleValue(MP); |
| 624 | assert((NewDefTarget || MP->use_empty()) && |
| 625 | "We can't delete this memory phi"); |
| 626 | } else { |
| 627 | NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess(); |
| 628 | } |
| 629 | |
| 630 | // Re-point the uses at our defining access |
| 631 | if (!MA->use_empty()) |
| 632 | MA->replaceAllUsesWith(NewDefTarget); |
| 633 | |
| 634 | // The call below to erase will destroy MA, so we can't change the order we |
| 635 | // are doing things here |
| 636 | removeFromLookups(MA); |
| 637 | } |
| 638 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 639 | void MemorySSA::print(raw_ostream &OS) const { |
| 640 | MemorySSAAnnotatedWriter Writer(this); |
| 641 | F.print(OS, &Writer); |
| 642 | } |
| 643 | |
| 644 | void MemorySSA::dump() const { |
| 645 | MemorySSAAnnotatedWriter Writer(this); |
| 646 | F.print(dbgs(), &Writer); |
| 647 | } |
| 648 | |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 649 | void MemorySSA::verifyMemorySSA() const { |
| 650 | verifyDefUses(F); |
| 651 | verifyDomination(F); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 652 | verifyOrdering(F); |
| 653 | } |
| 654 | |
| 655 | /// \brief Verify that the order and existence of MemoryAccesses matches the |
| 656 | /// order and existence of memory affecting instructions. |
| 657 | void MemorySSA::verifyOrdering(Function &F) const { |
| 658 | // Walk all the blocks, comparing what the lookups think and what the access |
| 659 | // lists think, as well as the order in the blocks vs the order in the access |
| 660 | // lists. |
| 661 | SmallVector<MemoryAccess *, 32> ActualAccesses; |
| 662 | for (BasicBlock &B : F) { |
| 663 | const AccessList *AL = getBlockAccesses(&B); |
| 664 | MemoryAccess *Phi = getMemoryAccess(&B); |
| 665 | if (Phi) |
| 666 | ActualAccesses.push_back(Phi); |
| 667 | for (Instruction &I : B) { |
| 668 | MemoryAccess *MA = getMemoryAccess(&I); |
| 669 | assert((!MA || AL) && "We have memory affecting instructions " |
| 670 | "in this block but they are not in the " |
| 671 | "access list"); |
| 672 | if (MA) |
| 673 | ActualAccesses.push_back(MA); |
| 674 | } |
| 675 | // Either we hit the assert, really have no accesses, or we have both |
| 676 | // accesses and an access list |
| 677 | if (!AL) |
| 678 | continue; |
| 679 | assert(AL->size() == ActualAccesses.size() && |
| 680 | "We don't have the same number of accesses in the block as on the " |
| 681 | "access list"); |
| 682 | auto ALI = AL->begin(); |
| 683 | auto AAI = ActualAccesses.begin(); |
| 684 | while (ALI != AL->end() && AAI != ActualAccesses.end()) { |
| 685 | assert(&*ALI == *AAI && "Not the same accesses in the same order"); |
| 686 | ++ALI; |
| 687 | ++AAI; |
| 688 | } |
| 689 | ActualAccesses.clear(); |
| 690 | } |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 691 | } |
| 692 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 693 | /// \brief Verify the domination properties of MemorySSA by checking that each |
| 694 | /// definition dominates all of its uses. |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 695 | void MemorySSA::verifyDomination(Function &F) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 696 | for (BasicBlock &B : F) { |
| 697 | // Phi nodes are attached to basic blocks |
| 698 | if (MemoryPhi *MP = getMemoryAccess(&B)) { |
| 699 | for (User *U : MP->users()) { |
| 700 | BasicBlock *UseBlock; |
| 701 | // Phi operands are used on edges, we simulate the right domination by |
| 702 | // acting as if the use occurred at the end of the predecessor block. |
| 703 | if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) { |
| 704 | for (const auto &Arg : P->operands()) { |
| 705 | if (Arg == MP) { |
| 706 | UseBlock = P->getIncomingBlock(Arg); |
| 707 | break; |
| 708 | } |
| 709 | } |
| 710 | } else { |
| 711 | UseBlock = cast<MemoryAccess>(U)->getBlock(); |
| 712 | } |
George Burgess IV | 60adac4 | 2016-02-02 23:26:01 +0000 | [diff] [blame] | 713 | (void)UseBlock; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 714 | assert(DT->dominates(MP->getBlock(), UseBlock) && |
| 715 | "Memory PHI does not dominate it's uses"); |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | for (Instruction &I : B) { |
| 720 | MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I)); |
| 721 | if (!MD) |
| 722 | continue; |
| 723 | |
Benjamin Kramer | 451f54c | 2016-02-22 13:11:58 +0000 | [diff] [blame] | 724 | for (User *U : MD->users()) { |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 725 | BasicBlock *UseBlock; |
| 726 | (void)UseBlock; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 727 | // Things are allowed to flow to phi nodes over their predecessor edge. |
| 728 | if (auto *P = dyn_cast<MemoryPhi>(U)) { |
| 729 | for (const auto &Arg : P->operands()) { |
| 730 | if (Arg == MD) { |
| 731 | UseBlock = P->getIncomingBlock(Arg); |
| 732 | break; |
| 733 | } |
| 734 | } |
| 735 | } else { |
| 736 | UseBlock = cast<MemoryAccess>(U)->getBlock(); |
| 737 | } |
| 738 | assert(DT->dominates(MD->getBlock(), UseBlock) && |
| 739 | "Memory Def does not dominate it's uses"); |
| 740 | } |
| 741 | } |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | /// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use |
| 746 | /// appears in the use list of \p Def. |
| 747 | /// |
| 748 | /// llvm_unreachable is used instead of asserts because this may be called in |
| 749 | /// a build without asserts. In that case, we don't want this to turn into a |
| 750 | /// nop. |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 751 | void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 752 | // The live on entry use may cause us to get a NULL def here |
| 753 | if (!Def) { |
| 754 | if (!isLiveOnEntryDef(Use)) |
| 755 | llvm_unreachable("Null def but use not point to live on entry def"); |
| 756 | } else if (std::find(Def->user_begin(), Def->user_end(), Use) == |
| 757 | Def->user_end()) { |
| 758 | llvm_unreachable("Did not find use in def's use list"); |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | /// \brief Verify the immediate use information, by walking all the memory |
| 763 | /// accesses and verifying that, for each use, it appears in the |
| 764 | /// appropriate def's use list |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 765 | void MemorySSA::verifyDefUses(Function &F) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 766 | for (BasicBlock &B : F) { |
| 767 | // Phi nodes are attached to basic blocks |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 768 | if (MemoryPhi *Phi = getMemoryAccess(&B)) { |
David Majnemer | 580e754 | 2016-06-25 00:04:06 +0000 | [diff] [blame] | 769 | assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance( |
| 770 | pred_begin(&B), pred_end(&B))) && |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 771 | "Incomplete MemoryPhi Node"); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 772 | for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) |
| 773 | verifyUseInDefs(Phi->getIncomingValue(I), Phi); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 774 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 775 | |
| 776 | for (Instruction &I : B) { |
| 777 | if (MemoryAccess *MA = getMemoryAccess(&I)) { |
| 778 | assert(isa<MemoryUseOrDef>(MA) && |
| 779 | "Found a phi node not attached to a bb"); |
| 780 | verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA); |
| 781 | } |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | |
| 786 | MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const { |
Daniel Berlin | f6c9ae9 | 2016-02-10 17:41:25 +0000 | [diff] [blame] | 787 | return ValueToMemoryAccess.lookup(I); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 788 | } |
| 789 | |
| 790 | MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const { |
| 791 | return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB)); |
| 792 | } |
| 793 | |
| 794 | /// \brief Determine, for two memory accesses in the same block, |
| 795 | /// whether \p Dominator dominates \p Dominatee. |
| 796 | /// \returns True if \p Dominator dominates \p Dominatee. |
| 797 | bool MemorySSA::locallyDominates(const MemoryAccess *Dominator, |
| 798 | const MemoryAccess *Dominatee) const { |
| 799 | |
| 800 | assert((Dominator->getBlock() == Dominatee->getBlock()) && |
| 801 | "Asking for local domination when accesses are in different blocks!"); |
Sebastian Pop | e1f60b1 | 2016-06-10 21:36:41 +0000 | [diff] [blame] | 802 | |
| 803 | // A node dominates itself. |
| 804 | if (Dominatee == Dominator) |
| 805 | return true; |
| 806 | |
| 807 | // When Dominatee is defined on function entry, it is not dominated by another |
| 808 | // memory access. |
| 809 | if (isLiveOnEntryDef(Dominatee)) |
| 810 | return false; |
| 811 | |
| 812 | // When Dominator is defined on function entry, it dominates the other memory |
| 813 | // access. |
| 814 | if (isLiveOnEntryDef(Dominator)) |
| 815 | return true; |
| 816 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 817 | // Get the access list for the block |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 818 | const AccessList *AccessList = getBlockAccesses(Dominator->getBlock()); |
| 819 | AccessList::const_reverse_iterator It(Dominator->getIterator()); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 820 | |
| 821 | // If we hit the beginning of the access list before we hit dominatee, we must |
| 822 | // dominate it |
| 823 | return std::none_of(It, AccessList->rend(), |
| 824 | [&](const MemoryAccess &MA) { return &MA == Dominatee; }); |
| 825 | } |
| 826 | |
| 827 | const static char LiveOnEntryStr[] = "liveOnEntry"; |
| 828 | |
| 829 | void MemoryDef::print(raw_ostream &OS) const { |
| 830 | MemoryAccess *UO = getDefiningAccess(); |
| 831 | |
| 832 | OS << getID() << " = MemoryDef("; |
| 833 | if (UO && UO->getID()) |
| 834 | OS << UO->getID(); |
| 835 | else |
| 836 | OS << LiveOnEntryStr; |
| 837 | OS << ')'; |
| 838 | } |
| 839 | |
| 840 | void MemoryPhi::print(raw_ostream &OS) const { |
| 841 | bool First = true; |
| 842 | OS << getID() << " = MemoryPhi("; |
| 843 | for (const auto &Op : operands()) { |
| 844 | BasicBlock *BB = getIncomingBlock(Op); |
| 845 | MemoryAccess *MA = cast<MemoryAccess>(Op); |
| 846 | if (!First) |
| 847 | OS << ','; |
| 848 | else |
| 849 | First = false; |
| 850 | |
| 851 | OS << '{'; |
| 852 | if (BB->hasName()) |
| 853 | OS << BB->getName(); |
| 854 | else |
| 855 | BB->printAsOperand(OS, false); |
| 856 | OS << ','; |
| 857 | if (unsigned ID = MA->getID()) |
| 858 | OS << ID; |
| 859 | else |
| 860 | OS << LiveOnEntryStr; |
| 861 | OS << '}'; |
| 862 | } |
| 863 | OS << ')'; |
| 864 | } |
| 865 | |
| 866 | MemoryAccess::~MemoryAccess() {} |
| 867 | |
| 868 | void MemoryUse::print(raw_ostream &OS) const { |
| 869 | MemoryAccess *UO = getDefiningAccess(); |
| 870 | OS << "MemoryUse("; |
| 871 | if (UO && UO->getID()) |
| 872 | OS << UO->getID(); |
| 873 | else |
| 874 | OS << LiveOnEntryStr; |
| 875 | OS << ')'; |
| 876 | } |
| 877 | |
| 878 | void MemoryAccess::dump() const { |
| 879 | print(dbgs()); |
| 880 | dbgs() << "\n"; |
| 881 | } |
| 882 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 883 | char MemorySSAAnalysis::PassID; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 884 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 885 | MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) { |
| 886 | auto &DT = AM.getResult<DominatorTreeAnalysis>(F); |
| 887 | auto &AA = AM.getResult<AAManager>(F); |
| 888 | return MemorySSA(F, &AA, &DT); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 889 | } |
| 890 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 891 | PreservedAnalyses MemorySSAPrinterPass::run(Function &F, |
| 892 | FunctionAnalysisManager &AM) { |
| 893 | OS << "MemorySSA for function: " << F.getName() << "\n"; |
| 894 | AM.getResult<MemorySSAAnalysis>(F).print(OS); |
| 895 | |
| 896 | return PreservedAnalyses::all(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 897 | } |
| 898 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 899 | PreservedAnalyses MemorySSAVerifierPass::run(Function &F, |
| 900 | FunctionAnalysisManager &AM) { |
| 901 | AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA(); |
| 902 | |
| 903 | return PreservedAnalyses::all(); |
| 904 | } |
| 905 | |
| 906 | char MemorySSAWrapperPass::ID = 0; |
| 907 | |
| 908 | MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) { |
| 909 | initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 910 | } |
| 911 | |
| 912 | void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); } |
| 913 | |
| 914 | void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 915 | AU.setPreservesAll(); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 916 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 917 | AU.addRequiredTransitive<AAResultsWrapperPass>(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 918 | } |
| 919 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 920 | bool MemorySSAWrapperPass::runOnFunction(Function &F) { |
| 921 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 922 | auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 923 | MSSA.reset(new MemorySSA(F, &AA, &DT)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 924 | return false; |
| 925 | } |
| 926 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 927 | void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 928 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 929 | void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 930 | MSSA->print(OS); |
| 931 | } |
| 932 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 933 | MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {} |
| 934 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 935 | MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A, |
| 936 | DominatorTree *D) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 937 | : MemorySSAWalker(M), AA(A), DT(D) {} |
| 938 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 939 | MemorySSA::CachingWalker::~CachingWalker() {} |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 940 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 941 | struct MemorySSA::CachingWalker::UpwardsMemoryQuery { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 942 | // True if we saw a phi whose predecessor was a backedge |
| 943 | bool SawBackedgePhi; |
| 944 | // True if our original query started off as a call |
| 945 | bool IsCall; |
| 946 | // The pointer location we started the query with. This will be empty if |
| 947 | // IsCall is true. |
| 948 | MemoryLocation StartingLoc; |
| 949 | // This is the instruction we were querying about. |
| 950 | const Instruction *Inst; |
| 951 | // Set of visited Instructions for this query. |
| 952 | DenseSet<MemoryAccessPair> Visited; |
George Burgess IV | 49cad7d | 2016-03-30 03:12:08 +0000 | [diff] [blame] | 953 | // Vector of visited call accesses for this query. This is separated out |
| 954 | // because you can always cache and lookup the result of call queries (IE when |
| 955 | // IsCall == true) for every call in the chain. The calls have no AA location |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 956 | // associated with them with them, and thus, no context dependence. |
George Burgess IV | 49cad7d | 2016-03-30 03:12:08 +0000 | [diff] [blame] | 957 | SmallVector<const MemoryAccess *, 32> VisitedCalls; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 958 | // The MemoryAccess we actually got called with, used to test local domination |
| 959 | const MemoryAccess *OriginalAccess; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 960 | |
| 961 | UpwardsMemoryQuery() |
| 962 | : SawBackedgePhi(false), IsCall(false), Inst(nullptr), |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 963 | OriginalAccess(nullptr) {} |
| 964 | |
| 965 | UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access) |
| 966 | : SawBackedgePhi(false), IsCall(ImmutableCallSite(Inst)), Inst(Inst), |
| 967 | OriginalAccess(Access) {} |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 968 | }; |
| 969 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 970 | void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) { |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 971 | |
| 972 | // TODO: We can do much better cache invalidation with differently stored |
| 973 | // caches. For now, for MemoryUses, we simply remove them |
| 974 | // from the cache, and kill the entire call/non-call cache for everything |
| 975 | // else. The problem is for phis or defs, currently we'd need to follow use |
| 976 | // chains down and invalidate anything below us in the chain that currently |
| 977 | // terminates at this access. |
| 978 | |
| 979 | // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse |
| 980 | // is by definition never a barrier, so nothing in the cache could point to |
| 981 | // this use. In that case, we only need invalidate the info for the use |
| 982 | // itself. |
| 983 | |
| 984 | if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) { |
| 985 | UpwardsMemoryQuery Q; |
| 986 | Instruction *I = MU->getMemoryInst(); |
| 987 | Q.IsCall = bool(ImmutableCallSite(I)); |
| 988 | Q.Inst = I; |
| 989 | if (!Q.IsCall) |
| 990 | Q.StartingLoc = MemoryLocation::get(I); |
| 991 | doCacheRemove(MA, Q, Q.StartingLoc); |
Geoff Berry | 9fe26e6 | 2016-04-22 14:44:10 +0000 | [diff] [blame] | 992 | } else { |
| 993 | // If it is not a use, the best we can do right now is destroy the cache. |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 994 | CachedUpwardsClobberingCall.clear(); |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 995 | CachedUpwardsClobberingAccess.clear(); |
Geoff Berry | 9fe26e6 | 2016-04-22 14:44:10 +0000 | [diff] [blame] | 996 | } |
| 997 | |
Filipe Cabecinhas | 0da9937 | 2016-04-29 15:22:48 +0000 | [diff] [blame] | 998 | #ifdef EXPENSIVE_CHECKS |
Geoff Berry | 9fe26e6 | 2016-04-22 14:44:10 +0000 | [diff] [blame] | 999 | // Run this only when expensive checks are enabled. |
| 1000 | verifyRemoved(MA); |
| 1001 | #endif |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 1002 | } |
| 1003 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1004 | void MemorySSA::CachingWalker::doCacheRemove(const MemoryAccess *M, |
| 1005 | const UpwardsMemoryQuery &Q, |
| 1006 | const MemoryLocation &Loc) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1007 | if (Q.IsCall) |
| 1008 | CachedUpwardsClobberingCall.erase(M); |
| 1009 | else |
| 1010 | CachedUpwardsClobberingAccess.erase({M, Loc}); |
| 1011 | } |
| 1012 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1013 | void MemorySSA::CachingWalker::doCacheInsert(const MemoryAccess *M, |
| 1014 | MemoryAccess *Result, |
| 1015 | const UpwardsMemoryQuery &Q, |
| 1016 | const MemoryLocation &Loc) { |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1017 | // This is fine for Phis, since there are times where we can't optimize them. |
| 1018 | // Making a def its own clobber is never correct, though. |
| 1019 | assert((Result != M || isa<MemoryPhi>(M)) && |
| 1020 | "Something can't clobber itself!"); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1021 | ++NumClobberCacheInserts; |
| 1022 | if (Q.IsCall) |
| 1023 | CachedUpwardsClobberingCall[M] = Result; |
| 1024 | else |
| 1025 | CachedUpwardsClobberingAccess[{M, Loc}] = Result; |
| 1026 | } |
| 1027 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1028 | MemoryAccess * |
| 1029 | MemorySSA::CachingWalker::doCacheLookup(const MemoryAccess *M, |
| 1030 | const UpwardsMemoryQuery &Q, |
| 1031 | const MemoryLocation &Loc) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1032 | ++NumClobberCacheLookups; |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1033 | MemoryAccess *Result; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1034 | |
| 1035 | if (Q.IsCall) |
| 1036 | Result = CachedUpwardsClobberingCall.lookup(M); |
| 1037 | else |
| 1038 | Result = CachedUpwardsClobberingAccess.lookup({M, Loc}); |
| 1039 | |
| 1040 | if (Result) |
| 1041 | ++NumClobberCacheHits; |
| 1042 | return Result; |
| 1043 | } |
| 1044 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1045 | bool MemorySSA::CachingWalker::instructionClobbersQuery( |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1046 | const MemoryDef *MD, UpwardsMemoryQuery &Q, |
| 1047 | const MemoryLocation &Loc) const { |
| 1048 | Instruction *DefMemoryInst = MD->getMemoryInst(); |
| 1049 | assert(DefMemoryInst && "Defining instruction not actually an instruction"); |
| 1050 | |
| 1051 | if (!Q.IsCall) |
| 1052 | return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod; |
| 1053 | |
| 1054 | // If this is a call, mark it for caching |
| 1055 | if (ImmutableCallSite(DefMemoryInst)) |
George Burgess IV | 49cad7d | 2016-03-30 03:12:08 +0000 | [diff] [blame] | 1056 | Q.VisitedCalls.push_back(MD); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1057 | ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst)); |
| 1058 | return I != MRI_NoModRef; |
| 1059 | } |
| 1060 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1061 | MemoryAccessPair MemorySSA::CachingWalker::UpwardsDFSWalk( |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1062 | MemoryAccess *StartingAccess, const MemoryLocation &Loc, |
| 1063 | UpwardsMemoryQuery &Q, bool FollowingBackedge) { |
| 1064 | MemoryAccess *ModifyingAccess = nullptr; |
| 1065 | |
| 1066 | auto DFI = df_begin(StartingAccess); |
| 1067 | for (auto DFE = df_end(StartingAccess); DFI != DFE;) { |
| 1068 | MemoryAccess *CurrAccess = *DFI; |
| 1069 | if (MSSA->isLiveOnEntryDef(CurrAccess)) |
| 1070 | return {CurrAccess, Loc}; |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1071 | // If this is a MemoryDef, check whether it clobbers our current query. This |
| 1072 | // needs to be done before consulting the cache, because the cache reports |
| 1073 | // the clobber for CurrAccess. If CurrAccess is a clobber for this query, |
| 1074 | // and we ask the cache for information first, then we might skip this |
| 1075 | // clobber, which is bad. |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1076 | if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) { |
| 1077 | // If we hit the top, stop following this path. |
| 1078 | // While we can do lookups, we can't sanely do inserts here unless we were |
| 1079 | // to track everything we saw along the way, since we don't know where we |
| 1080 | // will stop. |
| 1081 | if (instructionClobbersQuery(MD, Q, Loc)) { |
| 1082 | ModifyingAccess = CurrAccess; |
| 1083 | break; |
| 1084 | } |
| 1085 | } |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1086 | if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc)) |
| 1087 | return {CacheResult, Loc}; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1088 | |
| 1089 | // We need to know whether it is a phi so we can track backedges. |
| 1090 | // Otherwise, walk all upward defs. |
| 1091 | if (!isa<MemoryPhi>(CurrAccess)) { |
| 1092 | ++DFI; |
| 1093 | continue; |
| 1094 | } |
| 1095 | |
George Burgess IV | 0e48986 | 2016-03-23 18:31:55 +0000 | [diff] [blame] | 1096 | #ifndef NDEBUG |
| 1097 | // The loop below visits the phi's children for us. Because phis are the |
| 1098 | // only things with multiple edges, skipping the children should always lead |
| 1099 | // us to the end of the loop. |
| 1100 | // |
| 1101 | // Use a copy of DFI because skipChildren would kill our search stack, which |
| 1102 | // would make caching anything on the way back impossible. |
| 1103 | auto DFICopy = DFI; |
| 1104 | assert(DFICopy.skipChildren() == DFE && |
| 1105 | "Skipping phi's children doesn't end the DFS?"); |
| 1106 | #endif |
| 1107 | |
George Burgess IV | 82ee942 | 2016-03-30 00:26:26 +0000 | [diff] [blame] | 1108 | const MemoryAccessPair PHIPair(CurrAccess, Loc); |
| 1109 | |
| 1110 | // Don't try to optimize this phi again if we've already tried to do so. |
| 1111 | if (!Q.Visited.insert(PHIPair).second) { |
| 1112 | ModifyingAccess = CurrAccess; |
| 1113 | break; |
| 1114 | } |
| 1115 | |
George Burgess IV | 49cad7d | 2016-03-30 03:12:08 +0000 | [diff] [blame] | 1116 | std::size_t InitialVisitedCallSize = Q.VisitedCalls.size(); |
| 1117 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1118 | // Recurse on PHI nodes, since we need to change locations. |
| 1119 | // TODO: Allow graphtraits on pairs, which would turn this whole function |
| 1120 | // into a normal single depth first walk. |
| 1121 | MemoryAccess *FirstDef = nullptr; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1122 | for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end(); |
| 1123 | MPI != MPE; ++MPI) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1124 | bool Backedge = |
| 1125 | !FollowingBackedge && |
| 1126 | DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock()); |
| 1127 | |
| 1128 | MemoryAccessPair CurrentPair = |
| 1129 | UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge); |
| 1130 | // All the phi arguments should reach the same point if we can bypass |
| 1131 | // this phi. The alternative is that they hit this phi node, which |
| 1132 | // means we can skip this argument. |
| 1133 | if (FirstDef && CurrentPair.first != PHIPair.first && |
| 1134 | CurrentPair.first != FirstDef) { |
| 1135 | ModifyingAccess = CurrAccess; |
| 1136 | break; |
| 1137 | } |
| 1138 | |
| 1139 | if (!FirstDef) |
| 1140 | FirstDef = CurrentPair.first; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1141 | } |
| 1142 | |
George Burgess IV | 0e48986 | 2016-03-23 18:31:55 +0000 | [diff] [blame] | 1143 | // If we exited the loop early, go with the result it gave us. |
| 1144 | if (!ModifyingAccess) { |
George Burgess IV | 82ee942 | 2016-03-30 00:26:26 +0000 | [diff] [blame] | 1145 | assert(FirstDef && "Found a Phi with no upward defs?"); |
| 1146 | ModifyingAccess = FirstDef; |
George Burgess IV | 49cad7d | 2016-03-30 03:12:08 +0000 | [diff] [blame] | 1147 | } else { |
| 1148 | // If we can't optimize this Phi, then we can't safely cache any of the |
| 1149 | // calls we visited when trying to optimize it. Wipe them out now. |
| 1150 | Q.VisitedCalls.resize(InitialVisitedCallSize); |
George Burgess IV | 0e48986 | 2016-03-23 18:31:55 +0000 | [diff] [blame] | 1151 | } |
| 1152 | break; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1153 | } |
| 1154 | |
| 1155 | if (!ModifyingAccess) |
| 1156 | return {MSSA->getLiveOnEntryDef(), Q.StartingLoc}; |
| 1157 | |
George Burgess IV | 0e48986 | 2016-03-23 18:31:55 +0000 | [diff] [blame] | 1158 | const BasicBlock *OriginalBlock = StartingAccess->getBlock(); |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1159 | assert(DFI.getPathLength() > 0 && "We dropped our path?"); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1160 | unsigned N = DFI.getPathLength(); |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1161 | // If we found a clobbering def, the last element in the path will be our |
| 1162 | // clobber, so we don't want to cache that to itself. OTOH, if we optimized a |
| 1163 | // phi, we can add the last thing in the path to the cache, since that won't |
| 1164 | // be the result. |
| 1165 | if (DFI.getPath(N - 1) == ModifyingAccess) |
| 1166 | --N; |
| 1167 | for (; N > 1; --N) { |
George Burgess IV | 0e48986 | 2016-03-23 18:31:55 +0000 | [diff] [blame] | 1168 | MemoryAccess *CacheAccess = DFI.getPath(N - 1); |
| 1169 | BasicBlock *CurrBlock = CacheAccess->getBlock(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1170 | if (!FollowingBackedge) |
George Burgess IV | 0e48986 | 2016-03-23 18:31:55 +0000 | [diff] [blame] | 1171 | doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1172 | if (DT->dominates(CurrBlock, OriginalBlock) && |
| 1173 | (CurrBlock != OriginalBlock || !FollowingBackedge || |
George Burgess IV | 0e48986 | 2016-03-23 18:31:55 +0000 | [diff] [blame] | 1174 | MSSA->locallyDominates(CacheAccess, StartingAccess))) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1175 | break; |
| 1176 | } |
| 1177 | |
| 1178 | // Cache everything else on the way back. The caller should cache |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1179 | // StartingAccess for us. |
| 1180 | for (; N > 1; --N) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1181 | MemoryAccess *CacheAccess = DFI.getPath(N - 1); |
| 1182 | doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc); |
| 1183 | } |
| 1184 | assert(Q.Visited.size() < 1000 && "Visited too much"); |
| 1185 | |
| 1186 | return {ModifyingAccess, Loc}; |
| 1187 | } |
| 1188 | |
| 1189 | /// \brief Walk the use-def chains starting at \p MA and find |
| 1190 | /// the MemoryAccess that actually clobbers Loc. |
| 1191 | /// |
| 1192 | /// \returns our clobbering memory access |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1193 | MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess( |
| 1194 | MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1195 | return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first; |
| 1196 | } |
| 1197 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1198 | MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess( |
| 1199 | MemoryAccess *StartingAccess, MemoryLocation &Loc) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1200 | if (isa<MemoryPhi>(StartingAccess)) |
| 1201 | return StartingAccess; |
| 1202 | |
| 1203 | auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess); |
| 1204 | if (MSSA->isLiveOnEntryDef(StartingUseOrDef)) |
| 1205 | return StartingUseOrDef; |
| 1206 | |
| 1207 | Instruction *I = StartingUseOrDef->getMemoryInst(); |
| 1208 | |
| 1209 | // Conservatively, fences are always clobbers, so don't perform the walk if we |
| 1210 | // hit a fence. |
| 1211 | if (isa<FenceInst>(I)) |
| 1212 | return StartingUseOrDef; |
| 1213 | |
| 1214 | UpwardsMemoryQuery Q; |
| 1215 | Q.OriginalAccess = StartingUseOrDef; |
| 1216 | Q.StartingLoc = Loc; |
| 1217 | Q.Inst = StartingUseOrDef->getMemoryInst(); |
| 1218 | Q.IsCall = false; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1219 | |
| 1220 | if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc)) |
| 1221 | return CacheResult; |
| 1222 | |
| 1223 | // Unlike the other function, do not walk to the def of a def, because we are |
| 1224 | // handed something we already believe is the clobbering access. |
| 1225 | MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef) |
| 1226 | ? StartingUseOrDef->getDefiningAccess() |
| 1227 | : StartingUseOrDef; |
| 1228 | |
| 1229 | MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q); |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1230 | // Only cache this if it wouldn't make Clobber point to itself. |
| 1231 | if (Clobber != StartingAccess) |
| 1232 | doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1233 | DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is "); |
| 1234 | DEBUG(dbgs() << *StartingUseOrDef << "\n"); |
| 1235 | DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is "); |
| 1236 | DEBUG(dbgs() << *Clobber << "\n"); |
| 1237 | return Clobber; |
| 1238 | } |
| 1239 | |
| 1240 | MemoryAccess * |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1241 | MemorySSA::CachingWalker::getClobberingMemoryAccess(const Instruction *I) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1242 | // There should be no way to lookup an instruction and get a phi as the |
| 1243 | // access, since we only map BB's to PHI's. So, this must be a use or def. |
| 1244 | auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I)); |
| 1245 | |
| 1246 | // We can't sanely do anything with a FenceInst, they conservatively |
| 1247 | // clobber all memory, and have no locations to get pointers from to |
| 1248 | // try to disambiguate |
| 1249 | if (isa<FenceInst>(I)) |
| 1250 | return StartingAccess; |
| 1251 | |
| 1252 | UpwardsMemoryQuery Q; |
| 1253 | Q.OriginalAccess = StartingAccess; |
| 1254 | Q.IsCall = bool(ImmutableCallSite(I)); |
| 1255 | if (!Q.IsCall) |
| 1256 | Q.StartingLoc = MemoryLocation::get(I); |
| 1257 | Q.Inst = I; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1258 | if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc)) |
| 1259 | return CacheResult; |
| 1260 | |
| 1261 | // Start with the thing we already think clobbers this location |
| 1262 | MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess(); |
| 1263 | |
| 1264 | // At this point, DefiningAccess may be the live on entry def. |
| 1265 | // If it is, we will not get a better result. |
| 1266 | if (MSSA->isLiveOnEntryDef(DefiningAccess)) |
| 1267 | return DefiningAccess; |
| 1268 | |
| 1269 | MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q); |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1270 | // DFS won't cache a result for DefiningAccess. So, if DefiningAccess isn't |
| 1271 | // our clobber, be sure that it gets a cache entry, too. |
| 1272 | if (Result != DefiningAccess) |
| 1273 | doCacheInsert(DefiningAccess, Result, Q, Q.StartingLoc); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1274 | doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc); |
| 1275 | // TODO: When this implementation is more mature, we may want to figure out |
| 1276 | // what this additional caching buys us. It's most likely A Good Thing. |
| 1277 | if (Q.IsCall) |
| 1278 | for (const MemoryAccess *MA : Q.VisitedCalls) |
George Burgess IV | 1b1fef3 | 2016-04-29 18:42:55 +0000 | [diff] [blame] | 1279 | if (MA != Result) |
| 1280 | doCacheInsert(MA, Result, Q, Q.StartingLoc); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1281 | |
| 1282 | DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is "); |
| 1283 | DEBUG(dbgs() << *DefiningAccess << "\n"); |
| 1284 | DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is "); |
| 1285 | DEBUG(dbgs() << *Result << "\n"); |
| 1286 | |
| 1287 | return Result; |
| 1288 | } |
| 1289 | |
Geoff Berry | 9fe26e6 | 2016-04-22 14:44:10 +0000 | [diff] [blame] | 1290 | // Verify that MA doesn't exist in any of the caches. |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1291 | void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) { |
Geoff Berry | 9fe26e6 | 2016-04-22 14:44:10 +0000 | [diff] [blame] | 1292 | #ifndef NDEBUG |
| 1293 | for (auto &P : CachedUpwardsClobberingAccess) |
| 1294 | assert(P.first.first != MA && P.second != MA && |
| 1295 | "Found removed MemoryAccess in cache."); |
| 1296 | for (auto &P : CachedUpwardsClobberingCall) |
| 1297 | assert(P.first != MA && P.second != MA && |
| 1298 | "Found removed MemoryAccess in cache."); |
| 1299 | #endif // !NDEBUG |
| 1300 | } |
| 1301 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1302 | MemoryAccess * |
| 1303 | DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) { |
| 1304 | MemoryAccess *MA = MSSA->getMemoryAccess(I); |
| 1305 | if (auto *Use = dyn_cast<MemoryUseOrDef>(MA)) |
| 1306 | return Use->getDefiningAccess(); |
| 1307 | return MA; |
| 1308 | } |
| 1309 | |
| 1310 | MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess( |
| 1311 | MemoryAccess *StartingAccess, MemoryLocation &) { |
| 1312 | if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess)) |
| 1313 | return Use->getDefiningAccess(); |
| 1314 | return StartingAccess; |
| 1315 | } |
| 1316 | } |