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 | //===----------------------------------------------------------------===// |
| 13 | #include "llvm/ADT/DenseMap.h" |
| 14 | #include "llvm/ADT/DenseSet.h" |
| 15 | #include "llvm/ADT/DepthFirstIterator.h" |
| 16 | #include "llvm/ADT/GraphTraits.h" |
| 17 | #include "llvm/ADT/PostOrderIterator.h" |
| 18 | #include "llvm/ADT/STLExtras.h" |
| 19 | #include "llvm/ADT/SmallPtrSet.h" |
| 20 | #include "llvm/ADT/SmallSet.h" |
| 21 | #include "llvm/ADT/Statistic.h" |
| 22 | #include "llvm/Analysis/AliasAnalysis.h" |
| 23 | #include "llvm/Analysis/CFG.h" |
| 24 | #include "llvm/Analysis/GlobalsModRef.h" |
| 25 | #include "llvm/Analysis/IteratedDominanceFrontier.h" |
| 26 | #include "llvm/Analysis/MemoryLocation.h" |
| 27 | #include "llvm/Analysis/PHITransAddr.h" |
| 28 | #include "llvm/IR/AssemblyAnnotationWriter.h" |
| 29 | #include "llvm/IR/DataLayout.h" |
| 30 | #include "llvm/IR/Dominators.h" |
| 31 | #include "llvm/IR/GlobalVariable.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
| 33 | #include "llvm/IR/IntrinsicInst.h" |
| 34 | #include "llvm/IR/LLVMContext.h" |
| 35 | #include "llvm/IR/Metadata.h" |
| 36 | #include "llvm/IR/Module.h" |
| 37 | #include "llvm/IR/PatternMatch.h" |
| 38 | #include "llvm/Support/CommandLine.h" |
| 39 | #include "llvm/Support/Debug.h" |
| 40 | #include "llvm/Support/FormattedStream.h" |
| 41 | #include "llvm/Transforms/Scalar.h" |
| 42 | #include "llvm/Transforms/Utils/MemorySSA.h" |
| 43 | #include <algorithm> |
| 44 | |
| 45 | #define DEBUG_TYPE "memoryssa" |
| 46 | using namespace llvm; |
| 47 | STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups"); |
| 48 | STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits"); |
| 49 | STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts"); |
| 50 | INITIALIZE_PASS_WITH_OPTIONS_BEGIN(MemorySSAPrinterPass, "print-memoryssa", |
| 51 | "Memory SSA", true, true) |
| 52 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 53 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
| 54 | INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) |
| 55 | INITIALIZE_PASS_END(MemorySSAPrinterPass, "print-memoryssa", "Memory SSA", true, |
| 56 | true) |
| 57 | INITIALIZE_PASS(MemorySSALazy, "memoryssalazy", "Memory SSA", true, true) |
| 58 | |
| 59 | namespace llvm { |
| 60 | |
| 61 | /// \brief An assembly annotator class to print Memory SSA information in |
| 62 | /// comments. |
| 63 | class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter { |
| 64 | friend class MemorySSA; |
| 65 | const MemorySSA *MSSA; |
| 66 | |
| 67 | public: |
| 68 | MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {} |
| 69 | |
| 70 | virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, |
| 71 | formatted_raw_ostream &OS) { |
| 72 | if (MemoryAccess *MA = MSSA->getMemoryAccess(BB)) |
| 73 | OS << "; " << *MA << "\n"; |
| 74 | } |
| 75 | |
| 76 | virtual void emitInstructionAnnot(const Instruction *I, |
| 77 | formatted_raw_ostream &OS) { |
| 78 | if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) |
| 79 | OS << "; " << *MA << "\n"; |
| 80 | } |
| 81 | }; |
| 82 | } |
| 83 | |
| 84 | namespace { |
| 85 | struct RenamePassData { |
| 86 | DomTreeNode *DTN; |
| 87 | DomTreeNode::const_iterator ChildIt; |
| 88 | MemoryAccess *IncomingVal; |
| 89 | |
| 90 | RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It, |
| 91 | MemoryAccess *M) |
| 92 | : DTN(D), ChildIt(It), IncomingVal(M) {} |
| 93 | void swap(RenamePassData &RHS) { |
| 94 | std::swap(DTN, RHS.DTN); |
| 95 | std::swap(ChildIt, RHS.ChildIt); |
| 96 | std::swap(IncomingVal, RHS.IncomingVal); |
| 97 | } |
| 98 | }; |
| 99 | } |
| 100 | |
| 101 | namespace llvm { |
| 102 | /// \brief Rename a single basic block into MemorySSA form. |
| 103 | /// Uses the standard SSA renaming algorithm. |
| 104 | /// \returns The new incoming value. |
| 105 | MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, |
| 106 | MemoryAccess *IncomingVal) { |
| 107 | auto It = PerBlockAccesses.find(BB); |
| 108 | // Skip most processing if the list is empty. |
| 109 | if (It != PerBlockAccesses.end()) { |
| 110 | AccessListType *Accesses = It->second.get(); |
| 111 | for (MemoryAccess &L : *Accesses) { |
| 112 | switch (L.getValueID()) { |
| 113 | case Value::MemoryUseVal: |
| 114 | cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal); |
| 115 | break; |
| 116 | case Value::MemoryDefVal: |
| 117 | // We can't legally optimize defs, because we only allow single |
| 118 | // memory phis/uses on operations, and if we optimize these, we can |
| 119 | // end up with multiple reaching defs. Uses do not have this |
| 120 | // problem, since they do not produce a value |
| 121 | cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal); |
| 122 | IncomingVal = &L; |
| 123 | break; |
| 124 | case Value::MemoryPhiVal: |
| 125 | IncomingVal = &L; |
| 126 | break; |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | // Pass through values to our successors |
| 132 | for (const BasicBlock *S : successors(BB)) { |
| 133 | auto It = PerBlockAccesses.find(S); |
| 134 | // Rename the phi nodes in our successor block |
| 135 | if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front())) |
| 136 | continue; |
| 137 | AccessListType *Accesses = It->second.get(); |
| 138 | auto *Phi = cast<MemoryPhi>(&Accesses->front()); |
| 139 | assert(std::find(succ_begin(BB), succ_end(BB), S) != succ_end(BB) && |
| 140 | "Must be at least one edge from Succ to BB!"); |
| 141 | Phi->addIncoming(IncomingVal, BB); |
| 142 | } |
| 143 | |
| 144 | return IncomingVal; |
| 145 | } |
| 146 | |
| 147 | /// \brief This is the standard SSA renaming algorithm. |
| 148 | /// |
| 149 | /// We walk the dominator tree in preorder, renaming accesses, and then filling |
| 150 | /// in phi nodes in our successors. |
| 151 | void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal, |
| 152 | SmallPtrSet<BasicBlock *, 16> &Visited) { |
| 153 | SmallVector<RenamePassData, 32> WorkStack; |
| 154 | IncomingVal = renameBlock(Root->getBlock(), IncomingVal); |
| 155 | WorkStack.push_back({Root, Root->begin(), IncomingVal}); |
| 156 | Visited.insert(Root->getBlock()); |
| 157 | |
| 158 | while (!WorkStack.empty()) { |
| 159 | DomTreeNode *Node = WorkStack.back().DTN; |
| 160 | DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt; |
| 161 | IncomingVal = WorkStack.back().IncomingVal; |
| 162 | |
| 163 | if (ChildIt == Node->end()) { |
| 164 | WorkStack.pop_back(); |
| 165 | } else { |
| 166 | DomTreeNode *Child = *ChildIt; |
| 167 | ++WorkStack.back().ChildIt; |
| 168 | BasicBlock *BB = Child->getBlock(); |
| 169 | Visited.insert(BB); |
| 170 | IncomingVal = renameBlock(BB, IncomingVal); |
| 171 | WorkStack.push_back({Child, Child->begin(), IncomingVal}); |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// \brief Compute dominator levels, used by the phi insertion algorithm above. |
| 177 | void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) { |
| 178 | for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode()); |
| 179 | DFI != DFE; ++DFI) |
| 180 | DomLevels[*DFI] = DFI.getPathLength() - 1; |
| 181 | } |
| 182 | |
| 183 | /// \brief This handles unreachable block acccesses by deleting phi nodes in |
| 184 | /// unreachable blocks, and marking all other unreachable MemoryAccess's as |
| 185 | /// being uses of the live on entry definition. |
| 186 | void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) { |
| 187 | assert(!DT->isReachableFromEntry(BB) && |
| 188 | "Reachable block found while handling unreachable blocks"); |
| 189 | |
| 190 | auto It = PerBlockAccesses.find(BB); |
| 191 | if (It == PerBlockAccesses.end()) |
| 192 | return; |
| 193 | |
| 194 | auto &Accesses = It->second; |
| 195 | for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) { |
| 196 | auto Next = std::next(AI); |
| 197 | // If we have a phi, just remove it. We are going to replace all |
| 198 | // users with live on entry. |
| 199 | if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI)) |
| 200 | UseOrDef->setDefiningAccess(LiveOnEntryDef.get()); |
| 201 | else |
| 202 | Accesses->erase(AI); |
| 203 | AI = Next; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | MemorySSA::MemorySSA(Function &Func) |
| 208 | : AA(nullptr), DT(nullptr), F(Func), LiveOnEntryDef(nullptr), |
| 209 | Walker(nullptr), NextID(0) {} |
| 210 | |
| 211 | MemorySSA::~MemorySSA() { |
| 212 | // Drop all our references |
| 213 | for (const auto &Pair : PerBlockAccesses) |
| 214 | for (MemoryAccess &MA : *Pair.second) |
| 215 | MA.dropAllReferences(); |
| 216 | } |
| 217 | |
| 218 | MemorySSA::AccessListType *MemorySSA::getOrCreateAccessList(BasicBlock *BB) { |
| 219 | auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr)); |
| 220 | |
| 221 | if (Res.second) |
| 222 | Res.first->second = make_unique<AccessListType>(); |
| 223 | return Res.first->second.get(); |
| 224 | } |
| 225 | |
| 226 | MemorySSAWalker *MemorySSA::buildMemorySSA(AliasAnalysis *AA, |
| 227 | DominatorTree *DT) { |
| 228 | if (Walker) |
| 229 | return Walker; |
| 230 | |
| 231 | assert(!this->AA && !this->DT && |
| 232 | "MemorySSA without a walker already has AA or DT?"); |
| 233 | |
| 234 | auto *Result = new CachingMemorySSAWalker(this, AA, DT); |
| 235 | this->AA = AA; |
| 236 | this->DT = DT; |
| 237 | |
| 238 | // We create an access to represent "live on entry", for things like |
| 239 | // arguments or users of globals, where the memory they use is defined before |
| 240 | // the beginning of the function. We do not actually insert it into the IR. |
| 241 | // We do not define a live on exit for the immediate uses, and thus our |
| 242 | // semantics do *not* imply that something with no immediate uses can simply |
| 243 | // be removed. |
| 244 | BasicBlock &StartingPoint = F.getEntryBlock(); |
| 245 | LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr, |
| 246 | &StartingPoint, NextID++); |
| 247 | |
| 248 | // We maintain lists of memory accesses per-block, trading memory for time. We |
| 249 | // could just look up the memory access for every possible instruction in the |
| 250 | // stream. |
| 251 | SmallPtrSet<BasicBlock *, 32> DefiningBlocks; |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 252 | SmallPtrSet<BasicBlock *, 32> DefUseBlocks; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 253 | // Go through each block, figure out where defs occur, and chain together all |
| 254 | // the accesses. |
| 255 | for (BasicBlock &B : F) { |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 256 | bool InsertIntoDefUse = false; |
Daniel Berlin | 7898ca6 | 2016-02-07 01:52:15 +0000 | [diff] [blame] | 257 | bool InsertIntoDef = false; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 258 | AccessListType *Accesses = nullptr; |
| 259 | for (Instruction &I : B) { |
| 260 | MemoryAccess *MA = createNewAccess(&I, true); |
| 261 | if (!MA) |
| 262 | continue; |
| 263 | if (isa<MemoryDef>(MA)) |
Daniel Berlin | 7898ca6 | 2016-02-07 01:52:15 +0000 | [diff] [blame] | 264 | InsertIntoDef = true; |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 265 | else if (isa<MemoryUse>(MA)) |
| 266 | InsertIntoDefUse = true; |
| 267 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 268 | if (!Accesses) |
| 269 | Accesses = getOrCreateAccessList(&B); |
| 270 | Accesses->push_back(MA); |
| 271 | } |
Daniel Berlin | 7898ca6 | 2016-02-07 01:52:15 +0000 | [diff] [blame] | 272 | if (InsertIntoDef) |
| 273 | DefiningBlocks.insert(&B); |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 274 | if (InsertIntoDefUse) |
| 275 | DefUseBlocks.insert(&B); |
| 276 | } |
| 277 | |
| 278 | // Compute live-in. |
| 279 | // Live in is normally defined as "all the blocks on the path from each def to |
| 280 | // each of it's uses". |
| 281 | // MemoryDef's are implicit uses of previous state, so they are also uses. |
| 282 | // This means we don't really have def-only instructions. The only |
| 283 | // MemoryDef's that are not really uses are those that are of the LiveOnEntry |
| 284 | // variable (because LiveOnEntry can reach anywhere, and every def is a |
| 285 | // must-kill of LiveOnEntry). |
| 286 | // In theory, you could precisely compute live-in by using alias-analysis to |
| 287 | // disambiguate defs and uses to see which really pair up with which. |
| 288 | // In practice, this would be really expensive and difficult. So we simply |
| 289 | // assume all defs are also uses that need to be kept live. |
| 290 | // Because of this, the end result of this live-in computation will be "the |
| 291 | // entire set of basic blocks that reach any use". |
| 292 | |
| 293 | SmallPtrSet<BasicBlock *, 32> LiveInBlocks; |
| 294 | SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(), |
| 295 | DefUseBlocks.end()); |
| 296 | // Now that we have a set of blocks where a value is live-in, recursively add |
| 297 | // predecessors until we find the full region the value is live. |
| 298 | while (!LiveInBlockWorklist.empty()) { |
| 299 | BasicBlock *BB = LiveInBlockWorklist.pop_back_val(); |
| 300 | |
| 301 | // The block really is live in here, insert it into the set. If already in |
| 302 | // the set, then it has already been processed. |
| 303 | if (!LiveInBlocks.insert(BB).second) |
| 304 | continue; |
| 305 | |
| 306 | // Since the value is live into BB, it is either defined in a predecessor or |
| 307 | // live into it to. |
| 308 | LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 309 | } |
| 310 | |
| 311 | // Determine where our MemoryPhi's should go |
| 312 | IDFCalculator IDFs(*DT); |
| 313 | IDFs.setDefiningBlocks(DefiningBlocks); |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 314 | IDFs.setLiveInBlocks(LiveInBlocks); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 315 | SmallVector<BasicBlock *, 32> IDFBlocks; |
| 316 | IDFs.calculate(IDFBlocks); |
| 317 | |
| 318 | // Now place MemoryPhi nodes. |
| 319 | for (auto &BB : IDFBlocks) { |
| 320 | // Insert phi node |
| 321 | AccessListType *Accesses = getOrCreateAccessList(BB); |
| 322 | MemoryPhi *Phi = new MemoryPhi(F.getContext(), BB, NextID++); |
Daniel Berlin | f6c9ae9 | 2016-02-10 17:41:25 +0000 | [diff] [blame^] | 323 | ValueToMemoryAccess.insert(std::make_pair(BB, Phi)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 324 | // Phi's always are placed at the front of the block. |
| 325 | Accesses->push_front(Phi); |
| 326 | } |
| 327 | |
| 328 | // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get |
| 329 | // filled in with all blocks. |
| 330 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 331 | renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited); |
| 332 | |
| 333 | // Now optimize the MemoryUse's defining access to point to the nearest |
| 334 | // dominating clobbering def. |
| 335 | // This ensures that MemoryUse's that are killed by the same store are |
| 336 | // immediate users of that store, one of the invariants we guarantee. |
| 337 | for (auto DomNode : depth_first(DT)) { |
| 338 | BasicBlock *BB = DomNode->getBlock(); |
| 339 | auto AI = PerBlockAccesses.find(BB); |
| 340 | if (AI == PerBlockAccesses.end()) |
| 341 | continue; |
| 342 | AccessListType *Accesses = AI->second.get(); |
| 343 | for (auto &MA : *Accesses) { |
| 344 | if (auto *MU = dyn_cast<MemoryUse>(&MA)) { |
| 345 | Instruction *Inst = MU->getMemoryInst(); |
| 346 | MU->setDefiningAccess(Result->getClobberingMemoryAccess(Inst)); |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | // Mark the uses in unreachable blocks as live on entry, so that they go |
| 352 | // somewhere. |
| 353 | for (auto &BB : F) |
| 354 | if (!Visited.count(&BB)) |
| 355 | markUnreachableAsLiveOnEntry(&BB); |
| 356 | |
| 357 | Walker = Result; |
| 358 | return Walker; |
| 359 | } |
| 360 | |
| 361 | /// \brief Helper function to create new memory accesses |
| 362 | MemoryAccess *MemorySSA::createNewAccess(Instruction *I, bool IgnoreNonMemory) { |
| 363 | // Find out what affect this instruction has on memory. |
| 364 | ModRefInfo ModRef = AA->getModRefInfo(I); |
| 365 | bool Def = bool(ModRef & MRI_Mod); |
| 366 | bool Use = bool(ModRef & MRI_Ref); |
| 367 | |
| 368 | // It's possible for an instruction to not modify memory at all. During |
| 369 | // construction, we ignore them. |
| 370 | if (IgnoreNonMemory && !Def && !Use) |
| 371 | return nullptr; |
| 372 | |
| 373 | assert((Def || Use) && |
| 374 | "Trying to create a memory access with a non-memory instruction"); |
| 375 | |
| 376 | MemoryUseOrDef *MA; |
| 377 | if (Def) |
Daniel Berlin | f6c9ae9 | 2016-02-10 17:41:25 +0000 | [diff] [blame^] | 378 | MA = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 379 | else |
Daniel Berlin | f6c9ae9 | 2016-02-10 17:41:25 +0000 | [diff] [blame^] | 380 | MA = new MemoryUse(I->getContext(), nullptr, I, I->getParent()); |
| 381 | ValueToMemoryAccess.insert(std::make_pair(I, MA)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 382 | return MA; |
| 383 | } |
| 384 | |
| 385 | MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock, |
| 386 | enum InsertionPlace Where) { |
| 387 | // Handle the initial case |
| 388 | if (Where == Beginning) |
| 389 | // The only thing that could define us at the beginning is a phi node |
| 390 | if (MemoryPhi *Phi = getMemoryAccess(UseBlock)) |
| 391 | return Phi; |
| 392 | |
| 393 | DomTreeNode *CurrNode = DT->getNode(UseBlock); |
| 394 | // Need to be defined by our dominator |
| 395 | if (Where == Beginning) |
| 396 | CurrNode = CurrNode->getIDom(); |
| 397 | Where = End; |
| 398 | while (CurrNode) { |
| 399 | auto It = PerBlockAccesses.find(CurrNode->getBlock()); |
| 400 | if (It != PerBlockAccesses.end()) { |
| 401 | auto &Accesses = It->second; |
| 402 | for (auto RAI = Accesses->rbegin(), RAE = Accesses->rend(); RAI != RAE; |
| 403 | ++RAI) { |
| 404 | if (isa<MemoryDef>(*RAI) || isa<MemoryPhi>(*RAI)) |
| 405 | return &*RAI; |
| 406 | } |
| 407 | } |
| 408 | CurrNode = CurrNode->getIDom(); |
| 409 | } |
| 410 | return LiveOnEntryDef.get(); |
| 411 | } |
| 412 | |
| 413 | /// \brief Returns true if \p Replacer dominates \p Replacee . |
| 414 | bool MemorySSA::dominatesUse(const MemoryAccess *Replacer, |
| 415 | const MemoryAccess *Replacee) const { |
| 416 | if (isa<MemoryUseOrDef>(Replacee)) |
| 417 | return DT->dominates(Replacer->getBlock(), Replacee->getBlock()); |
| 418 | const auto *MP = cast<MemoryPhi>(Replacee); |
| 419 | // For a phi node, the use occurs in the predecessor block of the phi node. |
| 420 | // Since we may occur multiple times in the phi node, we have to check each |
| 421 | // operand to ensure Replacer dominates each operand where Replacee occurs. |
| 422 | for (const Use &Arg : MP->operands()) { |
George Burgess IV | b5a229f | 2016-02-02 23:15:26 +0000 | [diff] [blame] | 423 | if (Arg.get() != Replacee && |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 424 | !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg))) |
| 425 | return false; |
| 426 | } |
| 427 | return true; |
| 428 | } |
| 429 | |
| 430 | void MemorySSA::print(raw_ostream &OS) const { |
| 431 | MemorySSAAnnotatedWriter Writer(this); |
| 432 | F.print(OS, &Writer); |
| 433 | } |
| 434 | |
| 435 | void MemorySSA::dump() const { |
| 436 | MemorySSAAnnotatedWriter Writer(this); |
| 437 | F.print(dbgs(), &Writer); |
| 438 | } |
| 439 | |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 440 | void MemorySSA::verifyMemorySSA() const { |
| 441 | verifyDefUses(F); |
| 442 | verifyDomination(F); |
| 443 | } |
| 444 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 445 | /// \brief Verify the domination properties of MemorySSA by checking that each |
| 446 | /// definition dominates all of its uses. |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 447 | void MemorySSA::verifyDomination(Function &F) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 448 | for (BasicBlock &B : F) { |
| 449 | // Phi nodes are attached to basic blocks |
| 450 | if (MemoryPhi *MP = getMemoryAccess(&B)) { |
| 451 | for (User *U : MP->users()) { |
| 452 | BasicBlock *UseBlock; |
| 453 | // Phi operands are used on edges, we simulate the right domination by |
| 454 | // acting as if the use occurred at the end of the predecessor block. |
| 455 | if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) { |
| 456 | for (const auto &Arg : P->operands()) { |
| 457 | if (Arg == MP) { |
| 458 | UseBlock = P->getIncomingBlock(Arg); |
| 459 | break; |
| 460 | } |
| 461 | } |
| 462 | } else { |
| 463 | UseBlock = cast<MemoryAccess>(U)->getBlock(); |
| 464 | } |
George Burgess IV | 60adac4 | 2016-02-02 23:26:01 +0000 | [diff] [blame] | 465 | (void)UseBlock; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 466 | assert(DT->dominates(MP->getBlock(), UseBlock) && |
| 467 | "Memory PHI does not dominate it's uses"); |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | for (Instruction &I : B) { |
| 472 | MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I)); |
| 473 | if (!MD) |
| 474 | continue; |
| 475 | |
| 476 | for (const auto &U : MD->users()) { |
| 477 | BasicBlock *UseBlock; |
| 478 | // Things are allowed to flow to phi nodes over their predecessor edge. |
| 479 | if (auto *P = dyn_cast<MemoryPhi>(U)) { |
| 480 | for (const auto &Arg : P->operands()) { |
| 481 | if (Arg == MD) { |
| 482 | UseBlock = P->getIncomingBlock(Arg); |
| 483 | break; |
| 484 | } |
| 485 | } |
| 486 | } else { |
| 487 | UseBlock = cast<MemoryAccess>(U)->getBlock(); |
| 488 | } |
| 489 | assert(DT->dominates(MD->getBlock(), UseBlock) && |
| 490 | "Memory Def does not dominate it's uses"); |
| 491 | } |
| 492 | } |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | /// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use |
| 497 | /// appears in the use list of \p Def. |
| 498 | /// |
| 499 | /// llvm_unreachable is used instead of asserts because this may be called in |
| 500 | /// a build without asserts. In that case, we don't want this to turn into a |
| 501 | /// nop. |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 502 | void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 503 | // The live on entry use may cause us to get a NULL def here |
| 504 | if (!Def) { |
| 505 | if (!isLiveOnEntryDef(Use)) |
| 506 | llvm_unreachable("Null def but use not point to live on entry def"); |
| 507 | } else if (std::find(Def->user_begin(), Def->user_end(), Use) == |
| 508 | Def->user_end()) { |
| 509 | llvm_unreachable("Did not find use in def's use list"); |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | /// \brief Verify the immediate use information, by walking all the memory |
| 514 | /// accesses and verifying that, for each use, it appears in the |
| 515 | /// appropriate def's use list |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 516 | void MemorySSA::verifyDefUses(Function &F) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 517 | for (BasicBlock &B : F) { |
| 518 | // Phi nodes are attached to basic blocks |
| 519 | if (MemoryPhi *Phi = getMemoryAccess(&B)) |
| 520 | for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) |
| 521 | verifyUseInDefs(Phi->getIncomingValue(I), Phi); |
| 522 | |
| 523 | for (Instruction &I : B) { |
| 524 | if (MemoryAccess *MA = getMemoryAccess(&I)) { |
| 525 | assert(isa<MemoryUseOrDef>(MA) && |
| 526 | "Found a phi node not attached to a bb"); |
| 527 | verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA); |
| 528 | } |
| 529 | } |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const { |
Daniel Berlin | f6c9ae9 | 2016-02-10 17:41:25 +0000 | [diff] [blame^] | 534 | return ValueToMemoryAccess.lookup(I); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 535 | } |
| 536 | |
| 537 | MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const { |
| 538 | return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB)); |
| 539 | } |
| 540 | |
| 541 | /// \brief Determine, for two memory accesses in the same block, |
| 542 | /// whether \p Dominator dominates \p Dominatee. |
| 543 | /// \returns True if \p Dominator dominates \p Dominatee. |
| 544 | bool MemorySSA::locallyDominates(const MemoryAccess *Dominator, |
| 545 | const MemoryAccess *Dominatee) const { |
| 546 | |
| 547 | assert((Dominator->getBlock() == Dominatee->getBlock()) && |
| 548 | "Asking for local domination when accesses are in different blocks!"); |
| 549 | // Get the access list for the block |
| 550 | const AccessListType *AccessList = getBlockAccesses(Dominator->getBlock()); |
| 551 | AccessListType::const_reverse_iterator It(Dominator->getIterator()); |
| 552 | |
| 553 | // If we hit the beginning of the access list before we hit dominatee, we must |
| 554 | // dominate it |
| 555 | return std::none_of(It, AccessList->rend(), |
| 556 | [&](const MemoryAccess &MA) { return &MA == Dominatee; }); |
| 557 | } |
| 558 | |
| 559 | const static char LiveOnEntryStr[] = "liveOnEntry"; |
| 560 | |
| 561 | void MemoryDef::print(raw_ostream &OS) const { |
| 562 | MemoryAccess *UO = getDefiningAccess(); |
| 563 | |
| 564 | OS << getID() << " = MemoryDef("; |
| 565 | if (UO && UO->getID()) |
| 566 | OS << UO->getID(); |
| 567 | else |
| 568 | OS << LiveOnEntryStr; |
| 569 | OS << ')'; |
| 570 | } |
| 571 | |
| 572 | void MemoryPhi::print(raw_ostream &OS) const { |
| 573 | bool First = true; |
| 574 | OS << getID() << " = MemoryPhi("; |
| 575 | for (const auto &Op : operands()) { |
| 576 | BasicBlock *BB = getIncomingBlock(Op); |
| 577 | MemoryAccess *MA = cast<MemoryAccess>(Op); |
| 578 | if (!First) |
| 579 | OS << ','; |
| 580 | else |
| 581 | First = false; |
| 582 | |
| 583 | OS << '{'; |
| 584 | if (BB->hasName()) |
| 585 | OS << BB->getName(); |
| 586 | else |
| 587 | BB->printAsOperand(OS, false); |
| 588 | OS << ','; |
| 589 | if (unsigned ID = MA->getID()) |
| 590 | OS << ID; |
| 591 | else |
| 592 | OS << LiveOnEntryStr; |
| 593 | OS << '}'; |
| 594 | } |
| 595 | OS << ')'; |
| 596 | } |
| 597 | |
| 598 | MemoryAccess::~MemoryAccess() {} |
| 599 | |
| 600 | void MemoryUse::print(raw_ostream &OS) const { |
| 601 | MemoryAccess *UO = getDefiningAccess(); |
| 602 | OS << "MemoryUse("; |
| 603 | if (UO && UO->getID()) |
| 604 | OS << UO->getID(); |
| 605 | else |
| 606 | OS << LiveOnEntryStr; |
| 607 | OS << ')'; |
| 608 | } |
| 609 | |
| 610 | void MemoryAccess::dump() const { |
| 611 | print(dbgs()); |
| 612 | dbgs() << "\n"; |
| 613 | } |
| 614 | |
| 615 | char MemorySSAPrinterPass::ID = 0; |
| 616 | |
| 617 | MemorySSAPrinterPass::MemorySSAPrinterPass() : FunctionPass(ID) { |
| 618 | initializeMemorySSAPrinterPassPass(*PassRegistry::getPassRegistry()); |
| 619 | } |
| 620 | |
| 621 | void MemorySSAPrinterPass::releaseMemory() { |
| 622 | // Subtlety: Be sure to delete the walker before MSSA, because the walker's |
| 623 | // dtor may try to access MemorySSA. |
| 624 | Walker.reset(); |
| 625 | MSSA.reset(); |
| 626 | } |
| 627 | |
| 628 | void MemorySSAPrinterPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 629 | AU.setPreservesAll(); |
| 630 | AU.addRequired<AAResultsWrapperPass>(); |
| 631 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 632 | AU.addPreserved<DominatorTreeWrapperPass>(); |
| 633 | AU.addPreserved<GlobalsAAWrapperPass>(); |
| 634 | } |
| 635 | |
| 636 | bool MemorySSAPrinterPass::doInitialization(Module &M) { |
George Burgess IV | 60adac4 | 2016-02-02 23:26:01 +0000 | [diff] [blame] | 637 | VerifyMemorySSA = M.getContext() |
| 638 | .getOption<bool, MemorySSAPrinterPass, |
| 639 | &MemorySSAPrinterPass::VerifyMemorySSA>(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 640 | return false; |
| 641 | } |
| 642 | |
| 643 | void MemorySSAPrinterPass::registerOptions() { |
| 644 | OptionRegistry::registerOption<bool, MemorySSAPrinterPass, |
| 645 | &MemorySSAPrinterPass::VerifyMemorySSA>( |
| 646 | "verify-memoryssa", "Run the Memory SSA verifier", false); |
| 647 | } |
| 648 | |
| 649 | void MemorySSAPrinterPass::print(raw_ostream &OS, const Module *M) const { |
| 650 | MSSA->print(OS); |
| 651 | } |
| 652 | |
| 653 | bool MemorySSAPrinterPass::runOnFunction(Function &F) { |
| 654 | this->F = &F; |
| 655 | MSSA.reset(new MemorySSA(F)); |
| 656 | AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 657 | DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 658 | Walker.reset(MSSA->buildMemorySSA(AA, DT)); |
| 659 | |
| 660 | if (VerifyMemorySSA) { |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 661 | MSSA->verifyMemorySSA(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 662 | } |
| 663 | |
| 664 | return false; |
| 665 | } |
| 666 | |
| 667 | char MemorySSALazy::ID = 0; |
| 668 | |
| 669 | MemorySSALazy::MemorySSALazy() : FunctionPass(ID) { |
| 670 | initializeMemorySSALazyPass(*PassRegistry::getPassRegistry()); |
| 671 | } |
| 672 | |
| 673 | void MemorySSALazy::releaseMemory() { MSSA.reset(); } |
| 674 | |
| 675 | bool MemorySSALazy::runOnFunction(Function &F) { |
| 676 | MSSA.reset(new MemorySSA(F)); |
| 677 | return false; |
| 678 | } |
| 679 | |
| 680 | MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {} |
| 681 | |
| 682 | CachingMemorySSAWalker::CachingMemorySSAWalker(MemorySSA *M, AliasAnalysis *A, |
| 683 | DominatorTree *D) |
| 684 | : MemorySSAWalker(M), AA(A), DT(D) {} |
| 685 | |
| 686 | CachingMemorySSAWalker::~CachingMemorySSAWalker() {} |
| 687 | |
| 688 | struct CachingMemorySSAWalker::UpwardsMemoryQuery { |
| 689 | // True if we saw a phi whose predecessor was a backedge |
| 690 | bool SawBackedgePhi; |
| 691 | // True if our original query started off as a call |
| 692 | bool IsCall; |
| 693 | // The pointer location we started the query with. This will be empty if |
| 694 | // IsCall is true. |
| 695 | MemoryLocation StartingLoc; |
| 696 | // This is the instruction we were querying about. |
| 697 | const Instruction *Inst; |
| 698 | // Set of visited Instructions for this query. |
| 699 | DenseSet<MemoryAccessPair> Visited; |
| 700 | // Set of visited call accesses for this query. This is separated out because |
| 701 | // you can always cache and lookup the result of call queries (IE when IsCall |
| 702 | // == true) for every call in the chain. The calls have no AA location |
| 703 | // associated with them with them, and thus, no context dependence. |
| 704 | SmallPtrSet<const MemoryAccess *, 32> VisitedCalls; |
| 705 | // The MemoryAccess we actually got called with, used to test local domination |
| 706 | const MemoryAccess *OriginalAccess; |
| 707 | // The Datalayout for the module we started in |
| 708 | const DataLayout *DL; |
| 709 | |
| 710 | UpwardsMemoryQuery() |
| 711 | : SawBackedgePhi(false), IsCall(false), Inst(nullptr), |
| 712 | OriginalAccess(nullptr), DL(nullptr) {} |
| 713 | }; |
| 714 | |
| 715 | void CachingMemorySSAWalker::doCacheRemove(const MemoryAccess *M, |
| 716 | const UpwardsMemoryQuery &Q, |
| 717 | const MemoryLocation &Loc) { |
| 718 | if (Q.IsCall) |
| 719 | CachedUpwardsClobberingCall.erase(M); |
| 720 | else |
| 721 | CachedUpwardsClobberingAccess.erase({M, Loc}); |
| 722 | } |
| 723 | |
| 724 | void CachingMemorySSAWalker::doCacheInsert(const MemoryAccess *M, |
| 725 | MemoryAccess *Result, |
| 726 | const UpwardsMemoryQuery &Q, |
| 727 | const MemoryLocation &Loc) { |
| 728 | ++NumClobberCacheInserts; |
| 729 | if (Q.IsCall) |
| 730 | CachedUpwardsClobberingCall[M] = Result; |
| 731 | else |
| 732 | CachedUpwardsClobberingAccess[{M, Loc}] = Result; |
| 733 | } |
| 734 | |
| 735 | MemoryAccess *CachingMemorySSAWalker::doCacheLookup(const MemoryAccess *M, |
| 736 | const UpwardsMemoryQuery &Q, |
| 737 | const MemoryLocation &Loc) { |
| 738 | ++NumClobberCacheLookups; |
| 739 | MemoryAccess *Result = nullptr; |
| 740 | |
| 741 | if (Q.IsCall) |
| 742 | Result = CachedUpwardsClobberingCall.lookup(M); |
| 743 | else |
| 744 | Result = CachedUpwardsClobberingAccess.lookup({M, Loc}); |
| 745 | |
| 746 | if (Result) |
| 747 | ++NumClobberCacheHits; |
| 748 | return Result; |
| 749 | } |
| 750 | |
| 751 | bool CachingMemorySSAWalker::instructionClobbersQuery( |
| 752 | const MemoryDef *MD, UpwardsMemoryQuery &Q, |
| 753 | const MemoryLocation &Loc) const { |
| 754 | Instruction *DefMemoryInst = MD->getMemoryInst(); |
| 755 | assert(DefMemoryInst && "Defining instruction not actually an instruction"); |
| 756 | |
| 757 | if (!Q.IsCall) |
| 758 | return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod; |
| 759 | |
| 760 | // If this is a call, mark it for caching |
| 761 | if (ImmutableCallSite(DefMemoryInst)) |
| 762 | Q.VisitedCalls.insert(MD); |
| 763 | ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst)); |
| 764 | return I != MRI_NoModRef; |
| 765 | } |
| 766 | |
| 767 | MemoryAccessPair CachingMemorySSAWalker::UpwardsDFSWalk( |
| 768 | MemoryAccess *StartingAccess, const MemoryLocation &Loc, |
| 769 | UpwardsMemoryQuery &Q, bool FollowingBackedge) { |
| 770 | MemoryAccess *ModifyingAccess = nullptr; |
| 771 | |
| 772 | auto DFI = df_begin(StartingAccess); |
| 773 | for (auto DFE = df_end(StartingAccess); DFI != DFE;) { |
| 774 | MemoryAccess *CurrAccess = *DFI; |
| 775 | if (MSSA->isLiveOnEntryDef(CurrAccess)) |
| 776 | return {CurrAccess, Loc}; |
| 777 | if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc)) |
| 778 | return {CacheResult, Loc}; |
| 779 | // If this is a MemoryDef, check whether it clobbers our current query. |
| 780 | if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) { |
| 781 | // If we hit the top, stop following this path. |
| 782 | // While we can do lookups, we can't sanely do inserts here unless we were |
| 783 | // to track everything we saw along the way, since we don't know where we |
| 784 | // will stop. |
| 785 | if (instructionClobbersQuery(MD, Q, Loc)) { |
| 786 | ModifyingAccess = CurrAccess; |
| 787 | break; |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | // We need to know whether it is a phi so we can track backedges. |
| 792 | // Otherwise, walk all upward defs. |
| 793 | if (!isa<MemoryPhi>(CurrAccess)) { |
| 794 | ++DFI; |
| 795 | continue; |
| 796 | } |
| 797 | |
| 798 | // Recurse on PHI nodes, since we need to change locations. |
| 799 | // TODO: Allow graphtraits on pairs, which would turn this whole function |
| 800 | // into a normal single depth first walk. |
| 801 | MemoryAccess *FirstDef = nullptr; |
| 802 | DFI = DFI.skipChildren(); |
| 803 | const MemoryAccessPair PHIPair(CurrAccess, Loc); |
| 804 | bool VisitedOnlyOne = true; |
| 805 | for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end(); |
| 806 | MPI != MPE; ++MPI) { |
| 807 | // Don't follow this path again if we've followed it once |
| 808 | if (!Q.Visited.insert(*MPI).second) |
| 809 | continue; |
| 810 | |
| 811 | bool Backedge = |
| 812 | !FollowingBackedge && |
| 813 | DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock()); |
| 814 | |
| 815 | MemoryAccessPair CurrentPair = |
| 816 | UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge); |
| 817 | // All the phi arguments should reach the same point if we can bypass |
| 818 | // this phi. The alternative is that they hit this phi node, which |
| 819 | // means we can skip this argument. |
| 820 | if (FirstDef && CurrentPair.first != PHIPair.first && |
| 821 | CurrentPair.first != FirstDef) { |
| 822 | ModifyingAccess = CurrAccess; |
| 823 | break; |
| 824 | } |
| 825 | |
| 826 | if (!FirstDef) |
| 827 | FirstDef = CurrentPair.first; |
| 828 | else |
| 829 | VisitedOnlyOne = false; |
| 830 | } |
| 831 | |
| 832 | // The above loop determines if all arguments of the phi node reach the |
| 833 | // same place. However we skip arguments that are cyclically dependent |
| 834 | // only on the value of this phi node. This means in some cases, we may |
| 835 | // only visit one argument of the phi node, and the above loop will |
| 836 | // happily say that all the arguments are the same. However, in that case, |
| 837 | // we still can't walk past the phi node, because that argument still |
| 838 | // kills the access unless we hit the top of the function when walking |
| 839 | // that argument. |
| 840 | if (VisitedOnlyOne && FirstDef && !MSSA->isLiveOnEntryDef(FirstDef)) |
| 841 | ModifyingAccess = CurrAccess; |
| 842 | } |
| 843 | |
| 844 | if (!ModifyingAccess) |
| 845 | return {MSSA->getLiveOnEntryDef(), Q.StartingLoc}; |
| 846 | |
| 847 | const BasicBlock *OriginalBlock = Q.OriginalAccess->getBlock(); |
| 848 | unsigned N = DFI.getPathLength(); |
| 849 | MemoryAccess *FinalAccess = ModifyingAccess; |
| 850 | for (; N != 0; --N) { |
| 851 | ModifyingAccess = DFI.getPath(N - 1); |
| 852 | BasicBlock *CurrBlock = ModifyingAccess->getBlock(); |
| 853 | if (!FollowingBackedge) |
| 854 | doCacheInsert(ModifyingAccess, FinalAccess, Q, Loc); |
| 855 | if (DT->dominates(CurrBlock, OriginalBlock) && |
| 856 | (CurrBlock != OriginalBlock || !FollowingBackedge || |
| 857 | MSSA->locallyDominates(ModifyingAccess, Q.OriginalAccess))) |
| 858 | break; |
| 859 | } |
| 860 | |
| 861 | // Cache everything else on the way back. The caller should cache |
| 862 | // Q.OriginalAccess for us. |
| 863 | for (; N != 0; --N) { |
| 864 | MemoryAccess *CacheAccess = DFI.getPath(N - 1); |
| 865 | doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc); |
| 866 | } |
| 867 | assert(Q.Visited.size() < 1000 && "Visited too much"); |
| 868 | |
| 869 | return {ModifyingAccess, Loc}; |
| 870 | } |
| 871 | |
| 872 | /// \brief Walk the use-def chains starting at \p MA and find |
| 873 | /// the MemoryAccess that actually clobbers Loc. |
| 874 | /// |
| 875 | /// \returns our clobbering memory access |
| 876 | MemoryAccess * |
| 877 | CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess, |
| 878 | UpwardsMemoryQuery &Q) { |
| 879 | return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first; |
| 880 | } |
| 881 | |
| 882 | MemoryAccess * |
| 883 | CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess, |
| 884 | MemoryLocation &Loc) { |
| 885 | if (isa<MemoryPhi>(StartingAccess)) |
| 886 | return StartingAccess; |
| 887 | |
| 888 | auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess); |
| 889 | if (MSSA->isLiveOnEntryDef(StartingUseOrDef)) |
| 890 | return StartingUseOrDef; |
| 891 | |
| 892 | Instruction *I = StartingUseOrDef->getMemoryInst(); |
| 893 | |
| 894 | // Conservatively, fences are always clobbers, so don't perform the walk if we |
| 895 | // hit a fence. |
| 896 | if (isa<FenceInst>(I)) |
| 897 | return StartingUseOrDef; |
| 898 | |
| 899 | UpwardsMemoryQuery Q; |
| 900 | Q.OriginalAccess = StartingUseOrDef; |
| 901 | Q.StartingLoc = Loc; |
| 902 | Q.Inst = StartingUseOrDef->getMemoryInst(); |
| 903 | Q.IsCall = false; |
| 904 | Q.DL = &Q.Inst->getModule()->getDataLayout(); |
| 905 | |
| 906 | if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc)) |
| 907 | return CacheResult; |
| 908 | |
| 909 | // Unlike the other function, do not walk to the def of a def, because we are |
| 910 | // handed something we already believe is the clobbering access. |
| 911 | MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef) |
| 912 | ? StartingUseOrDef->getDefiningAccess() |
| 913 | : StartingUseOrDef; |
| 914 | |
| 915 | MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q); |
| 916 | doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc); |
| 917 | DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is "); |
| 918 | DEBUG(dbgs() << *StartingUseOrDef << "\n"); |
| 919 | DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is "); |
| 920 | DEBUG(dbgs() << *Clobber << "\n"); |
| 921 | return Clobber; |
| 922 | } |
| 923 | |
| 924 | MemoryAccess * |
| 925 | CachingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) { |
| 926 | // There should be no way to lookup an instruction and get a phi as the |
| 927 | // access, since we only map BB's to PHI's. So, this must be a use or def. |
| 928 | auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I)); |
| 929 | |
| 930 | // We can't sanely do anything with a FenceInst, they conservatively |
| 931 | // clobber all memory, and have no locations to get pointers from to |
| 932 | // try to disambiguate |
| 933 | if (isa<FenceInst>(I)) |
| 934 | return StartingAccess; |
| 935 | |
| 936 | UpwardsMemoryQuery Q; |
| 937 | Q.OriginalAccess = StartingAccess; |
| 938 | Q.IsCall = bool(ImmutableCallSite(I)); |
| 939 | if (!Q.IsCall) |
| 940 | Q.StartingLoc = MemoryLocation::get(I); |
| 941 | Q.Inst = I; |
| 942 | Q.DL = &Q.Inst->getModule()->getDataLayout(); |
| 943 | if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc)) |
| 944 | return CacheResult; |
| 945 | |
| 946 | // Start with the thing we already think clobbers this location |
| 947 | MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess(); |
| 948 | |
| 949 | // At this point, DefiningAccess may be the live on entry def. |
| 950 | // If it is, we will not get a better result. |
| 951 | if (MSSA->isLiveOnEntryDef(DefiningAccess)) |
| 952 | return DefiningAccess; |
| 953 | |
| 954 | MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q); |
| 955 | doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc); |
| 956 | // TODO: When this implementation is more mature, we may want to figure out |
| 957 | // what this additional caching buys us. It's most likely A Good Thing. |
| 958 | if (Q.IsCall) |
| 959 | for (const MemoryAccess *MA : Q.VisitedCalls) |
| 960 | doCacheInsert(MA, Result, Q, Q.StartingLoc); |
| 961 | |
| 962 | DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is "); |
| 963 | DEBUG(dbgs() << *DefiningAccess << "\n"); |
| 964 | DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is "); |
| 965 | DEBUG(dbgs() << *Result << "\n"); |
| 966 | |
| 967 | return Result; |
| 968 | } |
| 969 | |
| 970 | MemoryAccess * |
| 971 | DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) { |
| 972 | MemoryAccess *MA = MSSA->getMemoryAccess(I); |
| 973 | if (auto *Use = dyn_cast<MemoryUseOrDef>(MA)) |
| 974 | return Use->getDefiningAccess(); |
| 975 | return MA; |
| 976 | } |
| 977 | |
| 978 | MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess( |
| 979 | MemoryAccess *StartingAccess, MemoryLocation &) { |
| 980 | if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess)) |
| 981 | return Use->getDefiningAccess(); |
| 982 | return StartingAccess; |
| 983 | } |
| 984 | } |