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" |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/SmallBitVector.h" |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/SmallPtrSet.h" |
| 22 | #include "llvm/ADT/SmallSet.h" |
| 23 | #include "llvm/ADT/Statistic.h" |
| 24 | #include "llvm/Analysis/AliasAnalysis.h" |
| 25 | #include "llvm/Analysis/CFG.h" |
| 26 | #include "llvm/Analysis/GlobalsModRef.h" |
| 27 | #include "llvm/Analysis/IteratedDominanceFrontier.h" |
| 28 | #include "llvm/Analysis/MemoryLocation.h" |
| 29 | #include "llvm/Analysis/PHITransAddr.h" |
| 30 | #include "llvm/IR/AssemblyAnnotationWriter.h" |
| 31 | #include "llvm/IR/DataLayout.h" |
| 32 | #include "llvm/IR/Dominators.h" |
| 33 | #include "llvm/IR/GlobalVariable.h" |
| 34 | #include "llvm/IR/IRBuilder.h" |
| 35 | #include "llvm/IR/IntrinsicInst.h" |
| 36 | #include "llvm/IR/LLVMContext.h" |
| 37 | #include "llvm/IR/Metadata.h" |
| 38 | #include "llvm/IR/Module.h" |
| 39 | #include "llvm/IR/PatternMatch.h" |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 40 | #include "llvm/Support/Debug.h" |
| 41 | #include "llvm/Support/FormattedStream.h" |
| 42 | #include "llvm/Transforms/Scalar.h" |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 43 | #include <algorithm> |
| 44 | |
| 45 | #define DEBUG_TYPE "memoryssa" |
| 46 | using namespace llvm; |
Geoff Berry | efb0dd1 | 2016-06-14 21:19:40 +0000 | [diff] [blame] | 47 | INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false, |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 48 | true) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 49 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 50 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
Geoff Berry | efb0dd1 | 2016-06-14 21:19:40 +0000 | [diff] [blame] | 51 | INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false, |
| 52 | true) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 53 | |
Chad Rosier | 232e29e | 2016-07-06 21:20:47 +0000 | [diff] [blame] | 54 | INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa", |
| 55 | "Memory SSA Printer", false, false) |
| 56 | INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) |
| 57 | INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa", |
| 58 | "Memory SSA Printer", false, false) |
| 59 | |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 60 | static cl::opt<unsigned> MaxCheckLimit( |
| 61 | "memssa-check-limit", cl::Hidden, cl::init(100), |
| 62 | cl::desc("The maximum number of stores/phis MemorySSA" |
| 63 | "will consider trying to walk past (default = 100)")); |
| 64 | |
Chad Rosier | 232e29e | 2016-07-06 21:20:47 +0000 | [diff] [blame] | 65 | static cl::opt<bool> |
| 66 | VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden, |
| 67 | cl::desc("Verify MemorySSA in legacy printer pass.")); |
| 68 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 69 | namespace llvm { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 70 | /// \brief An assembly annotator class to print Memory SSA information in |
| 71 | /// comments. |
| 72 | class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter { |
| 73 | friend class MemorySSA; |
| 74 | const MemorySSA *MSSA; |
| 75 | |
| 76 | public: |
| 77 | MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {} |
| 78 | |
| 79 | virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, |
| 80 | formatted_raw_ostream &OS) { |
| 81 | if (MemoryAccess *MA = MSSA->getMemoryAccess(BB)) |
| 82 | OS << "; " << *MA << "\n"; |
| 83 | } |
| 84 | |
| 85 | virtual void emitInstructionAnnot(const Instruction *I, |
| 86 | formatted_raw_ostream &OS) { |
| 87 | if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) |
| 88 | OS << "; " << *MA << "\n"; |
| 89 | } |
| 90 | }; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 91 | } |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 92 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 93 | namespace { |
Daniel Berlin | dff31de | 2016-08-02 21:57:52 +0000 | [diff] [blame] | 94 | /// Our current alias analysis API differentiates heavily between calls and |
| 95 | /// non-calls, and functions called on one usually assert on the other. |
| 96 | /// This class encapsulates the distinction to simplify other code that wants |
| 97 | /// "Memory affecting instructions and related data" to use as a key. |
| 98 | /// For example, this class is used as a densemap key in the use optimizer. |
| 99 | class MemoryLocOrCall { |
| 100 | public: |
| 101 | MemoryLocOrCall() : IsCall(false) {} |
| 102 | MemoryLocOrCall(MemoryUseOrDef *MUD) |
| 103 | : MemoryLocOrCall(MUD->getMemoryInst()) {} |
Sebastian Pop | 5068d7a | 2016-10-13 03:23:33 +0000 | [diff] [blame] | 104 | MemoryLocOrCall(const MemoryUseOrDef *MUD) |
| 105 | : MemoryLocOrCall(MUD->getMemoryInst()) {} |
Daniel Berlin | dff31de | 2016-08-02 21:57:52 +0000 | [diff] [blame] | 106 | |
| 107 | MemoryLocOrCall(Instruction *Inst) { |
| 108 | if (ImmutableCallSite(Inst)) { |
| 109 | IsCall = true; |
| 110 | CS = ImmutableCallSite(Inst); |
| 111 | } else { |
| 112 | IsCall = false; |
| 113 | // There is no such thing as a memorylocation for a fence inst, and it is |
| 114 | // unique in that regard. |
| 115 | if (!isa<FenceInst>(Inst)) |
| 116 | Loc = MemoryLocation::get(Inst); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | explicit MemoryLocOrCall(const MemoryLocation &Loc) |
| 121 | : IsCall(false), Loc(Loc) {} |
| 122 | |
| 123 | bool IsCall; |
| 124 | ImmutableCallSite getCS() const { |
| 125 | assert(IsCall); |
| 126 | return CS; |
| 127 | } |
| 128 | MemoryLocation getLoc() const { |
| 129 | assert(!IsCall); |
| 130 | return Loc; |
| 131 | } |
| 132 | |
| 133 | bool operator==(const MemoryLocOrCall &Other) const { |
| 134 | if (IsCall != Other.IsCall) |
| 135 | return false; |
| 136 | |
| 137 | if (IsCall) |
| 138 | return CS.getCalledValue() == Other.CS.getCalledValue(); |
| 139 | return Loc == Other.Loc; |
| 140 | } |
| 141 | |
| 142 | private: |
Daniel Berlin | f536113 | 2016-10-22 04:15:41 +0000 | [diff] [blame] | 143 | union { |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 144 | ImmutableCallSite CS; |
| 145 | MemoryLocation Loc; |
Daniel Berlin | f536113 | 2016-10-22 04:15:41 +0000 | [diff] [blame] | 146 | }; |
Daniel Berlin | dff31de | 2016-08-02 21:57:52 +0000 | [diff] [blame] | 147 | }; |
| 148 | } |
| 149 | |
| 150 | namespace llvm { |
| 151 | template <> struct DenseMapInfo<MemoryLocOrCall> { |
| 152 | static inline MemoryLocOrCall getEmptyKey() { |
| 153 | return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey()); |
| 154 | } |
| 155 | static inline MemoryLocOrCall getTombstoneKey() { |
| 156 | return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey()); |
| 157 | } |
| 158 | static unsigned getHashValue(const MemoryLocOrCall &MLOC) { |
| 159 | if (MLOC.IsCall) |
| 160 | return hash_combine(MLOC.IsCall, |
| 161 | DenseMapInfo<const Value *>::getHashValue( |
| 162 | MLOC.getCS().getCalledValue())); |
| 163 | return hash_combine( |
| 164 | MLOC.IsCall, DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc())); |
| 165 | } |
| 166 | static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) { |
| 167 | return LHS == RHS; |
| 168 | } |
| 169 | }; |
Daniel Berlin | df10119 | 2016-08-03 00:01:46 +0000 | [diff] [blame] | 170 | |
George Burgess IV | f767285 | 2016-08-03 19:59:11 +0000 | [diff] [blame] | 171 | enum class Reorderability { Always, IfNoAlias, Never }; |
George Burgess IV | 82e355c | 2016-08-03 19:39:54 +0000 | [diff] [blame] | 172 | |
| 173 | /// This does one-way checks to see if Use could theoretically be hoisted above |
| 174 | /// MayClobber. This will not check the other way around. |
| 175 | /// |
| 176 | /// This assumes that, for the purposes of MemorySSA, Use comes directly after |
| 177 | /// MayClobber, with no potentially clobbering operations in between them. |
| 178 | /// (Where potentially clobbering ops are memory barriers, aliased stores, etc.) |
| 179 | static Reorderability getLoadReorderability(const LoadInst *Use, |
| 180 | const LoadInst *MayClobber) { |
| 181 | bool VolatileUse = Use->isVolatile(); |
| 182 | bool VolatileClobber = MayClobber->isVolatile(); |
| 183 | // Volatile operations may never be reordered with other volatile operations. |
| 184 | if (VolatileUse && VolatileClobber) |
| 185 | return Reorderability::Never; |
| 186 | |
| 187 | // The lang ref allows reordering of volatile and non-volatile operations. |
| 188 | // Whether an aliasing nonvolatile load and volatile load can be reordered, |
| 189 | // though, is ambiguous. Because it may not be best to exploit this ambiguity, |
| 190 | // we only allow volatile/non-volatile reordering if the volatile and |
| 191 | // non-volatile operations don't alias. |
| 192 | Reorderability Result = VolatileUse || VolatileClobber |
| 193 | ? Reorderability::IfNoAlias |
| 194 | : Reorderability::Always; |
| 195 | |
| 196 | // If a load is seq_cst, it cannot be moved above other loads. If its ordering |
| 197 | // is weaker, it can be moved above other loads. We just need to be sure that |
| 198 | // MayClobber isn't an acquire load, because loads can't be moved above |
| 199 | // acquire loads. |
| 200 | // |
| 201 | // Note that this explicitly *does* allow the free reordering of monotonic (or |
| 202 | // weaker) loads of the same address. |
| 203 | bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent; |
| 204 | bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(), |
| 205 | AtomicOrdering::Acquire); |
| 206 | if (SeqCstUse || MayClobberIsAcquire) |
| 207 | return Reorderability::Never; |
| 208 | return Result; |
| 209 | } |
| 210 | |
Sebastian Pop | d57d93c | 2016-10-12 03:08:40 +0000 | [diff] [blame] | 211 | static bool instructionClobbersQuery(MemoryDef *MD, |
| 212 | const MemoryLocation &UseLoc, |
| 213 | const Instruction *UseInst, |
| 214 | AliasAnalysis &AA) { |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 215 | Instruction *DefInst = MD->getMemoryInst(); |
| 216 | assert(DefInst && "Defining instruction not actually an instruction"); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 217 | |
Daniel Berlin | df10119 | 2016-08-03 00:01:46 +0000 | [diff] [blame] | 218 | if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) { |
| 219 | // These intrinsics will show up as affecting memory, but they are just |
| 220 | // markers. |
| 221 | switch (II->getIntrinsicID()) { |
| 222 | case Intrinsic::lifetime_start: |
| 223 | case Intrinsic::lifetime_end: |
| 224 | case Intrinsic::invariant_start: |
| 225 | case Intrinsic::invariant_end: |
| 226 | case Intrinsic::assume: |
| 227 | return false; |
| 228 | default: |
| 229 | break; |
| 230 | } |
| 231 | } |
| 232 | |
Daniel Berlin | dff31de | 2016-08-02 21:57:52 +0000 | [diff] [blame] | 233 | ImmutableCallSite UseCS(UseInst); |
| 234 | if (UseCS) { |
| 235 | ModRefInfo I = AA.getModRefInfo(DefInst, UseCS); |
| 236 | return I != MRI_NoModRef; |
| 237 | } |
George Burgess IV | 82e355c | 2016-08-03 19:39:54 +0000 | [diff] [blame] | 238 | |
| 239 | if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) { |
| 240 | if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) { |
| 241 | switch (getLoadReorderability(UseLoad, DefLoad)) { |
| 242 | case Reorderability::Always: |
| 243 | return false; |
| 244 | case Reorderability::Never: |
| 245 | return true; |
| 246 | case Reorderability::IfNoAlias: |
| 247 | return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad)); |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
Daniel Berlin | dff31de | 2016-08-02 21:57:52 +0000 | [diff] [blame] | 252 | return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod; |
| 253 | } |
| 254 | |
Sebastian Pop | 5068d7a | 2016-10-13 03:23:33 +0000 | [diff] [blame] | 255 | static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU, |
| 256 | const MemoryLocOrCall &UseMLOC, |
| 257 | AliasAnalysis &AA) { |
| 258 | // FIXME: This is a temporary hack to allow a single instructionClobbersQuery |
| 259 | // to exist while MemoryLocOrCall is pushed through places. |
| 260 | if (UseMLOC.IsCall) |
| 261 | return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(), |
| 262 | AA); |
| 263 | return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(), |
| 264 | AA); |
| 265 | } |
| 266 | |
Sebastian Pop | 5ba9f24 | 2016-10-13 01:39:10 +0000 | [diff] [blame] | 267 | // Return true when MD may alias MU, return false otherwise. |
Daniel Berlin | dcb004f | 2017-03-02 23:06:46 +0000 | [diff] [blame] | 268 | bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, |
| 269 | AliasAnalysis &AA) { |
Sebastian Pop | 5068d7a | 2016-10-13 03:23:33 +0000 | [diff] [blame] | 270 | return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA); |
Sebastian Pop | 5ba9f24 | 2016-10-13 01:39:10 +0000 | [diff] [blame] | 271 | } |
| 272 | } |
| 273 | |
| 274 | namespace { |
| 275 | struct UpwardsMemoryQuery { |
| 276 | // True if our original query started off as a call |
| 277 | bool IsCall; |
| 278 | // The pointer location we started the query with. This will be empty if |
| 279 | // IsCall is true. |
| 280 | MemoryLocation StartingLoc; |
| 281 | // This is the instruction we were querying about. |
| 282 | const Instruction *Inst; |
| 283 | // The MemoryAccess we actually got called with, used to test local domination |
| 284 | const MemoryAccess *OriginalAccess; |
| 285 | |
| 286 | UpwardsMemoryQuery() |
| 287 | : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {} |
| 288 | |
| 289 | UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access) |
| 290 | : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) { |
| 291 | if (!IsCall) |
| 292 | StartingLoc = MemoryLocation::get(Inst); |
| 293 | } |
| 294 | }; |
| 295 | |
| 296 | static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc, |
| 297 | AliasAnalysis &AA) { |
| 298 | Instruction *Inst = MD->getMemoryInst(); |
| 299 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { |
| 300 | switch (II->getIntrinsicID()) { |
| 301 | case Intrinsic::lifetime_start: |
| 302 | case Intrinsic::lifetime_end: |
| 303 | return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc); |
| 304 | default: |
| 305 | return false; |
| 306 | } |
| 307 | } |
| 308 | return false; |
| 309 | } |
| 310 | |
| 311 | static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA, |
| 312 | const Instruction *I) { |
| 313 | // If the memory can't be changed, then loads of the memory can't be |
| 314 | // clobbered. |
| 315 | // |
| 316 | // FIXME: We should handle invariant groups, as well. It's a bit harder, |
| 317 | // because we need to pay close attention to invariant group barriers. |
| 318 | return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) || |
| 319 | AA.pointsToConstantMemory(I)); |
| 320 | } |
| 321 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 322 | /// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing |
| 323 | /// inbetween `Start` and `ClobberAt` can clobbers `Start`. |
| 324 | /// |
| 325 | /// This is meant to be as simple and self-contained as possible. Because it |
| 326 | /// uses no cache, etc., it can be relatively expensive. |
| 327 | /// |
| 328 | /// \param Start The MemoryAccess that we want to walk from. |
| 329 | /// \param ClobberAt A clobber for Start. |
| 330 | /// \param StartLoc The MemoryLocation for Start. |
| 331 | /// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to. |
| 332 | /// \param Query The UpwardsMemoryQuery we used for our search. |
| 333 | /// \param AA The AliasAnalysis we used for our search. |
| 334 | static void LLVM_ATTRIBUTE_UNUSED |
| 335 | checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt, |
| 336 | const MemoryLocation &StartLoc, const MemorySSA &MSSA, |
| 337 | const UpwardsMemoryQuery &Query, AliasAnalysis &AA) { |
| 338 | assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?"); |
| 339 | |
| 340 | if (MSSA.isLiveOnEntryDef(Start)) { |
| 341 | assert(MSSA.isLiveOnEntryDef(ClobberAt) && |
| 342 | "liveOnEntry must clobber itself"); |
| 343 | return; |
| 344 | } |
| 345 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 346 | bool FoundClobber = false; |
| 347 | DenseSet<MemoryAccessPair> VisitedPhis; |
| 348 | SmallVector<MemoryAccessPair, 8> Worklist; |
| 349 | Worklist.emplace_back(Start, StartLoc); |
| 350 | // Walk all paths from Start to ClobberAt, while looking for clobbers. If one |
| 351 | // is found, complain. |
| 352 | while (!Worklist.empty()) { |
| 353 | MemoryAccessPair MAP = Worklist.pop_back_val(); |
| 354 | // All we care about is that nothing from Start to ClobberAt clobbers Start. |
| 355 | // We learn nothing from revisiting nodes. |
| 356 | if (!VisitedPhis.insert(MAP).second) |
| 357 | continue; |
| 358 | |
| 359 | for (MemoryAccess *MA : def_chain(MAP.first)) { |
| 360 | if (MA == ClobberAt) { |
| 361 | if (auto *MD = dyn_cast<MemoryDef>(MA)) { |
| 362 | // instructionClobbersQuery isn't essentially free, so don't use `|=`, |
| 363 | // since it won't let us short-circuit. |
| 364 | // |
| 365 | // Also, note that this can't be hoisted out of the `Worklist` loop, |
| 366 | // since MD may only act as a clobber for 1 of N MemoryLocations. |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 367 | FoundClobber = |
| 368 | FoundClobber || MSSA.isLiveOnEntryDef(MD) || |
| 369 | instructionClobbersQuery(MD, MAP.second, Query.Inst, AA); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 370 | } |
| 371 | break; |
| 372 | } |
| 373 | |
| 374 | // We should never hit liveOnEntry, unless it's the clobber. |
| 375 | assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?"); |
| 376 | |
| 377 | if (auto *MD = dyn_cast<MemoryDef>(MA)) { |
| 378 | (void)MD; |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 379 | assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) && |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 380 | "Found clobber before reaching ClobberAt!"); |
| 381 | continue; |
| 382 | } |
| 383 | |
| 384 | assert(isa<MemoryPhi>(MA)); |
| 385 | Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end()); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | // If ClobberAt is a MemoryPhi, we can assume something above it acted as a |
| 390 | // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point. |
| 391 | assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) && |
| 392 | "ClobberAt never acted as a clobber"); |
| 393 | } |
| 394 | |
| 395 | /// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up |
| 396 | /// in one class. |
| 397 | class ClobberWalker { |
| 398 | /// Save a few bytes by using unsigned instead of size_t. |
| 399 | using ListIndex = unsigned; |
| 400 | |
| 401 | /// Represents a span of contiguous MemoryDefs, potentially ending in a |
| 402 | /// MemoryPhi. |
| 403 | struct DefPath { |
| 404 | MemoryLocation Loc; |
| 405 | // Note that, because we always walk in reverse, Last will always dominate |
| 406 | // First. Also note that First and Last are inclusive. |
| 407 | MemoryAccess *First; |
| 408 | MemoryAccess *Last; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 409 | Optional<ListIndex> Previous; |
| 410 | |
| 411 | DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last, |
| 412 | Optional<ListIndex> Previous) |
| 413 | : Loc(Loc), First(First), Last(Last), Previous(Previous) {} |
| 414 | |
| 415 | DefPath(const MemoryLocation &Loc, MemoryAccess *Init, |
| 416 | Optional<ListIndex> Previous) |
| 417 | : DefPath(Loc, Init, Init, Previous) {} |
| 418 | }; |
| 419 | |
| 420 | const MemorySSA &MSSA; |
| 421 | AliasAnalysis &AA; |
| 422 | DominatorTree &DT; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 423 | UpwardsMemoryQuery *Query; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 424 | |
| 425 | // Phi optimization bookkeeping |
| 426 | SmallVector<DefPath, 32> Paths; |
| 427 | DenseSet<ConstMemoryAccessPair> VisitedPhis; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 428 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 429 | /// Find the nearest def or phi that `From` can legally be optimized to. |
Daniel Berlin | d042031 | 2017-04-01 09:01:12 +0000 | [diff] [blame] | 430 | const MemoryAccess *getWalkTarget(const MemoryPhi *From) const { |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 431 | assert(From->getNumOperands() && "Phi with no operands?"); |
| 432 | |
| 433 | BasicBlock *BB = From->getBlock(); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 434 | MemoryAccess *Result = MSSA.getLiveOnEntryDef(); |
| 435 | DomTreeNode *Node = DT.getNode(BB); |
| 436 | while ((Node = Node->getIDom())) { |
Daniel Berlin | 7500c56 | 2017-04-01 08:59:45 +0000 | [diff] [blame] | 437 | auto *Defs = MSSA.getBlockDefs(Node->getBlock()); |
| 438 | if (Defs) |
Daniel Berlin | d042031 | 2017-04-01 09:01:12 +0000 | [diff] [blame] | 439 | return &*Defs->rbegin(); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 440 | } |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 441 | return Result; |
| 442 | } |
| 443 | |
| 444 | /// Result of calling walkToPhiOrClobber. |
| 445 | struct UpwardsWalkResult { |
| 446 | /// The "Result" of the walk. Either a clobber, the last thing we walked, or |
| 447 | /// both. |
| 448 | MemoryAccess *Result; |
| 449 | bool IsKnownClobber; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 450 | }; |
| 451 | |
| 452 | /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last. |
| 453 | /// This will update Desc.Last as it walks. It will (optionally) also stop at |
| 454 | /// StopAt. |
| 455 | /// |
| 456 | /// This does not test for whether StopAt is a clobber |
Daniel Berlin | d042031 | 2017-04-01 09:01:12 +0000 | [diff] [blame] | 457 | UpwardsWalkResult |
| 458 | walkToPhiOrClobber(DefPath &Desc, |
| 459 | const MemoryAccess *StopAt = nullptr) const { |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 460 | assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world"); |
| 461 | |
| 462 | for (MemoryAccess *Current : def_chain(Desc.Last)) { |
| 463 | Desc.Last = Current; |
| 464 | if (Current == StopAt) |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 465 | return {Current, false}; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 466 | |
| 467 | if (auto *MD = dyn_cast<MemoryDef>(Current)) |
| 468 | if (MSSA.isLiveOnEntryDef(MD) || |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 469 | instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA)) |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 470 | return {MD, true}; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 471 | } |
| 472 | |
| 473 | assert(isa<MemoryPhi>(Desc.Last) && |
| 474 | "Ended at a non-clobber that's not a phi?"); |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 475 | return {Desc.Last, false}; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 476 | } |
| 477 | |
| 478 | void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches, |
| 479 | ListIndex PriorNode) { |
| 480 | auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}), |
| 481 | upward_defs_end()); |
| 482 | for (const MemoryAccessPair &P : UpwardDefs) { |
| 483 | PausedSearches.push_back(Paths.size()); |
| 484 | Paths.emplace_back(P.second, P.first, PriorNode); |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | /// Represents a search that terminated after finding a clobber. This clobber |
| 489 | /// may or may not be present in the path of defs from LastNode..SearchStart, |
| 490 | /// since it may have been retrieved from cache. |
| 491 | struct TerminatedPath { |
| 492 | MemoryAccess *Clobber; |
| 493 | ListIndex LastNode; |
| 494 | }; |
| 495 | |
| 496 | /// Get an access that keeps us from optimizing to the given phi. |
| 497 | /// |
| 498 | /// PausedSearches is an array of indices into the Paths array. Its incoming |
| 499 | /// value is the indices of searches that stopped at the last phi optimization |
| 500 | /// target. It's left in an unspecified state. |
| 501 | /// |
| 502 | /// If this returns None, NewPaused is a vector of searches that terminated |
| 503 | /// at StopWhere. Otherwise, NewPaused is left in an unspecified state. |
George Burgess IV | 14633b5 | 2016-08-03 01:22:19 +0000 | [diff] [blame] | 504 | Optional<TerminatedPath> |
Daniel Berlin | d042031 | 2017-04-01 09:01:12 +0000 | [diff] [blame] | 505 | getBlockingAccess(const MemoryAccess *StopWhere, |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 506 | SmallVectorImpl<ListIndex> &PausedSearches, |
| 507 | SmallVectorImpl<ListIndex> &NewPaused, |
| 508 | SmallVectorImpl<TerminatedPath> &Terminated) { |
| 509 | assert(!PausedSearches.empty() && "No searches to continue?"); |
| 510 | |
| 511 | // BFS vs DFS really doesn't make a difference here, so just do a DFS with |
| 512 | // PausedSearches as our stack. |
| 513 | while (!PausedSearches.empty()) { |
| 514 | ListIndex PathIndex = PausedSearches.pop_back_val(); |
| 515 | DefPath &Node = Paths[PathIndex]; |
| 516 | |
| 517 | // If we've already visited this path with this MemoryLocation, we don't |
| 518 | // need to do so again. |
| 519 | // |
| 520 | // NOTE: That we just drop these paths on the ground makes caching |
| 521 | // behavior sporadic. e.g. given a diamond: |
| 522 | // A |
| 523 | // B C |
| 524 | // D |
| 525 | // |
| 526 | // ...If we walk D, B, A, C, we'll only cache the result of phi |
| 527 | // optimization for A, B, and D; C will be skipped because it dies here. |
| 528 | // This arguably isn't the worst thing ever, since: |
| 529 | // - We generally query things in a top-down order, so if we got below D |
| 530 | // without needing cache entries for {C, MemLoc}, then chances are |
| 531 | // that those cache entries would end up ultimately unused. |
| 532 | // - We still cache things for A, so C only needs to walk up a bit. |
| 533 | // If this behavior becomes problematic, we can fix without a ton of extra |
| 534 | // work. |
| 535 | if (!VisitedPhis.insert({Node.Last, Node.Loc}).second) |
| 536 | continue; |
| 537 | |
| 538 | UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere); |
| 539 | if (Res.IsKnownClobber) { |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 540 | assert(Res.Result != StopWhere); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 541 | // If this wasn't a cache hit, we hit a clobber when walking. That's a |
| 542 | // failure. |
George Burgess IV | 14633b5 | 2016-08-03 01:22:19 +0000 | [diff] [blame] | 543 | TerminatedPath Term{Res.Result, PathIndex}; |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 544 | if (!MSSA.dominates(Res.Result, StopWhere)) |
George Burgess IV | 14633b5 | 2016-08-03 01:22:19 +0000 | [diff] [blame] | 545 | return Term; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 546 | |
| 547 | // Otherwise, it's a valid thing to potentially optimize to. |
George Burgess IV | 14633b5 | 2016-08-03 01:22:19 +0000 | [diff] [blame] | 548 | Terminated.push_back(Term); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 549 | continue; |
| 550 | } |
| 551 | |
| 552 | if (Res.Result == StopWhere) { |
| 553 | // We've hit our target. Save this path off for if we want to continue |
| 554 | // walking. |
| 555 | NewPaused.push_back(PathIndex); |
| 556 | continue; |
| 557 | } |
| 558 | |
| 559 | assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber"); |
| 560 | addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex); |
| 561 | } |
| 562 | |
| 563 | return None; |
| 564 | } |
| 565 | |
| 566 | template <typename T, typename Walker> |
| 567 | struct generic_def_path_iterator |
| 568 | : public iterator_facade_base<generic_def_path_iterator<T, Walker>, |
| 569 | std::forward_iterator_tag, T *> { |
| 570 | generic_def_path_iterator() : W(nullptr), N(None) {} |
| 571 | generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {} |
| 572 | |
| 573 | T &operator*() const { return curNode(); } |
| 574 | |
| 575 | generic_def_path_iterator &operator++() { |
| 576 | N = curNode().Previous; |
| 577 | return *this; |
| 578 | } |
| 579 | |
| 580 | bool operator==(const generic_def_path_iterator &O) const { |
| 581 | if (N.hasValue() != O.N.hasValue()) |
| 582 | return false; |
| 583 | return !N.hasValue() || *N == *O.N; |
| 584 | } |
| 585 | |
| 586 | private: |
| 587 | T &curNode() const { return W->Paths[*N]; } |
| 588 | |
| 589 | Walker *W; |
| 590 | Optional<ListIndex> N; |
| 591 | }; |
| 592 | |
| 593 | using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>; |
| 594 | using const_def_path_iterator = |
| 595 | generic_def_path_iterator<const DefPath, const ClobberWalker>; |
| 596 | |
| 597 | iterator_range<def_path_iterator> def_path(ListIndex From) { |
| 598 | return make_range(def_path_iterator(this, From), def_path_iterator()); |
| 599 | } |
| 600 | |
| 601 | iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const { |
| 602 | return make_range(const_def_path_iterator(this, From), |
| 603 | const_def_path_iterator()); |
| 604 | } |
| 605 | |
| 606 | struct OptznResult { |
| 607 | /// The path that contains our result. |
| 608 | TerminatedPath PrimaryClobber; |
| 609 | /// The paths that we can legally cache back from, but that aren't |
| 610 | /// necessarily the result of the Phi optimization. |
| 611 | SmallVector<TerminatedPath, 4> OtherClobbers; |
| 612 | }; |
| 613 | |
| 614 | ListIndex defPathIndex(const DefPath &N) const { |
| 615 | // The assert looks nicer if we don't need to do &N |
| 616 | const DefPath *NP = &N; |
| 617 | assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() && |
| 618 | "Out of bounds DefPath!"); |
| 619 | return NP - &Paths.front(); |
| 620 | } |
| 621 | |
| 622 | /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths |
| 623 | /// that act as legal clobbers. Note that this won't return *all* clobbers. |
| 624 | /// |
| 625 | /// Phi optimization algorithm tl;dr: |
| 626 | /// - Find the earliest def/phi, A, we can optimize to |
| 627 | /// - Find if all paths from the starting memory access ultimately reach A |
| 628 | /// - If not, optimization isn't possible. |
| 629 | /// - Otherwise, walk from A to another clobber or phi, A'. |
| 630 | /// - If A' is a def, we're done. |
| 631 | /// - If A' is a phi, try to optimize it. |
| 632 | /// |
| 633 | /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path |
| 634 | /// terminates when a MemoryAccess that clobbers said MemoryLocation is found. |
| 635 | OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start, |
| 636 | const MemoryLocation &Loc) { |
| 637 | assert(Paths.empty() && VisitedPhis.empty() && |
| 638 | "Reset the optimization state."); |
| 639 | |
| 640 | Paths.emplace_back(Loc, Start, Phi, None); |
| 641 | // Stores how many "valid" optimization nodes we had prior to calling |
| 642 | // addSearches/getBlockingAccess. Necessary for caching if we had a blocker. |
| 643 | auto PriorPathsSize = Paths.size(); |
| 644 | |
| 645 | SmallVector<ListIndex, 16> PausedSearches; |
| 646 | SmallVector<ListIndex, 8> NewPaused; |
| 647 | SmallVector<TerminatedPath, 4> TerminatedPaths; |
| 648 | |
| 649 | addSearches(Phi, PausedSearches, 0); |
| 650 | |
| 651 | // Moves the TerminatedPath with the "most dominated" Clobber to the end of |
| 652 | // Paths. |
| 653 | auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) { |
| 654 | assert(!Paths.empty() && "Need a path to move"); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 655 | auto Dom = Paths.begin(); |
| 656 | for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I) |
| 657 | if (!MSSA.dominates(I->Clobber, Dom->Clobber)) |
| 658 | Dom = I; |
| 659 | auto Last = Paths.end() - 1; |
| 660 | if (Last != Dom) |
| 661 | std::iter_swap(Last, Dom); |
| 662 | }; |
| 663 | |
| 664 | MemoryPhi *Current = Phi; |
| 665 | while (1) { |
| 666 | assert(!MSSA.isLiveOnEntryDef(Current) && |
| 667 | "liveOnEntry wasn't treated as a clobber?"); |
| 668 | |
Daniel Berlin | d042031 | 2017-04-01 09:01:12 +0000 | [diff] [blame] | 669 | const auto *Target = getWalkTarget(Current); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 670 | // If a TerminatedPath doesn't dominate Target, then it wasn't a legal |
| 671 | // optimization for the prior phi. |
| 672 | assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) { |
| 673 | return MSSA.dominates(P.Clobber, Target); |
| 674 | })); |
| 675 | |
| 676 | // FIXME: This is broken, because the Blocker may be reported to be |
| 677 | // liveOnEntry, and we'll happily wait for that to disappear (read: never) |
George Burgess IV | 7f414b9 | 2016-08-22 23:40:01 +0000 | [diff] [blame] | 678 | // For the moment, this is fine, since we do nothing with blocker info. |
George Burgess IV | 14633b5 | 2016-08-03 01:22:19 +0000 | [diff] [blame] | 679 | if (Optional<TerminatedPath> Blocker = getBlockingAccess( |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 680 | Target, PausedSearches, NewPaused, TerminatedPaths)) { |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 681 | |
| 682 | // Find the node we started at. We can't search based on N->Last, since |
| 683 | // we may have gone around a loop with a different MemoryLocation. |
George Burgess IV | 14633b5 | 2016-08-03 01:22:19 +0000 | [diff] [blame] | 684 | auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) { |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 685 | return defPathIndex(N) < PriorPathsSize; |
| 686 | }); |
| 687 | assert(Iter != def_path_iterator()); |
| 688 | |
| 689 | DefPath &CurNode = *Iter; |
| 690 | assert(CurNode.Last == Current); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 691 | |
| 692 | // Two things: |
| 693 | // A. We can't reliably cache all of NewPaused back. Consider a case |
| 694 | // where we have two paths in NewPaused; one of which can't optimize |
| 695 | // above this phi, whereas the other can. If we cache the second path |
| 696 | // back, we'll end up with suboptimal cache entries. We can handle |
| 697 | // cases like this a bit better when we either try to find all |
| 698 | // clobbers that block phi optimization, or when our cache starts |
| 699 | // supporting unfinished searches. |
| 700 | // B. We can't reliably cache TerminatedPaths back here without doing |
| 701 | // extra checks; consider a case like: |
| 702 | // T |
| 703 | // / \ |
| 704 | // D C |
| 705 | // \ / |
| 706 | // S |
| 707 | // Where T is our target, C is a node with a clobber on it, D is a |
| 708 | // diamond (with a clobber *only* on the left or right node, N), and |
| 709 | // S is our start. Say we walk to D, through the node opposite N |
| 710 | // (read: ignoring the clobber), and see a cache entry in the top |
| 711 | // node of D. That cache entry gets put into TerminatedPaths. We then |
| 712 | // walk up to C (N is later in our worklist), find the clobber, and |
| 713 | // quit. If we append TerminatedPaths to OtherClobbers, we'll cache |
| 714 | // the bottom part of D to the cached clobber, ignoring the clobber |
| 715 | // in N. Again, this problem goes away if we start tracking all |
| 716 | // blockers for a given phi optimization. |
| 717 | TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)}; |
| 718 | return {Result, {}}; |
| 719 | } |
| 720 | |
| 721 | // If there's nothing left to search, then all paths led to valid clobbers |
| 722 | // that we got from our cache; pick the nearest to the start, and allow |
| 723 | // the rest to be cached back. |
| 724 | if (NewPaused.empty()) { |
| 725 | MoveDominatedPathToEnd(TerminatedPaths); |
| 726 | TerminatedPath Result = TerminatedPaths.pop_back_val(); |
| 727 | return {Result, std::move(TerminatedPaths)}; |
| 728 | } |
| 729 | |
| 730 | MemoryAccess *DefChainEnd = nullptr; |
| 731 | SmallVector<TerminatedPath, 4> Clobbers; |
| 732 | for (ListIndex Paused : NewPaused) { |
| 733 | UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]); |
| 734 | if (WR.IsKnownClobber) |
| 735 | Clobbers.push_back({WR.Result, Paused}); |
| 736 | else |
| 737 | // Micro-opt: If we hit the end of the chain, save it. |
| 738 | DefChainEnd = WR.Result; |
| 739 | } |
| 740 | |
| 741 | if (!TerminatedPaths.empty()) { |
| 742 | // If we couldn't find the dominating phi/liveOnEntry in the above loop, |
| 743 | // do it now. |
| 744 | if (!DefChainEnd) |
Daniel Berlin | d042031 | 2017-04-01 09:01:12 +0000 | [diff] [blame] | 745 | for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target))) |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 746 | DefChainEnd = MA; |
| 747 | |
| 748 | // If any of the terminated paths don't dominate the phi we'll try to |
| 749 | // optimize, we need to figure out what they are and quit. |
| 750 | const BasicBlock *ChainBB = DefChainEnd->getBlock(); |
| 751 | for (const TerminatedPath &TP : TerminatedPaths) { |
| 752 | // Because we know that DefChainEnd is as "high" as we can go, we |
| 753 | // don't need local dominance checks; BB dominance is sufficient. |
| 754 | if (DT.dominates(ChainBB, TP.Clobber->getBlock())) |
| 755 | Clobbers.push_back(TP); |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | // If we have clobbers in the def chain, find the one closest to Current |
| 760 | // and quit. |
| 761 | if (!Clobbers.empty()) { |
| 762 | MoveDominatedPathToEnd(Clobbers); |
| 763 | TerminatedPath Result = Clobbers.pop_back_val(); |
| 764 | return {Result, std::move(Clobbers)}; |
| 765 | } |
| 766 | |
| 767 | assert(all_of(NewPaused, |
| 768 | [&](ListIndex I) { return Paths[I].Last == DefChainEnd; })); |
| 769 | |
| 770 | // Because liveOnEntry is a clobber, this must be a phi. |
| 771 | auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd); |
| 772 | |
| 773 | PriorPathsSize = Paths.size(); |
| 774 | PausedSearches.clear(); |
| 775 | for (ListIndex I : NewPaused) |
| 776 | addSearches(DefChainPhi, PausedSearches, I); |
| 777 | NewPaused.clear(); |
| 778 | |
| 779 | Current = DefChainPhi; |
| 780 | } |
| 781 | } |
| 782 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 783 | void verifyOptResult(const OptznResult &R) const { |
| 784 | assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) { |
| 785 | return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber); |
| 786 | })); |
| 787 | } |
| 788 | |
| 789 | void resetPhiOptznState() { |
| 790 | Paths.clear(); |
| 791 | VisitedPhis.clear(); |
| 792 | } |
| 793 | |
| 794 | public: |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 795 | ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT) |
| 796 | : MSSA(MSSA), AA(AA), DT(DT) {} |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 797 | |
Daniel Berlin | 7500c56 | 2017-04-01 08:59:45 +0000 | [diff] [blame] | 798 | void reset() {} |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 799 | |
| 800 | /// Finds the nearest clobber for the given query, optimizing phis if |
| 801 | /// possible. |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 802 | MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q) { |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 803 | Query = &Q; |
| 804 | |
| 805 | MemoryAccess *Current = Start; |
| 806 | // This walker pretends uses don't exist. If we're handed one, silently grab |
| 807 | // its def. (This has the nice side-effect of ensuring we never cache uses) |
| 808 | if (auto *MU = dyn_cast<MemoryUse>(Start)) |
| 809 | Current = MU->getDefiningAccess(); |
| 810 | |
| 811 | DefPath FirstDesc(Q.StartingLoc, Current, Current, None); |
| 812 | // Fast path for the overly-common case (no crazy phi optimization |
| 813 | // necessary) |
| 814 | UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc); |
George Burgess IV | 93ea19b | 2016-07-24 07:03:49 +0000 | [diff] [blame] | 815 | MemoryAccess *Result; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 816 | if (WalkResult.IsKnownClobber) { |
George Burgess IV | 93ea19b | 2016-07-24 07:03:49 +0000 | [diff] [blame] | 817 | Result = WalkResult.Result; |
| 818 | } else { |
| 819 | OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last), |
| 820 | Current, Q.StartingLoc); |
| 821 | verifyOptResult(OptRes); |
George Burgess IV | 93ea19b | 2016-07-24 07:03:49 +0000 | [diff] [blame] | 822 | resetPhiOptznState(); |
| 823 | Result = OptRes.PrimaryClobber.Clobber; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 824 | } |
| 825 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 826 | #ifdef EXPENSIVE_CHECKS |
George Burgess IV | 93ea19b | 2016-07-24 07:03:49 +0000 | [diff] [blame] | 827 | checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 828 | #endif |
George Burgess IV | 93ea19b | 2016-07-24 07:03:49 +0000 | [diff] [blame] | 829 | return Result; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 830 | } |
Geoff Berry | cdf5333 | 2016-08-08 17:52:01 +0000 | [diff] [blame] | 831 | |
| 832 | void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); } |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 833 | }; |
| 834 | |
| 835 | struct RenamePassData { |
| 836 | DomTreeNode *DTN; |
| 837 | DomTreeNode::const_iterator ChildIt; |
| 838 | MemoryAccess *IncomingVal; |
| 839 | |
| 840 | RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It, |
| 841 | MemoryAccess *M) |
| 842 | : DTN(D), ChildIt(It), IncomingVal(M) {} |
| 843 | void swap(RenamePassData &RHS) { |
| 844 | std::swap(DTN, RHS.DTN); |
| 845 | std::swap(ChildIt, RHS.ChildIt); |
| 846 | std::swap(IncomingVal, RHS.IncomingVal); |
| 847 | } |
| 848 | }; |
| 849 | } // anonymous namespace |
| 850 | |
| 851 | namespace llvm { |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 852 | /// \brief A MemorySSAWalker that does AA walks to disambiguate accesses. It no longer does caching on its own, |
| 853 | /// but the name has been retained for the moment. |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 854 | class MemorySSA::CachingWalker final : public MemorySSAWalker { |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 855 | ClobberWalker Walker; |
| 856 | bool AutoResetWalker; |
| 857 | |
| 858 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &); |
| 859 | void verifyRemoved(MemoryAccess *); |
| 860 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 861 | public: |
| 862 | CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *); |
| 863 | ~CachingWalker() override; |
| 864 | |
George Burgess IV | 400ae40 | 2016-07-20 19:51:34 +0000 | [diff] [blame] | 865 | using MemorySSAWalker::getClobberingMemoryAccess; |
| 866 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override; |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 867 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, |
George Burgess IV | 013fd73 | 2016-10-28 19:22:46 +0000 | [diff] [blame] | 868 | const MemoryLocation &) override; |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 869 | void invalidateInfo(MemoryAccess *) override; |
| 870 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 871 | /// Whether we call resetClobberWalker() after each time we *actually* walk to |
| 872 | /// answer a clobber query. |
| 873 | void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; } |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 874 | |
Daniel Berlin | 7500c56 | 2017-04-01 08:59:45 +0000 | [diff] [blame] | 875 | /// Drop the walker's persistent data structures. |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 876 | void resetClobberWalker() { Walker.reset(); } |
Geoff Berry | cdf5333 | 2016-08-08 17:52:01 +0000 | [diff] [blame] | 877 | |
| 878 | void verify(const MemorySSA *MSSA) override { |
| 879 | MemorySSAWalker::verify(MSSA); |
| 880 | Walker.verify(MSSA); |
| 881 | } |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 882 | }; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 883 | |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 884 | void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal, |
| 885 | bool RenameAllUses) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 886 | // Pass through values to our successors |
| 887 | for (const BasicBlock *S : successors(BB)) { |
| 888 | auto It = PerBlockAccesses.find(S); |
| 889 | // Rename the phi nodes in our successor block |
| 890 | if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front())) |
| 891 | continue; |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 892 | AccessList *Accesses = It->second.get(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 893 | auto *Phi = cast<MemoryPhi>(&Accesses->front()); |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 894 | if (RenameAllUses) { |
| 895 | int PhiIndex = Phi->getBasicBlockIndex(BB); |
| 896 | assert(PhiIndex != -1 && "Incomplete phi during partial rename"); |
| 897 | Phi->setIncomingValue(PhiIndex, IncomingVal); |
| 898 | } else |
| 899 | Phi->addIncoming(IncomingVal, BB); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 900 | } |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 901 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 902 | |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 903 | /// \brief Rename a single basic block into MemorySSA form. |
| 904 | /// Uses the standard SSA renaming algorithm. |
| 905 | /// \returns The new incoming value. |
| 906 | MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal, |
| 907 | bool RenameAllUses) { |
| 908 | auto It = PerBlockAccesses.find(BB); |
| 909 | // Skip most processing if the list is empty. |
| 910 | if (It != PerBlockAccesses.end()) { |
| 911 | AccessList *Accesses = It->second.get(); |
| 912 | for (MemoryAccess &L : *Accesses) { |
| 913 | if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) { |
| 914 | if (MUD->getDefiningAccess() == nullptr || RenameAllUses) |
| 915 | MUD->setDefiningAccess(IncomingVal); |
| 916 | if (isa<MemoryDef>(&L)) |
| 917 | IncomingVal = &L; |
| 918 | } else { |
| 919 | IncomingVal = &L; |
| 920 | } |
| 921 | } |
| 922 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 923 | return IncomingVal; |
| 924 | } |
| 925 | |
| 926 | /// \brief This is the standard SSA renaming algorithm. |
| 927 | /// |
| 928 | /// We walk the dominator tree in preorder, renaming accesses, and then filling |
| 929 | /// in phi nodes in our successors. |
| 930 | void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal, |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 931 | SmallPtrSetImpl<BasicBlock *> &Visited, |
| 932 | bool SkipVisited, bool RenameAllUses) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 933 | SmallVector<RenamePassData, 32> WorkStack; |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 934 | // Skip everything if we already renamed this block and we are skipping. |
| 935 | // Note: You can't sink this into the if, because we need it to occur |
| 936 | // regardless of whether we skip blocks or not. |
| 937 | bool AlreadyVisited = !Visited.insert(Root->getBlock()).second; |
| 938 | if (SkipVisited && AlreadyVisited) |
| 939 | return; |
| 940 | |
| 941 | IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses); |
| 942 | renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 943 | WorkStack.push_back({Root, Root->begin(), IncomingVal}); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 944 | |
| 945 | while (!WorkStack.empty()) { |
| 946 | DomTreeNode *Node = WorkStack.back().DTN; |
| 947 | DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt; |
| 948 | IncomingVal = WorkStack.back().IncomingVal; |
| 949 | |
| 950 | if (ChildIt == Node->end()) { |
| 951 | WorkStack.pop_back(); |
| 952 | } else { |
| 953 | DomTreeNode *Child = *ChildIt; |
| 954 | ++WorkStack.back().ChildIt; |
| 955 | BasicBlock *BB = Child->getBlock(); |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 956 | // Note: You can't sink this into the if, because we need it to occur |
| 957 | // regardless of whether we skip blocks or not. |
| 958 | AlreadyVisited = !Visited.insert(BB).second; |
| 959 | if (SkipVisited && AlreadyVisited) { |
| 960 | // We already visited this during our renaming, which can happen when |
| 961 | // being asked to rename multiple blocks. Figure out the incoming val, |
| 962 | // which is the last def. |
| 963 | // Incoming value can only change if there is a block def, and in that |
| 964 | // case, it's the last block def in the list. |
| 965 | if (auto *BlockDefs = getWritableBlockDefs(BB)) |
| 966 | IncomingVal = &*BlockDefs->rbegin(); |
| 967 | } else |
| 968 | IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses); |
| 969 | renameSuccessorPhis(BB, IncomingVal, RenameAllUses); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 970 | WorkStack.push_back({Child, Child->begin(), IncomingVal}); |
| 971 | } |
| 972 | } |
| 973 | } |
| 974 | |
| 975 | /// \brief Compute dominator levels, used by the phi insertion algorithm above. |
| 976 | void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) { |
| 977 | for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode()); |
| 978 | DFI != DFE; ++DFI) |
| 979 | DomLevels[*DFI] = DFI.getPathLength() - 1; |
| 980 | } |
| 981 | |
George Burgess IV | a362b09 | 2016-07-06 00:28:43 +0000 | [diff] [blame] | 982 | /// \brief This handles unreachable block accesses by deleting phi nodes in |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 983 | /// unreachable blocks, and marking all other unreachable MemoryAccess's as |
| 984 | /// being uses of the live on entry definition. |
| 985 | void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) { |
| 986 | assert(!DT->isReachableFromEntry(BB) && |
| 987 | "Reachable block found while handling unreachable blocks"); |
| 988 | |
Daniel Berlin | fc7e651 | 2016-07-06 05:32:05 +0000 | [diff] [blame] | 989 | // Make sure phi nodes in our reachable successors end up with a |
| 990 | // LiveOnEntryDef for our incoming edge, even though our block is forward |
| 991 | // unreachable. We could just disconnect these blocks from the CFG fully, |
| 992 | // but we do not right now. |
| 993 | for (const BasicBlock *S : successors(BB)) { |
| 994 | if (!DT->isReachableFromEntry(S)) |
| 995 | continue; |
| 996 | auto It = PerBlockAccesses.find(S); |
| 997 | // Rename the phi nodes in our successor block |
| 998 | if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front())) |
| 999 | continue; |
| 1000 | AccessList *Accesses = It->second.get(); |
| 1001 | auto *Phi = cast<MemoryPhi>(&Accesses->front()); |
| 1002 | Phi->addIncoming(LiveOnEntryDef.get(), BB); |
| 1003 | } |
| 1004 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1005 | auto It = PerBlockAccesses.find(BB); |
| 1006 | if (It == PerBlockAccesses.end()) |
| 1007 | return; |
| 1008 | |
| 1009 | auto &Accesses = It->second; |
| 1010 | for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) { |
| 1011 | auto Next = std::next(AI); |
| 1012 | // If we have a phi, just remove it. We are going to replace all |
| 1013 | // users with live on entry. |
| 1014 | if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI)) |
| 1015 | UseOrDef->setDefiningAccess(LiveOnEntryDef.get()); |
| 1016 | else |
| 1017 | Accesses->erase(AI); |
| 1018 | AI = Next; |
| 1019 | } |
| 1020 | } |
| 1021 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1022 | MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT) |
| 1023 | : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr), |
Daniel Berlin | cd2deac | 2016-10-20 20:13:45 +0000 | [diff] [blame] | 1024 | NextID(INVALID_MEMORYACCESS_ID) { |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 1025 | buildMemorySSA(); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1026 | } |
| 1027 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1028 | MemorySSA::~MemorySSA() { |
| 1029 | // Drop all our references |
| 1030 | for (const auto &Pair : PerBlockAccesses) |
| 1031 | for (MemoryAccess &MA : *Pair.second) |
| 1032 | MA.dropAllReferences(); |
| 1033 | } |
| 1034 | |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1035 | MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1036 | auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr)); |
| 1037 | |
| 1038 | if (Res.second) |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 1039 | Res.first->second = make_unique<AccessList>(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1040 | return Res.first->second.get(); |
| 1041 | } |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1042 | MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) { |
| 1043 | auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr)); |
| 1044 | |
| 1045 | if (Res.second) |
| 1046 | Res.first->second = make_unique<DefsList>(); |
| 1047 | return Res.first->second.get(); |
| 1048 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1049 | |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1050 | /// This class is a batch walker of all MemoryUse's in the program, and points |
| 1051 | /// their defining access at the thing that actually clobbers them. Because it |
| 1052 | /// is a batch walker that touches everything, it does not operate like the |
| 1053 | /// other walkers. This walker is basically performing a top-down SSA renaming |
| 1054 | /// pass, where the version stack is used as the cache. This enables it to be |
| 1055 | /// significantly more time and memory efficient than using the regular walker, |
| 1056 | /// which is walking bottom-up. |
| 1057 | class MemorySSA::OptimizeUses { |
| 1058 | public: |
| 1059 | OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA, |
| 1060 | DominatorTree *DT) |
| 1061 | : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) { |
| 1062 | Walker = MSSA->getWalker(); |
| 1063 | } |
| 1064 | |
| 1065 | void optimizeUses(); |
| 1066 | |
| 1067 | private: |
| 1068 | /// This represents where a given memorylocation is in the stack. |
| 1069 | struct MemlocStackInfo { |
| 1070 | // This essentially is keeping track of versions of the stack. Whenever |
| 1071 | // the stack changes due to pushes or pops, these versions increase. |
| 1072 | unsigned long StackEpoch; |
| 1073 | unsigned long PopEpoch; |
| 1074 | // This is the lower bound of places on the stack to check. It is equal to |
| 1075 | // the place the last stack walk ended. |
| 1076 | // Note: Correctness depends on this being initialized to 0, which densemap |
| 1077 | // does |
| 1078 | unsigned long LowerBound; |
Daniel Berlin | 4b4c722 | 2016-08-08 04:44:53 +0000 | [diff] [blame] | 1079 | const BasicBlock *LowerBoundBlock; |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1080 | // This is where the last walk for this memory location ended. |
| 1081 | unsigned long LastKill; |
| 1082 | bool LastKillValid; |
| 1083 | }; |
| 1084 | void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &, |
| 1085 | SmallVectorImpl<MemoryAccess *> &, |
| 1086 | DenseMap<MemoryLocOrCall, MemlocStackInfo> &); |
| 1087 | MemorySSA *MSSA; |
| 1088 | MemorySSAWalker *Walker; |
| 1089 | AliasAnalysis *AA; |
| 1090 | DominatorTree *DT; |
| 1091 | }; |
| 1092 | |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1093 | /// Optimize the uses in a given block This is basically the SSA renaming |
| 1094 | /// algorithm, with one caveat: We are able to use a single stack for all |
| 1095 | /// MemoryUses. This is because the set of *possible* reaching MemoryDefs is |
| 1096 | /// the same for every MemoryUse. The *actual* clobbering MemoryDef is just |
| 1097 | /// going to be some position in that stack of possible ones. |
| 1098 | /// |
| 1099 | /// We track the stack positions that each MemoryLocation needs |
| 1100 | /// to check, and last ended at. This is because we only want to check the |
| 1101 | /// things that changed since last time. The same MemoryLocation should |
| 1102 | /// get clobbered by the same store (getModRefInfo does not use invariantness or |
| 1103 | /// things like this, and if they start, we can modify MemoryLocOrCall to |
| 1104 | /// include relevant data) |
| 1105 | void MemorySSA::OptimizeUses::optimizeUsesInBlock( |
| 1106 | const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch, |
| 1107 | SmallVectorImpl<MemoryAccess *> &VersionStack, |
| 1108 | DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) { |
| 1109 | |
| 1110 | /// If no accesses, nothing to do. |
| 1111 | MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB); |
| 1112 | if (Accesses == nullptr) |
| 1113 | return; |
| 1114 | |
| 1115 | // Pop everything that doesn't dominate the current block off the stack, |
| 1116 | // increment the PopEpoch to account for this. |
Piotr Padlewski | cc5868c1 | 2017-02-18 20:34:36 +0000 | [diff] [blame] | 1117 | while (true) { |
| 1118 | assert( |
| 1119 | !VersionStack.empty() && |
| 1120 | "Version stack should have liveOnEntry sentinel dominating everything"); |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1121 | BasicBlock *BackBlock = VersionStack.back()->getBlock(); |
| 1122 | if (DT->dominates(BackBlock, BB)) |
| 1123 | break; |
| 1124 | while (VersionStack.back()->getBlock() == BackBlock) |
| 1125 | VersionStack.pop_back(); |
| 1126 | ++PopEpoch; |
| 1127 | } |
Piotr Padlewski | cc5868c1 | 2017-02-18 20:34:36 +0000 | [diff] [blame] | 1128 | |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1129 | for (MemoryAccess &MA : *Accesses) { |
| 1130 | auto *MU = dyn_cast<MemoryUse>(&MA); |
| 1131 | if (!MU) { |
| 1132 | VersionStack.push_back(&MA); |
| 1133 | ++StackEpoch; |
| 1134 | continue; |
| 1135 | } |
| 1136 | |
George Burgess IV | 024f3d2 | 2016-08-03 19:57:02 +0000 | [diff] [blame] | 1137 | if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) { |
Daniel Berlin | cd2deac | 2016-10-20 20:13:45 +0000 | [diff] [blame] | 1138 | MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true); |
George Burgess IV | 024f3d2 | 2016-08-03 19:57:02 +0000 | [diff] [blame] | 1139 | continue; |
| 1140 | } |
| 1141 | |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1142 | MemoryLocOrCall UseMLOC(MU); |
| 1143 | auto &LocInfo = LocStackInfo[UseMLOC]; |
Daniel Berlin | 26fcea9 | 2016-08-02 20:02:21 +0000 | [diff] [blame] | 1144 | // If the pop epoch changed, it means we've removed stuff from top of |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1145 | // stack due to changing blocks. We may have to reset the lower bound or |
| 1146 | // last kill info. |
| 1147 | if (LocInfo.PopEpoch != PopEpoch) { |
| 1148 | LocInfo.PopEpoch = PopEpoch; |
| 1149 | LocInfo.StackEpoch = StackEpoch; |
Daniel Berlin | 4b4c722 | 2016-08-08 04:44:53 +0000 | [diff] [blame] | 1150 | // If the lower bound was in something that no longer dominates us, we |
| 1151 | // have to reset it. |
| 1152 | // We can't simply track stack size, because the stack may have had |
| 1153 | // pushes/pops in the meantime. |
| 1154 | // XXX: This is non-optimal, but only is slower cases with heavily |
| 1155 | // branching dominator trees. To get the optimal number of queries would |
| 1156 | // be to make lowerbound and lastkill a per-loc stack, and pop it until |
| 1157 | // the top of that stack dominates us. This does not seem worth it ATM. |
| 1158 | // A much cheaper optimization would be to always explore the deepest |
| 1159 | // branch of the dominator tree first. This will guarantee this resets on |
| 1160 | // the smallest set of blocks. |
| 1161 | if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB && |
Daniel Berlin | 1e98c04 | 2016-09-26 17:22:54 +0000 | [diff] [blame] | 1162 | !DT->dominates(LocInfo.LowerBoundBlock, BB)) { |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1163 | // Reset the lower bound of things to check. |
| 1164 | // TODO: Some day we should be able to reset to last kill, rather than |
| 1165 | // 0. |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1166 | LocInfo.LowerBound = 0; |
Daniel Berlin | 4b4c722 | 2016-08-08 04:44:53 +0000 | [diff] [blame] | 1167 | LocInfo.LowerBoundBlock = VersionStack[0]->getBlock(); |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1168 | LocInfo.LastKillValid = false; |
| 1169 | } |
| 1170 | } else if (LocInfo.StackEpoch != StackEpoch) { |
| 1171 | // If all that has changed is the StackEpoch, we only have to check the |
| 1172 | // new things on the stack, because we've checked everything before. In |
| 1173 | // this case, the lower bound of things to check remains the same. |
| 1174 | LocInfo.PopEpoch = PopEpoch; |
| 1175 | LocInfo.StackEpoch = StackEpoch; |
| 1176 | } |
| 1177 | if (!LocInfo.LastKillValid) { |
| 1178 | LocInfo.LastKill = VersionStack.size() - 1; |
| 1179 | LocInfo.LastKillValid = true; |
| 1180 | } |
| 1181 | |
| 1182 | // At this point, we should have corrected last kill and LowerBound to be |
| 1183 | // in bounds. |
| 1184 | assert(LocInfo.LowerBound < VersionStack.size() && |
| 1185 | "Lower bound out of range"); |
| 1186 | assert(LocInfo.LastKill < VersionStack.size() && |
| 1187 | "Last kill info out of range"); |
| 1188 | // In any case, the new upper bound is the top of the stack. |
| 1189 | unsigned long UpperBound = VersionStack.size() - 1; |
| 1190 | |
| 1191 | if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) { |
Daniel Berlin | 26fcea9 | 2016-08-02 20:02:21 +0000 | [diff] [blame] | 1192 | DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " (" |
| 1193 | << *(MU->getMemoryInst()) << ")" |
| 1194 | << " because there are " << UpperBound - LocInfo.LowerBound |
| 1195 | << " stores to disambiguate\n"); |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1196 | // Because we did not walk, LastKill is no longer valid, as this may |
| 1197 | // have been a kill. |
| 1198 | LocInfo.LastKillValid = false; |
| 1199 | continue; |
| 1200 | } |
| 1201 | bool FoundClobberResult = false; |
| 1202 | while (UpperBound > LocInfo.LowerBound) { |
| 1203 | if (isa<MemoryPhi>(VersionStack[UpperBound])) { |
| 1204 | // For phis, use the walker, see where we ended up, go there |
| 1205 | Instruction *UseInst = MU->getMemoryInst(); |
| 1206 | MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst); |
| 1207 | // We are guaranteed to find it or something is wrong |
| 1208 | while (VersionStack[UpperBound] != Result) { |
| 1209 | assert(UpperBound != 0); |
| 1210 | --UpperBound; |
| 1211 | } |
| 1212 | FoundClobberResult = true; |
| 1213 | break; |
| 1214 | } |
| 1215 | |
| 1216 | MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]); |
Daniel Berlin | df10119 | 2016-08-03 00:01:46 +0000 | [diff] [blame] | 1217 | // If the lifetime of the pointer ends at this instruction, it's live on |
| 1218 | // entry. |
| 1219 | if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) { |
| 1220 | // Reset UpperBound to liveOnEntryDef's place in the stack |
| 1221 | UpperBound = 0; |
| 1222 | FoundClobberResult = true; |
| 1223 | break; |
| 1224 | } |
Daniel Berlin | dff31de | 2016-08-02 21:57:52 +0000 | [diff] [blame] | 1225 | if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) { |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1226 | FoundClobberResult = true; |
| 1227 | break; |
| 1228 | } |
| 1229 | --UpperBound; |
| 1230 | } |
| 1231 | // At the end of this loop, UpperBound is either a clobber, or lower bound |
| 1232 | // PHI walking may cause it to be < LowerBound, and in fact, < LastKill. |
| 1233 | if (FoundClobberResult || UpperBound < LocInfo.LastKill) { |
Daniel Berlin | cd2deac | 2016-10-20 20:13:45 +0000 | [diff] [blame] | 1234 | MU->setDefiningAccess(VersionStack[UpperBound], true); |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1235 | // We were last killed now by where we got to |
| 1236 | LocInfo.LastKill = UpperBound; |
| 1237 | } else { |
| 1238 | // Otherwise, we checked all the new ones, and now we know we can get to |
| 1239 | // LastKill. |
Daniel Berlin | cd2deac | 2016-10-20 20:13:45 +0000 | [diff] [blame] | 1240 | MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true); |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1241 | } |
| 1242 | LocInfo.LowerBound = VersionStack.size() - 1; |
Daniel Berlin | 4b4c722 | 2016-08-08 04:44:53 +0000 | [diff] [blame] | 1243 | LocInfo.LowerBoundBlock = BB; |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1244 | } |
| 1245 | } |
| 1246 | |
| 1247 | /// Optimize uses to point to their actual clobbering definitions. |
| 1248 | void MemorySSA::OptimizeUses::optimizeUses() { |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1249 | SmallVector<MemoryAccess *, 16> VersionStack; |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1250 | DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo; |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1251 | VersionStack.push_back(MSSA->getLiveOnEntryDef()); |
| 1252 | |
| 1253 | unsigned long StackEpoch = 1; |
| 1254 | unsigned long PopEpoch = 1; |
Piotr Padlewski | cc5868c1 | 2017-02-18 20:34:36 +0000 | [diff] [blame] | 1255 | // We perform a non-recursive top-down dominator tree walk. |
Daniel Berlin | 7ac3d74 | 2016-08-05 22:09:14 +0000 | [diff] [blame] | 1256 | for (const auto *DomNode : depth_first(DT->getRootNode())) |
| 1257 | optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack, |
| 1258 | LocStackInfo); |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1259 | } |
| 1260 | |
Daniel Berlin | 3d512a2 | 2016-08-22 19:14:30 +0000 | [diff] [blame] | 1261 | void MemorySSA::placePHINodes( |
Mandeep Singh Grang | 73f0095 | 2016-11-21 19:33:02 +0000 | [diff] [blame] | 1262 | const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks, |
| 1263 | const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) { |
Daniel Berlin | 3d512a2 | 2016-08-22 19:14:30 +0000 | [diff] [blame] | 1264 | // Determine where our MemoryPhi's should go |
| 1265 | ForwardIDFCalculator IDFs(*DT); |
| 1266 | IDFs.setDefiningBlocks(DefiningBlocks); |
Daniel Berlin | 3d512a2 | 2016-08-22 19:14:30 +0000 | [diff] [blame] | 1267 | SmallVector<BasicBlock *, 32> IDFBlocks; |
| 1268 | IDFs.calculate(IDFBlocks); |
| 1269 | |
Mandeep Singh Grang | 73f0095 | 2016-11-21 19:33:02 +0000 | [diff] [blame] | 1270 | std::sort(IDFBlocks.begin(), IDFBlocks.end(), |
| 1271 | [&BBNumbers](const BasicBlock *A, const BasicBlock *B) { |
| 1272 | return BBNumbers.lookup(A) < BBNumbers.lookup(B); |
| 1273 | }); |
| 1274 | |
Daniel Berlin | 3d512a2 | 2016-08-22 19:14:30 +0000 | [diff] [blame] | 1275 | // Now place MemoryPhi nodes. |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1276 | for (auto &BB : IDFBlocks) |
| 1277 | createMemoryPhi(BB); |
Daniel Berlin | 3d512a2 | 2016-08-22 19:14:30 +0000 | [diff] [blame] | 1278 | } |
| 1279 | |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 1280 | void MemorySSA::buildMemorySSA() { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1281 | // We create an access to represent "live on entry", for things like |
| 1282 | // arguments or users of globals, where the memory they use is defined before |
| 1283 | // the beginning of the function. We do not actually insert it into the IR. |
| 1284 | // We do not define a live on exit for the immediate uses, and thus our |
| 1285 | // semantics do *not* imply that something with no immediate uses can simply |
| 1286 | // be removed. |
| 1287 | BasicBlock &StartingPoint = F.getEntryBlock(); |
| 1288 | LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr, |
| 1289 | &StartingPoint, NextID++); |
Mandeep Singh Grang | 73f0095 | 2016-11-21 19:33:02 +0000 | [diff] [blame] | 1290 | DenseMap<const BasicBlock *, unsigned int> BBNumbers; |
| 1291 | unsigned NextBBNum = 0; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1292 | |
| 1293 | // We maintain lists of memory accesses per-block, trading memory for time. We |
| 1294 | // could just look up the memory access for every possible instruction in the |
| 1295 | // stream. |
| 1296 | SmallPtrSet<BasicBlock *, 32> DefiningBlocks; |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 1297 | SmallPtrSet<BasicBlock *, 32> DefUseBlocks; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1298 | // Go through each block, figure out where defs occur, and chain together all |
| 1299 | // the accesses. |
| 1300 | for (BasicBlock &B : F) { |
Mandeep Singh Grang | 73f0095 | 2016-11-21 19:33:02 +0000 | [diff] [blame] | 1301 | BBNumbers[&B] = NextBBNum++; |
Daniel Berlin | 7898ca6 | 2016-02-07 01:52:15 +0000 | [diff] [blame] | 1302 | bool InsertIntoDef = false; |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 1303 | AccessList *Accesses = nullptr; |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1304 | DefsList *Defs = nullptr; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1305 | for (Instruction &I : B) { |
Peter Collingbourne | ffecb14 | 2016-05-26 01:19:17 +0000 | [diff] [blame] | 1306 | MemoryUseOrDef *MUD = createNewAccess(&I); |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 1307 | if (!MUD) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1308 | continue; |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 1309 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1310 | if (!Accesses) |
| 1311 | Accesses = getOrCreateAccessList(&B); |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 1312 | Accesses->push_back(MUD); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1313 | if (isa<MemoryDef>(MUD)) { |
| 1314 | InsertIntoDef = true; |
| 1315 | if (!Defs) |
| 1316 | Defs = getOrCreateDefsList(&B); |
| 1317 | Defs->push_back(*MUD); |
| 1318 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1319 | } |
Daniel Berlin | 7898ca6 | 2016-02-07 01:52:15 +0000 | [diff] [blame] | 1320 | if (InsertIntoDef) |
| 1321 | DefiningBlocks.insert(&B); |
George Burgess IV | 3887a41 | 2016-03-21 21:25:39 +0000 | [diff] [blame] | 1322 | if (Accesses) |
Daniel Berlin | 1b51a29 | 2016-02-07 01:52:19 +0000 | [diff] [blame] | 1323 | DefUseBlocks.insert(&B); |
| 1324 | } |
Mandeep Singh Grang | 73f0095 | 2016-11-21 19:33:02 +0000 | [diff] [blame] | 1325 | placePHINodes(DefiningBlocks, BBNumbers); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1326 | |
| 1327 | // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get |
| 1328 | // filled in with all blocks. |
| 1329 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 1330 | renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited); |
| 1331 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1332 | CachingWalker *Walker = getWalkerImpl(); |
| 1333 | |
| 1334 | // We're doing a batch of updates; don't drop useful caches between them. |
| 1335 | Walker->setAutoResetWalker(false); |
Daniel Berlin | c43aa5a | 2016-08-02 16:24:03 +0000 | [diff] [blame] | 1336 | OptimizeUses(this, Walker, AA, DT).optimizeUses(); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1337 | Walker->setAutoResetWalker(true); |
| 1338 | Walker->resetClobberWalker(); |
| 1339 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1340 | // Mark the uses in unreachable blocks as live on entry, so that they go |
| 1341 | // somewhere. |
| 1342 | for (auto &BB : F) |
| 1343 | if (!Visited.count(&BB)) |
| 1344 | markUnreachableAsLiveOnEntry(&BB); |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 1345 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1346 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1347 | MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); } |
| 1348 | |
| 1349 | MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() { |
Daniel Berlin | 16ed57c | 2016-06-27 18:22:27 +0000 | [diff] [blame] | 1350 | if (Walker) |
| 1351 | return Walker.get(); |
| 1352 | |
| 1353 | Walker = make_unique<CachingWalker>(this, AA, DT); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1354 | return Walker.get(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1355 | } |
| 1356 | |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1357 | // This is a helper function used by the creation routines. It places NewAccess |
| 1358 | // into the access and defs lists for a given basic block, at the given |
| 1359 | // insertion point. |
| 1360 | void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess, |
| 1361 | const BasicBlock *BB, |
| 1362 | InsertionPlace Point) { |
| 1363 | auto *Accesses = getOrCreateAccessList(BB); |
| 1364 | if (Point == Beginning) { |
| 1365 | // If it's a phi node, it goes first, otherwise, it goes after any phi |
| 1366 | // nodes. |
| 1367 | if (isa<MemoryPhi>(NewAccess)) { |
| 1368 | Accesses->push_front(NewAccess); |
| 1369 | auto *Defs = getOrCreateDefsList(BB); |
| 1370 | Defs->push_front(*NewAccess); |
| 1371 | } else { |
| 1372 | auto AI = find_if_not( |
| 1373 | *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); }); |
| 1374 | Accesses->insert(AI, NewAccess); |
| 1375 | if (!isa<MemoryUse>(NewAccess)) { |
| 1376 | auto *Defs = getOrCreateDefsList(BB); |
| 1377 | auto DI = find_if_not( |
| 1378 | *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); }); |
| 1379 | Defs->insert(DI, *NewAccess); |
| 1380 | } |
| 1381 | } |
| 1382 | } else { |
| 1383 | Accesses->push_back(NewAccess); |
| 1384 | if (!isa<MemoryUse>(NewAccess)) { |
| 1385 | auto *Defs = getOrCreateDefsList(BB); |
| 1386 | Defs->push_back(*NewAccess); |
| 1387 | } |
| 1388 | } |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 1389 | BlockNumberingValid.erase(BB); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1390 | } |
| 1391 | |
| 1392 | void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB, |
| 1393 | AccessList::iterator InsertPt) { |
| 1394 | auto *Accesses = getWritableBlockAccesses(BB); |
| 1395 | bool WasEnd = InsertPt == Accesses->end(); |
| 1396 | Accesses->insert(AccessList::iterator(InsertPt), What); |
| 1397 | if (!isa<MemoryUse>(What)) { |
| 1398 | auto *Defs = getOrCreateDefsList(BB); |
| 1399 | // If we got asked to insert at the end, we have an easy job, just shove it |
| 1400 | // at the end. If we got asked to insert before an existing def, we also get |
| 1401 | // an terator. If we got asked to insert before a use, we have to hunt for |
| 1402 | // the next def. |
| 1403 | if (WasEnd) { |
| 1404 | Defs->push_back(*What); |
| 1405 | } else if (isa<MemoryDef>(InsertPt)) { |
| 1406 | Defs->insert(InsertPt->getDefsIterator(), *What); |
| 1407 | } else { |
| 1408 | while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt)) |
| 1409 | ++InsertPt; |
| 1410 | // Either we found a def, or we are inserting at the end |
| 1411 | if (InsertPt == Accesses->end()) |
| 1412 | Defs->push_back(*What); |
| 1413 | else |
| 1414 | Defs->insert(InsertPt->getDefsIterator(), *What); |
| 1415 | } |
| 1416 | } |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 1417 | BlockNumberingValid.erase(BB); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1418 | } |
| 1419 | |
Daniel Berlin | 60ead05 | 2017-01-28 01:23:13 +0000 | [diff] [blame] | 1420 | // Move What before Where in the IR. The end result is taht What will belong to |
| 1421 | // the right lists and have the right Block set, but will not otherwise be |
| 1422 | // correct. It will not have the right defining access, and if it is a def, |
| 1423 | // things below it will not properly be updated. |
| 1424 | void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB, |
| 1425 | AccessList::iterator Where) { |
| 1426 | // Keep it in the lookup tables, remove from the lists |
| 1427 | removeFromLists(What, false); |
| 1428 | What->setBlock(BB); |
| 1429 | insertIntoListsBefore(What, BB, Where); |
| 1430 | } |
| 1431 | |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 1432 | void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB, |
| 1433 | InsertionPlace Point) { |
| 1434 | removeFromLists(What, false); |
| 1435 | What->setBlock(BB); |
| 1436 | insertIntoListsForBlock(What, BB, Point); |
| 1437 | } |
| 1438 | |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1439 | MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) { |
| 1440 | assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB"); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1441 | MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++); |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 1442 | // Phi's always are placed at the front of the block. |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1443 | insertIntoListsForBlock(Phi, BB, Beginning); |
Daniel Berlin | 5130cc8 | 2016-07-31 21:08:20 +0000 | [diff] [blame] | 1444 | ValueToMemoryAccess[BB] = Phi; |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1445 | return Phi; |
| 1446 | } |
| 1447 | |
| 1448 | MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I, |
| 1449 | MemoryAccess *Definition) { |
| 1450 | assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI"); |
| 1451 | MemoryUseOrDef *NewAccess = createNewAccess(I); |
| 1452 | assert( |
| 1453 | NewAccess != nullptr && |
| 1454 | "Tried to create a memory access for a non-memory touching instruction"); |
| 1455 | NewAccess->setDefiningAccess(Definition); |
| 1456 | return NewAccess; |
| 1457 | } |
| 1458 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1459 | /// \brief Helper function to create new memory accesses |
Peter Collingbourne | ffecb14 | 2016-05-26 01:19:17 +0000 | [diff] [blame] | 1460 | MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) { |
Peter Collingbourne | b9aa1f4 | 2016-05-26 04:58:46 +0000 | [diff] [blame] | 1461 | // The assume intrinsic has a control dependency which we model by claiming |
| 1462 | // that it writes arbitrarily. Ignore that fake memory dependency here. |
| 1463 | // FIXME: Replace this special casing with a more accurate modelling of |
| 1464 | // assume's control dependency. |
| 1465 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) |
| 1466 | if (II->getIntrinsicID() == Intrinsic::assume) |
| 1467 | return nullptr; |
| 1468 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1469 | // Find out what affect this instruction has on memory. |
| 1470 | ModRefInfo ModRef = AA->getModRefInfo(I); |
| 1471 | bool Def = bool(ModRef & MRI_Mod); |
| 1472 | bool Use = bool(ModRef & MRI_Ref); |
| 1473 | |
| 1474 | // It's possible for an instruction to not modify memory at all. During |
| 1475 | // construction, we ignore them. |
Peter Collingbourne | ffecb14 | 2016-05-26 01:19:17 +0000 | [diff] [blame] | 1476 | if (!Def && !Use) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1477 | return nullptr; |
| 1478 | |
| 1479 | assert((Def || Use) && |
| 1480 | "Trying to create a memory access with a non-memory instruction"); |
| 1481 | |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 1482 | MemoryUseOrDef *MUD; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1483 | if (Def) |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 1484 | MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1485 | else |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 1486 | MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent()); |
Daniel Berlin | 5130cc8 | 2016-07-31 21:08:20 +0000 | [diff] [blame] | 1487 | ValueToMemoryAccess[I] = MUD; |
George Burgess IV | b42b762 | 2016-03-11 19:34:03 +0000 | [diff] [blame] | 1488 | return MUD; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1489 | } |
| 1490 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1491 | /// \brief Returns true if \p Replacer dominates \p Replacee . |
| 1492 | bool MemorySSA::dominatesUse(const MemoryAccess *Replacer, |
| 1493 | const MemoryAccess *Replacee) const { |
| 1494 | if (isa<MemoryUseOrDef>(Replacee)) |
| 1495 | return DT->dominates(Replacer->getBlock(), Replacee->getBlock()); |
| 1496 | const auto *MP = cast<MemoryPhi>(Replacee); |
| 1497 | // For a phi node, the use occurs in the predecessor block of the phi node. |
| 1498 | // Since we may occur multiple times in the phi node, we have to check each |
| 1499 | // operand to ensure Replacer dominates each operand where Replacee occurs. |
| 1500 | for (const Use &Arg : MP->operands()) { |
George Burgess IV | b5a229f | 2016-02-02 23:15:26 +0000 | [diff] [blame] | 1501 | if (Arg.get() != Replacee && |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1502 | !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg))) |
| 1503 | return false; |
| 1504 | } |
| 1505 | return true; |
| 1506 | } |
| 1507 | |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 1508 | /// \brief Properly remove \p MA from all of MemorySSA's lookup tables. |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 1509 | void MemorySSA::removeFromLookups(MemoryAccess *MA) { |
| 1510 | assert(MA->use_empty() && |
| 1511 | "Trying to remove memory access that still has uses"); |
Daniel Berlin | 5c46b94 | 2016-07-19 22:49:43 +0000 | [diff] [blame] | 1512 | BlockNumbering.erase(MA); |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 1513 | if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) |
| 1514 | MUD->setDefiningAccess(nullptr); |
| 1515 | // Invalidate our walker's cache if necessary |
| 1516 | if (!isa<MemoryUse>(MA)) |
| 1517 | Walker->invalidateInfo(MA); |
| 1518 | // The call below to erase will destroy MA, so we can't change the order we |
| 1519 | // are doing things here |
| 1520 | Value *MemoryInst; |
| 1521 | if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) { |
| 1522 | MemoryInst = MUD->getMemoryInst(); |
| 1523 | } else { |
| 1524 | MemoryInst = MA->getBlock(); |
| 1525 | } |
Daniel Berlin | 5130cc8 | 2016-07-31 21:08:20 +0000 | [diff] [blame] | 1526 | auto VMA = ValueToMemoryAccess.find(MemoryInst); |
| 1527 | if (VMA->second == MA) |
| 1528 | ValueToMemoryAccess.erase(VMA); |
Daniel Berlin | 60ead05 | 2017-01-28 01:23:13 +0000 | [diff] [blame] | 1529 | } |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 1530 | |
Daniel Berlin | 60ead05 | 2017-01-28 01:23:13 +0000 | [diff] [blame] | 1531 | /// \brief Properly remove \p MA from all of MemorySSA's lists. |
| 1532 | /// |
| 1533 | /// Because of the way the intrusive list and use lists work, it is important to |
| 1534 | /// do removal in the right order. |
| 1535 | /// ShouldDelete defaults to true, and will cause the memory access to also be |
| 1536 | /// deleted, not just removed. |
| 1537 | void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) { |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1538 | // The access list owns the reference, so we erase it from the non-owning list |
| 1539 | // first. |
| 1540 | if (!isa<MemoryUse>(MA)) { |
| 1541 | auto DefsIt = PerBlockDefs.find(MA->getBlock()); |
| 1542 | std::unique_ptr<DefsList> &Defs = DefsIt->second; |
| 1543 | Defs->remove(*MA); |
| 1544 | if (Defs->empty()) |
| 1545 | PerBlockDefs.erase(DefsIt); |
| 1546 | } |
| 1547 | |
Daniel Berlin | 60ead05 | 2017-01-28 01:23:13 +0000 | [diff] [blame] | 1548 | // The erase call here will delete it. If we don't want it deleted, we call |
| 1549 | // remove instead. |
George Burgess IV | e0e6e48 | 2016-03-02 02:35:04 +0000 | [diff] [blame] | 1550 | auto AccessIt = PerBlockAccesses.find(MA->getBlock()); |
Daniel Berlin | ada263d | 2016-06-20 20:21:33 +0000 | [diff] [blame] | 1551 | std::unique_ptr<AccessList> &Accesses = AccessIt->second; |
Daniel Berlin | 60ead05 | 2017-01-28 01:23:13 +0000 | [diff] [blame] | 1552 | if (ShouldDelete) |
| 1553 | Accesses->erase(MA); |
| 1554 | else |
| 1555 | Accesses->remove(MA); |
| 1556 | |
George Burgess IV | e0e6e48 | 2016-03-02 02:35:04 +0000 | [diff] [blame] | 1557 | if (Accesses->empty()) |
| 1558 | PerBlockAccesses.erase(AccessIt); |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 1559 | } |
| 1560 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1561 | void MemorySSA::print(raw_ostream &OS) const { |
| 1562 | MemorySSAAnnotatedWriter Writer(this); |
| 1563 | F.print(OS, &Writer); |
| 1564 | } |
| 1565 | |
Matthias Braun | 8c209aa | 2017-01-28 02:02:38 +0000 | [diff] [blame] | 1566 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 1567 | LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); } |
Matthias Braun | 8c209aa | 2017-01-28 02:02:38 +0000 | [diff] [blame] | 1568 | #endif |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1569 | |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 1570 | void MemorySSA::verifyMemorySSA() const { |
| 1571 | verifyDefUses(F); |
| 1572 | verifyDomination(F); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1573 | verifyOrdering(F); |
Geoff Berry | cdf5333 | 2016-08-08 17:52:01 +0000 | [diff] [blame] | 1574 | Walker->verify(this); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1575 | } |
| 1576 | |
| 1577 | /// \brief Verify that the order and existence of MemoryAccesses matches the |
| 1578 | /// order and existence of memory affecting instructions. |
| 1579 | void MemorySSA::verifyOrdering(Function &F) const { |
| 1580 | // Walk all the blocks, comparing what the lookups think and what the access |
| 1581 | // lists think, as well as the order in the blocks vs the order in the access |
| 1582 | // lists. |
| 1583 | SmallVector<MemoryAccess *, 32> ActualAccesses; |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1584 | SmallVector<MemoryAccess *, 32> ActualDefs; |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1585 | for (BasicBlock &B : F) { |
| 1586 | const AccessList *AL = getBlockAccesses(&B); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1587 | const auto *DL = getBlockDefs(&B); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1588 | MemoryAccess *Phi = getMemoryAccess(&B); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1589 | if (Phi) { |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1590 | ActualAccesses.push_back(Phi); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1591 | ActualDefs.push_back(Phi); |
| 1592 | } |
| 1593 | |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1594 | for (Instruction &I : B) { |
| 1595 | MemoryAccess *MA = getMemoryAccess(&I); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1596 | assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) && |
| 1597 | "We have memory affecting instructions " |
| 1598 | "in this block but they are not in the " |
| 1599 | "access list or defs list"); |
| 1600 | if (MA) { |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1601 | ActualAccesses.push_back(MA); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1602 | if (isa<MemoryDef>(MA)) |
| 1603 | ActualDefs.push_back(MA); |
| 1604 | } |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1605 | } |
| 1606 | // Either we hit the assert, really have no accesses, or we have both |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1607 | // accesses and an access list. |
| 1608 | // Same with defs. |
| 1609 | if (!AL && !DL) |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1610 | continue; |
| 1611 | assert(AL->size() == ActualAccesses.size() && |
| 1612 | "We don't have the same number of accesses in the block as on the " |
| 1613 | "access list"); |
Davide Italiano | 6c77de0 | 2017-01-30 03:16:43 +0000 | [diff] [blame] | 1614 | assert((DL || ActualDefs.size() == 0) && |
| 1615 | "Either we should have a defs list, or we should have no defs"); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1616 | assert((!DL || DL->size() == ActualDefs.size()) && |
| 1617 | "We don't have the same number of defs in the block as on the " |
| 1618 | "def list"); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1619 | auto ALI = AL->begin(); |
| 1620 | auto AAI = ActualAccesses.begin(); |
| 1621 | while (ALI != AL->end() && AAI != ActualAccesses.end()) { |
| 1622 | assert(&*ALI == *AAI && "Not the same accesses in the same order"); |
| 1623 | ++ALI; |
| 1624 | ++AAI; |
| 1625 | } |
| 1626 | ActualAccesses.clear(); |
Daniel Berlin | d602e04 | 2017-01-25 20:56:19 +0000 | [diff] [blame] | 1627 | if (DL) { |
| 1628 | auto DLI = DL->begin(); |
| 1629 | auto ADI = ActualDefs.begin(); |
| 1630 | while (DLI != DL->end() && ADI != ActualDefs.end()) { |
| 1631 | assert(&*DLI == *ADI && "Not the same defs in the same order"); |
| 1632 | ++DLI; |
| 1633 | ++ADI; |
| 1634 | } |
| 1635 | } |
| 1636 | ActualDefs.clear(); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1637 | } |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 1638 | } |
| 1639 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1640 | /// \brief Verify the domination properties of MemorySSA by checking that each |
| 1641 | /// definition dominates all of its uses. |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 1642 | void MemorySSA::verifyDomination(Function &F) const { |
Daniel Berlin | 7af9587 | 2016-08-05 21:47:20 +0000 | [diff] [blame] | 1643 | #ifndef NDEBUG |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1644 | for (BasicBlock &B : F) { |
| 1645 | // Phi nodes are attached to basic blocks |
Daniel Berlin | 2919b1c | 2016-08-05 21:46:52 +0000 | [diff] [blame] | 1646 | if (MemoryPhi *MP = getMemoryAccess(&B)) |
| 1647 | for (const Use &U : MP->uses()) |
| 1648 | assert(dominates(MP, U) && "Memory PHI does not dominate it's uses"); |
Daniel Berlin | 7af9587 | 2016-08-05 21:47:20 +0000 | [diff] [blame] | 1649 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1650 | for (Instruction &I : B) { |
| 1651 | MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I)); |
| 1652 | if (!MD) |
| 1653 | continue; |
| 1654 | |
Daniel Berlin | 2919b1c | 2016-08-05 21:46:52 +0000 | [diff] [blame] | 1655 | for (const Use &U : MD->uses()) |
| 1656 | assert(dominates(MD, U) && "Memory Def does not dominate it's uses"); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1657 | } |
| 1658 | } |
Daniel Berlin | 7af9587 | 2016-08-05 21:47:20 +0000 | [diff] [blame] | 1659 | #endif |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1660 | } |
| 1661 | |
| 1662 | /// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use |
| 1663 | /// appears in the use list of \p Def. |
Daniel Berlin | 7af9587 | 2016-08-05 21:47:20 +0000 | [diff] [blame] | 1664 | |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 1665 | void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const { |
Daniel Berlin | 7af9587 | 2016-08-05 21:47:20 +0000 | [diff] [blame] | 1666 | #ifndef NDEBUG |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1667 | // The live on entry use may cause us to get a NULL def here |
Daniel Berlin | 7af9587 | 2016-08-05 21:47:20 +0000 | [diff] [blame] | 1668 | if (!Def) |
| 1669 | assert(isLiveOnEntryDef(Use) && |
| 1670 | "Null def but use not point to live on entry def"); |
| 1671 | else |
Daniel Berlin | da2f38e | 2016-08-11 21:26:50 +0000 | [diff] [blame] | 1672 | assert(is_contained(Def->users(), Use) && |
Daniel Berlin | 7af9587 | 2016-08-05 21:47:20 +0000 | [diff] [blame] | 1673 | "Did not find use in def's use list"); |
| 1674 | #endif |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1675 | } |
| 1676 | |
| 1677 | /// \brief Verify the immediate use information, by walking all the memory |
| 1678 | /// accesses and verifying that, for each use, it appears in the |
| 1679 | /// appropriate def's use list |
Daniel Berlin | 932b4cb | 2016-02-10 17:39:43 +0000 | [diff] [blame] | 1680 | void MemorySSA::verifyDefUses(Function &F) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1681 | for (BasicBlock &B : F) { |
| 1682 | // Phi nodes are attached to basic blocks |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1683 | if (MemoryPhi *Phi = getMemoryAccess(&B)) { |
David Majnemer | 580e754 | 2016-06-25 00:04:06 +0000 | [diff] [blame] | 1684 | assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance( |
| 1685 | pred_begin(&B), pred_end(&B))) && |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1686 | "Incomplete MemoryPhi Node"); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1687 | for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) |
| 1688 | verifyUseInDefs(Phi->getIncomingValue(I), Phi); |
Daniel Berlin | 1430026 | 2016-06-21 18:39:20 +0000 | [diff] [blame] | 1689 | } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1690 | |
| 1691 | for (Instruction &I : B) { |
George Burgess IV | 66837ab | 2016-11-01 21:17:46 +0000 | [diff] [blame] | 1692 | if (MemoryUseOrDef *MA = getMemoryAccess(&I)) { |
| 1693 | verifyUseInDefs(MA->getDefiningAccess(), MA); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1694 | } |
| 1695 | } |
| 1696 | } |
| 1697 | } |
| 1698 | |
George Burgess IV | 66837ab | 2016-11-01 21:17:46 +0000 | [diff] [blame] | 1699 | MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const { |
| 1700 | return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1701 | } |
| 1702 | |
| 1703 | MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const { |
George Burgess IV | 66837ab | 2016-11-01 21:17:46 +0000 | [diff] [blame] | 1704 | return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB))); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1705 | } |
| 1706 | |
Daniel Berlin | 5c46b94 | 2016-07-19 22:49:43 +0000 | [diff] [blame] | 1707 | /// Perform a local numbering on blocks so that instruction ordering can be |
| 1708 | /// determined in constant time. |
| 1709 | /// TODO: We currently just number in order. If we numbered by N, we could |
| 1710 | /// allow at least N-1 sequences of insertBefore or insertAfter (and at least |
| 1711 | /// log2(N) sequences of mixed before and after) without needing to invalidate |
| 1712 | /// the numbering. |
| 1713 | void MemorySSA::renumberBlock(const BasicBlock *B) const { |
| 1714 | // The pre-increment ensures the numbers really start at 1. |
| 1715 | unsigned long CurrentNumber = 0; |
| 1716 | const AccessList *AL = getBlockAccesses(B); |
| 1717 | assert(AL != nullptr && "Asking to renumber an empty block"); |
| 1718 | for (const auto &I : *AL) |
| 1719 | BlockNumbering[&I] = ++CurrentNumber; |
| 1720 | BlockNumberingValid.insert(B); |
| 1721 | } |
| 1722 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1723 | /// \brief Determine, for two memory accesses in the same block, |
| 1724 | /// whether \p Dominator dominates \p Dominatee. |
| 1725 | /// \returns True if \p Dominator dominates \p Dominatee. |
| 1726 | bool MemorySSA::locallyDominates(const MemoryAccess *Dominator, |
| 1727 | const MemoryAccess *Dominatee) const { |
Sebastian Pop | e1f60b1 | 2016-06-10 21:36:41 +0000 | [diff] [blame] | 1728 | |
Daniel Berlin | 5c46b94 | 2016-07-19 22:49:43 +0000 | [diff] [blame] | 1729 | const BasicBlock *DominatorBlock = Dominator->getBlock(); |
Daniel Berlin | 5c46b94 | 2016-07-19 22:49:43 +0000 | [diff] [blame] | 1730 | |
Daniel Berlin | 1986030 | 2016-07-19 23:08:08 +0000 | [diff] [blame] | 1731 | assert((DominatorBlock == Dominatee->getBlock()) && |
Daniel Berlin | 5c46b94 | 2016-07-19 22:49:43 +0000 | [diff] [blame] | 1732 | "Asking for local domination when accesses are in different blocks!"); |
Sebastian Pop | e1f60b1 | 2016-06-10 21:36:41 +0000 | [diff] [blame] | 1733 | // A node dominates itself. |
| 1734 | if (Dominatee == Dominator) |
| 1735 | return true; |
| 1736 | |
| 1737 | // When Dominatee is defined on function entry, it is not dominated by another |
| 1738 | // memory access. |
| 1739 | if (isLiveOnEntryDef(Dominatee)) |
| 1740 | return false; |
| 1741 | |
| 1742 | // When Dominator is defined on function entry, it dominates the other memory |
| 1743 | // access. |
| 1744 | if (isLiveOnEntryDef(Dominator)) |
| 1745 | return true; |
| 1746 | |
Daniel Berlin | 5c46b94 | 2016-07-19 22:49:43 +0000 | [diff] [blame] | 1747 | if (!BlockNumberingValid.count(DominatorBlock)) |
| 1748 | renumberBlock(DominatorBlock); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1749 | |
Daniel Berlin | 5c46b94 | 2016-07-19 22:49:43 +0000 | [diff] [blame] | 1750 | unsigned long DominatorNum = BlockNumbering.lookup(Dominator); |
| 1751 | // All numbers start with 1 |
| 1752 | assert(DominatorNum != 0 && "Block was not numbered properly"); |
| 1753 | unsigned long DominateeNum = BlockNumbering.lookup(Dominatee); |
| 1754 | assert(DominateeNum != 0 && "Block was not numbered properly"); |
| 1755 | return DominatorNum < DominateeNum; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1756 | } |
| 1757 | |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1758 | bool MemorySSA::dominates(const MemoryAccess *Dominator, |
| 1759 | const MemoryAccess *Dominatee) const { |
| 1760 | if (Dominator == Dominatee) |
| 1761 | return true; |
| 1762 | |
| 1763 | if (isLiveOnEntryDef(Dominatee)) |
| 1764 | return false; |
| 1765 | |
| 1766 | if (Dominator->getBlock() != Dominatee->getBlock()) |
| 1767 | return DT->dominates(Dominator->getBlock(), Dominatee->getBlock()); |
| 1768 | return locallyDominates(Dominator, Dominatee); |
| 1769 | } |
| 1770 | |
Daniel Berlin | 2919b1c | 2016-08-05 21:46:52 +0000 | [diff] [blame] | 1771 | bool MemorySSA::dominates(const MemoryAccess *Dominator, |
| 1772 | const Use &Dominatee) const { |
| 1773 | if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) { |
| 1774 | BasicBlock *UseBB = MP->getIncomingBlock(Dominatee); |
| 1775 | // The def must dominate the incoming block of the phi. |
| 1776 | if (UseBB != Dominator->getBlock()) |
| 1777 | return DT->dominates(Dominator->getBlock(), UseBB); |
| 1778 | // If the UseBB and the DefBB are the same, compare locally. |
| 1779 | return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee)); |
| 1780 | } |
| 1781 | // If it's not a PHI node use, the normal dominates can already handle it. |
| 1782 | return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser())); |
| 1783 | } |
| 1784 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1785 | const static char LiveOnEntryStr[] = "liveOnEntry"; |
| 1786 | |
| 1787 | void MemoryDef::print(raw_ostream &OS) const { |
| 1788 | MemoryAccess *UO = getDefiningAccess(); |
| 1789 | |
| 1790 | OS << getID() << " = MemoryDef("; |
| 1791 | if (UO && UO->getID()) |
| 1792 | OS << UO->getID(); |
| 1793 | else |
| 1794 | OS << LiveOnEntryStr; |
| 1795 | OS << ')'; |
| 1796 | } |
| 1797 | |
| 1798 | void MemoryPhi::print(raw_ostream &OS) const { |
| 1799 | bool First = true; |
| 1800 | OS << getID() << " = MemoryPhi("; |
| 1801 | for (const auto &Op : operands()) { |
| 1802 | BasicBlock *BB = getIncomingBlock(Op); |
| 1803 | MemoryAccess *MA = cast<MemoryAccess>(Op); |
| 1804 | if (!First) |
| 1805 | OS << ','; |
| 1806 | else |
| 1807 | First = false; |
| 1808 | |
| 1809 | OS << '{'; |
| 1810 | if (BB->hasName()) |
| 1811 | OS << BB->getName(); |
| 1812 | else |
| 1813 | BB->printAsOperand(OS, false); |
| 1814 | OS << ','; |
| 1815 | if (unsigned ID = MA->getID()) |
| 1816 | OS << ID; |
| 1817 | else |
| 1818 | OS << LiveOnEntryStr; |
| 1819 | OS << '}'; |
| 1820 | } |
| 1821 | OS << ')'; |
| 1822 | } |
| 1823 | |
| 1824 | MemoryAccess::~MemoryAccess() {} |
| 1825 | |
| 1826 | void MemoryUse::print(raw_ostream &OS) const { |
| 1827 | MemoryAccess *UO = getDefiningAccess(); |
| 1828 | OS << "MemoryUse("; |
| 1829 | if (UO && UO->getID()) |
| 1830 | OS << UO->getID(); |
| 1831 | else |
| 1832 | OS << LiveOnEntryStr; |
| 1833 | OS << ')'; |
| 1834 | } |
| 1835 | |
| 1836 | void MemoryAccess::dump() const { |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 1837 | // Cannot completely remove virtual function even in release mode. |
Matthias Braun | 8c209aa | 2017-01-28 02:02:38 +0000 | [diff] [blame] | 1838 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1839 | print(dbgs()); |
| 1840 | dbgs() << "\n"; |
Matthias Braun | 8c209aa | 2017-01-28 02:02:38 +0000 | [diff] [blame] | 1841 | #endif |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1842 | } |
| 1843 | |
Chad Rosier | 232e29e | 2016-07-06 21:20:47 +0000 | [diff] [blame] | 1844 | char MemorySSAPrinterLegacyPass::ID = 0; |
| 1845 | |
| 1846 | MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) { |
| 1847 | initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 1848 | } |
| 1849 | |
| 1850 | void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 1851 | AU.setPreservesAll(); |
| 1852 | AU.addRequired<MemorySSAWrapperPass>(); |
| 1853 | AU.addPreserved<MemorySSAWrapperPass>(); |
| 1854 | } |
| 1855 | |
| 1856 | bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) { |
| 1857 | auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); |
| 1858 | MSSA.print(dbgs()); |
| 1859 | if (VerifyMemorySSA) |
| 1860 | MSSA.verifyMemorySSA(); |
| 1861 | return false; |
| 1862 | } |
| 1863 | |
Chandler Carruth | dab4eae | 2016-11-23 17:53:26 +0000 | [diff] [blame] | 1864 | AnalysisKey MemorySSAAnalysis::Key; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1865 | |
Daniel Berlin | 1e98c04 | 2016-09-26 17:22:54 +0000 | [diff] [blame] | 1866 | MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F, |
| 1867 | FunctionAnalysisManager &AM) { |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1868 | auto &DT = AM.getResult<DominatorTreeAnalysis>(F); |
| 1869 | auto &AA = AM.getResult<AAManager>(F); |
Geoff Berry | 290a13e | 2016-08-08 18:27:22 +0000 | [diff] [blame] | 1870 | return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1871 | } |
| 1872 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1873 | PreservedAnalyses MemorySSAPrinterPass::run(Function &F, |
| 1874 | FunctionAnalysisManager &AM) { |
| 1875 | OS << "MemorySSA for function: " << F.getName() << "\n"; |
Geoff Berry | 290a13e | 2016-08-08 18:27:22 +0000 | [diff] [blame] | 1876 | AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1877 | |
| 1878 | return PreservedAnalyses::all(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1879 | } |
| 1880 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1881 | PreservedAnalyses MemorySSAVerifierPass::run(Function &F, |
| 1882 | FunctionAnalysisManager &AM) { |
Geoff Berry | 290a13e | 2016-08-08 18:27:22 +0000 | [diff] [blame] | 1883 | AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA(); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1884 | |
| 1885 | return PreservedAnalyses::all(); |
| 1886 | } |
| 1887 | |
| 1888 | char MemorySSAWrapperPass::ID = 0; |
| 1889 | |
| 1890 | MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) { |
| 1891 | initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 1892 | } |
| 1893 | |
| 1894 | void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); } |
| 1895 | |
| 1896 | void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1897 | AU.setPreservesAll(); |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1898 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 1899 | AU.addRequiredTransitive<AAResultsWrapperPass>(); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1900 | } |
| 1901 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1902 | bool MemorySSAWrapperPass::runOnFunction(Function &F) { |
| 1903 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 1904 | auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 1905 | MSSA.reset(new MemorySSA(F, &AA, &DT)); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1906 | return false; |
| 1907 | } |
| 1908 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1909 | void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); } |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1910 | |
Geoff Berry | b96d3b2 | 2016-06-01 21:30:40 +0000 | [diff] [blame] | 1911 | void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1912 | MSSA->print(OS); |
| 1913 | } |
| 1914 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1915 | MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {} |
| 1916 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1917 | MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A, |
| 1918 | DominatorTree *D) |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 1919 | : MemorySSAWalker(M), Walker(*M, *A, *D), AutoResetWalker(true) {} |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1920 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1921 | MemorySSA::CachingWalker::~CachingWalker() {} |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1922 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1923 | void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) { |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 1924 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) |
| 1925 | MUD->resetOptimized(); |
Daniel Berlin | 83fc77b | 2016-03-01 18:46:54 +0000 | [diff] [blame] | 1926 | } |
| 1927 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1928 | /// \brief Walk the use-def chains starting at \p MA and find |
| 1929 | /// the MemoryAccess that actually clobbers Loc. |
| 1930 | /// |
| 1931 | /// \returns our clobbering memory access |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1932 | MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess( |
| 1933 | MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) { |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1934 | MemoryAccess *New = Walker.findClobber(StartingAccess, Q); |
| 1935 | #ifdef EXPENSIVE_CHECKS |
Daniel Berlin | d7a7ae0 | 2017-04-05 19:01:58 +0000 | [diff] [blame^] | 1936 | MemoryAccess *NewNoCache = Walker.findClobber(StartingAccess, Q); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1937 | assert(NewNoCache == New && "Cache made us hand back a different result?"); |
| 1938 | #endif |
| 1939 | if (AutoResetWalker) |
| 1940 | resetClobberWalker(); |
| 1941 | return New; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1942 | } |
| 1943 | |
George Burgess IV | fd1f2f8 | 2016-06-24 21:02:12 +0000 | [diff] [blame] | 1944 | MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess( |
George Burgess IV | 013fd73 | 2016-10-28 19:22:46 +0000 | [diff] [blame] | 1945 | MemoryAccess *StartingAccess, const MemoryLocation &Loc) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1946 | if (isa<MemoryPhi>(StartingAccess)) |
| 1947 | return StartingAccess; |
| 1948 | |
| 1949 | auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess); |
| 1950 | if (MSSA->isLiveOnEntryDef(StartingUseOrDef)) |
| 1951 | return StartingUseOrDef; |
| 1952 | |
| 1953 | Instruction *I = StartingUseOrDef->getMemoryInst(); |
| 1954 | |
| 1955 | // Conservatively, fences are always clobbers, so don't perform the walk if we |
| 1956 | // hit a fence. |
David Majnemer | a940f36 | 2016-07-15 17:19:24 +0000 | [diff] [blame] | 1957 | if (!ImmutableCallSite(I) && I->isFenceLike()) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1958 | return StartingUseOrDef; |
| 1959 | |
| 1960 | UpwardsMemoryQuery Q; |
| 1961 | Q.OriginalAccess = StartingUseOrDef; |
| 1962 | Q.StartingLoc = Loc; |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1963 | Q.Inst = I; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1964 | Q.IsCall = false; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1965 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1966 | // Unlike the other function, do not walk to the def of a def, because we are |
| 1967 | // handed something we already believe is the clobbering access. |
| 1968 | MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef) |
| 1969 | ? StartingUseOrDef->getDefiningAccess() |
| 1970 | : StartingUseOrDef; |
| 1971 | |
| 1972 | MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1973 | DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is "); |
| 1974 | DEBUG(dbgs() << *StartingUseOrDef << "\n"); |
| 1975 | DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is "); |
| 1976 | DEBUG(dbgs() << *Clobber << "\n"); |
| 1977 | return Clobber; |
| 1978 | } |
| 1979 | |
| 1980 | MemoryAccess * |
George Burgess IV | 400ae40 | 2016-07-20 19:51:34 +0000 | [diff] [blame] | 1981 | MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) { |
| 1982 | auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA); |
| 1983 | // If this is a MemoryPhi, we can't do anything. |
| 1984 | if (!StartingAccess) |
| 1985 | return MA; |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1986 | |
Daniel Berlin | cd2deac | 2016-10-20 20:13:45 +0000 | [diff] [blame] | 1987 | // If this is an already optimized use or def, return the optimized result. |
| 1988 | // Note: Currently, we do not store the optimized def result because we'd need |
| 1989 | // a separate field, since we can't use it as the defining access. |
Daniel Berlin | e33bc31 | 2017-04-04 23:43:10 +0000 | [diff] [blame] | 1990 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess)) |
| 1991 | if (MUD->isOptimized()) |
| 1992 | return MUD->getOptimized(); |
Daniel Berlin | cd2deac | 2016-10-20 20:13:45 +0000 | [diff] [blame] | 1993 | |
George Burgess IV | 400ae40 | 2016-07-20 19:51:34 +0000 | [diff] [blame] | 1994 | const Instruction *I = StartingAccess->getMemoryInst(); |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1995 | UpwardsMemoryQuery Q(I, StartingAccess); |
David Majnemer | a940f36 | 2016-07-15 17:19:24 +0000 | [diff] [blame] | 1996 | // We can't sanely do anything with a fences, they conservatively |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 1997 | // clobber all memory, and have no locations to get pointers from to |
David Majnemer | a940f36 | 2016-07-15 17:19:24 +0000 | [diff] [blame] | 1998 | // try to disambiguate. |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 1999 | if (!Q.IsCall && I->isFenceLike()) |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 2000 | return StartingAccess; |
| 2001 | |
George Burgess IV | 024f3d2 | 2016-08-03 19:57:02 +0000 | [diff] [blame] | 2002 | if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) { |
| 2003 | MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef(); |
Daniel Berlin | e33bc31 | 2017-04-04 23:43:10 +0000 | [diff] [blame] | 2004 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess)) |
| 2005 | MUD->setOptimized(LiveOnEntry); |
George Burgess IV | 024f3d2 | 2016-08-03 19:57:02 +0000 | [diff] [blame] | 2006 | return LiveOnEntry; |
| 2007 | } |
| 2008 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 2009 | // Start with the thing we already think clobbers this location |
| 2010 | MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess(); |
| 2011 | |
| 2012 | // At this point, DefiningAccess may be the live on entry def. |
| 2013 | // If it is, we will not get a better result. |
| 2014 | if (MSSA->isLiveOnEntryDef(DefiningAccess)) |
| 2015 | return DefiningAccess; |
| 2016 | |
| 2017 | MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 2018 | DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is "); |
| 2019 | DEBUG(dbgs() << *DefiningAccess << "\n"); |
| 2020 | DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is "); |
| 2021 | DEBUG(dbgs() << *Result << "\n"); |
Daniel Berlin | e33bc31 | 2017-04-04 23:43:10 +0000 | [diff] [blame] | 2022 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess)) |
| 2023 | MUD->setOptimized(Result); |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 2024 | |
| 2025 | return Result; |
| 2026 | } |
| 2027 | |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 2028 | MemoryAccess * |
George Burgess IV | 400ae40 | 2016-07-20 19:51:34 +0000 | [diff] [blame] | 2029 | DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 2030 | if (auto *Use = dyn_cast<MemoryUseOrDef>(MA)) |
| 2031 | return Use->getDefiningAccess(); |
| 2032 | return MA; |
| 2033 | } |
| 2034 | |
| 2035 | MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess( |
George Burgess IV | 013fd73 | 2016-10-28 19:22:46 +0000 | [diff] [blame] | 2036 | MemoryAccess *StartingAccess, const MemoryLocation &) { |
George Burgess IV | e1100f5 | 2016-02-02 22:46:49 +0000 | [diff] [blame] | 2037 | if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess)) |
| 2038 | return Use->getDefiningAccess(); |
| 2039 | return StartingAccess; |
| 2040 | } |
George Burgess IV | 5f30897 | 2016-07-19 01:29:15 +0000 | [diff] [blame] | 2041 | } // namespace llvm |